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 std::unique_ptr<MemoryBuffer> MB;
40 if (MemoryBuffer::getFile(LockFileName, MB))
45 std::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)
71 static error_code unix_create_symbolic_link(const Twine &to,
74 SmallString<128> from_storage;
75 SmallString<128> to_storage;
76 StringRef f = from.toNullTerminatedStringRef(from_storage);
77 StringRef t = to.toNullTerminatedStringRef(to_storage);
79 if (::symlink(t.begin(), f.begin()) == -1)
80 return error_code(errno, system_category());
82 return error_code::success();
86 LockFileManager::LockFileManager(StringRef FileName)
88 this->FileName = FileName;
89 LockFileName = FileName;
90 LockFileName += ".lock";
92 // If the lock file already exists, don't bother to try to create our own
93 // lock file; it won't work anyway. Just figure out who owns this lock file.
94 if ((Owner = readLockFile(LockFileName)))
97 // Create a lock file that is unique to this instance.
98 UniqueLockFileName = LockFileName;
99 UniqueLockFileName += "-%%%%%%%%";
100 int UniqueLockFileID;
102 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
104 UniqueLockFileName)) {
109 // Write our process ID to our unique lock file.
111 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
114 // FIXME: move getpid() call into LLVM
118 gethostname(hostname, 255);
119 Out << hostname << ' ' << getpid();
121 Out << "localhost 1";
125 if (Out.has_error()) {
126 // We failed to write out PID, so make up an excuse, remove the
127 // unique lock file, and fail.
128 Error = make_error_code(errc::no_space_on_device);
129 sys::fs::remove(UniqueLockFileName.c_str());
136 // Create a symbolic link from the lock file name. If this succeeds, we're
137 // done. Note that we are using symbolic link because hard links are not
138 // supported by all filesystems.
140 = unix_create_symbolic_link(UniqueLockFileName.str(),
143 // We can't use symbolic links for windows.
144 // Create a hard link from the lock file name. If this succeeds, we're done.
146 = sys::fs::create_hard_link(UniqueLockFileName.str(),
149 if (EC == errc::success)
152 if (EC != errc::file_exists) {
157 // Someone else managed to create the lock file first. Read the process ID
158 // from the lock file.
159 if ((Owner = readLockFile(LockFileName))) {
160 // Wipe out our unique lock file (it's useless now)
161 sys::fs::remove(UniqueLockFileName.str());
165 if (!sys::fs::exists(LockFileName.str())) {
166 // The previous owner released the lock file before we could read it.
167 // Try to get ownership again.
171 // There is a lock file that nobody owns; try to clean it up and get
173 if ((EC = sys::fs::remove(LockFileName.str()))) {
180 LockFileManager::LockFileState LockFileManager::getState() const {
190 LockFileManager::~LockFileManager() {
191 if (getState() != LFS_Owned)
194 // Since we own the lock, remove the lock file and our own unique lock file.
195 sys::fs::remove(LockFileName.str());
196 sys::fs::remove(UniqueLockFileName.str());
199 void LockFileManager::waitForUnlock() {
200 if (getState() != LFS_Shared)
204 unsigned long Interval = 1;
206 struct timespec Interval;
208 Interval.tv_nsec = 1000000;
210 // Don't wait more than five minutes for the file to appear.
211 unsigned MaxSeconds = 300;
212 bool LockFileGone = false;
214 // Sleep for the designated interval, to allow the owning process time to
215 // finish up and remove the lock file.
216 // FIXME: Should we hook in to system APIs to get a notification when the
217 // lock file is deleted?
221 nanosleep(&Interval, NULL);
223 bool LockFileJustDisappeared = false;
225 // If the lock file is still expected to be there, check whether it still
229 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
231 LockFileJustDisappeared = true;
235 // If the lock file is no longer there, check if the original file is
238 if (sys::fs::exists(FileName.str())) {
242 // The lock file is gone, so now we're waiting for the original file to
243 // show up. If this just happened, reset our waiting intervals and keep
245 if (LockFileJustDisappeared) {
252 Interval.tv_nsec = 1000000;
258 // If we're looking for the lock file to disappear, but the process
259 // owning the lock died without cleaning up, just bail out.
261 !processStillExecuting((*Owner).first, (*Owner).second)) {
265 // Exponentially increase the time we wait for the lock to be removed.
269 Interval.tv_sec *= 2;
270 Interval.tv_nsec *= 2;
271 if (Interval.tv_nsec >= 1000000000) {
273 Interval.tv_nsec -= 1000000000;
278 Interval < MaxSeconds * 1000
280 Interval.tv_sec < (time_t)MaxSeconds