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