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/StringExtras.h"
11 #include "llvm/Support/Errc.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 // Read the owning host and PID out of the lock file. If it appears that the
33 // owning process is dead, the lock file is invalid.
34 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
35 MemoryBuffer::getFile(LockFileName);
37 sys::fs::remove(LockFileName);
40 MemoryBuffer &MB = *MBOrErr.get();
44 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
45 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
47 if (!PIDStr.getAsInteger(10, PID)) {
48 auto Owner = std::make_pair(std::string(Hostname), PID);
49 if (processStillExecuting(Owner.first, Owner.second))
53 // Delete the lock file. It's invalid anyway.
54 sys::fs::remove(LockFileName);
58 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
59 #if LLVM_ON_UNIX && !defined(__ANDROID__)
63 gethostname(MyHostname, 255);
64 // Check whether the process is dead. If so, we're done.
65 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
72 LockFileManager::LockFileManager(StringRef FileName)
74 this->FileName = FileName;
75 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
79 LockFileName = this->FileName;
80 LockFileName += ".lock";
82 // If the lock file already exists, don't bother to try to create our own
83 // lock file; it won't work anyway. Just figure out who owns this lock file.
84 if ((Owner = readLockFile(LockFileName)))
87 // Create a lock file that is unique to this instance.
88 UniqueLockFileName = LockFileName;
89 UniqueLockFileName += "-%%%%%%%%";
91 if (std::error_code EC = sys::fs::createUniqueFile(
92 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
97 // Write our process ID to our unique lock file.
99 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
102 // FIXME: move getpid() call into LLVM
106 gethostname(hostname, 255);
107 Out << hostname << ' ' << getpid();
109 Out << "localhost 1";
113 if (Out.has_error()) {
114 // We failed to write out PID, so make up an excuse, remove the
115 // unique lock file, and fail.
116 Error = make_error_code(errc::no_space_on_device);
117 sys::fs::remove(UniqueLockFileName);
123 // Create a link from the lock file name. If this succeeds, we're done.
125 sys::fs::create_link(UniqueLockFileName, LockFileName);
129 if (EC != errc::file_exists) {
134 // Someone else managed to create the lock file first. Read the process ID
135 // from the lock file.
136 if ((Owner = readLockFile(LockFileName))) {
137 // Wipe out our unique lock file (it's useless now)
138 sys::fs::remove(UniqueLockFileName);
142 if (!sys::fs::exists(LockFileName)) {
143 // The previous owner released the lock file before we could read it.
144 // Try to get ownership again.
148 // There is a lock file that nobody owns; try to clean it up and get
150 if ((EC = sys::fs::remove(LockFileName))) {
157 LockFileManager::LockFileState LockFileManager::getState() const {
167 LockFileManager::~LockFileManager() {
168 if (getState() != LFS_Owned)
171 // Since we own the lock, remove the lock file and our own unique lock file.
172 sys::fs::remove(LockFileName);
173 sys::fs::remove(UniqueLockFileName);
176 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
177 if (getState() != LFS_Shared)
181 unsigned long Interval = 1;
183 struct timespec Interval;
185 Interval.tv_nsec = 1000000;
187 // Don't wait more than five minutes per iteration. Total timeout for the file
188 // to appear is ~8.5 mins.
189 const unsigned MaxSeconds = 5*60;
191 // Sleep for the designated interval, to allow the owning process time to
192 // finish up and remove the lock file.
193 // FIXME: Should we hook in to system APIs to get a notification when the
194 // lock file is deleted?
198 nanosleep(&Interval, nullptr);
201 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
202 errc::no_such_file_or_directory) {
203 // If the original file wasn't created, somone thought the lock was dead.
204 if (!sys::fs::exists(FileName))
205 return Res_OwnerDied;
209 // If the process owning the lock died without cleaning up, just bail out.
210 if (!processStillExecuting((*Owner).first, (*Owner).second))
211 return Res_OwnerDied;
213 // Exponentially increase the time we wait for the lock to be removed.
217 Interval.tv_sec *= 2;
218 Interval.tv_nsec *= 2;
219 if (Interval.tv_nsec >= 1000000000) {
221 Interval.tv_nsec -= 1000000000;
226 Interval < MaxSeconds * 1000
228 Interval.tv_sec < (time_t)MaxSeconds
236 std::error_code LockFileManager::unsafeRemoveLockFile() {
237 return sys::fs::remove(LockFileName);