blob: c8472d880554fe409768ecd583c11ca215b9e91d [file] [log] [blame]
Douglas Gregor7039e352012-01-29 20:15:10 +00001//===--- 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"
Reid Klecknerd78273f2013-08-06 22:51:21 +000010#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/StringExtras.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000012#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000013#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000014#include "llvm/Support/raw_ostream.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000015#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include <sys/types.h>
Douglas Gregor7039e352012-01-29 20:15:10 +000017#if LLVM_ON_WIN32
18#include <windows.h>
19#endif
20#if LLVM_ON_UNIX
21#include <unistd.h>
22#endif
23using 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
30Optional<std::pair<std::string, int> >
31LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000032 // 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.
Ahmed Charles56440fd2014-03-06 05:51:42 +000034 std::unique_ptr<MemoryBuffer> MB;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000035 if (MemoryBuffer::getFile(LockFileName, MB)) {
36 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000037 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000038 }
Reid Kleckner7de8ea32013-08-07 01:22:04 +000039
40 StringRef Hostname;
41 StringRef PIDStr;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +000042 std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000043 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);
Douglas Gregor7039e352012-01-29 20:15:10 +000047
48 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000049 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000050 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000051}
52
53bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +000054#if LLVM_ON_UNIX && !defined(__ANDROID__)
Douglas Gregor7039e352012-01-29 20:15:10 +000055 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
67LockFileManager::LockFileManager(StringRef FileName)
68{
Douglas Gregor056eafd2013-01-10 02:01:35 +000069 this->FileName = FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +000070 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
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +000083 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
84 UniqueLockFileID,
85 UniqueLockFileName)) {
Douglas Gregor7039e352012-01-29 20:15:10 +000086 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);
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000110 sys::fs::remove(UniqueLockFileName.c_str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000111 return;
112 }
113 }
114
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000115 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000116 // 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());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000119 if (EC == errc::success)
120 return;
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000121
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000122 if (EC != errc::file_exists) {
123 Error = EC;
124 return;
125 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000126
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000127 // 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 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000148}
149
150LockFileManager::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
160LockFileManager::~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.
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000165 sys::fs::remove(LockFileName.str());
166 sys::fs::remove(UniqueLockFileName.str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000167}
168
169void 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
Douglas Gregor0cb68462013-04-05 20:53:57 +0000180 // Don't wait more than five minutes for the file to appear.
181 unsigned MaxSeconds = 300;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000182 bool LockFileGone = false;
Douglas Gregor7039e352012-01-29 20:15:10 +0000183 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
Douglas Gregor0cb68462013-04-05 20:53:57 +0000193 bool LockFileJustDisappeared = false;
194
195 // If the lock file is still expected to be there, check whether it still
196 // is.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000197 if (!LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000198 bool Exists;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000199 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
200 LockFileGone = true;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000201 LockFileJustDisappeared = true;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000202 }
203 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000204
205 // If the lock file is no longer there, check if the original file is
206 // available now.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000207 if (LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000208 if (sys::fs::exists(FileName.str())) {
Douglas Gregor056eafd2013-01-10 02:01:35 +0000209 return;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000210 }
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 }
Douglas Gregor056eafd2013-01-10 02:01:35 +0000226 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000227
Douglas Gregor0cb68462013-04-05 20:53:57 +0000228 // 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)) {
Douglas Gregor7039e352012-01-29 20:15:10 +0000232 return;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000233 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000234
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}