17039e358SDouglas Gregor //===--- LockFileManager.cpp - File-level Locking Utility------------------===//
27039e358SDouglas Gregor //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67039e358SDouglas Gregor //
77039e358SDouglas Gregor //===----------------------------------------------------------------------===//
833d7b762SEugene Zelenko
97039e358SDouglas Gregor #include "llvm/Support/LockFileManager.h"
1033d7b762SEugene Zelenko #include "llvm/ADT/None.h"
1133d7b762SEugene Zelenko #include "llvm/ADT/SmallVector.h"
12d78273f4SReid Kleckner #include "llvm/ADT/StringExtras.h"
132a826e40SRafael Espindola #include "llvm/Support/Errc.h"
1433d7b762SEugene Zelenko #include "llvm/Support/ErrorOr.h"
157039e358SDouglas Gregor #include "llvm/Support/FileSystem.h"
16d78273f4SReid Kleckner #include "llvm/Support/MemoryBuffer.h"
175cef3107SSergej Jaskiewicz #include "llvm/Support/Process.h"
1863aa8c5dSBen Langmuir #include "llvm/Support/Signals.h"
196bda14b3SChandler Carruth #include "llvm/Support/raw_ostream.h"
2033d7b762SEugene Zelenko #include <cerrno>
21a2086230SLadd Van Tol #include <chrono>
2233d7b762SEugene Zelenko #include <ctime>
2333d7b762SEugene Zelenko #include <memory>
24a2086230SLadd Van Tol #include <random>
257039e358SDouglas Gregor #include <sys/stat.h>
26ed0881b2SChandler Carruth #include <sys/types.h>
276bda14b3SChandler Carruth #include <system_error>
28a2086230SLadd Van Tol #include <thread>
296bda14b3SChandler Carruth #include <tuple>
30a2086230SLadd Van Tol
310dfbf6b6SSven van Haastregt #ifdef _WIN32
327039e358SDouglas Gregor #include <windows.h>
337039e358SDouglas Gregor #endif
347039e358SDouglas Gregor #if LLVM_ON_UNIX
357039e358SDouglas Gregor #include <unistd.h>
367039e358SDouglas Gregor #endif
37450461cbSBen Langmuir
38*e6126fabSLouis Dionne #if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ > 1050)
39450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 1
40450461cbSBen Langmuir #else
41450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 0
42450461cbSBen Langmuir #endif
43450461cbSBen Langmuir
44450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID
45450461cbSBen Langmuir #include <uuid/uuid.h>
46450461cbSBen Langmuir #endif
4733d7b762SEugene Zelenko
487039e358SDouglas Gregor using namespace llvm;
497039e358SDouglas Gregor
505f8f34e4SAdrian Prantl /// Attempt to read the lock file with the given name, if it exists.
517039e358SDouglas Gregor ///
527039e358SDouglas Gregor /// \param LockFileName The name of the lock file to read.
537039e358SDouglas Gregor ///
547039e358SDouglas Gregor /// \returns The process ID of the process that owns this lock file
557039e358SDouglas Gregor Optional<std::pair<std::string, int> >
readLockFile(StringRef LockFileName)567039e358SDouglas Gregor LockFileManager::readLockFile(StringRef LockFileName) {
577039e358SDouglas Gregor // Read the owning host and PID out of the lock file. If it appears that the
587039e358SDouglas Gregor // owning process is dead, the lock file is invalid.
59adf21f2aSRafael Espindola ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
60adf21f2aSRafael Espindola MemoryBuffer::getFile(LockFileName);
61adf21f2aSRafael Espindola if (!MBOrErr) {
6237575693SArgyrios Kyrtzidis sys::fs::remove(LockFileName);
637de8ea3dSReid Kleckner return None;
6437575693SArgyrios Kyrtzidis }
653f6481d0SRafael Espindola MemoryBuffer &MB = *MBOrErr.get();
667de8ea3dSReid Kleckner
67d78273f4SReid Kleckner StringRef Hostname;
68d78273f4SReid Kleckner StringRef PIDStr;
693f6481d0SRafael Espindola std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
707de8ea3dSReid Kleckner PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
71d78273f4SReid Kleckner int PID;
7244ec0a7dSArgyrios Kyrtzidis if (!PIDStr.getAsInteger(10, PID)) {
7344ec0a7dSArgyrios Kyrtzidis auto Owner = std::make_pair(std::string(Hostname), PID);
7444ec0a7dSArgyrios Kyrtzidis if (processStillExecuting(Owner.first, Owner.second))
7544ec0a7dSArgyrios Kyrtzidis return Owner;
7644ec0a7dSArgyrios Kyrtzidis }
777039e358SDouglas Gregor
787039e358SDouglas Gregor // Delete the lock file. It's invalid anyway.
79d78273f4SReid Kleckner sys::fs::remove(LockFileName);
80ef04593dSDavid Blaikie return None;
817039e358SDouglas Gregor }
827039e358SDouglas Gregor
getHostID(SmallVectorImpl<char> & HostID)83450461cbSBen Langmuir static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
84450461cbSBen Langmuir HostID.clear();
85450461cbSBen Langmuir
86450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID
87450461cbSBen Langmuir // On OS X, use the more stable hardware UUID instead of hostname.
88450461cbSBen Langmuir struct timespec wait = {1, 0}; // 1 second.
89450461cbSBen Langmuir uuid_t uuid;
90450461cbSBen Langmuir if (gethostuuid(uuid, &wait) != 0)
91450461cbSBen Langmuir return std::error_code(errno, std::system_category());
92450461cbSBen Langmuir
93450461cbSBen Langmuir uuid_string_t UUIDStr;
94450461cbSBen Langmuir uuid_unparse(uuid, UUIDStr);
95450461cbSBen Langmuir StringRef UUIDRef(UUIDStr);
96450461cbSBen Langmuir HostID.append(UUIDRef.begin(), UUIDRef.end());
97450461cbSBen Langmuir
98450461cbSBen Langmuir #elif LLVM_ON_UNIX
99450461cbSBen Langmuir char HostName[256];
100450461cbSBen Langmuir HostName[255] = 0;
101450461cbSBen Langmuir HostName[0] = 0;
102450461cbSBen Langmuir gethostname(HostName, 255);
103450461cbSBen Langmuir StringRef HostNameRef(HostName);
104450461cbSBen Langmuir HostID.append(HostNameRef.begin(), HostNameRef.end());
105450461cbSBen Langmuir
106450461cbSBen Langmuir #else
107450461cbSBen Langmuir StringRef Dummy("localhost");
108450461cbSBen Langmuir HostID.append(Dummy.begin(), Dummy.end());
109450461cbSBen Langmuir #endif
110450461cbSBen Langmuir
111450461cbSBen Langmuir return std::error_code();
112450461cbSBen Langmuir }
113450461cbSBen Langmuir
processStillExecuting(StringRef HostID,int PID)114450461cbSBen Langmuir bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
115c439a426SEvgeniy Stepanov #if LLVM_ON_UNIX && !defined(__ANDROID__)
116450461cbSBen Langmuir SmallString<256> StoredHostID;
117450461cbSBen Langmuir if (getHostID(StoredHostID))
118450461cbSBen Langmuir return true; // Conservatively assume it's executing on error.
119450461cbSBen Langmuir
1207039e358SDouglas Gregor // Check whether the process is dead. If so, we're done.
121450461cbSBen Langmuir if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
1227039e358SDouglas Gregor return false;
1237039e358SDouglas Gregor #endif
1247039e358SDouglas Gregor
1257039e358SDouglas Gregor return true;
1267039e358SDouglas Gregor }
1277039e358SDouglas Gregor
128881ba104SPeter Collingbourne namespace {
129881ba104SPeter Collingbourne
130881ba104SPeter Collingbourne /// An RAII helper object ensure that the unique lock file is removed.
131881ba104SPeter Collingbourne ///
132881ba104SPeter Collingbourne /// Ensures that if there is an error or a signal before we finish acquiring the
133881ba104SPeter Collingbourne /// lock, the unique file will be removed. And if we successfully take the lock,
134881ba104SPeter Collingbourne /// the signal handler is left in place so that signals while the lock is held
135881ba104SPeter Collingbourne /// will remove the unique lock file. The caller should ensure there is a
136881ba104SPeter Collingbourne /// matching call to sys::DontRemoveFileOnSignal when the lock is released.
137881ba104SPeter Collingbourne class RemoveUniqueLockFileOnSignal {
138881ba104SPeter Collingbourne StringRef Filename;
139881ba104SPeter Collingbourne bool RemoveImmediately;
140881ba104SPeter Collingbourne public:
RemoveUniqueLockFileOnSignal(StringRef Name)141881ba104SPeter Collingbourne RemoveUniqueLockFileOnSignal(StringRef Name)
142881ba104SPeter Collingbourne : Filename(Name), RemoveImmediately(true) {
143881ba104SPeter Collingbourne sys::RemoveFileOnSignal(Filename, nullptr);
144881ba104SPeter Collingbourne }
145881ba104SPeter Collingbourne
~RemoveUniqueLockFileOnSignal()146881ba104SPeter Collingbourne ~RemoveUniqueLockFileOnSignal() {
147881ba104SPeter Collingbourne if (!RemoveImmediately) {
148881ba104SPeter Collingbourne // Leave the signal handler enabled. It will be removed when the lock is
149881ba104SPeter Collingbourne // released.
150881ba104SPeter Collingbourne return;
151881ba104SPeter Collingbourne }
152881ba104SPeter Collingbourne sys::fs::remove(Filename);
153881ba104SPeter Collingbourne sys::DontRemoveFileOnSignal(Filename);
154881ba104SPeter Collingbourne }
155881ba104SPeter Collingbourne
lockAcquired()156881ba104SPeter Collingbourne void lockAcquired() { RemoveImmediately = false; }
157881ba104SPeter Collingbourne };
158881ba104SPeter Collingbourne
159881ba104SPeter Collingbourne } // end anonymous namespace
160881ba104SPeter Collingbourne
LockFileManager(StringRef FileName)1617039e358SDouglas Gregor LockFileManager::LockFileManager(StringRef FileName)
1627039e358SDouglas Gregor {
163056eafd4SDouglas Gregor this->FileName = FileName;
164db4ed0bdSRafael Espindola if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
16542b1f65fSBruno Cardoso Lopes std::string S("failed to obtain absolute path for ");
166adcd0268SBenjamin Kramer S.append(std::string(this->FileName.str()));
16742b1f65fSBruno Cardoso Lopes setError(EC, S);
168900e9a3dSArgyrios Kyrtzidis return;
169900e9a3dSArgyrios Kyrtzidis }
170900e9a3dSArgyrios Kyrtzidis LockFileName = this->FileName;
1717039e358SDouglas Gregor LockFileName += ".lock";
1727039e358SDouglas Gregor
1737039e358SDouglas Gregor // If the lock file already exists, don't bother to try to create our own
1747039e358SDouglas Gregor // lock file; it won't work anyway. Just figure out who owns this lock file.
1757039e358SDouglas Gregor if ((Owner = readLockFile(LockFileName)))
1767039e358SDouglas Gregor return;
1777039e358SDouglas Gregor
1787039e358SDouglas Gregor // Create a lock file that is unique to this instance.
179881ba104SPeter Collingbourne UniqueLockFileName = LockFileName;
180881ba104SPeter Collingbourne UniqueLockFileName += "-%%%%%%%%";
181881ba104SPeter Collingbourne int UniqueLockFileID;
182881ba104SPeter Collingbourne if (std::error_code EC = sys::fs::createUniqueFile(
183881ba104SPeter Collingbourne UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
184881ba104SPeter Collingbourne std::string S("failed to create unique file ");
185adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str()));
18642b1f65fSBruno Cardoso Lopes setError(EC, S);
1877039e358SDouglas Gregor return;
1887039e358SDouglas Gregor }
1897039e358SDouglas Gregor
1907039e358SDouglas Gregor // Write our process ID to our unique lock file.
1917039e358SDouglas Gregor {
192450461cbSBen Langmuir SmallString<256> HostID;
193450461cbSBen Langmuir if (auto EC = getHostID(HostID)) {
19442b1f65fSBruno Cardoso Lopes setError(EC, "failed to get host id");
195450461cbSBen Langmuir return;
196450461cbSBen Langmuir }
1975123eecdSBen Langmuir
198881ba104SPeter Collingbourne raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
1995cef3107SSergej Jaskiewicz Out << HostID << ' ' << sys::Process::getProcessId();
200881ba104SPeter Collingbourne Out.close();
2017039e358SDouglas Gregor
2027039e358SDouglas Gregor if (Out.has_error()) {
2039ce2d03eSBob Haarman // We failed to write out PID, so report the error, remove the
2047039e358SDouglas Gregor // unique lock file, and fail.
20542b1f65fSBruno Cardoso Lopes std::string S("failed to write to ");
206adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str()));
2079ce2d03eSBob Haarman setError(Out.error(), S);
208881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName);
2097039e358SDouglas Gregor return;
2107039e358SDouglas Gregor }
2117039e358SDouglas Gregor }
2127039e358SDouglas Gregor
213881ba104SPeter Collingbourne // Clean up the unique file on signal, which also releases the lock if it is
214881ba104SPeter Collingbourne // held since the .lock symlink will point to a nonexistent file.
215881ba104SPeter Collingbourne RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
216881ba104SPeter Collingbourne
21733d7b762SEugene Zelenko while (true) {
21883f858e5SRafael Espindola // Create a link from the lock file name. If this succeeds, we're done.
219db4ed0bdSRafael Espindola std::error_code EC =
220881ba104SPeter Collingbourne sys::fs::create_link(UniqueLockFileName, LockFileName);
22163aa8c5dSBen Langmuir if (!EC) {
222881ba104SPeter Collingbourne RemoveUniqueFile.lockAcquired();
2237039e358SDouglas Gregor return;
22463aa8c5dSBen Langmuir }
2257039e358SDouglas Gregor
2262a826e40SRafael Espindola if (EC != errc::file_exists) {
22742b1f65fSBruno Cardoso Lopes std::string S("failed to create link ");
22842b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(S);
229881ba104SPeter Collingbourne OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
23042b1f65fSBruno Cardoso Lopes setError(EC, OSS.str());
2314147978cSArgyrios Kyrtzidis return;
2324147978cSArgyrios Kyrtzidis }
2334147978cSArgyrios Kyrtzidis
2344147978cSArgyrios Kyrtzidis // Someone else managed to create the lock file first. Read the process ID
2354147978cSArgyrios Kyrtzidis // from the lock file.
236881ba104SPeter Collingbourne if ((Owner = readLockFile(LockFileName))) {
237881ba104SPeter Collingbourne // Wipe out our unique lock file (it's useless now)
238881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName);
239881ba104SPeter Collingbourne return;
240881ba104SPeter Collingbourne }
2414147978cSArgyrios Kyrtzidis
24292e1b62dSYaron Keren if (!sys::fs::exists(LockFileName)) {
2434147978cSArgyrios Kyrtzidis // The previous owner released the lock file before we could read it.
2444147978cSArgyrios Kyrtzidis // Try to get ownership again.
2454147978cSArgyrios Kyrtzidis continue;
2464147978cSArgyrios Kyrtzidis }
2474147978cSArgyrios Kyrtzidis
2484147978cSArgyrios Kyrtzidis // There is a lock file that nobody owns; try to clean it up and get
2494147978cSArgyrios Kyrtzidis // ownership.
25092e1b62dSYaron Keren if ((EC = sys::fs::remove(LockFileName))) {
25142b1f65fSBruno Cardoso Lopes std::string S("failed to remove lockfile ");
252adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str()));
25342b1f65fSBruno Cardoso Lopes setError(EC, S);
2544147978cSArgyrios Kyrtzidis return;
2554147978cSArgyrios Kyrtzidis }
2564147978cSArgyrios Kyrtzidis }
2577039e358SDouglas Gregor }
2587039e358SDouglas Gregor
getState() const2597039e358SDouglas Gregor LockFileManager::LockFileState LockFileManager::getState() const {
2607039e358SDouglas Gregor if (Owner)
2617039e358SDouglas Gregor return LFS_Shared;
2627039e358SDouglas Gregor
2638c42d323SRafael Espindola if (ErrorCode)
2647039e358SDouglas Gregor return LFS_Error;
2657039e358SDouglas Gregor
2667039e358SDouglas Gregor return LFS_Owned;
2677039e358SDouglas Gregor }
2687039e358SDouglas Gregor
getErrorMessage() const26942b1f65fSBruno Cardoso Lopes std::string LockFileManager::getErrorMessage() const {
2708c42d323SRafael Espindola if (ErrorCode) {
27142b1f65fSBruno Cardoso Lopes std::string Str(ErrorDiagMsg);
2728c42d323SRafael Espindola std::string ErrCodeMsg = ErrorCode.message();
27342b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(Str);
27442b1f65fSBruno Cardoso Lopes if (!ErrCodeMsg.empty())
275c8434103SRafael Espindola OSS << ": " << ErrCodeMsg;
276c8434103SRafael Espindola return OSS.str();
27742b1f65fSBruno Cardoso Lopes }
27842b1f65fSBruno Cardoso Lopes return "";
27942b1f65fSBruno Cardoso Lopes }
28042b1f65fSBruno Cardoso Lopes
~LockFileManager()2817039e358SDouglas Gregor LockFileManager::~LockFileManager() {
2827039e358SDouglas Gregor if (getState() != LFS_Owned)
2837039e358SDouglas Gregor return;
2847039e358SDouglas Gregor
2857039e358SDouglas Gregor // Since we own the lock, remove the lock file and our own unique lock file.
28692e1b62dSYaron Keren sys::fs::remove(LockFileName);
287881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName);
288881ba104SPeter Collingbourne // The unique file is now gone, so remove it from the signal handler. This
289881ba104SPeter Collingbourne // matches a sys::RemoveFileOnSignal() in LockFileManager().
290881ba104SPeter Collingbourne sys::DontRemoveFileOnSignal(UniqueLockFileName);
2917039e358SDouglas Gregor }
2927039e358SDouglas Gregor
293e05e2199SVedant Kumar LockFileManager::WaitForUnlockResult
waitForUnlock(const unsigned MaxSeconds)294e05e2199SVedant Kumar LockFileManager::waitForUnlock(const unsigned MaxSeconds) {
2957039e358SDouglas Gregor if (getState() != LFS_Shared)
29644ec0a7dSArgyrios Kyrtzidis return Res_Success;
2977039e358SDouglas Gregor
298a2086230SLadd Van Tol // Since we don't yet have an event-based method to wait for the lock file,
299a2086230SLadd Van Tol // implement randomized exponential backoff, similar to Ethernet collision
300a2086230SLadd Van Tol // algorithm. This improves performance on machines with high core counts
301a2086230SLadd Van Tol // when the file lock is heavily contended by multiple clang processes
302a2086230SLadd Van Tol const unsigned long MinWaitDurationMS = 10;
303a2086230SLadd Van Tol const unsigned long MaxWaitMultiplier = 50; // 500ms max wait
304a2086230SLadd Van Tol unsigned long WaitMultiplier = 1;
305a2086230SLadd Van Tol unsigned long ElapsedTimeSeconds = 0;
306a2086230SLadd Van Tol
307a2086230SLadd Van Tol std::random_device Device;
308a2086230SLadd Van Tol std::default_random_engine Engine(Device());
309a2086230SLadd Van Tol
310a2086230SLadd Van Tol auto StartTime = std::chrono::steady_clock::now();
311a2086230SLadd Van Tol
3127039e358SDouglas Gregor do {
313a2086230SLadd Van Tol // FIXME: implement event-based waiting
314a2086230SLadd Van Tol
3157039e358SDouglas Gregor // Sleep for the designated interval, to allow the owning process time to
3167039e358SDouglas Gregor // finish up and remove the lock file.
317a2086230SLadd Van Tol std::uniform_int_distribution<unsigned long> Distribution(1,
318a2086230SLadd Van Tol WaitMultiplier);
319a2086230SLadd Van Tol unsigned long WaitDurationMS = MinWaitDurationMS * Distribution(Engine);
320a2086230SLadd Van Tol std::this_thread::sleep_for(std::chrono::milliseconds(WaitDurationMS));
3210cb68460SDouglas Gregor
322281f23adSRafael Espindola if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
323281f23adSRafael Espindola errc::no_such_file_or_directory) {
32408970917SBen Langmuir // If the original file wasn't created, somone thought the lock was dead.
32592e1b62dSYaron Keren if (!sys::fs::exists(FileName))
32608970917SBen Langmuir return Res_OwnerDied;
32744ec0a7dSArgyrios Kyrtzidis return Res_Success;
328056eafd4SDouglas Gregor }
3297039e358SDouglas Gregor
33008970917SBen Langmuir // If the process owning the lock died without cleaning up, just bail out.
33108970917SBen Langmuir if (!processStillExecuting((*Owner).first, (*Owner).second))
33244ec0a7dSArgyrios Kyrtzidis return Res_OwnerDied;
3337039e358SDouglas Gregor
334a2086230SLadd Van Tol WaitMultiplier *= 2;
335a2086230SLadd Van Tol if (WaitMultiplier > MaxWaitMultiplier) {
336a2086230SLadd Van Tol WaitMultiplier = MaxWaitMultiplier;
3377039e358SDouglas Gregor }
338a2086230SLadd Van Tol
339a2086230SLadd Van Tol ElapsedTimeSeconds = std::chrono::duration_cast<std::chrono::seconds>(
340a2086230SLadd Van Tol std::chrono::steady_clock::now() - StartTime)
341a2086230SLadd Van Tol .count();
342a2086230SLadd Van Tol
343a2086230SLadd Van Tol } while (ElapsedTimeSeconds < MaxSeconds);
3447039e358SDouglas Gregor
3457039e358SDouglas Gregor // Give up.
34644ec0a7dSArgyrios Kyrtzidis return Res_Timeout;
3477039e358SDouglas Gregor }
348d2d52de2SBen Langmuir
unsafeRemoveLockFile()349d2d52de2SBen Langmuir std::error_code LockFileManager::unsafeRemoveLockFile() {
35092e1b62dSYaron Keren return sys::fs::remove(LockFileName);
351d2d52de2SBen Langmuir }
352