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 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/LockFileManager.h"
11 #include "llvm/ADT/None.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/Support/Errc.h"
15 #include "llvm/Support/ErrorOr.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Support/Signals.h"
24 #include <system_error>
26 #include <sys/types.h>
34 #if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
35 #define USE_OSX_GETHOSTUUID 1
37 #define USE_OSX_GETHOSTUUID 0
40 #if USE_OSX_GETHOSTUUID
41 #include <uuid/uuid.h>
46 /// \brief Attempt to read the lock file with the given name, if it exists.
48 /// \param LockFileName The name of the lock file to read.
50 /// \returns The process ID of the process that owns this lock file
51 Optional<std::pair<std::string, int> >
52 LockFileManager::readLockFile(StringRef LockFileName) {
53 // Read the owning host and PID out of the lock file. If it appears that the
54 // owning process is dead, the lock file is invalid.
55 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
56 MemoryBuffer::getFile(LockFileName);
58 sys::fs::remove(LockFileName);
61 MemoryBuffer &MB = *MBOrErr.get();
65 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
66 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
68 if (!PIDStr.getAsInteger(10, PID)) {
69 auto Owner = std::make_pair(std::string(Hostname), PID);
70 if (processStillExecuting(Owner.first, Owner.second))
74 // Delete the lock file. It's invalid anyway.
75 sys::fs::remove(LockFileName);
79 static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
82 #if USE_OSX_GETHOSTUUID
83 // On OS X, use the more stable hardware UUID instead of hostname.
84 struct timespec wait = {1, 0}; // 1 second.
86 if (gethostuuid(uuid, &wait) != 0)
87 return std::error_code(errno, std::system_category());
89 uuid_string_t UUIDStr;
90 uuid_unparse(uuid, UUIDStr);
91 StringRef UUIDRef(UUIDStr);
92 HostID.append(UUIDRef.begin(), UUIDRef.end());
98 gethostname(HostName, 255);
99 StringRef HostNameRef(HostName);
100 HostID.append(HostNameRef.begin(), HostNameRef.end());
103 StringRef Dummy("localhost");
104 HostID.append(Dummy.begin(), Dummy.end());
107 return std::error_code();
110 bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
111 #if LLVM_ON_UNIX && !defined(__ANDROID__)
112 SmallString<256> StoredHostID;
113 if (getHostID(StoredHostID))
114 return true; // Conservatively assume it's executing on error.
116 // Check whether the process is dead. If so, we're done.
117 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
126 /// An RAII helper object ensure that the unique lock file is removed.
128 /// Ensures that if there is an error or a signal before we finish acquiring the
129 /// lock, the unique file will be removed. And if we successfully take the lock,
130 /// the signal handler is left in place so that signals while the lock is held
131 /// will remove the unique lock file. The caller should ensure there is a
132 /// matching call to sys::DontRemoveFileOnSignal when the lock is released.
133 class RemoveUniqueLockFileOnSignal {
135 bool RemoveImmediately;
137 RemoveUniqueLockFileOnSignal(StringRef Name)
138 : Filename(Name), RemoveImmediately(true) {
139 sys::RemoveFileOnSignal(Filename, nullptr);
142 ~RemoveUniqueLockFileOnSignal() {
143 if (!RemoveImmediately) {
144 // Leave the signal handler enabled. It will be removed when the lock is
148 sys::fs::remove(Filename);
149 sys::DontRemoveFileOnSignal(Filename);
152 void lockAcquired() { RemoveImmediately = false; }
155 } // end anonymous namespace
157 LockFileManager::LockFileManager(StringRef FileName)
159 this->FileName = FileName;
160 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
161 std::string S("failed to obtain absolute path for ");
162 S.append(this->FileName.str());
166 LockFileName = this->FileName;
167 LockFileName += ".lock";
169 // If the lock file already exists, don't bother to try to create our own
170 // lock file; it won't work anyway. Just figure out who owns this lock file.
171 if ((Owner = readLockFile(LockFileName)))
174 // Create a lock file that is unique to this instance.
175 UniqueLockFileName = LockFileName;
176 UniqueLockFileName += "-%%%%%%%%";
177 int UniqueLockFileID;
178 if (std::error_code EC = sys::fs::createUniqueFile(
179 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
180 std::string S("failed to create unique file ");
181 S.append(UniqueLockFileName.str());
186 // Write our process ID to our unique lock file.
188 SmallString<256> HostID;
189 if (auto EC = getHostID(HostID)) {
190 setError(EC, "failed to get host id");
194 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
195 Out << HostID << ' ';
203 if (Out.has_error()) {
204 // We failed to write out PID, so make up an excuse, remove the
205 // unique lock file, and fail.
206 auto EC = make_error_code(errc::no_space_on_device);
207 std::string S("failed to write to ");
208 S.append(UniqueLockFileName.str());
210 sys::fs::remove(UniqueLockFileName);
215 // Clean up the unique file on signal, which also releases the lock if it is
216 // held since the .lock symlink will point to a nonexistent file.
217 RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
220 // Create a link from the lock file name. If this succeeds, we're done.
222 sys::fs::create_link(UniqueLockFileName, LockFileName);
224 RemoveUniqueFile.lockAcquired();
228 if (EC != errc::file_exists) {
229 std::string S("failed to create link ");
230 raw_string_ostream OSS(S);
231 OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
232 setError(EC, OSS.str());
236 // Someone else managed to create the lock file first. Read the process ID
237 // from the lock file.
238 if ((Owner = readLockFile(LockFileName))) {
239 // Wipe out our unique lock file (it's useless now)
240 sys::fs::remove(UniqueLockFileName);
244 if (!sys::fs::exists(LockFileName)) {
245 // The previous owner released the lock file before we could read it.
246 // Try to get ownership again.
250 // There is a lock file that nobody owns; try to clean it up and get
252 if ((EC = sys::fs::remove(LockFileName))) {
253 std::string S("failed to remove lockfile ");
254 S.append(UniqueLockFileName.str());
261 LockFileManager::LockFileState LockFileManager::getState() const {
271 std::string LockFileManager::getErrorMessage() const {
273 std::string Str(ErrorDiagMsg);
274 std::string ErrCodeMsg = Error->message();
275 raw_string_ostream OSS(Str);
276 if (!ErrCodeMsg.empty())
277 OSS << ": " << Error->message();
284 LockFileManager::~LockFileManager() {
285 if (getState() != LFS_Owned)
288 // Since we own the lock, remove the lock file and our own unique lock file.
289 sys::fs::remove(LockFileName);
290 sys::fs::remove(UniqueLockFileName);
291 // The unique file is now gone, so remove it from the signal handler. This
292 // matches a sys::RemoveFileOnSignal() in LockFileManager().
293 sys::DontRemoveFileOnSignal(UniqueLockFileName);
296 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
297 if (getState() != LFS_Shared)
301 unsigned long Interval = 1;
303 struct timespec Interval;
305 Interval.tv_nsec = 1000000;
307 // Don't wait more than 40s per iteration. Total timeout for the file
308 // to appear is ~1.5 minutes.
309 const unsigned MaxSeconds = 40;
311 // Sleep for the designated interval, to allow the owning process time to
312 // finish up and remove the lock file.
313 // FIXME: Should we hook in to system APIs to get a notification when the
314 // lock file is deleted?
318 nanosleep(&Interval, nullptr);
321 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
322 errc::no_such_file_or_directory) {
323 // If the original file wasn't created, somone thought the lock was dead.
324 if (!sys::fs::exists(FileName))
325 return Res_OwnerDied;
329 // If the process owning the lock died without cleaning up, just bail out.
330 if (!processStillExecuting((*Owner).first, (*Owner).second))
331 return Res_OwnerDied;
333 // Exponentially increase the time we wait for the lock to be removed.
337 Interval.tv_sec *= 2;
338 Interval.tv_nsec *= 2;
339 if (Interval.tv_nsec >= 1000000000) {
341 Interval.tv_nsec -= 1000000000;
346 Interval < MaxSeconds * 1000
348 Interval.tv_sec < (time_t)MaxSeconds
356 std::error_code LockFileManager::unsafeRemoveLockFile() {
357 return sys::fs::remove(LockFileName);