blob: 357d0e378568bdaa10f8360b3e3ff6f03746393f [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//===----------------------------------------------------------------------===//
Eugene Zelenko33d7b762016-08-23 17:14:32 +00009
Douglas Gregor7039e352012-01-29 20:15:10 +000010#include "llvm/Support/LockFileManager.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000011#include "llvm/ADT/None.h"
12#include "llvm/ADT/SmallVector.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000013#include "llvm/ADT/StringExtras.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000014#include "llvm/Support/Errc.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/Support/ErrorOr.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000016#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000017#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000018#include "llvm/Support/raw_ostream.h"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000019#include "llvm/Support/Signals.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include <cerrno>
21#include <ctime>
22#include <memory>
23#include <tuple>
Douglas Gregor7039e352012-01-29 20:15:10 +000024#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include <sys/types.h>
Douglas Gregor7039e352012-01-29 20:15:10 +000026#if LLVM_ON_WIN32
27#include <windows.h>
28#endif
29#if LLVM_ON_UNIX
30#include <unistd.h>
31#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000032
33#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
34#define USE_OSX_GETHOSTUUID 1
35#else
36#define USE_OSX_GETHOSTUUID 0
37#endif
38
39#if USE_OSX_GETHOSTUUID
40#include <uuid/uuid.h>
41#endif
Eugene Zelenko33d7b762016-08-23 17:14:32 +000042
Douglas Gregor7039e352012-01-29 20:15:10 +000043using namespace llvm;
44
45/// \brief Attempt to read the lock file with the given name, if it exists.
46///
47/// \param LockFileName The name of the lock file to read.
48///
49/// \returns The process ID of the process that owns this lock file
50Optional<std::pair<std::string, int> >
51LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000052 // Read the owning host and PID out of the lock file. If it appears that the
53 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000054 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
55 MemoryBuffer::getFile(LockFileName);
56 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000057 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000058 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000059 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000060 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000061
62 StringRef Hostname;
63 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000064 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000065 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
66 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000067 if (!PIDStr.getAsInteger(10, PID)) {
68 auto Owner = std::make_pair(std::string(Hostname), PID);
69 if (processStillExecuting(Owner.first, Owner.second))
70 return Owner;
71 }
Douglas Gregor7039e352012-01-29 20:15:10 +000072
73 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000074 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000075 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000076}
77
Ben Langmuir450461c2015-06-29 22:16:39 +000078static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
79 HostID.clear();
80
81#if USE_OSX_GETHOSTUUID
82 // On OS X, use the more stable hardware UUID instead of hostname.
83 struct timespec wait = {1, 0}; // 1 second.
84 uuid_t uuid;
85 if (gethostuuid(uuid, &wait) != 0)
86 return std::error_code(errno, std::system_category());
87
88 uuid_string_t UUIDStr;
89 uuid_unparse(uuid, UUIDStr);
90 StringRef UUIDRef(UUIDStr);
91 HostID.append(UUIDRef.begin(), UUIDRef.end());
92
93#elif LLVM_ON_UNIX
94 char HostName[256];
95 HostName[255] = 0;
96 HostName[0] = 0;
97 gethostname(HostName, 255);
98 StringRef HostNameRef(HostName);
99 HostID.append(HostNameRef.begin(), HostNameRef.end());
100
101#else
102 StringRef Dummy("localhost");
103 HostID.append(Dummy.begin(), Dummy.end());
104#endif
105
106 return std::error_code();
107}
108
109bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000110#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000111 SmallString<256> StoredHostID;
112 if (getHostID(StoredHostID))
113 return true; // Conservatively assume it's executing on error.
114
Douglas Gregor7039e352012-01-29 20:15:10 +0000115 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000116 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000117 return false;
118#endif
119
120 return true;
121}
122
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000123namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000124
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000125/// An RAII helper object ensure that the unique lock file is removed.
126///
127/// Ensures that if there is an error or a signal before we finish acquiring the
128/// lock, the unique file will be removed. And if we successfully take the lock,
129/// the signal handler is left in place so that signals while the lock is held
130/// will remove the unique lock file. The caller should ensure there is a
131/// matching call to sys::DontRemoveFileOnSignal when the lock is released.
132class RemoveUniqueLockFileOnSignal {
133 StringRef Filename;
134 bool RemoveImmediately;
135public:
136 RemoveUniqueLockFileOnSignal(StringRef Name)
137 : Filename(Name), RemoveImmediately(true) {
138 sys::RemoveFileOnSignal(Filename, nullptr);
139 }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000140
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000141 ~RemoveUniqueLockFileOnSignal() {
142 if (!RemoveImmediately) {
143 // Leave the signal handler enabled. It will be removed when the lock is
144 // released.
145 return;
146 }
147 sys::fs::remove(Filename);
148 sys::DontRemoveFileOnSignal(Filename);
149 }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000150
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000151 void lockAcquired() { RemoveImmediately = false; }
152};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000153
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000154} // end anonymous namespace
155
Douglas Gregor7039e352012-01-29 20:15:10 +0000156LockFileManager::LockFileManager(StringRef FileName)
157{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000158 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000159 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000160 std::string S("failed to obtain absolute path for ");
161 S.append(this->FileName.str());
162 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000163 return;
164 }
165 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000166 LockFileName += ".lock";
167
168 // If the lock file already exists, don't bother to try to create our own
169 // lock file; it won't work anyway. Just figure out who owns this lock file.
170 if ((Owner = readLockFile(LockFileName)))
171 return;
172
173 // Create a lock file that is unique to this instance.
174 UniqueLockFileName = LockFileName;
175 UniqueLockFileName += "-%%%%%%%%";
176 int UniqueLockFileID;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000177 if (std::error_code EC = sys::fs::createUniqueFile(
Yaron Keren92e1b622015-03-18 10:17:07 +0000178 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000179 std::string S("failed to create unique file ");
180 S.append(UniqueLockFileName.str());
181 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000182 return;
183 }
184
185 // Write our process ID to our unique lock file.
186 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000187 SmallString<256> HostID;
188 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000189 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000190 return;
191 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000192
Ben Langmuir450461c2015-06-29 22:16:39 +0000193 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
194 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000195#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000196 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000197#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000198 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000199#endif
200 Out.close();
201
202 if (Out.has_error()) {
203 // We failed to write out PID, so make up an excuse, remove the
204 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000205 auto EC = make_error_code(errc::no_space_on_device);
206 std::string S("failed to write to ");
207 S.append(UniqueLockFileName.str());
208 setError(EC, S);
Yaron Keren92e1b622015-03-18 10:17:07 +0000209 sys::fs::remove(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000210 return;
211 }
212 }
213
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000214 // Clean up the unique file on signal, which also releases the lock if it is
215 // held since the .lock symlink will point to a nonexistent file.
216 RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
217
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000218 while (true) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000219 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000220 std::error_code EC =
Yaron Keren92e1b622015-03-18 10:17:07 +0000221 sys::fs::create_link(UniqueLockFileName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000222 if (!EC) {
223 RemoveUniqueFile.lockAcquired();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000224 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000225 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000226
Rafael Espindola2a826e42014-06-13 17:20:48 +0000227 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000228 std::string S("failed to create link ");
229 raw_string_ostream OSS(S);
230 OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
231 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000232 return;
233 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000234
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000235 // Someone else managed to create the lock file first. Read the process ID
236 // from the lock file.
237 if ((Owner = readLockFile(LockFileName))) {
238 // Wipe out our unique lock file (it's useless now)
Yaron Keren92e1b622015-03-18 10:17:07 +0000239 sys::fs::remove(UniqueLockFileName);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000240 return;
241 }
242
Yaron Keren92e1b622015-03-18 10:17:07 +0000243 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000244 // The previous owner released the lock file before we could read it.
245 // Try to get ownership again.
246 continue;
247 }
248
249 // There is a lock file that nobody owns; try to clean it up and get
250 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000251 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000252 std::string S("failed to remove lockfile ");
253 S.append(UniqueLockFileName.str());
254 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000255 return;
256 }
257 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000258}
259
260LockFileManager::LockFileState LockFileManager::getState() const {
261 if (Owner)
262 return LFS_Shared;
263
264 if (Error)
265 return LFS_Error;
266
267 return LFS_Owned;
268}
269
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000270std::string LockFileManager::getErrorMessage() const {
271 if (Error) {
272 std::string Str(ErrorDiagMsg);
273 std::string ErrCodeMsg = Error->message();
274 raw_string_ostream OSS(Str);
275 if (!ErrCodeMsg.empty())
276 OSS << ": " << Error->message();
277 OSS.flush();
278 return Str;
279 }
280 return "";
281}
282
Douglas Gregor7039e352012-01-29 20:15:10 +0000283LockFileManager::~LockFileManager() {
284 if (getState() != LFS_Owned)
285 return;
286
287 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000288 sys::fs::remove(LockFileName);
289 sys::fs::remove(UniqueLockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000290 // The unique file is now gone, so remove it from the signal handler. This
291 // matches a sys::RemoveFileOnSignal() in LockFileManager().
292 sys::DontRemoveFileOnSignal(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000293}
294
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000295LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000296 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000297 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000298
299#if LLVM_ON_WIN32
300 unsigned long Interval = 1;
301#else
302 struct timespec Interval;
303 Interval.tv_sec = 0;
304 Interval.tv_nsec = 1000000;
305#endif
Argyrios Kyrtzidisdc8f9792015-03-04 22:54:38 +0000306 // Don't wait more than five minutes per iteration. Total timeout for the file
307 // to appear is ~8.5 mins.
308 const unsigned MaxSeconds = 5*60;
Douglas Gregor7039e352012-01-29 20:15:10 +0000309 do {
310 // Sleep for the designated interval, to allow the owning process time to
311 // finish up and remove the lock file.
312 // FIXME: Should we hook in to system APIs to get a notification when the
313 // lock file is deleted?
314#if LLVM_ON_WIN32
315 Sleep(Interval);
316#else
Craig Topperc10719f2014-04-07 04:17:22 +0000317 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000318#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000319
Ben Langmuir08970912015-02-19 18:22:35 +0000320 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
321 errc::no_such_file_or_directory) {
322 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000323 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000324 return Res_OwnerDied;
325 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000326 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000327
Ben Langmuir08970912015-02-19 18:22:35 +0000328 // If the process owning the lock died without cleaning up, just bail out.
329 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000330 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000331
332 // Exponentially increase the time we wait for the lock to be removed.
333#if LLVM_ON_WIN32
334 Interval *= 2;
335#else
336 Interval.tv_sec *= 2;
337 Interval.tv_nsec *= 2;
338 if (Interval.tv_nsec >= 1000000000) {
339 ++Interval.tv_sec;
340 Interval.tv_nsec -= 1000000000;
341 }
342#endif
343 } while (
344#if LLVM_ON_WIN32
345 Interval < MaxSeconds * 1000
346#else
347 Interval.tv_sec < (time_t)MaxSeconds
348#endif
349 );
350
351 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000352 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000353}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000354
355std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000356 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000357}