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 //===----------------------------------------------------------------------===//
97039e358SDouglas Gregor #include "llvm/Support/LockFileManager.h"
10d78273f4SReid Kleckner #include "llvm/ADT/STLExtras.h"
11d78273f4SReid Kleckner #include "llvm/ADT/StringExtras.h"
127039e358SDouglas Gregor #include "llvm/Support/FileSystem.h"
13d78273f4SReid Kleckner #include "llvm/Support/MemoryBuffer.h"
14531a5be4SArgyrios Kyrtzidis #include "llvm/Support/Path.h"
157039e358SDouglas Gregor #include "llvm/Support/raw_ostream.h"
167039e358SDouglas Gregor #include <sys/stat.h>
17ed0881b2SChandler Carruth #include <sys/types.h>
187039e358SDouglas Gregor #if LLVM_ON_WIN32
197039e358SDouglas Gregor #include <windows.h>
207039e358SDouglas Gregor #endif
217039e358SDouglas Gregor #if LLVM_ON_UNIX
227039e358SDouglas Gregor #include <unistd.h>
237039e358SDouglas Gregor #endif
247039e358SDouglas Gregor using namespace llvm;
257039e358SDouglas Gregor 
267039e358SDouglas Gregor /// \brief Attempt to read the lock file with the given name, if it exists.
277039e358SDouglas Gregor ///
287039e358SDouglas Gregor /// \param LockFileName The name of the lock file to read.
297039e358SDouglas Gregor ///
307039e358SDouglas Gregor /// \returns The process ID of the process that owns this lock file
317039e358SDouglas Gregor Optional<std::pair<std::string, int> >
327039e358SDouglas Gregor LockFileManager::readLockFile(StringRef LockFileName) {
337039e358SDouglas Gregor   // Read the owning host and PID out of the lock file. If it appears that the
347039e358SDouglas Gregor   // owning process is dead, the lock file is invalid.
3556440fd8SAhmed Charles   std::unique_ptr<MemoryBuffer> MB;
3637575693SArgyrios Kyrtzidis   if (MemoryBuffer::getFile(LockFileName, MB)) {
3737575693SArgyrios Kyrtzidis     sys::fs::remove(LockFileName);
387de8ea3dSReid Kleckner     return None;
3937575693SArgyrios Kyrtzidis   }
407de8ea3dSReid Kleckner 
41d78273f4SReid Kleckner   StringRef Hostname;
42d78273f4SReid Kleckner   StringRef PIDStr;
43d6f1f84fSBenjamin Kramer   std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
447de8ea3dSReid Kleckner   PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
45d78273f4SReid Kleckner   int PID;
4644ec0a7dSArgyrios Kyrtzidis   if (!PIDStr.getAsInteger(10, PID)) {
4744ec0a7dSArgyrios Kyrtzidis     auto Owner = std::make_pair(std::string(Hostname), PID);
4844ec0a7dSArgyrios Kyrtzidis     if (processStillExecuting(Owner.first, Owner.second))
4944ec0a7dSArgyrios Kyrtzidis       return Owner;
5044ec0a7dSArgyrios Kyrtzidis   }
517039e358SDouglas Gregor 
527039e358SDouglas Gregor   // Delete the lock file. It's invalid anyway.
53d78273f4SReid Kleckner   sys::fs::remove(LockFileName);
54ef04593dSDavid Blaikie   return None;
557039e358SDouglas Gregor }
567039e358SDouglas Gregor 
577039e358SDouglas Gregor bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
58c439a426SEvgeniy Stepanov #if LLVM_ON_UNIX && !defined(__ANDROID__)
597039e358SDouglas Gregor   char MyHostname[256];
607039e358SDouglas Gregor   MyHostname[255] = 0;
617039e358SDouglas Gregor   MyHostname[0] = 0;
627039e358SDouglas Gregor   gethostname(MyHostname, 255);
637039e358SDouglas Gregor   // Check whether the process is dead. If so, we're done.
647039e358SDouglas Gregor   if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
657039e358SDouglas Gregor     return false;
667039e358SDouglas Gregor #endif
677039e358SDouglas Gregor 
687039e358SDouglas Gregor   return true;
697039e358SDouglas Gregor }
707039e358SDouglas Gregor 
717039e358SDouglas Gregor LockFileManager::LockFileManager(StringRef FileName)
727039e358SDouglas Gregor {
73056eafd4SDouglas Gregor   this->FileName = FileName;
74*db4ed0bdSRafael Espindola   if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
75900e9a3dSArgyrios Kyrtzidis     Error = EC;
76900e9a3dSArgyrios Kyrtzidis     return;
77900e9a3dSArgyrios Kyrtzidis   }
78900e9a3dSArgyrios Kyrtzidis   LockFileName = this->FileName;
797039e358SDouglas Gregor   LockFileName += ".lock";
807039e358SDouglas Gregor 
817039e358SDouglas Gregor   // If the lock file already exists, don't bother to try to create our own
827039e358SDouglas Gregor   // lock file; it won't work anyway. Just figure out who owns this lock file.
837039e358SDouglas Gregor   if ((Owner = readLockFile(LockFileName)))
847039e358SDouglas Gregor     return;
857039e358SDouglas Gregor 
867039e358SDouglas Gregor   // Create a lock file that is unique to this instance.
877039e358SDouglas Gregor   UniqueLockFileName = LockFileName;
887039e358SDouglas Gregor   UniqueLockFileName += "-%%%%%%%%";
897039e358SDouglas Gregor   int UniqueLockFileID;
90*db4ed0bdSRafael Espindola   if (std::error_code EC = sys::fs::createUniqueFile(
91*db4ed0bdSRafael Espindola           UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) {
927039e358SDouglas Gregor     Error = EC;
937039e358SDouglas Gregor     return;
947039e358SDouglas Gregor   }
957039e358SDouglas Gregor 
967039e358SDouglas Gregor   // Write our process ID to our unique lock file.
977039e358SDouglas Gregor   {
987039e358SDouglas Gregor     raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
997039e358SDouglas Gregor 
1007039e358SDouglas Gregor #if LLVM_ON_UNIX
1017039e358SDouglas Gregor     // FIXME: move getpid() call into LLVM
1027039e358SDouglas Gregor     char hostname[256];
1037039e358SDouglas Gregor     hostname[255] = 0;
1047039e358SDouglas Gregor     hostname[0] = 0;
1057039e358SDouglas Gregor     gethostname(hostname, 255);
1067039e358SDouglas Gregor     Out << hostname << ' ' << getpid();
1077039e358SDouglas Gregor #else
1087039e358SDouglas Gregor     Out << "localhost 1";
1097039e358SDouglas Gregor #endif
1107039e358SDouglas Gregor     Out.close();
1117039e358SDouglas Gregor 
1127039e358SDouglas Gregor     if (Out.has_error()) {
1137039e358SDouglas Gregor       // We failed to write out PID, so make up an excuse, remove the
1147039e358SDouglas Gregor       // unique lock file, and fail.
115ed6882b8SRafael Espindola       Error = std::make_error_code(std::errc::no_space_on_device);
11681e7fd01SRafael Espindola       sys::fs::remove(UniqueLockFileName.c_str());
1177039e358SDouglas Gregor       return;
1187039e358SDouglas Gregor     }
1197039e358SDouglas Gregor   }
1207039e358SDouglas Gregor 
1214147978cSArgyrios Kyrtzidis   while (1) {
12283f858e5SRafael Espindola     // Create a link from the lock file name. If this succeeds, we're done.
123*db4ed0bdSRafael Espindola     std::error_code EC =
124900e9a3dSArgyrios Kyrtzidis         sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
125a3f2e3f0SRafael Espindola     if (!EC)
1267039e358SDouglas Gregor       return;
1277039e358SDouglas Gregor 
1285c4f8294SRafael Espindola     if (EC != std::errc::file_exists) {
12962a979ccSArgyrios Kyrtzidis       Error = EC;
1304147978cSArgyrios Kyrtzidis       return;
1314147978cSArgyrios Kyrtzidis     }
1324147978cSArgyrios Kyrtzidis 
1334147978cSArgyrios Kyrtzidis     // Someone else managed to create the lock file first. Read the process ID
1344147978cSArgyrios Kyrtzidis     // from the lock file.
1354147978cSArgyrios Kyrtzidis     if ((Owner = readLockFile(LockFileName))) {
1364147978cSArgyrios Kyrtzidis       // Wipe out our unique lock file (it's useless now)
1374147978cSArgyrios Kyrtzidis       sys::fs::remove(UniqueLockFileName.str());
1384147978cSArgyrios Kyrtzidis       return;
1394147978cSArgyrios Kyrtzidis     }
1404147978cSArgyrios Kyrtzidis 
1414147978cSArgyrios Kyrtzidis     if (!sys::fs::exists(LockFileName.str())) {
1424147978cSArgyrios Kyrtzidis       // The previous owner released the lock file before we could read it.
1434147978cSArgyrios Kyrtzidis       // Try to get ownership again.
1444147978cSArgyrios Kyrtzidis       continue;
1454147978cSArgyrios Kyrtzidis     }
1464147978cSArgyrios Kyrtzidis 
1474147978cSArgyrios Kyrtzidis     // There is a lock file that nobody owns; try to clean it up and get
1484147978cSArgyrios Kyrtzidis     // ownership.
1494147978cSArgyrios Kyrtzidis     if ((EC = sys::fs::remove(LockFileName.str()))) {
1504147978cSArgyrios Kyrtzidis       Error = EC;
1514147978cSArgyrios Kyrtzidis       return;
1524147978cSArgyrios Kyrtzidis     }
1534147978cSArgyrios Kyrtzidis   }
1547039e358SDouglas Gregor }
1557039e358SDouglas Gregor 
1567039e358SDouglas Gregor LockFileManager::LockFileState LockFileManager::getState() const {
1577039e358SDouglas Gregor   if (Owner)
1587039e358SDouglas Gregor     return LFS_Shared;
1597039e358SDouglas Gregor 
1607039e358SDouglas Gregor   if (Error)
1617039e358SDouglas Gregor     return LFS_Error;
1627039e358SDouglas Gregor 
1637039e358SDouglas Gregor   return LFS_Owned;
1647039e358SDouglas Gregor }
1657039e358SDouglas Gregor 
1667039e358SDouglas Gregor LockFileManager::~LockFileManager() {
1677039e358SDouglas Gregor   if (getState() != LFS_Owned)
1687039e358SDouglas Gregor     return;
1697039e358SDouglas Gregor 
1707039e358SDouglas Gregor   // Since we own the lock, remove the lock file and our own unique lock file.
17181e7fd01SRafael Espindola   sys::fs::remove(LockFileName.str());
17281e7fd01SRafael Espindola   sys::fs::remove(UniqueLockFileName.str());
1737039e358SDouglas Gregor }
1747039e358SDouglas Gregor 
17544ec0a7dSArgyrios Kyrtzidis LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
1767039e358SDouglas Gregor   if (getState() != LFS_Shared)
17744ec0a7dSArgyrios Kyrtzidis     return Res_Success;
1787039e358SDouglas Gregor 
1797039e358SDouglas Gregor #if LLVM_ON_WIN32
1807039e358SDouglas Gregor   unsigned long Interval = 1;
1817039e358SDouglas Gregor #else
1827039e358SDouglas Gregor   struct timespec Interval;
1837039e358SDouglas Gregor   Interval.tv_sec = 0;
1847039e358SDouglas Gregor   Interval.tv_nsec = 1000000;
1857039e358SDouglas Gregor #endif
1860cb68460SDouglas Gregor   // Don't wait more than five minutes for the file to appear.
1870cb68460SDouglas Gregor   unsigned MaxSeconds = 300;
188056eafd4SDouglas Gregor   bool LockFileGone = false;
1897039e358SDouglas Gregor   do {
1907039e358SDouglas Gregor     // Sleep for the designated interval, to allow the owning process time to
1917039e358SDouglas Gregor     // finish up and remove the lock file.
1927039e358SDouglas Gregor     // FIXME: Should we hook in to system APIs to get a notification when the
1937039e358SDouglas Gregor     // lock file is deleted?
1947039e358SDouglas Gregor #if LLVM_ON_WIN32
1957039e358SDouglas Gregor     Sleep(Interval);
1967039e358SDouglas Gregor #else
197c10719f5SCraig Topper     nanosleep(&Interval, nullptr);
1987039e358SDouglas Gregor #endif
1990cb68460SDouglas Gregor     bool LockFileJustDisappeared = false;
2000cb68460SDouglas Gregor 
2010cb68460SDouglas Gregor     // If the lock file is still expected to be there, check whether it still
2020cb68460SDouglas Gregor     // is.
203056eafd4SDouglas Gregor     if (!LockFileGone) {
2049e7a638bSRafael Espindola       bool Exists;
205056eafd4SDouglas Gregor       if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
206056eafd4SDouglas Gregor         LockFileGone = true;
2070cb68460SDouglas Gregor         LockFileJustDisappeared = true;
208056eafd4SDouglas Gregor       }
209056eafd4SDouglas Gregor     }
2100cb68460SDouglas Gregor 
2110cb68460SDouglas Gregor     // If the lock file is no longer there, check if the original file is
2120cb68460SDouglas Gregor     // available now.
213056eafd4SDouglas Gregor     if (LockFileGone) {
2149e7a638bSRafael Espindola       if (sys::fs::exists(FileName.str())) {
21544ec0a7dSArgyrios Kyrtzidis         return Res_Success;
216056eafd4SDouglas Gregor       }
2177039e358SDouglas Gregor 
2180cb68460SDouglas Gregor       // The lock file is gone, so now we're waiting for the original file to
2190cb68460SDouglas Gregor       // show up. If this just happened, reset our waiting intervals and keep
2200cb68460SDouglas Gregor       // waiting.
2210cb68460SDouglas Gregor       if (LockFileJustDisappeared) {
2220cb68460SDouglas Gregor         MaxSeconds = 5;
2230cb68460SDouglas Gregor 
2240cb68460SDouglas Gregor #if LLVM_ON_WIN32
2250cb68460SDouglas Gregor         Interval = 1;
2260cb68460SDouglas Gregor #else
2270cb68460SDouglas Gregor         Interval.tv_sec = 0;
2280cb68460SDouglas Gregor         Interval.tv_nsec = 1000000;
2290cb68460SDouglas Gregor #endif
2300cb68460SDouglas Gregor         continue;
2310cb68460SDouglas Gregor       }
2320cb68460SDouglas Gregor     }
2330cb68460SDouglas Gregor 
2340cb68460SDouglas Gregor     // If we're looking for the lock file to disappear, but the process
2350cb68460SDouglas Gregor     // owning the lock died without cleaning up, just bail out.
2360cb68460SDouglas Gregor     if (!LockFileGone &&
2370cb68460SDouglas Gregor         !processStillExecuting((*Owner).first, (*Owner).second)) {
23844ec0a7dSArgyrios Kyrtzidis       return Res_OwnerDied;
2390cb68460SDouglas Gregor     }
2407039e358SDouglas Gregor 
2417039e358SDouglas Gregor     // Exponentially increase the time we wait for the lock to be removed.
2427039e358SDouglas Gregor #if LLVM_ON_WIN32
2437039e358SDouglas Gregor     Interval *= 2;
2447039e358SDouglas Gregor #else
2457039e358SDouglas Gregor     Interval.tv_sec *= 2;
2467039e358SDouglas Gregor     Interval.tv_nsec *= 2;
2477039e358SDouglas Gregor     if (Interval.tv_nsec >= 1000000000) {
2487039e358SDouglas Gregor       ++Interval.tv_sec;
2497039e358SDouglas Gregor       Interval.tv_nsec -= 1000000000;
2507039e358SDouglas Gregor     }
2517039e358SDouglas Gregor #endif
2527039e358SDouglas Gregor   } while (
2537039e358SDouglas Gregor #if LLVM_ON_WIN32
2547039e358SDouglas Gregor            Interval < MaxSeconds * 1000
2557039e358SDouglas Gregor #else
2567039e358SDouglas Gregor            Interval.tv_sec < (time_t)MaxSeconds
2577039e358SDouglas Gregor #endif
2587039e358SDouglas Gregor            );
2597039e358SDouglas Gregor 
2607039e358SDouglas Gregor   // Give up.
26144ec0a7dSArgyrios Kyrtzidis   return Res_Timeout;
2627039e358SDouglas Gregor }
263