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 /// \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 for cleanups.
128 std::function<void()> Fn;
129 bool Canceled = false;
132 RAIICleanup(std::function<void()> Fn) : Fn(Fn) {}
140 void cancel() { Canceled = true; }
143 } // end anonymous namespace
145 LockFileManager::LockFileManager(StringRef FileName)
147 this->FileName = FileName;
148 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
149 std::string S("failed to obtain absolute path for ");
150 S.append(this->FileName.str());
154 LockFileName = this->FileName;
155 LockFileName += ".lock";
157 // If the lock file already exists, don't bother to try to create our own
158 // lock file; it won't work anyway. Just figure out who owns this lock file.
159 if ((Owner = readLockFile(LockFileName)))
162 // Create a lock file that is unique to this instance.
163 Expected<sys::fs::TempFile> Temp =
164 sys::fs::TempFile::create(LockFileName + "-%%%%%%%%");
166 std::error_code EC = errorToErrorCode(Temp.takeError());
167 std::string S("failed to create unique file with prefix ");
168 S.append(LockFileName.str());
172 UniqueLockFile = std::move(*Temp);
174 // Make sure we discard the temporary file on exit.
175 RAIICleanup RemoveTempFile([&]() {
176 if (Error E = UniqueLockFile->discard())
177 setError(errorToErrorCode(std::move(E)));
180 // Write our process ID to our unique lock file.
182 SmallString<256> HostID;
183 if (auto EC = getHostID(HostID)) {
184 setError(EC, "failed to get host id");
188 raw_fd_ostream Out(UniqueLockFile->FD, /*shouldClose=*/false);
189 Out << HostID << ' ';
197 if (Out.has_error()) {
198 // We failed to write out PID, so report the error, remove the
199 // unique lock file, and fail.
200 std::string S("failed to write to ");
201 S.append(UniqueLockFile->TmpName);
202 setError(Out.error(), S);
208 // Create a link from the lock file name. If this succeeds, we're done.
210 sys::fs::create_link(UniqueLockFile->TmpName, LockFileName);
212 RemoveTempFile.cancel();
216 if (EC != errc::file_exists) {
217 std::string S("failed to create link ");
218 raw_string_ostream OSS(S);
219 OSS << LockFileName.str() << " to " << UniqueLockFile->TmpName;
220 setError(EC, OSS.str());
224 // Someone else managed to create the lock file first. Read the process ID
225 // from the lock file.
226 if ((Owner = readLockFile(LockFileName)))
227 return; // RemoveTempFile will delete out our unique lock file.
229 if (!sys::fs::exists(LockFileName)) {
230 // The previous owner released the lock file before we could read it.
231 // Try to get ownership again.
235 // There is a lock file that nobody owns; try to clean it up and get
237 if ((EC = sys::fs::remove(LockFileName))) {
238 std::string S("failed to remove lockfile ");
239 S.append(LockFileName.str());
246 LockFileManager::LockFileState LockFileManager::getState() const {
256 std::string LockFileManager::getErrorMessage() const {
258 std::string Str(ErrorDiagMsg);
259 std::string ErrCodeMsg = ErrorCode.message();
260 raw_string_ostream OSS(Str);
261 if (!ErrCodeMsg.empty())
262 OSS << ": " << ErrCodeMsg;
268 LockFileManager::~LockFileManager() {
269 if (getState() != LFS_Owned)
272 // Since we own the lock, remove the lock file and our own unique lock file.
273 sys::fs::remove(LockFileName);
274 consumeError(UniqueLockFile->discard());
277 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
278 if (getState() != LFS_Shared)
282 unsigned long Interval = 1;
284 struct timespec Interval;
286 Interval.tv_nsec = 1000000;
288 // Don't wait more than 40s per iteration. Total timeout for the file
289 // to appear is ~1.5 minutes.
290 const unsigned MaxSeconds = 40;
292 // Sleep for the designated interval, to allow the owning process time to
293 // finish up and remove the lock file.
294 // FIXME: Should we hook in to system APIs to get a notification when the
295 // lock file is deleted?
299 nanosleep(&Interval, nullptr);
302 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
303 errc::no_such_file_or_directory) {
304 // If the original file wasn't created, somone thought the lock was dead.
305 if (!sys::fs::exists(FileName))
306 return Res_OwnerDied;
310 // If the process owning the lock died without cleaning up, just bail out.
311 if (!processStillExecuting((*Owner).first, (*Owner).second))
312 return Res_OwnerDied;
314 // Exponentially increase the time we wait for the lock to be removed.
318 Interval.tv_sec *= 2;
319 Interval.tv_nsec *= 2;
320 if (Interval.tv_nsec >= 1000000000) {
322 Interval.tv_nsec -= 1000000000;
327 Interval < MaxSeconds * 1000
329 Interval.tv_sec < (time_t)MaxSeconds
337 std::error_code LockFileManager::unsafeRemoveLockFile() {
338 return sys::fs::remove(LockFileName);