1 //===--- LockFileManager.cpp - File-level Locking Utility------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/LockFileManager.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/raw_ostream.h"
16 #include <sys/types.h>
25 /// \brief Attempt to read the lock file with the given name, if it exists.
27 /// \param LockFileName The name of the lock file to read.
29 /// \returns The process ID of the process that owns this lock file
30 Optional<std::pair<std::string, int> >
31 LockFileManager::readLockFile(StringRef LockFileName) {
32 // Check whether the lock file exists. If not, clearly there's nothing
33 // to read, so we just return.
34 if (!sys::fs::exists(LockFileName))
37 // Read the owning host and PID out of the lock file. If it appears that the
38 // owning process is dead, the lock file is invalid.
39 OwningPtr<MemoryBuffer> MB;
40 if (MemoryBuffer::getFile(LockFileName, MB))
45 tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
46 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
48 if (!PIDStr.getAsInteger(10, PID))
49 return std::make_pair(std::string(Hostname), PID);
51 // Delete the lock file. It's invalid anyway.
52 sys::fs::remove(LockFileName);
56 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
57 #if LLVM_ON_UNIX && !defined(__ANDROID__)
61 gethostname(MyHostname, 255);
62 // Check whether the process is dead. If so, we're done.
63 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
70 LockFileManager::LockFileManager(StringRef FileName)
72 this->FileName = FileName;
73 LockFileName = FileName;
74 LockFileName += ".lock";
76 // If the lock file already exists, don't bother to try to create our own
77 // lock file; it won't work anyway. Just figure out who owns this lock file.
78 if ((Owner = readLockFile(LockFileName)))
81 // Create a lock file that is unique to this instance.
82 UniqueLockFileName = LockFileName;
83 UniqueLockFileName += "-%%%%%%%%";
86 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
88 UniqueLockFileName)) {
93 // Write our process ID to our unique lock file.
95 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
98 // FIXME: move getpid() call into LLVM
102 gethostname(hostname, 255);
103 Out << hostname << ' ' << getpid();
105 Out << "localhost 1";
109 if (Out.has_error()) {
110 // We failed to write out PID, so make up an excuse, remove the
111 // unique lock file, and fail.
112 Error = make_error_code(errc::no_space_on_device);
113 sys::fs::remove(UniqueLockFileName.c_str());
118 // Create a hard link from the lock file name. If this succeeds, we're done.
120 = sys::fs::create_hard_link(UniqueLockFileName.str(),
122 if (EC == errc::success)
125 // Creating the hard link failed.
128 // The creation of the hard link may appear to fail, but if stat'ing the
129 // unique file returns a link count of 2, then we can still declare success.
131 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
132 StatBuf.st_nlink == 2)
136 // Someone else managed to create the lock file first. Wipe out our unique
137 // lock file (it's useless now) and read the process ID from the lock file.
138 sys::fs::remove(UniqueLockFileName.str());
139 if ((Owner = readLockFile(LockFileName)))
142 // There is a lock file that nobody owns; try to clean it up and report
144 sys::fs::remove(LockFileName.str());
148 LockFileManager::LockFileState LockFileManager::getState() const {
158 LockFileManager::~LockFileManager() {
159 if (getState() != LFS_Owned)
162 // Since we own the lock, remove the lock file and our own unique lock file.
163 sys::fs::remove(LockFileName.str());
164 sys::fs::remove(UniqueLockFileName.str());
167 void LockFileManager::waitForUnlock() {
168 if (getState() != LFS_Shared)
172 unsigned long Interval = 1;
174 struct timespec Interval;
176 Interval.tv_nsec = 1000000;
178 // Don't wait more than five minutes for the file to appear.
179 unsigned MaxSeconds = 300;
180 bool LockFileGone = false;
182 // Sleep for the designated interval, to allow the owning process time to
183 // finish up and remove the lock file.
184 // FIXME: Should we hook in to system APIs to get a notification when the
185 // lock file is deleted?
189 nanosleep(&Interval, NULL);
191 bool LockFileJustDisappeared = false;
193 // If the lock file is still expected to be there, check whether it still
197 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
199 LockFileJustDisappeared = true;
203 // If the lock file is no longer there, check if the original file is
206 if (sys::fs::exists(FileName.str())) {
210 // The lock file is gone, so now we're waiting for the original file to
211 // show up. If this just happened, reset our waiting intervals and keep
213 if (LockFileJustDisappeared) {
220 Interval.tv_nsec = 1000000;
226 // If we're looking for the lock file to disappear, but the process
227 // owning the lock died without cleaning up, just bail out.
229 !processStillExecuting((*Owner).first, (*Owner).second)) {
233 // Exponentially increase the time we wait for the lock to be removed.
237 Interval.tv_sec *= 2;
238 Interval.tv_nsec *= 2;
239 if (Interval.tv_nsec >= 1000000000) {
241 Interval.tv_nsec -= 1000000000;
246 Interval < MaxSeconds * 1000
248 Interval.tv_sec < (time_t)MaxSeconds