17039e358SDouglas Gregor //===--- LockFileManager.cpp - File-level Locking Utility------------------===// 27039e358SDouglas Gregor // 37039e358SDouglas Gregor // The LLVM Compiler Infrastructure 47039e358SDouglas Gregor // 57039e358SDouglas Gregor // This file is distributed under the University of Illinois Open Source 67039e358SDouglas Gregor // License. See LICENSE.TXT for details. 77039e358SDouglas Gregor // 87039e358SDouglas Gregor //===----------------------------------------------------------------------===// 933d7b762SEugene Zelenko 107039e358SDouglas Gregor #include "llvm/Support/LockFileManager.h" 1133d7b762SEugene Zelenko #include "llvm/ADT/None.h" 1233d7b762SEugene Zelenko #include "llvm/ADT/SmallVector.h" 13d78273f4SReid Kleckner #include "llvm/ADT/StringExtras.h" 142a826e40SRafael Espindola #include "llvm/Support/Errc.h" 1533d7b762SEugene Zelenko #include "llvm/Support/ErrorOr.h" 167039e358SDouglas Gregor #include "llvm/Support/FileSystem.h" 17d78273f4SReid Kleckner #include "llvm/Support/MemoryBuffer.h" 1863aa8c5dSBen Langmuir #include "llvm/Support/Signals.h" 196bda14b3SChandler Carruth #include "llvm/Support/raw_ostream.h" 2033d7b762SEugene Zelenko #include <cerrno> 2133d7b762SEugene Zelenko #include <ctime> 2233d7b762SEugene Zelenko #include <memory> 237039e358SDouglas Gregor #include <sys/stat.h> 24ed0881b2SChandler Carruth #include <sys/types.h> 256bda14b3SChandler Carruth #include <system_error> 266bda14b3SChandler Carruth #include <tuple> 277039e358SDouglas Gregor #if LLVM_ON_WIN32 287039e358SDouglas Gregor #include <windows.h> 297039e358SDouglas Gregor #endif 307039e358SDouglas Gregor #if LLVM_ON_UNIX 317039e358SDouglas Gregor #include <unistd.h> 327039e358SDouglas Gregor #endif 33450461cbSBen Langmuir 34450461cbSBen Langmuir #if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) 35450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 1 36450461cbSBen Langmuir #else 37450461cbSBen Langmuir #define USE_OSX_GETHOSTUUID 0 38450461cbSBen Langmuir #endif 39450461cbSBen Langmuir 40450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID 41450461cbSBen Langmuir #include <uuid/uuid.h> 42450461cbSBen Langmuir #endif 4333d7b762SEugene Zelenko 447039e358SDouglas Gregor using namespace llvm; 457039e358SDouglas Gregor 467039e358SDouglas Gregor /// \brief Attempt to read the lock file with the given name, if it exists. 477039e358SDouglas Gregor /// 487039e358SDouglas Gregor /// \param LockFileName The name of the lock file to read. 497039e358SDouglas Gregor /// 507039e358SDouglas Gregor /// \returns The process ID of the process that owns this lock file 517039e358SDouglas Gregor Optional<std::pair<std::string, int> > 527039e358SDouglas Gregor LockFileManager::readLockFile(StringRef LockFileName) { 537039e358SDouglas Gregor // Read the owning host and PID out of the lock file. If it appears that the 547039e358SDouglas Gregor // owning process is dead, the lock file is invalid. 55adf21f2aSRafael Espindola ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 56adf21f2aSRafael Espindola MemoryBuffer::getFile(LockFileName); 57adf21f2aSRafael Espindola if (!MBOrErr) { 5837575693SArgyrios Kyrtzidis sys::fs::remove(LockFileName); 597de8ea3dSReid Kleckner return None; 6037575693SArgyrios Kyrtzidis } 613f6481d0SRafael Espindola MemoryBuffer &MB = *MBOrErr.get(); 627de8ea3dSReid Kleckner 63d78273f4SReid Kleckner StringRef Hostname; 64d78273f4SReid Kleckner StringRef PIDStr; 653f6481d0SRafael Espindola std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " "); 667de8ea3dSReid Kleckner PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" ")); 67d78273f4SReid Kleckner int PID; 6844ec0a7dSArgyrios Kyrtzidis if (!PIDStr.getAsInteger(10, PID)) { 6944ec0a7dSArgyrios Kyrtzidis auto Owner = std::make_pair(std::string(Hostname), PID); 7044ec0a7dSArgyrios Kyrtzidis if (processStillExecuting(Owner.first, Owner.second)) 7144ec0a7dSArgyrios Kyrtzidis return Owner; 7244ec0a7dSArgyrios Kyrtzidis } 737039e358SDouglas Gregor 747039e358SDouglas Gregor // Delete the lock file. It's invalid anyway. 75d78273f4SReid Kleckner sys::fs::remove(LockFileName); 76ef04593dSDavid Blaikie return None; 777039e358SDouglas Gregor } 787039e358SDouglas Gregor 79450461cbSBen Langmuir static std::error_code getHostID(SmallVectorImpl<char> &HostID) { 80450461cbSBen Langmuir HostID.clear(); 81450461cbSBen Langmuir 82450461cbSBen Langmuir #if USE_OSX_GETHOSTUUID 83450461cbSBen Langmuir // On OS X, use the more stable hardware UUID instead of hostname. 84450461cbSBen Langmuir struct timespec wait = {1, 0}; // 1 second. 85450461cbSBen Langmuir uuid_t uuid; 86450461cbSBen Langmuir if (gethostuuid(uuid, &wait) != 0) 87450461cbSBen Langmuir return std::error_code(errno, std::system_category()); 88450461cbSBen Langmuir 89450461cbSBen Langmuir uuid_string_t UUIDStr; 90450461cbSBen Langmuir uuid_unparse(uuid, UUIDStr); 91450461cbSBen Langmuir StringRef UUIDRef(UUIDStr); 92450461cbSBen Langmuir HostID.append(UUIDRef.begin(), UUIDRef.end()); 93450461cbSBen Langmuir 94450461cbSBen Langmuir #elif LLVM_ON_UNIX 95450461cbSBen Langmuir char HostName[256]; 96450461cbSBen Langmuir HostName[255] = 0; 97450461cbSBen Langmuir HostName[0] = 0; 98450461cbSBen Langmuir gethostname(HostName, 255); 99450461cbSBen Langmuir StringRef HostNameRef(HostName); 100450461cbSBen Langmuir HostID.append(HostNameRef.begin(), HostNameRef.end()); 101450461cbSBen Langmuir 102450461cbSBen Langmuir #else 103450461cbSBen Langmuir StringRef Dummy("localhost"); 104450461cbSBen Langmuir HostID.append(Dummy.begin(), Dummy.end()); 105450461cbSBen Langmuir #endif 106450461cbSBen Langmuir 107450461cbSBen Langmuir return std::error_code(); 108450461cbSBen Langmuir } 109450461cbSBen Langmuir 110450461cbSBen Langmuir bool LockFileManager::processStillExecuting(StringRef HostID, int PID) { 111c439a426SEvgeniy Stepanov #if LLVM_ON_UNIX && !defined(__ANDROID__) 112450461cbSBen Langmuir SmallString<256> StoredHostID; 113450461cbSBen Langmuir if (getHostID(StoredHostID)) 114450461cbSBen Langmuir return true; // Conservatively assume it's executing on error. 115450461cbSBen Langmuir 1167039e358SDouglas Gregor // Check whether the process is dead. If so, we're done. 117450461cbSBen Langmuir if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH) 1187039e358SDouglas Gregor return false; 1197039e358SDouglas Gregor #endif 1207039e358SDouglas Gregor 1217039e358SDouglas Gregor return true; 1227039e358SDouglas Gregor } 1237039e358SDouglas Gregor 12463aa8c5dSBen Langmuir namespace { 12533d7b762SEugene Zelenko 12663aa8c5dSBen Langmuir /// An RAII helper object ensure that the unique lock file is removed. 12763aa8c5dSBen Langmuir /// 12863aa8c5dSBen Langmuir /// Ensures that if there is an error or a signal before we finish acquiring the 12963aa8c5dSBen Langmuir /// lock, the unique file will be removed. And if we successfully take the lock, 13063aa8c5dSBen Langmuir /// the signal handler is left in place so that signals while the lock is held 13163aa8c5dSBen Langmuir /// will remove the unique lock file. The caller should ensure there is a 13263aa8c5dSBen Langmuir /// matching call to sys::DontRemoveFileOnSignal when the lock is released. 13363aa8c5dSBen Langmuir class RemoveUniqueLockFileOnSignal { 13463aa8c5dSBen Langmuir StringRef Filename; 13563aa8c5dSBen Langmuir bool RemoveImmediately; 13663aa8c5dSBen Langmuir public: 13763aa8c5dSBen Langmuir RemoveUniqueLockFileOnSignal(StringRef Name) 13863aa8c5dSBen Langmuir : Filename(Name), RemoveImmediately(true) { 13963aa8c5dSBen Langmuir sys::RemoveFileOnSignal(Filename, nullptr); 14063aa8c5dSBen Langmuir } 14133d7b762SEugene Zelenko 14263aa8c5dSBen Langmuir ~RemoveUniqueLockFileOnSignal() { 14363aa8c5dSBen Langmuir if (!RemoveImmediately) { 14463aa8c5dSBen Langmuir // Leave the signal handler enabled. It will be removed when the lock is 14563aa8c5dSBen Langmuir // released. 14663aa8c5dSBen Langmuir return; 14763aa8c5dSBen Langmuir } 14863aa8c5dSBen Langmuir sys::fs::remove(Filename); 14963aa8c5dSBen Langmuir sys::DontRemoveFileOnSignal(Filename); 15063aa8c5dSBen Langmuir } 15133d7b762SEugene Zelenko 15263aa8c5dSBen Langmuir void lockAcquired() { RemoveImmediately = false; } 15363aa8c5dSBen Langmuir }; 15433d7b762SEugene Zelenko 15563aa8c5dSBen Langmuir } // end anonymous namespace 15663aa8c5dSBen Langmuir 1577039e358SDouglas Gregor LockFileManager::LockFileManager(StringRef FileName) 1587039e358SDouglas Gregor { 159056eafd4SDouglas Gregor this->FileName = FileName; 160db4ed0bdSRafael Espindola if (std::error_code EC = sys::fs::make_absolute(this->FileName)) { 16142b1f65fSBruno Cardoso Lopes std::string S("failed to obtain absolute path for "); 16242b1f65fSBruno Cardoso Lopes S.append(this->FileName.str()); 16342b1f65fSBruno Cardoso Lopes setError(EC, S); 164900e9a3dSArgyrios Kyrtzidis return; 165900e9a3dSArgyrios Kyrtzidis } 166900e9a3dSArgyrios Kyrtzidis LockFileName = this->FileName; 1677039e358SDouglas Gregor LockFileName += ".lock"; 1687039e358SDouglas Gregor 1697039e358SDouglas Gregor // If the lock file already exists, don't bother to try to create our own 1707039e358SDouglas Gregor // lock file; it won't work anyway. Just figure out who owns this lock file. 1717039e358SDouglas Gregor if ((Owner = readLockFile(LockFileName))) 1727039e358SDouglas Gregor return; 1737039e358SDouglas Gregor 1747039e358SDouglas Gregor // Create a lock file that is unique to this instance. 1757039e358SDouglas Gregor UniqueLockFileName = LockFileName; 1767039e358SDouglas Gregor UniqueLockFileName += "-%%%%%%%%"; 1777039e358SDouglas Gregor int UniqueLockFileID; 178db4ed0bdSRafael Espindola if (std::error_code EC = sys::fs::createUniqueFile( 17992e1b62dSYaron Keren UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) { 18042b1f65fSBruno Cardoso Lopes std::string S("failed to create unique file "); 18142b1f65fSBruno Cardoso Lopes S.append(UniqueLockFileName.str()); 18242b1f65fSBruno Cardoso Lopes setError(EC, S); 1837039e358SDouglas Gregor return; 1847039e358SDouglas Gregor } 1857039e358SDouglas Gregor 1867039e358SDouglas Gregor // Write our process ID to our unique lock file. 1877039e358SDouglas Gregor { 188450461cbSBen Langmuir SmallString<256> HostID; 189450461cbSBen Langmuir if (auto EC = getHostID(HostID)) { 19042b1f65fSBruno Cardoso Lopes setError(EC, "failed to get host id"); 191450461cbSBen Langmuir return; 192450461cbSBen Langmuir } 1935123eecdSBen Langmuir 194450461cbSBen Langmuir raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true); 195450461cbSBen Langmuir Out << HostID << ' '; 1967039e358SDouglas Gregor #if LLVM_ON_UNIX 197450461cbSBen Langmuir Out << getpid(); 1987039e358SDouglas Gregor #else 199450461cbSBen Langmuir Out << "1"; 2007039e358SDouglas Gregor #endif 2017039e358SDouglas Gregor Out.close(); 2027039e358SDouglas Gregor 2037039e358SDouglas Gregor if (Out.has_error()) { 204*9ce2d03eSBob Haarman // We failed to write out PID, so report the error, remove the 2057039e358SDouglas Gregor // unique lock file, and fail. 20642b1f65fSBruno Cardoso Lopes std::string S("failed to write to "); 20742b1f65fSBruno Cardoso Lopes S.append(UniqueLockFileName.str()); 208*9ce2d03eSBob Haarman setError(Out.error(), S); 20992e1b62dSYaron Keren sys::fs::remove(UniqueLockFileName); 2107039e358SDouglas Gregor return; 2117039e358SDouglas Gregor } 2127039e358SDouglas Gregor } 2137039e358SDouglas Gregor 21463aa8c5dSBen Langmuir // Clean up the unique file on signal, which also releases the lock if it is 21563aa8c5dSBen Langmuir // held since the .lock symlink will point to a nonexistent file. 21663aa8c5dSBen Langmuir RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName); 21763aa8c5dSBen Langmuir 21833d7b762SEugene Zelenko while (true) { 21983f858e5SRafael Espindola // Create a link from the lock file name. If this succeeds, we're done. 220db4ed0bdSRafael Espindola std::error_code EC = 22192e1b62dSYaron Keren sys::fs::create_link(UniqueLockFileName, LockFileName); 22263aa8c5dSBen Langmuir if (!EC) { 22363aa8c5dSBen Langmuir RemoveUniqueFile.lockAcquired(); 2247039e358SDouglas Gregor return; 22563aa8c5dSBen Langmuir } 2267039e358SDouglas Gregor 2272a826e40SRafael Espindola if (EC != errc::file_exists) { 22842b1f65fSBruno Cardoso Lopes std::string S("failed to create link "); 22942b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(S); 23042b1f65fSBruno Cardoso Lopes OSS << LockFileName.str() << " to " << UniqueLockFileName.str(); 23142b1f65fSBruno Cardoso Lopes setError(EC, OSS.str()); 2324147978cSArgyrios Kyrtzidis return; 2334147978cSArgyrios Kyrtzidis } 2344147978cSArgyrios Kyrtzidis 2354147978cSArgyrios Kyrtzidis // Someone else managed to create the lock file first. Read the process ID 2364147978cSArgyrios Kyrtzidis // from the lock file. 2374147978cSArgyrios Kyrtzidis if ((Owner = readLockFile(LockFileName))) { 2384147978cSArgyrios Kyrtzidis // Wipe out our unique lock file (it's useless now) 23992e1b62dSYaron Keren sys::fs::remove(UniqueLockFileName); 2404147978cSArgyrios Kyrtzidis return; 2414147978cSArgyrios Kyrtzidis } 2424147978cSArgyrios Kyrtzidis 24392e1b62dSYaron Keren if (!sys::fs::exists(LockFileName)) { 2444147978cSArgyrios Kyrtzidis // The previous owner released the lock file before we could read it. 2454147978cSArgyrios Kyrtzidis // Try to get ownership again. 2464147978cSArgyrios Kyrtzidis continue; 2474147978cSArgyrios Kyrtzidis } 2484147978cSArgyrios Kyrtzidis 2494147978cSArgyrios Kyrtzidis // There is a lock file that nobody owns; try to clean it up and get 2504147978cSArgyrios Kyrtzidis // ownership. 25192e1b62dSYaron Keren if ((EC = sys::fs::remove(LockFileName))) { 25242b1f65fSBruno Cardoso Lopes std::string S("failed to remove lockfile "); 25342b1f65fSBruno Cardoso Lopes S.append(UniqueLockFileName.str()); 25442b1f65fSBruno Cardoso Lopes setError(EC, S); 2554147978cSArgyrios Kyrtzidis return; 2564147978cSArgyrios Kyrtzidis } 2574147978cSArgyrios Kyrtzidis } 2587039e358SDouglas Gregor } 2597039e358SDouglas Gregor 2607039e358SDouglas Gregor LockFileManager::LockFileState LockFileManager::getState() const { 2617039e358SDouglas Gregor if (Owner) 2627039e358SDouglas Gregor return LFS_Shared; 2637039e358SDouglas Gregor 2647039e358SDouglas Gregor if (Error) 2657039e358SDouglas Gregor return LFS_Error; 2667039e358SDouglas Gregor 2677039e358SDouglas Gregor return LFS_Owned; 2687039e358SDouglas Gregor } 2697039e358SDouglas Gregor 27042b1f65fSBruno Cardoso Lopes std::string LockFileManager::getErrorMessage() const { 27142b1f65fSBruno Cardoso Lopes if (Error) { 27242b1f65fSBruno Cardoso Lopes std::string Str(ErrorDiagMsg); 27342b1f65fSBruno Cardoso Lopes std::string ErrCodeMsg = Error->message(); 27442b1f65fSBruno Cardoso Lopes raw_string_ostream OSS(Str); 27542b1f65fSBruno Cardoso Lopes if (!ErrCodeMsg.empty()) 27642b1f65fSBruno Cardoso Lopes OSS << ": " << Error->message(); 27742b1f65fSBruno Cardoso Lopes OSS.flush(); 27842b1f65fSBruno Cardoso Lopes return Str; 27942b1f65fSBruno Cardoso Lopes } 28042b1f65fSBruno Cardoso Lopes return ""; 28142b1f65fSBruno Cardoso Lopes } 28242b1f65fSBruno Cardoso Lopes 2837039e358SDouglas Gregor LockFileManager::~LockFileManager() { 2847039e358SDouglas Gregor if (getState() != LFS_Owned) 2857039e358SDouglas Gregor return; 2867039e358SDouglas Gregor 2877039e358SDouglas Gregor // Since we own the lock, remove the lock file and our own unique lock file. 28892e1b62dSYaron Keren sys::fs::remove(LockFileName); 28992e1b62dSYaron Keren sys::fs::remove(UniqueLockFileName); 29063aa8c5dSBen Langmuir // The unique file is now gone, so remove it from the signal handler. This 29163aa8c5dSBen Langmuir // matches a sys::RemoveFileOnSignal() in LockFileManager(). 29263aa8c5dSBen Langmuir sys::DontRemoveFileOnSignal(UniqueLockFileName); 2937039e358SDouglas Gregor } 2947039e358SDouglas Gregor 29544ec0a7dSArgyrios Kyrtzidis LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() { 2967039e358SDouglas Gregor if (getState() != LFS_Shared) 29744ec0a7dSArgyrios Kyrtzidis return Res_Success; 2987039e358SDouglas Gregor 2997039e358SDouglas Gregor #if LLVM_ON_WIN32 3007039e358SDouglas Gregor unsigned long Interval = 1; 3017039e358SDouglas Gregor #else 3027039e358SDouglas Gregor struct timespec Interval; 3037039e358SDouglas Gregor Interval.tv_sec = 0; 3047039e358SDouglas Gregor Interval.tv_nsec = 1000000; 3057039e358SDouglas Gregor #endif 3068fef5556SBruno Cardoso Lopes // Don't wait more than 40s per iteration. Total timeout for the file 3078fef5556SBruno Cardoso Lopes // to appear is ~1.5 minutes. 3088fef5556SBruno Cardoso Lopes const unsigned MaxSeconds = 40; 3097039e358SDouglas Gregor do { 3107039e358SDouglas Gregor // Sleep for the designated interval, to allow the owning process time to 3117039e358SDouglas Gregor // finish up and remove the lock file. 3127039e358SDouglas Gregor // FIXME: Should we hook in to system APIs to get a notification when the 3137039e358SDouglas Gregor // lock file is deleted? 3147039e358SDouglas Gregor #if LLVM_ON_WIN32 3157039e358SDouglas Gregor Sleep(Interval); 3167039e358SDouglas Gregor #else 317c10719f5SCraig Topper nanosleep(&Interval, nullptr); 3187039e358SDouglas Gregor #endif 3190cb68460SDouglas Gregor 320281f23adSRafael Espindola if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) == 321281f23adSRafael Espindola errc::no_such_file_or_directory) { 32208970917SBen Langmuir // If the original file wasn't created, somone thought the lock was dead. 32392e1b62dSYaron Keren if (!sys::fs::exists(FileName)) 32408970917SBen Langmuir return Res_OwnerDied; 32544ec0a7dSArgyrios Kyrtzidis return Res_Success; 326056eafd4SDouglas Gregor } 3277039e358SDouglas Gregor 32808970917SBen Langmuir // If the process owning the lock died without cleaning up, just bail out. 32908970917SBen Langmuir if (!processStillExecuting((*Owner).first, (*Owner).second)) 33044ec0a7dSArgyrios Kyrtzidis return Res_OwnerDied; 3317039e358SDouglas Gregor 3327039e358SDouglas Gregor // Exponentially increase the time we wait for the lock to be removed. 3337039e358SDouglas Gregor #if LLVM_ON_WIN32 3347039e358SDouglas Gregor Interval *= 2; 3357039e358SDouglas Gregor #else 3367039e358SDouglas Gregor Interval.tv_sec *= 2; 3377039e358SDouglas Gregor Interval.tv_nsec *= 2; 3387039e358SDouglas Gregor if (Interval.tv_nsec >= 1000000000) { 3397039e358SDouglas Gregor ++Interval.tv_sec; 3407039e358SDouglas Gregor Interval.tv_nsec -= 1000000000; 3417039e358SDouglas Gregor } 3427039e358SDouglas Gregor #endif 3437039e358SDouglas Gregor } while ( 3447039e358SDouglas Gregor #if LLVM_ON_WIN32 3457039e358SDouglas Gregor Interval < MaxSeconds * 1000 3467039e358SDouglas Gregor #else 3477039e358SDouglas Gregor Interval.tv_sec < (time_t)MaxSeconds 3487039e358SDouglas Gregor #endif 3497039e358SDouglas Gregor ); 3507039e358SDouglas Gregor 3517039e358SDouglas Gregor // Give up. 35244ec0a7dSArgyrios Kyrtzidis return Res_Timeout; 3537039e358SDouglas Gregor } 354d2d52de2SBen Langmuir 355d2d52de2SBen Langmuir std::error_code LockFileManager::unsafeRemoveLockFile() { 35692e1b62dSYaron Keren return sys::fs::remove(LockFileName); 357d2d52de2SBen Langmuir } 358