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/Signals.h"
19 #include "llvm/Support/raw_ostream.h"
24 #include <sys/types.h>
25 #include <system_error>
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 /// 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 report the error, remove the
205 // unique lock file, and fail.
206 std::string S("failed to write to ");
207 S.append(UniqueLockFileName.str());
208 setError(Out.error(), S);
209 sys::fs::remove(UniqueLockFileName);
214 // Clean up the unique file on signal, which also releases the lock if it is
215 // held since the .lock symlink will point to a nonexistent file.
216 RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
219 // Create a link from the lock file name. If this succeeds, we're done.
221 sys::fs::create_link(UniqueLockFileName, LockFileName);
223 RemoveUniqueFile.lockAcquired();
227 if (EC != errc::file_exists) {
228 std::string S("failed to create link ");
229 raw_string_ostream OSS(S);
230 OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
231 setError(EC, OSS.str());
235 // Someone else managed to create the lock file first. Read the process ID
236 // from the lock file.
237 if ((Owner = readLockFile(LockFileName))) {
238 // Wipe out our unique lock file (it's useless now)
239 sys::fs::remove(UniqueLockFileName);
243 if (!sys::fs::exists(LockFileName)) {
244 // The previous owner released the lock file before we could read it.
245 // Try to get ownership again.
249 // There is a lock file that nobody owns; try to clean it up and get
251 if ((EC = sys::fs::remove(LockFileName))) {
252 std::string S("failed to remove lockfile ");
253 S.append(UniqueLockFileName.str());
260 LockFileManager::LockFileState LockFileManager::getState() const {
270 std::string LockFileManager::getErrorMessage() const {
272 std::string Str(ErrorDiagMsg);
273 std::string ErrCodeMsg = ErrorCode.message();
274 raw_string_ostream OSS(Str);
275 if (!ErrCodeMsg.empty())
276 OSS << ": " << ErrCodeMsg;
282 LockFileManager::~LockFileManager() {
283 if (getState() != LFS_Owned)
286 // Since we own the lock, remove the lock file and our own unique lock file.
287 sys::fs::remove(LockFileName);
288 sys::fs::remove(UniqueLockFileName);
289 // The unique file is now gone, so remove it from the signal handler. This
290 // matches a sys::RemoveFileOnSignal() in LockFileManager().
291 sys::DontRemoveFileOnSignal(UniqueLockFileName);
294 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
295 if (getState() != LFS_Shared)
299 unsigned long Interval = 1;
301 struct timespec Interval;
303 Interval.tv_nsec = 1000000;
305 // Don't wait more than 40s per iteration. Total timeout for the file
306 // to appear is ~1.5 minutes.
307 const unsigned MaxSeconds = 40;
309 // Sleep for the designated interval, to allow the owning process time to
310 // finish up and remove the lock file.
311 // FIXME: Should we hook in to system APIs to get a notification when the
312 // lock file is deleted?
316 nanosleep(&Interval, nullptr);
319 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
320 errc::no_such_file_or_directory) {
321 // If the original file wasn't created, somone thought the lock was dead.
322 if (!sys::fs::exists(FileName))
323 return Res_OwnerDied;
327 // If the process owning the lock died without cleaning up, just bail out.
328 if (!processStillExecuting((*Owner).first, (*Owner).second))
329 return Res_OwnerDied;
331 // Exponentially increase the time we wait for the lock to be removed.
335 Interval.tv_sec *= 2;
336 Interval.tv_nsec *= 2;
337 if (Interval.tv_nsec >= 1000000000) {
339 Interval.tv_nsec -= 1000000000;
344 Interval < MaxSeconds * 1000
346 Interval.tv_sec < (time_t)MaxSeconds
354 std::error_code LockFileManager::unsafeRemoveLockFile() {
355 return sys::fs::remove(LockFileName);