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"
147039e358SDouglas Gregor #include "llvm/Support/raw_ostream.h"
157039e358SDouglas Gregor #include <sys/stat.h>
16ed0881b2SChandler Carruth #include <sys/types.h>
177039e358SDouglas Gregor #if LLVM_ON_WIN32
187039e358SDouglas Gregor #include <windows.h>
197039e358SDouglas Gregor #endif
207039e358SDouglas Gregor #if LLVM_ON_UNIX
217039e358SDouglas Gregor #include <unistd.h>
227039e358SDouglas Gregor #endif
237039e358SDouglas Gregor using namespace llvm;
247039e358SDouglas Gregor 
257039e358SDouglas Gregor /// \brief Attempt to read the lock file with the given name, if it exists.
267039e358SDouglas Gregor ///
277039e358SDouglas Gregor /// \param LockFileName The name of the lock file to read.
287039e358SDouglas Gregor ///
297039e358SDouglas Gregor /// \returns The process ID of the process that owns this lock file
307039e358SDouglas Gregor Optional<std::pair<std::string, int> >
317039e358SDouglas Gregor LockFileManager::readLockFile(StringRef LockFileName) {
327039e358SDouglas Gregor   // Check whether the lock file exists. If not, clearly there's nothing
337039e358SDouglas Gregor   // to read, so we just return.
347039e358SDouglas Gregor   bool Exists = false;
357039e358SDouglas Gregor   if (sys::fs::exists(LockFileName, Exists) || !Exists)
36ef04593dSDavid Blaikie     return None;
377039e358SDouglas Gregor 
387039e358SDouglas Gregor   // Read the owning host and PID out of the lock file. If it appears that the
397039e358SDouglas Gregor   // owning process is dead, the lock file is invalid.
40d78273f4SReid Kleckner   OwningPtr<MemoryBuffer> MB;
41*7de8ea3dSReid Kleckner   if (MemoryBuffer::getFile(LockFileName, MB))
42*7de8ea3dSReid Kleckner     return None;
43*7de8ea3dSReid Kleckner 
44d78273f4SReid Kleckner   StringRef Hostname;
45d78273f4SReid Kleckner   StringRef PIDStr;
46d78273f4SReid Kleckner   tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
47*7de8ea3dSReid Kleckner   PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
48d78273f4SReid Kleckner   int PID;
49*7de8ea3dSReid Kleckner   if (!PIDStr.getAsInteger(10, PID))
50d78273f4SReid Kleckner     return std::make_pair(std::string(Hostname), PID);
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;
747039e358SDouglas Gregor   LockFileName = FileName;
757039e358SDouglas Gregor   LockFileName += ".lock";
767039e358SDouglas Gregor 
777039e358SDouglas Gregor   // If the lock file already exists, don't bother to try to create our own
787039e358SDouglas Gregor   // lock file; it won't work anyway. Just figure out who owns this lock file.
797039e358SDouglas Gregor   if ((Owner = readLockFile(LockFileName)))
807039e358SDouglas Gregor     return;
817039e358SDouglas Gregor 
827039e358SDouglas Gregor   // Create a lock file that is unique to this instance.
837039e358SDouglas Gregor   UniqueLockFileName = LockFileName;
847039e358SDouglas Gregor   UniqueLockFileName += "-%%%%%%%%";
857039e358SDouglas Gregor   int UniqueLockFileID;
867039e358SDouglas Gregor   if (error_code EC
87c9d2e5b8SRafael Espindola         = sys::fs::createUniqueFile(UniqueLockFileName.str(),
887039e358SDouglas Gregor                                     UniqueLockFileID,
89c9d2e5b8SRafael Espindola                                     UniqueLockFileName)) {
907039e358SDouglas Gregor     Error = EC;
917039e358SDouglas Gregor     return;
927039e358SDouglas Gregor   }
937039e358SDouglas Gregor 
947039e358SDouglas Gregor   // Write our process ID to our unique lock file.
957039e358SDouglas Gregor   {
967039e358SDouglas Gregor     raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
977039e358SDouglas Gregor 
987039e358SDouglas Gregor #if LLVM_ON_UNIX
997039e358SDouglas Gregor     // FIXME: move getpid() call into LLVM
1007039e358SDouglas Gregor     char hostname[256];
1017039e358SDouglas Gregor     hostname[255] = 0;
1027039e358SDouglas Gregor     hostname[0] = 0;
1037039e358SDouglas Gregor     gethostname(hostname, 255);
1047039e358SDouglas Gregor     Out << hostname << ' ' << getpid();
1057039e358SDouglas Gregor #else
1067039e358SDouglas Gregor     Out << "localhost 1";
1077039e358SDouglas Gregor #endif
1087039e358SDouglas Gregor     Out.close();
1097039e358SDouglas Gregor 
1107039e358SDouglas Gregor     if (Out.has_error()) {
1117039e358SDouglas Gregor       // We failed to write out PID, so make up an excuse, remove the
1127039e358SDouglas Gregor       // unique lock file, and fail.
1137039e358SDouglas Gregor       Error = make_error_code(errc::no_space_on_device);
1147039e358SDouglas Gregor       bool Existed;
1157039e358SDouglas Gregor       sys::fs::remove(UniqueLockFileName.c_str(), Existed);
1167039e358SDouglas Gregor       return;
1177039e358SDouglas Gregor     }
1187039e358SDouglas Gregor   }
1197039e358SDouglas Gregor 
1207039e358SDouglas Gregor   // Create a hard link from the lock file name. If this succeeds, we're done.
1217039e358SDouglas Gregor   error_code EC
1227039e358SDouglas Gregor     = sys::fs::create_hard_link(UniqueLockFileName.str(),
1237039e358SDouglas Gregor                                       LockFileName.str());
1247039e358SDouglas Gregor   if (EC == errc::success)
1257039e358SDouglas Gregor     return;
1267039e358SDouglas Gregor 
1277039e358SDouglas Gregor   // Creating the hard link failed.
1287039e358SDouglas Gregor 
1297039e358SDouglas Gregor #ifdef LLVM_ON_UNIX
1307039e358SDouglas Gregor   // The creation of the hard link may appear to fail, but if stat'ing the
1317039e358SDouglas Gregor   // unique file returns a link count of 2, then we can still declare success.
1327039e358SDouglas Gregor   struct stat StatBuf;
1337039e358SDouglas Gregor   if (stat(UniqueLockFileName.c_str(), &StatBuf) == 0 &&
1347039e358SDouglas Gregor       StatBuf.st_nlink == 2)
1357039e358SDouglas Gregor     return;
1367039e358SDouglas Gregor #endif
1377039e358SDouglas Gregor 
1387039e358SDouglas Gregor   // Someone else managed to create the lock file first. Wipe out our unique
1397039e358SDouglas Gregor   // lock file (it's useless now) and read the process ID from the lock file.
1407039e358SDouglas Gregor   bool Existed;
1417039e358SDouglas Gregor   sys::fs::remove(UniqueLockFileName.str(), Existed);
1427039e358SDouglas Gregor   if ((Owner = readLockFile(LockFileName)))
1437039e358SDouglas Gregor     return;
1447039e358SDouglas Gregor 
1457039e358SDouglas Gregor   // There is a lock file that nobody owns; try to clean it up and report
1467039e358SDouglas Gregor   // an error.
1477039e358SDouglas Gregor   sys::fs::remove(LockFileName.str(), Existed);
1487039e358SDouglas Gregor   Error = EC;
1497039e358SDouglas Gregor }
1507039e358SDouglas Gregor 
1517039e358SDouglas Gregor LockFileManager::LockFileState LockFileManager::getState() const {
1527039e358SDouglas Gregor   if (Owner)
1537039e358SDouglas Gregor     return LFS_Shared;
1547039e358SDouglas Gregor 
1557039e358SDouglas Gregor   if (Error)
1567039e358SDouglas Gregor     return LFS_Error;
1577039e358SDouglas Gregor 
1587039e358SDouglas Gregor   return LFS_Owned;
1597039e358SDouglas Gregor }
1607039e358SDouglas Gregor 
1617039e358SDouglas Gregor LockFileManager::~LockFileManager() {
1627039e358SDouglas Gregor   if (getState() != LFS_Owned)
1637039e358SDouglas Gregor     return;
1647039e358SDouglas Gregor 
1657039e358SDouglas Gregor   // Since we own the lock, remove the lock file and our own unique lock file.
1667039e358SDouglas Gregor   bool Existed;
1677039e358SDouglas Gregor   sys::fs::remove(LockFileName.str(), Existed);
1687039e358SDouglas Gregor   sys::fs::remove(UniqueLockFileName.str(), Existed);
1697039e358SDouglas Gregor }
1707039e358SDouglas Gregor 
1717039e358SDouglas Gregor void LockFileManager::waitForUnlock() {
1727039e358SDouglas Gregor   if (getState() != LFS_Shared)
1737039e358SDouglas Gregor     return;
1747039e358SDouglas Gregor 
1757039e358SDouglas Gregor #if LLVM_ON_WIN32
1767039e358SDouglas Gregor   unsigned long Interval = 1;
1777039e358SDouglas Gregor #else
1787039e358SDouglas Gregor   struct timespec Interval;
1797039e358SDouglas Gregor   Interval.tv_sec = 0;
1807039e358SDouglas Gregor   Interval.tv_nsec = 1000000;
1817039e358SDouglas Gregor #endif
1820cb68460SDouglas Gregor   // Don't wait more than five minutes for the file to appear.
1830cb68460SDouglas Gregor   unsigned MaxSeconds = 300;
184056eafd4SDouglas Gregor   bool LockFileGone = false;
1857039e358SDouglas Gregor   do {
1867039e358SDouglas Gregor     // Sleep for the designated interval, to allow the owning process time to
1877039e358SDouglas Gregor     // finish up and remove the lock file.
1887039e358SDouglas Gregor     // FIXME: Should we hook in to system APIs to get a notification when the
1897039e358SDouglas Gregor     // lock file is deleted?
1907039e358SDouglas Gregor #if LLVM_ON_WIN32
1917039e358SDouglas Gregor     Sleep(Interval);
1927039e358SDouglas Gregor #else
1937039e358SDouglas Gregor     nanosleep(&Interval, NULL);
1947039e358SDouglas Gregor #endif
1957039e358SDouglas Gregor     bool Exists = false;
1960cb68460SDouglas Gregor     bool LockFileJustDisappeared = false;
1970cb68460SDouglas Gregor 
1980cb68460SDouglas Gregor     // If the lock file is still expected to be there, check whether it still
1990cb68460SDouglas Gregor     // is.
200056eafd4SDouglas Gregor     if (!LockFileGone) {
201056eafd4SDouglas Gregor       if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
202056eafd4SDouglas Gregor         LockFileGone = true;
2030cb68460SDouglas Gregor         LockFileJustDisappeared = true;
204056eafd4SDouglas Gregor         Exists = false;
205056eafd4SDouglas Gregor       }
206056eafd4SDouglas Gregor     }
2070cb68460SDouglas Gregor 
2080cb68460SDouglas Gregor     // If the lock file is no longer there, check if the original file is
2090cb68460SDouglas Gregor     // available now.
210056eafd4SDouglas Gregor     if (LockFileGone) {
2110cb68460SDouglas Gregor       if (!sys::fs::exists(FileName.str(), Exists) && Exists) {
2127039e358SDouglas Gregor         return;
213056eafd4SDouglas Gregor       }
2147039e358SDouglas Gregor 
2150cb68460SDouglas Gregor       // The lock file is gone, so now we're waiting for the original file to
2160cb68460SDouglas Gregor       // show up. If this just happened, reset our waiting intervals and keep
2170cb68460SDouglas Gregor       // waiting.
2180cb68460SDouglas Gregor       if (LockFileJustDisappeared) {
2190cb68460SDouglas Gregor         MaxSeconds = 5;
2200cb68460SDouglas Gregor 
2210cb68460SDouglas Gregor #if LLVM_ON_WIN32
2220cb68460SDouglas Gregor         Interval = 1;
2230cb68460SDouglas Gregor #else
2240cb68460SDouglas Gregor         Interval.tv_sec = 0;
2250cb68460SDouglas Gregor         Interval.tv_nsec = 1000000;
2260cb68460SDouglas Gregor #endif
2270cb68460SDouglas Gregor         continue;
2280cb68460SDouglas Gregor       }
2290cb68460SDouglas Gregor     }
2300cb68460SDouglas Gregor 
2310cb68460SDouglas Gregor     // If we're looking for the lock file to disappear, but the process
2320cb68460SDouglas Gregor     // owning the lock died without cleaning up, just bail out.
2330cb68460SDouglas Gregor     if (!LockFileGone &&
2340cb68460SDouglas Gregor         !processStillExecuting((*Owner).first, (*Owner).second)) {
2357039e358SDouglas Gregor       return;
2360cb68460SDouglas Gregor     }
2377039e358SDouglas Gregor 
2387039e358SDouglas Gregor     // Exponentially increase the time we wait for the lock to be removed.
2397039e358SDouglas Gregor #if LLVM_ON_WIN32
2407039e358SDouglas Gregor     Interval *= 2;
2417039e358SDouglas Gregor #else
2427039e358SDouglas Gregor     Interval.tv_sec *= 2;
2437039e358SDouglas Gregor     Interval.tv_nsec *= 2;
2447039e358SDouglas Gregor     if (Interval.tv_nsec >= 1000000000) {
2457039e358SDouglas Gregor       ++Interval.tv_sec;
2467039e358SDouglas Gregor       Interval.tv_nsec -= 1000000000;
2477039e358SDouglas Gregor     }
2487039e358SDouglas Gregor #endif
2497039e358SDouglas Gregor   } while (
2507039e358SDouglas Gregor #if LLVM_ON_WIN32
2517039e358SDouglas Gregor            Interval < MaxSeconds * 1000
2527039e358SDouglas Gregor #else
2537039e358SDouglas Gregor            Interval.tv_sec < (time_t)MaxSeconds
2547039e358SDouglas Gregor #endif
2557039e358SDouglas Gregor            );
2567039e358SDouglas Gregor 
2577039e358SDouglas Gregor   // Give up.
2587039e358SDouglas Gregor }
259