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" 1763aa8c5dSBen Langmuir #include "llvm/Support/Signals.h" 186bda14b3SChandler Carruth #include "llvm/Support/raw_ostream.h" 1933d7b762SEugene Zelenko #include <cerrno> 20*a2086230SLadd Van Tol #include <chrono> 2133d7b762SEugene Zelenko #include <ctime> 2233d7b762SEugene Zelenko #include <memory> 23*a2086230SLadd Van Tol #include <random> 247039e358SDouglas Gregor #include <sys/stat.h> 25ed0881b2SChandler Carruth #include <sys/types.h> 266bda14b3SChandler Carruth #include <system_error> 27*a2086230SLadd Van Tol #include <thread> 286bda14b3SChandler Carruth #include <tuple> 29*a2086230SLadd Van Tol 300dfbf6b6SSven van Haastregt #ifdef _WIN32 317039e358SDouglas Gregor #include <windows.h> 327039e358SDouglas Gregor #endif 337039e358SDouglas Gregor #if LLVM_ON_UNIX 347039e358SDouglas Gregor #include <unistd.h> 357039e358SDouglas Gregor #endif 36450461cbSBen Langmuir 37450461cbSBen Langmuir #if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) 38450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 1 39450461cbSBen Langmuir #else 40450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 0 41450461cbSBen Langmuir #endif 42450461cbSBen Langmuir 43450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID 44450461cbSBen Langmuir #include <uuid/uuid.h> 45450461cbSBen Langmuir #endif 4633d7b762SEugene Zelenko 477039e358SDouglas Gregor using namespace llvm; 487039e358SDouglas Gregor 495f8f34e4SAdrian Prantl /// Attempt to read the lock file with the given name, if it exists. 507039e358SDouglas Gregor /// 517039e358SDouglas Gregor /// \param LockFileName The name of the lock file to read. 527039e358SDouglas Gregor /// 537039e358SDouglas Gregor /// \returns The process ID of the process that owns this lock file 547039e358SDouglas Gregor Optional<std::pair<std::string, int> > 557039e358SDouglas Gregor LockFileManager::readLockFile(StringRef LockFileName) { 567039e358SDouglas Gregor // Read the owning host and PID out of the lock file. If it appears that the 577039e358SDouglas Gregor // owning process is dead, the lock file is invalid. 58adf21f2aSRafael Espindola ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 59adf21f2aSRafael Espindola MemoryBuffer::getFile(LockFileName); 60adf21f2aSRafael Espindola if (!MBOrErr) { 6137575693SArgyrios Kyrtzidis sys::fs::remove(LockFileName); 627de8ea3dSReid Kleckner return None; 6337575693SArgyrios Kyrtzidis } 643f6481d0SRafael Espindola MemoryBuffer &MB = *MBOrErr.get(); 657de8ea3dSReid Kleckner 66d78273f4SReid Kleckner StringRef Hostname; 67d78273f4SReid Kleckner StringRef PIDStr; 683f6481d0SRafael Espindola std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " "); 697de8ea3dSReid Kleckner PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" ")); 70d78273f4SReid Kleckner int PID; 7144ec0a7dSArgyrios Kyrtzidis if (!PIDStr.getAsInteger(10, PID)) { 7244ec0a7dSArgyrios Kyrtzidis auto Owner = std::make_pair(std::string(Hostname), PID); 7344ec0a7dSArgyrios Kyrtzidis if (processStillExecuting(Owner.first, Owner.second)) 7444ec0a7dSArgyrios Kyrtzidis return Owner; 7544ec0a7dSArgyrios Kyrtzidis } 767039e358SDouglas Gregor 777039e358SDouglas Gregor // Delete the lock file. It's invalid anyway. 78d78273f4SReid Kleckner sys::fs::remove(LockFileName); 79ef04593dSDavid Blaikie return None; 807039e358SDouglas Gregor } 817039e358SDouglas Gregor 82450461cbSBen Langmuir static std::error_code getHostID(SmallVectorImpl<char> &HostID) { 83450461cbSBen Langmuir HostID.clear(); 84450461cbSBen Langmuir 85450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID 86450461cbSBen Langmuir // On OS X, use the more stable hardware UUID instead of hostname. 87450461cbSBen Langmuir struct timespec wait = {1, 0}; // 1 second. 88450461cbSBen Langmuir uuid_t uuid; 89450461cbSBen Langmuir if (gethostuuid(uuid, &wait) != 0) 90450461cbSBen Langmuir return std::error_code(errno, std::system_category()); 91450461cbSBen Langmuir 92450461cbSBen Langmuir uuid_string_t UUIDStr; 93450461cbSBen Langmuir uuid_unparse(uuid, UUIDStr); 94450461cbSBen Langmuir StringRef UUIDRef(UUIDStr); 95450461cbSBen Langmuir HostID.append(UUIDRef.begin(), UUIDRef.end()); 96450461cbSBen Langmuir 97450461cbSBen Langmuir #elif LLVM_ON_UNIX 98450461cbSBen Langmuir char HostName[256]; 99450461cbSBen Langmuir HostName[255] = 0; 100450461cbSBen Langmuir HostName[0] = 0; 101450461cbSBen Langmuir gethostname(HostName, 255); 102450461cbSBen Langmuir StringRef HostNameRef(HostName); 103450461cbSBen Langmuir HostID.append(HostNameRef.begin(), HostNameRef.end()); 104450461cbSBen Langmuir 105450461cbSBen Langmuir #else 106450461cbSBen Langmuir StringRef Dummy("localhost"); 107450461cbSBen Langmuir HostID.append(Dummy.begin(), Dummy.end()); 108450461cbSBen Langmuir #endif 109450461cbSBen Langmuir 110450461cbSBen Langmuir return std::error_code(); 111450461cbSBen Langmuir } 112450461cbSBen Langmuir 113450461cbSBen Langmuir bool LockFileManager::processStillExecuting(StringRef HostID, int PID) { 114c439a426SEvgeniy Stepanov #if LLVM_ON_UNIX && !defined(__ANDROID__) 115450461cbSBen Langmuir SmallString<256> StoredHostID; 116450461cbSBen Langmuir if (getHostID(StoredHostID)) 117450461cbSBen Langmuir return true; // Conservatively assume it's executing on error. 118450461cbSBen Langmuir 1197039e358SDouglas Gregor // Check whether the process is dead. If so, we're done. 120450461cbSBen Langmuir if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH) 1217039e358SDouglas Gregor return false; 1227039e358SDouglas Gregor #endif 1237039e358SDouglas Gregor 1247039e358SDouglas Gregor return true; 1257039e358SDouglas Gregor } 1267039e358SDouglas Gregor 127881ba104SPeter Collingbourne namespace { 128881ba104SPeter Collingbourne 129881ba104SPeter Collingbourne /// An RAII helper object ensure that the unique lock file is removed. 130881ba104SPeter Collingbourne /// 131881ba104SPeter Collingbourne /// Ensures that if there is an error or a signal before we finish acquiring the 132881ba104SPeter Collingbourne /// lock, the unique file will be removed. And if we successfully take the lock, 133881ba104SPeter Collingbourne /// the signal handler is left in place so that signals while the lock is held 134881ba104SPeter Collingbourne /// will remove the unique lock file. The caller should ensure there is a 135881ba104SPeter Collingbourne /// matching call to sys::DontRemoveFileOnSignal when the lock is released. 136881ba104SPeter Collingbourne class RemoveUniqueLockFileOnSignal { 137881ba104SPeter Collingbourne StringRef Filename; 138881ba104SPeter Collingbourne bool RemoveImmediately; 139881ba104SPeter Collingbourne public: 140881ba104SPeter Collingbourne RemoveUniqueLockFileOnSignal(StringRef Name) 141881ba104SPeter Collingbourne : Filename(Name), RemoveImmediately(true) { 142881ba104SPeter Collingbourne sys::RemoveFileOnSignal(Filename, nullptr); 143881ba104SPeter Collingbourne } 144881ba104SPeter Collingbourne 145881ba104SPeter Collingbourne ~RemoveUniqueLockFileOnSignal() { 146881ba104SPeter Collingbourne if (!RemoveImmediately) { 147881ba104SPeter Collingbourne // Leave the signal handler enabled. It will be removed when the lock is 148881ba104SPeter Collingbourne // released. 149881ba104SPeter Collingbourne return; 150881ba104SPeter Collingbourne } 151881ba104SPeter Collingbourne sys::fs::remove(Filename); 152881ba104SPeter Collingbourne sys::DontRemoveFileOnSignal(Filename); 153881ba104SPeter Collingbourne } 154881ba104SPeter Collingbourne 155881ba104SPeter Collingbourne void lockAcquired() { RemoveImmediately = false; } 156881ba104SPeter Collingbourne }; 157881ba104SPeter Collingbourne 158881ba104SPeter Collingbourne } // end anonymous namespace 159881ba104SPeter Collingbourne 1607039e358SDouglas Gregor LockFileManager::LockFileManager(StringRef FileName) 1617039e358SDouglas Gregor { 162056eafd4SDouglas Gregor this->FileName = FileName; 163db4ed0bdSRafael Espindola if (std::error_code EC = sys::fs::make_absolute(this->FileName)) { 16442b1f65fSBruno Cardoso Lopes std::string S("failed to obtain absolute path for "); 165adcd0268SBenjamin Kramer S.append(std::string(this->FileName.str())); 16642b1f65fSBruno Cardoso Lopes setError(EC, S); 167900e9a3dSArgyrios Kyrtzidis return; 168900e9a3dSArgyrios Kyrtzidis } 169900e9a3dSArgyrios Kyrtzidis LockFileName = this->FileName; 1707039e358SDouglas Gregor LockFileName += ".lock"; 1717039e358SDouglas Gregor 1727039e358SDouglas Gregor // If the lock file already exists, don't bother to try to create our own 1737039e358SDouglas Gregor // lock file; it won't work anyway. Just figure out who owns this lock file. 1747039e358SDouglas Gregor if ((Owner = readLockFile(LockFileName))) 1757039e358SDouglas Gregor return; 1767039e358SDouglas Gregor 1777039e358SDouglas Gregor // Create a lock file that is unique to this instance. 178881ba104SPeter Collingbourne UniqueLockFileName = LockFileName; 179881ba104SPeter Collingbourne UniqueLockFileName += "-%%%%%%%%"; 180881ba104SPeter Collingbourne int UniqueLockFileID; 181881ba104SPeter Collingbourne if (std::error_code EC = sys::fs::createUniqueFile( 182881ba104SPeter Collingbourne UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) { 183881ba104SPeter Collingbourne std::string S("failed to create unique file "); 184adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str())); 18542b1f65fSBruno Cardoso Lopes setError(EC, S); 1867039e358SDouglas Gregor return; 1877039e358SDouglas Gregor } 1887039e358SDouglas Gregor 1897039e358SDouglas Gregor // Write our process ID to our unique lock file. 1907039e358SDouglas Gregor { 191450461cbSBen Langmuir SmallString<256> HostID; 192450461cbSBen Langmuir if (auto EC = getHostID(HostID)) { 19342b1f65fSBruno Cardoso Lopes setError(EC, "failed to get host id"); 194450461cbSBen Langmuir return; 195450461cbSBen Langmuir } 1965123eecdSBen Langmuir 197881ba104SPeter Collingbourne raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true); 198450461cbSBen Langmuir Out << HostID << ' '; 1997039e358SDouglas Gregor #if LLVM_ON_UNIX 200450461cbSBen Langmuir Out << getpid(); 2017039e358SDouglas Gregor #else 202450461cbSBen Langmuir Out << "1"; 2037039e358SDouglas Gregor #endif 204881ba104SPeter Collingbourne Out.close(); 2057039e358SDouglas Gregor 2067039e358SDouglas Gregor if (Out.has_error()) { 2079ce2d03eSBob Haarman // We failed to write out PID, so report the error, remove the 2087039e358SDouglas Gregor // unique lock file, and fail. 20942b1f65fSBruno Cardoso Lopes std::string S("failed to write to "); 210adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str())); 2119ce2d03eSBob Haarman setError(Out.error(), S); 212881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName); 2137039e358SDouglas Gregor return; 2147039e358SDouglas Gregor } 2157039e358SDouglas Gregor } 2167039e358SDouglas Gregor 217881ba104SPeter Collingbourne // Clean up the unique file on signal, which also releases the lock if it is 218881ba104SPeter Collingbourne // held since the .lock symlink will point to a nonexistent file. 219881ba104SPeter Collingbourne RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName); 220881ba104SPeter Collingbourne 22133d7b762SEugene Zelenko while (true) { 22283f858e5SRafael Espindola // Create a link from the lock file name. If this succeeds, we're done. 223db4ed0bdSRafael Espindola std::error_code EC = 224881ba104SPeter Collingbourne sys::fs::create_link(UniqueLockFileName, LockFileName); 22563aa8c5dSBen Langmuir if (!EC) { 226881ba104SPeter Collingbourne RemoveUniqueFile.lockAcquired(); 2277039e358SDouglas Gregor return; 22863aa8c5dSBen Langmuir } 2297039e358SDouglas Gregor 2302a826e40SRafael Espindola if (EC != errc::file_exists) { 23142b1f65fSBruno Cardoso Lopes std::string S("failed to create link "); 23242b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(S); 233881ba104SPeter Collingbourne OSS << LockFileName.str() << " to " << UniqueLockFileName.str(); 23442b1f65fSBruno Cardoso Lopes setError(EC, OSS.str()); 2354147978cSArgyrios Kyrtzidis return; 2364147978cSArgyrios Kyrtzidis } 2374147978cSArgyrios Kyrtzidis 2384147978cSArgyrios Kyrtzidis // Someone else managed to create the lock file first. Read the process ID 2394147978cSArgyrios Kyrtzidis // from the lock file. 240881ba104SPeter Collingbourne if ((Owner = readLockFile(LockFileName))) { 241881ba104SPeter Collingbourne // Wipe out our unique lock file (it's useless now) 242881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName); 243881ba104SPeter Collingbourne return; 244881ba104SPeter Collingbourne } 2454147978cSArgyrios Kyrtzidis 24692e1b62dSYaron Keren if (!sys::fs::exists(LockFileName)) { 2474147978cSArgyrios Kyrtzidis // The previous owner released the lock file before we could read it. 2484147978cSArgyrios Kyrtzidis // Try to get ownership again. 2494147978cSArgyrios Kyrtzidis continue; 2504147978cSArgyrios Kyrtzidis } 2514147978cSArgyrios Kyrtzidis 2524147978cSArgyrios Kyrtzidis // There is a lock file that nobody owns; try to clean it up and get 2534147978cSArgyrios Kyrtzidis // ownership. 25492e1b62dSYaron Keren if ((EC = sys::fs::remove(LockFileName))) { 25542b1f65fSBruno Cardoso Lopes std::string S("failed to remove lockfile "); 256adcd0268SBenjamin Kramer S.append(std::string(UniqueLockFileName.str())); 25742b1f65fSBruno Cardoso Lopes setError(EC, S); 2584147978cSArgyrios Kyrtzidis return; 2594147978cSArgyrios Kyrtzidis } 2604147978cSArgyrios Kyrtzidis } 2617039e358SDouglas Gregor } 2627039e358SDouglas Gregor 2637039e358SDouglas Gregor LockFileManager::LockFileState LockFileManager::getState() const { 2647039e358SDouglas Gregor if (Owner) 2657039e358SDouglas Gregor return LFS_Shared; 2667039e358SDouglas Gregor 2678c42d323SRafael Espindola if (ErrorCode) 2687039e358SDouglas Gregor return LFS_Error; 2697039e358SDouglas Gregor 2707039e358SDouglas Gregor return LFS_Owned; 2717039e358SDouglas Gregor } 2727039e358SDouglas Gregor 27342b1f65fSBruno Cardoso Lopes std::string LockFileManager::getErrorMessage() const { 2748c42d323SRafael Espindola if (ErrorCode) { 27542b1f65fSBruno Cardoso Lopes std::string Str(ErrorDiagMsg); 2768c42d323SRafael Espindola std::string ErrCodeMsg = ErrorCode.message(); 27742b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(Str); 27842b1f65fSBruno Cardoso Lopes if (!ErrCodeMsg.empty()) 279c8434103SRafael Espindola OSS << ": " << ErrCodeMsg; 280c8434103SRafael Espindola return OSS.str(); 28142b1f65fSBruno Cardoso Lopes } 28242b1f65fSBruno Cardoso Lopes return ""; 28342b1f65fSBruno Cardoso Lopes } 28442b1f65fSBruno Cardoso Lopes 2857039e358SDouglas Gregor LockFileManager::~LockFileManager() { 2867039e358SDouglas Gregor if (getState() != LFS_Owned) 2877039e358SDouglas Gregor return; 2887039e358SDouglas Gregor 2897039e358SDouglas Gregor // Since we own the lock, remove the lock file and our own unique lock file. 29092e1b62dSYaron Keren sys::fs::remove(LockFileName); 291881ba104SPeter Collingbourne sys::fs::remove(UniqueLockFileName); 292881ba104SPeter Collingbourne // The unique file is now gone, so remove it from the signal handler. This 293881ba104SPeter Collingbourne // matches a sys::RemoveFileOnSignal() in LockFileManager(). 294881ba104SPeter Collingbourne sys::DontRemoveFileOnSignal(UniqueLockFileName); 2957039e358SDouglas Gregor } 2967039e358SDouglas Gregor 297e05e2199SVedant Kumar LockFileManager::WaitForUnlockResult 298e05e2199SVedant Kumar LockFileManager::waitForUnlock(const unsigned MaxSeconds) { 2997039e358SDouglas Gregor if (getState() != LFS_Shared) 30044ec0a7dSArgyrios Kyrtzidis return Res_Success; 3017039e358SDouglas Gregor 302*a2086230SLadd Van Tol // Since we don't yet have an event-based method to wait for the lock file, 303*a2086230SLadd Van Tol // implement randomized exponential backoff, similar to Ethernet collision 304*a2086230SLadd Van Tol // algorithm. This improves performance on machines with high core counts 305*a2086230SLadd Van Tol // when the file lock is heavily contended by multiple clang processes 306*a2086230SLadd Van Tol const unsigned long MinWaitDurationMS = 10; 307*a2086230SLadd Van Tol const unsigned long MaxWaitMultiplier = 50; // 500ms max wait 308*a2086230SLadd Van Tol unsigned long WaitMultiplier = 1; 309*a2086230SLadd Van Tol unsigned long ElapsedTimeSeconds = 0; 310*a2086230SLadd Van Tol 311*a2086230SLadd Van Tol std::random_device Device; 312*a2086230SLadd Van Tol std::default_random_engine Engine(Device()); 313*a2086230SLadd Van Tol 314*a2086230SLadd Van Tol auto StartTime = std::chrono::steady_clock::now(); 315*a2086230SLadd Van Tol 3167039e358SDouglas Gregor do { 317*a2086230SLadd Van Tol // FIXME: implement event-based waiting 318*a2086230SLadd Van Tol 3197039e358SDouglas Gregor // Sleep for the designated interval, to allow the owning process time to 3207039e358SDouglas Gregor // finish up and remove the lock file. 321*a2086230SLadd Van Tol std::uniform_int_distribution<unsigned long> Distribution(1, 322*a2086230SLadd Van Tol WaitMultiplier); 323*a2086230SLadd Van Tol unsigned long WaitDurationMS = MinWaitDurationMS * Distribution(Engine); 324*a2086230SLadd Van Tol std::this_thread::sleep_for(std::chrono::milliseconds(WaitDurationMS)); 3250cb68460SDouglas Gregor 326281f23adSRafael Espindola if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) == 327281f23adSRafael Espindola errc::no_such_file_or_directory) { 32808970917SBen Langmuir // If the original file wasn't created, somone thought the lock was dead. 32992e1b62dSYaron Keren if (!sys::fs::exists(FileName)) 33008970917SBen Langmuir return Res_OwnerDied; 33144ec0a7dSArgyrios Kyrtzidis return Res_Success; 332056eafd4SDouglas Gregor } 3337039e358SDouglas Gregor 33408970917SBen Langmuir // If the process owning the lock died without cleaning up, just bail out. 33508970917SBen Langmuir if (!processStillExecuting((*Owner).first, (*Owner).second)) 33644ec0a7dSArgyrios Kyrtzidis return Res_OwnerDied; 3377039e358SDouglas Gregor 338*a2086230SLadd Van Tol WaitMultiplier *= 2; 339*a2086230SLadd Van Tol if (WaitMultiplier > MaxWaitMultiplier) { 340*a2086230SLadd Van Tol WaitMultiplier = MaxWaitMultiplier; 3417039e358SDouglas Gregor } 342*a2086230SLadd Van Tol 343*a2086230SLadd Van Tol ElapsedTimeSeconds = std::chrono::duration_cast<std::chrono::seconds>( 344*a2086230SLadd Van Tol std::chrono::steady_clock::now() - StartTime) 345*a2086230SLadd Van Tol .count(); 346*a2086230SLadd Van Tol 347*a2086230SLadd Van Tol } while (ElapsedTimeSeconds < MaxSeconds); 3487039e358SDouglas Gregor 3497039e358SDouglas Gregor // Give up. 35044ec0a7dSArgyrios Kyrtzidis return Res_Timeout; 3517039e358SDouglas Gregor } 352d2d52de2SBen Langmuir 353d2d52de2SBen Langmuir std::error_code LockFileManager::unsafeRemoveLockFile() { 35492e1b62dSYaron Keren return sys::fs::remove(LockFileName); 355d2d52de2SBen Langmuir } 356