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/Path.h"
15 #include "llvm/Support/raw_ostream.h"
17 #include <sys/types.h>
26 /// \brief Attempt to read the lock file with the given name, if it exists.
28 /// \param LockFileName The name of the lock file to read.
30 /// \returns The process ID of the process that owns this lock file
31 Optional<std::pair<std::string, int> >
32 LockFileManager::readLockFile(StringRef LockFileName) {
33 // Read the owning host and PID out of the lock file. If it appears that the
34 // owning process is dead, the lock file is invalid.
35 std::unique_ptr<MemoryBuffer> MB;
36 if (MemoryBuffer::getFile(LockFileName, MB)) {
37 sys::fs::remove(LockFileName);
43 std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
44 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
46 if (!PIDStr.getAsInteger(10, PID))
47 return std::make_pair(std::string(Hostname), PID);
49 // Delete the lock file. It's invalid anyway.
50 sys::fs::remove(LockFileName);
54 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
55 #if LLVM_ON_UNIX && !defined(__ANDROID__)
59 gethostname(MyHostname, 255);
60 // Check whether the process is dead. If so, we're done.
61 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
68 LockFileManager::LockFileManager(StringRef FileName)
70 this->FileName = FileName;
71 LockFileName = FileName;
72 LockFileName += ".lock";
74 // If the lock file already exists, don't bother to try to create our own
75 // lock file; it won't work anyway. Just figure out who owns this lock file.
76 if ((Owner = readLockFile(LockFileName)))
79 // Create a lock file that is unique to this instance.
80 UniqueLockFileName = LockFileName;
81 UniqueLockFileName += "-%%%%%%%%";
84 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
86 UniqueLockFileName)) {
91 // Write our process ID to our unique lock file.
93 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
96 // FIXME: move getpid() call into LLVM
100 gethostname(hostname, 255);
101 Out << hostname << ' ' << getpid();
103 Out << "localhost 1";
107 if (Out.has_error()) {
108 // We failed to write out PID, so make up an excuse, remove the
109 // unique lock file, and fail.
110 Error = make_error_code(errc::no_space_on_device);
111 sys::fs::remove(UniqueLockFileName.c_str());
117 // Create a link from the lock file name. If this succeeds, we're done.
119 sys::fs::create_link(sys::path::filename(UniqueLockFileName.str()),
121 if (EC == errc::success)
124 if (EC != errc::file_exists) {
129 // Someone else managed to create the lock file first. Read the process ID
130 // from the lock file.
131 if ((Owner = readLockFile(LockFileName))) {
132 // Wipe out our unique lock file (it's useless now)
133 sys::fs::remove(UniqueLockFileName.str());
137 if (!sys::fs::exists(LockFileName.str())) {
138 // The previous owner released the lock file before we could read it.
139 // Try to get ownership again.
143 // There is a lock file that nobody owns; try to clean it up and get
145 if ((EC = sys::fs::remove(LockFileName.str()))) {
152 LockFileManager::LockFileState LockFileManager::getState() const {
162 LockFileManager::~LockFileManager() {
163 if (getState() != LFS_Owned)
166 // Since we own the lock, remove the lock file and our own unique lock file.
167 sys::fs::remove(LockFileName.str());
168 sys::fs::remove(UniqueLockFileName.str());
171 void LockFileManager::waitForUnlock() {
172 if (getState() != LFS_Shared)
176 unsigned long Interval = 1;
178 struct timespec Interval;
180 Interval.tv_nsec = 1000000;
182 // Don't wait more than five minutes for the file to appear.
183 unsigned MaxSeconds = 300;
184 bool LockFileGone = false;
186 // Sleep for the designated interval, to allow the owning process time to
187 // finish up and remove the lock file.
188 // FIXME: Should we hook in to system APIs to get a notification when the
189 // lock file is deleted?
193 nanosleep(&Interval, NULL);
195 bool LockFileJustDisappeared = false;
197 // If the lock file is still expected to be there, check whether it still
201 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
203 LockFileJustDisappeared = true;
207 // If the lock file is no longer there, check if the original file is
210 if (sys::fs::exists(FileName.str())) {
214 // The lock file is gone, so now we're waiting for the original file to
215 // show up. If this just happened, reset our waiting intervals and keep
217 if (LockFileJustDisappeared) {
224 Interval.tv_nsec = 1000000;
230 // If we're looking for the lock file to disappear, but the process
231 // owning the lock died without cleaning up, just bail out.
233 !processStillExecuting((*Owner).first, (*Owner).second)) {
237 // Exponentially increase the time we wait for the lock to be removed.
241 Interval.tv_sec *= 2;
242 Interval.tv_nsec *= 2;
243 if (Interval.tv_nsec >= 1000000000) {
245 Interval.tv_nsec -= 1000000000;
250 Interval < MaxSeconds * 1000
252 Interval.tv_sec < (time_t)MaxSeconds