83c67b8de7621b98e640a77473528c31f030ecf5
[oota-llvm.git] / lib / Support / LockFileManager.cpp
1 //===--- LockFileManager.cpp - File-level Locking Utility------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/LockFileManager.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/Support/Errc.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Support/Signals.h"
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #if LLVM_ON_WIN32
19 #include <windows.h>
20 #endif
21 #if LLVM_ON_UNIX
22 #include <unistd.h>
23 #endif
24
25 #if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
26 #define USE_OSX_GETHOSTUUID 1
27 #else
28 #define USE_OSX_GETHOSTUUID 0
29 #endif
30
31 #if USE_OSX_GETHOSTUUID
32 #include <uuid/uuid.h>
33 #endif
34 using namespace llvm;
35
36 /// \brief Attempt to read the lock file with the given name, if it exists.
37 ///
38 /// \param LockFileName The name of the lock file to read.
39 ///
40 /// \returns The process ID of the process that owns this lock file
41 Optional<std::pair<std::string, int> >
42 LockFileManager::readLockFile(StringRef LockFileName) {
43   // Read the owning host and PID out of the lock file. If it appears that the
44   // owning process is dead, the lock file is invalid.
45   ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
46       MemoryBuffer::getFile(LockFileName);
47   if (!MBOrErr) {
48     sys::fs::remove(LockFileName);
49     return None;
50   }
51   MemoryBuffer &MB = *MBOrErr.get();
52
53   StringRef Hostname;
54   StringRef PIDStr;
55   std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
56   PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
57   int PID;
58   if (!PIDStr.getAsInteger(10, PID)) {
59     auto Owner = std::make_pair(std::string(Hostname), PID);
60     if (processStillExecuting(Owner.first, Owner.second))
61       return Owner;
62   }
63
64   // Delete the lock file. It's invalid anyway.
65   sys::fs::remove(LockFileName);
66   return None;
67 }
68
69 static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
70   HostID.clear();
71
72 #if USE_OSX_GETHOSTUUID
73   // On OS X, use the more stable hardware UUID instead of hostname.
74   struct timespec wait = {1, 0}; // 1 second.
75   uuid_t uuid;
76   if (gethostuuid(uuid, &wait) != 0)
77     return std::error_code(errno, std::system_category());
78
79   uuid_string_t UUIDStr;
80   uuid_unparse(uuid, UUIDStr);
81   assert(strlen(UUIDStr) == 36);
82   HostID.append(&UUIDStr[0], &UUIDStr[36]);
83
84 #elif LLVM_ON_UNIX
85   char hostname[256];
86   hostname[255] = 0;
87   hostname[0] = 0;
88   gethostname(hostname, 255);
89   HostID = hostname;
90
91 #else
92   HostID = "localhost";
93 #endif
94
95   return std::error_code();
96 }
97
98 bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
99 #if LLVM_ON_UNIX && !defined(__ANDROID__)
100   SmallString<256> StoredHostID;
101   if (getHostID(StoredHostID))
102     return true; // Conservatively assume it's executing on error.
103
104   // Check whether the process is dead. If so, we're done.
105   if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
106     return false;
107 #endif
108
109   return true;
110 }
111
112 namespace {
113 /// An RAII helper object ensure that the unique lock file is removed.
114 ///
115 /// Ensures that if there is an error or a signal before we finish acquiring the
116 /// lock, the unique file will be removed. And if we successfully take the lock,
117 /// the signal handler is left in place so that signals while the lock is held
118 /// will remove the unique lock file. The caller should ensure there is a
119 /// matching call to sys::DontRemoveFileOnSignal when the lock is released.
120 class RemoveUniqueLockFileOnSignal {
121   StringRef Filename;
122   bool RemoveImmediately;
123 public:
124   RemoveUniqueLockFileOnSignal(StringRef Name)
125   : Filename(Name), RemoveImmediately(true) {
126     sys::RemoveFileOnSignal(Filename, nullptr);
127   }
128   ~RemoveUniqueLockFileOnSignal() {
129     if (!RemoveImmediately) {
130       // Leave the signal handler enabled. It will be removed when the lock is
131       // released.
132       return;
133     }
134     sys::fs::remove(Filename);
135     sys::DontRemoveFileOnSignal(Filename);
136   }
137   void lockAcquired() { RemoveImmediately = false; }
138 };
139 } // end anonymous namespace
140
141 LockFileManager::LockFileManager(StringRef FileName)
142 {
143   this->FileName = FileName;
144   if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
145     Error = EC;
146     return;
147   }
148   LockFileName = this->FileName;
149   LockFileName += ".lock";
150
151   // If the lock file already exists, don't bother to try to create our own
152   // lock file; it won't work anyway. Just figure out who owns this lock file.
153   if ((Owner = readLockFile(LockFileName)))
154     return;
155
156   // Create a lock file that is unique to this instance.
157   UniqueLockFileName = LockFileName;
158   UniqueLockFileName += "-%%%%%%%%";
159   int UniqueLockFileID;
160   if (std::error_code EC = sys::fs::createUniqueFile(
161           UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
162     Error = EC;
163     return;
164   }
165
166   // Write our process ID to our unique lock file.
167   {
168     SmallString<256> HostID;
169     if (auto EC = getHostID(HostID)) {
170       Error = EC;
171       return;
172     }
173
174     raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
175     Out << HostID << ' ';
176 #if LLVM_ON_UNIX
177     Out << getpid();
178 #else
179     Out << "1";
180 #endif
181     Out.close();
182
183     if (Out.has_error()) {
184       // We failed to write out PID, so make up an excuse, remove the
185       // unique lock file, and fail.
186       Error = make_error_code(errc::no_space_on_device);
187       sys::fs::remove(UniqueLockFileName);
188       return;
189     }
190   }
191
192   // Clean up the unique file on signal, which also releases the lock if it is
193   // held since the .lock symlink will point to a nonexistent file.
194   RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
195
196   while (1) {
197     // Create a link from the lock file name. If this succeeds, we're done.
198     std::error_code EC =
199         sys::fs::create_link(UniqueLockFileName, LockFileName);
200     if (!EC) {
201       RemoveUniqueFile.lockAcquired();
202       return;
203     }
204
205     if (EC != errc::file_exists) {
206       Error = EC;
207       return;
208     }
209
210     // Someone else managed to create the lock file first. Read the process ID
211     // from the lock file.
212     if ((Owner = readLockFile(LockFileName))) {
213       // Wipe out our unique lock file (it's useless now)
214       sys::fs::remove(UniqueLockFileName);
215       return;
216     }
217
218     if (!sys::fs::exists(LockFileName)) {
219       // The previous owner released the lock file before we could read it.
220       // Try to get ownership again.
221       continue;
222     }
223
224     // There is a lock file that nobody owns; try to clean it up and get
225     // ownership.
226     if ((EC = sys::fs::remove(LockFileName))) {
227       Error = EC;
228       return;
229     }
230   }
231 }
232
233 LockFileManager::LockFileState LockFileManager::getState() const {
234   if (Owner)
235     return LFS_Shared;
236
237   if (Error)
238     return LFS_Error;
239
240   return LFS_Owned;
241 }
242
243 LockFileManager::~LockFileManager() {
244   if (getState() != LFS_Owned)
245     return;
246
247   // Since we own the lock, remove the lock file and our own unique lock file.
248   sys::fs::remove(LockFileName);
249   sys::fs::remove(UniqueLockFileName);
250   // The unique file is now gone, so remove it from the signal handler. This
251   // matches a sys::RemoveFileOnSignal() in LockFileManager().
252   sys::DontRemoveFileOnSignal(UniqueLockFileName);
253 }
254
255 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
256   if (getState() != LFS_Shared)
257     return Res_Success;
258
259 #if LLVM_ON_WIN32
260   unsigned long Interval = 1;
261 #else
262   struct timespec Interval;
263   Interval.tv_sec = 0;
264   Interval.tv_nsec = 1000000;
265 #endif
266   // Don't wait more than five minutes per iteration. Total timeout for the file
267   // to appear is ~8.5 mins.
268   const unsigned MaxSeconds = 5*60;
269   do {
270     // Sleep for the designated interval, to allow the owning process time to
271     // finish up and remove the lock file.
272     // FIXME: Should we hook in to system APIs to get a notification when the
273     // lock file is deleted?
274 #if LLVM_ON_WIN32
275     Sleep(Interval);
276 #else
277     nanosleep(&Interval, nullptr);
278 #endif
279
280     if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
281         errc::no_such_file_or_directory) {
282       // If the original file wasn't created, somone thought the lock was dead.
283       if (!sys::fs::exists(FileName))
284         return Res_OwnerDied;
285       return Res_Success;
286     }
287
288     // If the process owning the lock died without cleaning up, just bail out.
289     if (!processStillExecuting((*Owner).first, (*Owner).second))
290       return Res_OwnerDied;
291
292     // Exponentially increase the time we wait for the lock to be removed.
293 #if LLVM_ON_WIN32
294     Interval *= 2;
295 #else
296     Interval.tv_sec *= 2;
297     Interval.tv_nsec *= 2;
298     if (Interval.tv_nsec >= 1000000000) {
299       ++Interval.tv_sec;
300       Interval.tv_nsec -= 1000000000;
301     }
302 #endif
303   } while (
304 #if LLVM_ON_WIN32
305            Interval < MaxSeconds * 1000
306 #else
307            Interval.tv_sec < (time_t)MaxSeconds
308 #endif
309            );
310
311   // Give up.
312   return Res_Timeout;
313 }
314
315 std::error_code LockFileManager::unsafeRemoveLockFile() {
316   return sys::fs::remove(LockFileName);
317 }