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/Support/FileSystem.h"
11 #include "llvm/Support/raw_ostream.h"
14 #include <sys/types.h>
23 /// \brief Attempt to read the lock file with the given name, if it exists.
25 /// \param LockFileName The name of the lock file to read.
27 /// \returns The process ID of the process that owns this lock file
28 Optional<std::pair<std::string, int> >
29 LockFileManager::readLockFile(StringRef LockFileName) {
30 // Check whether the lock file exists. If not, clearly there's nothing
31 // to read, so we just return.
33 if (sys::fs::exists(LockFileName, Exists) || !Exists)
34 return Optional<std::pair<std::string, int> >();
36 // Read the owning host and PID out of the lock file. If it appears that the
37 // owning process is dead, the lock file is invalid.
40 std::ifstream Input(LockFileName.str().c_str());
41 if (Input >> Hostname >> PID && PID > 0 &&
42 processStillExecuting(Hostname, PID))
43 return std::make_pair(Hostname, PID);
45 // Delete the lock file. It's invalid anyway.
47 sys::fs::remove(LockFileName, Existed);
48 return Optional<std::pair<std::string, int> >();
51 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
52 #if LLVM_ON_UNIX && !defined(__ANDROID__)
56 gethostname(MyHostname, 255);
57 // Check whether the process is dead. If so, we're done.
58 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
65 LockFileManager::LockFileManager(StringRef FileName)
67 LockFileName = FileName;
68 LockFileName += ".lock";
70 // If the lock file already exists, don't bother to try to create our own
71 // lock file; it won't work anyway. Just figure out who owns this lock file.
72 if ((Owner = readLockFile(LockFileName)))
75 // Create a lock file that is unique to this instance.
76 UniqueLockFileName = LockFileName;
77 UniqueLockFileName += "-%%%%%%%%";
80 = sys::fs::unique_file(UniqueLockFileName.str(),
83 /*makeAbsolute=*/false)) {
88 // Write our process ID to our unique lock file.
90 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
93 // FIXME: move getpid() call into LLVM
97 gethostname(hostname, 255);
98 Out << hostname << ' ' << getpid();
100 Out << "localhost 1";
104 if (Out.has_error()) {
105 // We failed to write out PID, so make up an excuse, remove the
106 // unique lock file, and fail.
107 Error = make_error_code(errc::no_space_on_device);
109 sys::fs::remove(UniqueLockFileName.c_str(), Existed);
114 // Create a hard link from the lock file name. If this succeeds, we're done.
116 = sys::fs::create_hard_link(UniqueLockFileName.str(),
118 if (EC == errc::success)
121 // Creating the hard link failed.
124 // The creation of the hard link may appear to fail, but if stat'ing the
125 // unique file returns a link count of 2, then we can still declare success.
127 if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
128 StatBuf.st_nlink == 2)
132 // Someone else managed to create the lock file first. Wipe out our unique
133 // lock file (it's useless now) and read the process ID from the lock file.
135 sys::fs::remove(UniqueLockFileName.str(), Existed);
136 if ((Owner = readLockFile(LockFileName)))
139 // There is a lock file that nobody owns; try to clean it up and report
141 sys::fs::remove(LockFileName.str(), Existed);
145 LockFileManager::LockFileState LockFileManager::getState() const {
155 LockFileManager::~LockFileManager() {
156 if (getState() != LFS_Owned)
159 // Since we own the lock, remove the lock file and our own unique lock file.
161 sys::fs::remove(LockFileName.str(), Existed);
162 sys::fs::remove(UniqueLockFileName.str(), Existed);
165 void LockFileManager::waitForUnlock() {
166 if (getState() != LFS_Shared)
170 unsigned long Interval = 1;
172 struct timespec Interval;
174 Interval.tv_nsec = 1000000;
176 // Don't wait more than an hour for the file to appear.
177 const unsigned MaxSeconds = 3600;
179 // Sleep for the designated interval, to allow the owning process time to
180 // finish up and remove the lock file.
181 // FIXME: Should we hook in to system APIs to get a notification when the
182 // lock file is deleted?
186 nanosleep(&Interval, NULL);
188 // If the file no longer exists, we're done.
190 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists)
193 if (!processStillExecuting((*Owner).first, (*Owner).second))
196 // Exponentially increase the time we wait for the lock to be removed.
200 Interval.tv_sec *= 2;
201 Interval.tv_nsec *= 2;
202 if (Interval.tv_nsec >= 1000000000) {
204 Interval.tv_nsec -= 1000000000;
209 Interval < MaxSeconds * 1000
211 Interval.tv_sec < (time_t)MaxSeconds