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 if (error_code EC = sys::fs::make_absolute(this->FileName)) {
75 LockFileName = this->FileName;
76 LockFileName += ".lock";
78 // If the lock file already exists, don't bother to try to create our own
79 // lock file; it won't work anyway. Just figure out who owns this lock file.
80 if ((Owner = readLockFile(LockFileName)))
83 // Create a lock file that is unique to this instance.
84 UniqueLockFileName = LockFileName;
85 UniqueLockFileName += "-%%%%%%%%";
88 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
90 UniqueLockFileName)) {
95 // Write our process ID to our unique lock file.
97 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
100 // FIXME: move getpid() call into LLVM
104 gethostname(hostname, 255);
105 Out << hostname << ' ' << getpid();
107 Out << "localhost 1";
111 if (Out.has_error()) {
112 // We failed to write out PID, so make up an excuse, remove the
113 // unique lock file, and fail.
114 Error = make_error_code(errc::no_space_on_device);
115 sys::fs::remove(UniqueLockFileName.c_str());
121 // Create a link from the lock file name. If this succeeds, we're done.
123 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
124 if (EC == errc::success)
127 if (EC != errc::file_exists) {
132 // Someone else managed to create the lock file first. Read the process ID
133 // from the lock file.
134 if ((Owner = readLockFile(LockFileName))) {
135 // Wipe out our unique lock file (it's useless now)
136 sys::fs::remove(UniqueLockFileName.str());
140 if (!sys::fs::exists(LockFileName.str())) {
141 // The previous owner released the lock file before we could read it.
142 // Try to get ownership again.
146 // There is a lock file that nobody owns; try to clean it up and get
148 if ((EC = sys::fs::remove(LockFileName.str()))) {
155 LockFileManager::LockFileState LockFileManager::getState() const {
165 LockFileManager::~LockFileManager() {
166 if (getState() != LFS_Owned)
169 // Since we own the lock, remove the lock file and our own unique lock file.
170 sys::fs::remove(LockFileName.str());
171 sys::fs::remove(UniqueLockFileName.str());
174 void LockFileManager::waitForUnlock() {
175 if (getState() != LFS_Shared)
179 unsigned long Interval = 1;
181 struct timespec Interval;
183 Interval.tv_nsec = 1000000;
185 // Don't wait more than five minutes for the file to appear.
186 unsigned MaxSeconds = 300;
187 bool LockFileGone = false;
189 // Sleep for the designated interval, to allow the owning process time to
190 // finish up and remove the lock file.
191 // FIXME: Should we hook in to system APIs to get a notification when the
192 // lock file is deleted?
196 nanosleep(&Interval, NULL);
198 bool LockFileJustDisappeared = false;
200 // If the lock file is still expected to be there, check whether it still
204 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
206 LockFileJustDisappeared = true;
210 // If the lock file is no longer there, check if the original file is
213 if (sys::fs::exists(FileName.str())) {
217 // The lock file is gone, so now we're waiting for the original file to
218 // show up. If this just happened, reset our waiting intervals and keep
220 if (LockFileJustDisappeared) {
227 Interval.tv_nsec = 1000000;
233 // If we're looking for the lock file to disappear, but the process
234 // owning the lock died without cleaning up, just bail out.
236 !processStillExecuting((*Owner).first, (*Owner).second)) {
240 // Exponentially increase the time we wait for the lock to be removed.
244 Interval.tv_sec *= 2;
245 Interval.tv_nsec *= 2;
246 if (Interval.tv_nsec >= 1000000000) {
248 Interval.tv_nsec -= 1000000000;
253 Interval < MaxSeconds * 1000
255 Interval.tv_sec < (time_t)MaxSeconds