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 auto Owner = std::make_pair(std::string(Hostname), PID);
48 if (processStillExecuting(Owner.first, Owner.second))
52 // Delete the lock file. It's invalid anyway.
53 sys::fs::remove(LockFileName);
57 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
58 #if LLVM_ON_UNIX && !defined(__ANDROID__)
62 gethostname(MyHostname, 255);
63 // Check whether the process is dead. If so, we're done.
64 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
71 LockFileManager::LockFileManager(StringRef FileName)
73 this->FileName = FileName;
74 if (error_code EC = sys::fs::make_absolute(this->FileName)) {
78 LockFileName = this->FileName;
79 LockFileName += ".lock";
81 // If the lock file already exists, don't bother to try to create our own
82 // lock file; it won't work anyway. Just figure out who owns this lock file.
83 if ((Owner = readLockFile(LockFileName)))
86 // Create a lock file that is unique to this instance.
87 UniqueLockFileName = LockFileName;
88 UniqueLockFileName += "-%%%%%%%%";
91 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
93 UniqueLockFileName)) {
98 // Write our process ID to our unique lock file.
100 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
103 // FIXME: move getpid() call into LLVM
107 gethostname(hostname, 255);
108 Out << hostname << ' ' << getpid();
110 Out << "localhost 1";
114 if (Out.has_error()) {
115 // We failed to write out PID, so make up an excuse, remove the
116 // unique lock file, and fail.
117 Error = make_error_code(errc::no_space_on_device);
118 sys::fs::remove(UniqueLockFileName.c_str());
124 // Create a link from the lock file name. If this succeeds, we're done.
126 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
127 if (EC == errc::success)
130 if (EC != errc::file_exists) {
135 // Someone else managed to create the lock file first. Read the process ID
136 // from the lock file.
137 if ((Owner = readLockFile(LockFileName))) {
138 // Wipe out our unique lock file (it's useless now)
139 sys::fs::remove(UniqueLockFileName.str());
143 if (!sys::fs::exists(LockFileName.str())) {
144 // The previous owner released the lock file before we could read it.
145 // Try to get ownership again.
149 // There is a lock file that nobody owns; try to clean it up and get
151 if ((EC = sys::fs::remove(LockFileName.str()))) {
158 LockFileManager::LockFileState LockFileManager::getState() const {
168 LockFileManager::~LockFileManager() {
169 if (getState() != LFS_Owned)
172 // Since we own the lock, remove the lock file and our own unique lock file.
173 sys::fs::remove(LockFileName.str());
174 sys::fs::remove(UniqueLockFileName.str());
177 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
178 if (getState() != LFS_Shared)
182 unsigned long Interval = 1;
184 struct timespec Interval;
186 Interval.tv_nsec = 1000000;
188 // Don't wait more than five minutes for the file to appear.
189 unsigned MaxSeconds = 300;
190 bool LockFileGone = false;
192 // Sleep for the designated interval, to allow the owning process time to
193 // finish up and remove the lock file.
194 // FIXME: Should we hook in to system APIs to get a notification when the
195 // lock file is deleted?
199 nanosleep(&Interval, nullptr);
201 bool LockFileJustDisappeared = false;
203 // If the lock file is still expected to be there, check whether it still
207 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
209 LockFileJustDisappeared = true;
213 // If the lock file is no longer there, check if the original file is
216 if (sys::fs::exists(FileName.str())) {
220 // The lock file is gone, so now we're waiting for the original file to
221 // show up. If this just happened, reset our waiting intervals and keep
223 if (LockFileJustDisappeared) {
230 Interval.tv_nsec = 1000000;
236 // If we're looking for the lock file to disappear, but the process
237 // owning the lock died without cleaning up, just bail out.
239 !processStillExecuting((*Owner).first, (*Owner).second)) {
240 return Res_OwnerDied;
243 // Exponentially increase the time we wait for the lock to be removed.
247 Interval.tv_sec *= 2;
248 Interval.tv_nsec *= 2;
249 if (Interval.tv_nsec >= 1000000000) {
251 Interval.tv_nsec -= 1000000000;
256 Interval < MaxSeconds * 1000
258 Interval.tv_sec < (time_t)MaxSeconds