[Support] Make sure sys::fs::remove can remove symbolic links and make sure LockFileM...
[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/STLExtras.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/Support/FileSystem.h"
13 #include "llvm/Support/MemoryBuffer.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #if LLVM_ON_WIN32
18 #include <windows.h>
19 #endif
20 #if LLVM_ON_UNIX
21 #include <unistd.h>
22 #endif
23 using namespace llvm;
24
25 /// \brief Attempt to read the lock file with the given name, if it exists.
26 ///
27 /// \param LockFileName The name of the lock file to read.
28 ///
29 /// \returns The process ID of the process that owns this lock file
30 Optional<std::pair<std::string, int> >
31 LockFileManager::readLockFile(StringRef LockFileName) {
32   // Read the owning host and PID out of the lock file. If it appears that the
33   // owning process is dead, the lock file is invalid.
34   std::unique_ptr<MemoryBuffer> MB;
35   if (MemoryBuffer::getFile(LockFileName, MB)) {
36     sys::fs::remove(LockFileName);
37     return None;
38   }
39
40   StringRef Hostname;
41   StringRef PIDStr;
42   std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
43   PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
44   int PID;
45   if (!PIDStr.getAsInteger(10, PID))
46     return std::make_pair(std::string(Hostname), PID);
47
48   // Delete the lock file. It's invalid anyway.
49   sys::fs::remove(LockFileName);
50   return None;
51 }
52
53 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
54 #if LLVM_ON_UNIX && !defined(__ANDROID__)
55   char MyHostname[256];
56   MyHostname[255] = 0;
57   MyHostname[0] = 0;
58   gethostname(MyHostname, 255);
59   // Check whether the process is dead. If so, we're done.
60   if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
61     return false;
62 #endif
63
64   return true;
65 }
66
67 LockFileManager::LockFileManager(StringRef FileName)
68 {
69   this->FileName = FileName;
70   LockFileName = FileName;
71   LockFileName += ".lock";
72
73   // If the lock file already exists, don't bother to try to create our own
74   // lock file; it won't work anyway. Just figure out who owns this lock file.
75   if ((Owner = readLockFile(LockFileName)))
76     return;
77
78   // Create a lock file that is unique to this instance.
79   UniqueLockFileName = LockFileName;
80   UniqueLockFileName += "-%%%%%%%%";
81   int UniqueLockFileID;
82   if (error_code EC
83         = sys::fs::createUniqueFile(UniqueLockFileName.str(),
84                                     UniqueLockFileID,
85                                     UniqueLockFileName)) {
86     Error = EC;
87     return;
88   }
89
90   // Write our process ID to our unique lock file.
91   {
92     raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
93
94 #if LLVM_ON_UNIX
95     // FIXME: move getpid() call into LLVM
96     char hostname[256];
97     hostname[255] = 0;
98     hostname[0] = 0;
99     gethostname(hostname, 255);
100     Out << hostname << ' ' << getpid();
101 #else
102     Out << "localhost 1";
103 #endif
104     Out.close();
105
106     if (Out.has_error()) {
107       // We failed to write out PID, so make up an excuse, remove the
108       // unique lock file, and fail.
109       Error = make_error_code(errc::no_space_on_device);
110       sys::fs::remove(UniqueLockFileName.c_str());
111       return;
112     }
113   }
114
115   while (1) {
116     // Create a link from the lock file name. If this succeeds, we're done.
117     error_code EC =
118         sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
119     if (EC == errc::success)
120       return;
121
122     if (EC != errc::file_exists) {
123       Error = EC;
124       return;
125     }
126
127     // Someone else managed to create the lock file first. Read the process ID
128     // from the lock file.
129     if ((Owner = readLockFile(LockFileName))) {
130       // Wipe out our unique lock file (it's useless now)
131       sys::fs::remove(UniqueLockFileName.str());
132       return;
133     }
134
135     if (!sys::fs::exists(LockFileName.str())) {
136       // The previous owner released the lock file before we could read it.
137       // Try to get ownership again.
138       continue;
139     }
140
141     // There is a lock file that nobody owns; try to clean it up and get
142     // ownership.
143     if ((EC = sys::fs::remove(LockFileName.str()))) {
144       Error = EC;
145       return;
146     }
147   }
148 }
149
150 LockFileManager::LockFileState LockFileManager::getState() const {
151   if (Owner)
152     return LFS_Shared;
153
154   if (Error)
155     return LFS_Error;
156
157   return LFS_Owned;
158 }
159
160 LockFileManager::~LockFileManager() {
161   if (getState() != LFS_Owned)
162     return;
163
164   // Since we own the lock, remove the lock file and our own unique lock file.
165   sys::fs::remove(LockFileName.str());
166   sys::fs::remove(UniqueLockFileName.str());
167 }
168
169 void LockFileManager::waitForUnlock() {
170   if (getState() != LFS_Shared)
171     return;
172
173 #if LLVM_ON_WIN32
174   unsigned long Interval = 1;
175 #else
176   struct timespec Interval;
177   Interval.tv_sec = 0;
178   Interval.tv_nsec = 1000000;
179 #endif
180   // Don't wait more than five minutes for the file to appear.
181   unsigned MaxSeconds = 300;
182   bool LockFileGone = false;
183   do {
184     // Sleep for the designated interval, to allow the owning process time to
185     // finish up and remove the lock file.
186     // FIXME: Should we hook in to system APIs to get a notification when the
187     // lock file is deleted?
188 #if LLVM_ON_WIN32
189     Sleep(Interval);
190 #else
191     nanosleep(&Interval, NULL);
192 #endif
193     bool LockFileJustDisappeared = false;
194
195     // If the lock file is still expected to be there, check whether it still
196     // is.
197     if (!LockFileGone) {
198       bool Exists;
199       if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
200         LockFileGone = true;
201         LockFileJustDisappeared = true;
202       }
203     }
204
205     // If the lock file is no longer there, check if the original file is
206     // available now.
207     if (LockFileGone) {
208       if (sys::fs::exists(FileName.str())) {
209         return;
210       }
211
212       // The lock file is gone, so now we're waiting for the original file to
213       // show up. If this just happened, reset our waiting intervals and keep
214       // waiting.
215       if (LockFileJustDisappeared) {
216         MaxSeconds = 5;
217
218 #if LLVM_ON_WIN32
219         Interval = 1;
220 #else
221         Interval.tv_sec = 0;
222         Interval.tv_nsec = 1000000;
223 #endif
224         continue;
225       }
226     }
227
228     // If we're looking for the lock file to disappear, but the process
229     // owning the lock died without cleaning up, just bail out.
230     if (!LockFileGone &&
231         !processStillExecuting((*Owner).first, (*Owner).second)) {
232       return;
233     }
234
235     // Exponentially increase the time we wait for the lock to be removed.
236 #if LLVM_ON_WIN32
237     Interval *= 2;
238 #else
239     Interval.tv_sec *= 2;
240     Interval.tv_nsec *= 2;
241     if (Interval.tv_nsec >= 1000000000) {
242       ++Interval.tv_sec;
243       Interval.tv_nsec -= 1000000000;
244     }
245 #endif
246   } while (
247 #if LLVM_ON_WIN32
248            Interval < MaxSeconds * 1000
249 #else
250            Interval.tv_sec < (time_t)MaxSeconds
251 #endif
252            );
253
254   // Give up.
255 }