blob: 88489a658953f934461fd78b08a490a01743d27d [file] [log] [blame]
Douglas Gregor7039e352012-01-29 20:15:10 +00001//===--- LockFileManager.cpp - File-level Locking Utility------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregor7039e352012-01-29 20:15:10 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko33d7b762016-08-23 17:14:32 +00008
Douglas Gregor7039e352012-01-29 20:15:10 +00009#include "llvm/Support/LockFileManager.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000010#include "llvm/ADT/None.h"
11#include "llvm/ADT/SmallVector.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000012#include "llvm/ADT/StringExtras.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000013#include "llvm/Support/Errc.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000014#include "llvm/Support/ErrorOr.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000015#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000016#include "llvm/Support/MemoryBuffer.h"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000017#include "llvm/Support/Signals.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include <cerrno>
Ladd Van Tola2086232020-03-23 14:16:55 -070020#include <chrono>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000021#include <ctime>
22#include <memory>
Ladd Van Tola2086232020-03-23 14:16:55 -070023#include <random>
Douglas Gregor7039e352012-01-29 20:15:10 +000024#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include <sys/types.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include <system_error>
Ladd Van Tola2086232020-03-23 14:16:55 -070027#include <thread>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include <tuple>
Ladd Van Tola2086232020-03-23 14:16:55 -070029
Sven van Haastregt0dfbf6b2018-08-23 09:42:58 +000030#ifdef _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +000031#include <windows.h>
32#endif
33#if LLVM_ON_UNIX
34#include <unistd.h>
35#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000036
37#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
38#define USE_OSX_GETHOSTUUID 1
39#else
40#define USE_OSX_GETHOSTUUID 0
41#endif
42
43#if USE_OSX_GETHOSTUUID
44#include <uuid/uuid.h>
45#endif
Eugene Zelenko33d7b762016-08-23 17:14:32 +000046
Douglas Gregor7039e352012-01-29 20:15:10 +000047using namespace llvm;
48
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000049/// Attempt to read the lock file with the given name, if it exists.
Douglas Gregor7039e352012-01-29 20:15:10 +000050///
51/// \param LockFileName The name of the lock file to read.
52///
53/// \returns The process ID of the process that owns this lock file
54Optional<std::pair<std::string, int> >
55LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000056 // Read the owning host and PID out of the lock file. If it appears that the
57 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000058 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
59 MemoryBuffer::getFile(LockFileName);
60 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000061 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000062 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000063 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000064 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000065
66 StringRef Hostname;
67 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000068 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000069 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
70 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000071 if (!PIDStr.getAsInteger(10, PID)) {
72 auto Owner = std::make_pair(std::string(Hostname), PID);
73 if (processStillExecuting(Owner.first, Owner.second))
74 return Owner;
75 }
Douglas Gregor7039e352012-01-29 20:15:10 +000076
77 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000078 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000079 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000080}
81
Ben Langmuir450461c2015-06-29 22:16:39 +000082static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
83 HostID.clear();
84
85#if USE_OSX_GETHOSTUUID
86 // On OS X, use the more stable hardware UUID instead of hostname.
87 struct timespec wait = {1, 0}; // 1 second.
88 uuid_t uuid;
89 if (gethostuuid(uuid, &wait) != 0)
90 return std::error_code(errno, std::system_category());
91
92 uuid_string_t UUIDStr;
93 uuid_unparse(uuid, UUIDStr);
94 StringRef UUIDRef(UUIDStr);
95 HostID.append(UUIDRef.begin(), UUIDRef.end());
96
97#elif LLVM_ON_UNIX
98 char HostName[256];
99 HostName[255] = 0;
100 HostName[0] = 0;
101 gethostname(HostName, 255);
102 StringRef HostNameRef(HostName);
103 HostID.append(HostNameRef.begin(), HostNameRef.end());
104
105#else
106 StringRef Dummy("localhost");
107 HostID.append(Dummy.begin(), Dummy.end());
108#endif
109
110 return std::error_code();
111}
112
113bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000114#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000115 SmallString<256> StoredHostID;
116 if (getHostID(StoredHostID))
117 return true; // Conservatively assume it's executing on error.
118
Douglas Gregor7039e352012-01-29 20:15:10 +0000119 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000120 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000121 return false;
122#endif
123
124 return true;
125}
126
Peter Collingbourne881ba102018-06-13 18:03:14 +0000127namespace {
128
129/// An RAII helper object ensure that the unique lock file is removed.
130///
131/// Ensures that if there is an error or a signal before we finish acquiring the
132/// lock, the unique file will be removed. And if we successfully take the lock,
133/// the signal handler is left in place so that signals while the lock is held
134/// will remove the unique lock file. The caller should ensure there is a
135/// matching call to sys::DontRemoveFileOnSignal when the lock is released.
136class RemoveUniqueLockFileOnSignal {
137 StringRef Filename;
138 bool RemoveImmediately;
139public:
140 RemoveUniqueLockFileOnSignal(StringRef Name)
141 : Filename(Name), RemoveImmediately(true) {
142 sys::RemoveFileOnSignal(Filename, nullptr);
143 }
144
145 ~RemoveUniqueLockFileOnSignal() {
146 if (!RemoveImmediately) {
147 // Leave the signal handler enabled. It will be removed when the lock is
148 // released.
149 return;
150 }
151 sys::fs::remove(Filename);
152 sys::DontRemoveFileOnSignal(Filename);
153 }
154
155 void lockAcquired() { RemoveImmediately = false; }
156};
157
158} // end anonymous namespace
159
Douglas Gregor7039e352012-01-29 20:15:10 +0000160LockFileManager::LockFileManager(StringRef FileName)
161{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000162 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000163 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000164 std::string S("failed to obtain absolute path for ");
Benjamin Krameradcd0262020-01-28 20:23:46 +0100165 S.append(std::string(this->FileName.str()));
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000166 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000167 return;
168 }
169 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000170 LockFileName += ".lock";
171
172 // If the lock file already exists, don't bother to try to create our own
173 // lock file; it won't work anyway. Just figure out who owns this lock file.
174 if ((Owner = readLockFile(LockFileName)))
175 return;
176
177 // Create a lock file that is unique to this instance.
Peter Collingbourne881ba102018-06-13 18:03:14 +0000178 UniqueLockFileName = LockFileName;
179 UniqueLockFileName += "-%%%%%%%%";
180 int UniqueLockFileID;
181 if (std::error_code EC = sys::fs::createUniqueFile(
182 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
183 std::string S("failed to create unique file ");
Benjamin Krameradcd0262020-01-28 20:23:46 +0100184 S.append(std::string(UniqueLockFileName.str()));
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000185 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000186 return;
187 }
188
189 // Write our process ID to our unique lock file.
190 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000191 SmallString<256> HostID;
192 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000193 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000194 return;
195 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000196
Peter Collingbourne881ba102018-06-13 18:03:14 +0000197 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
Ben Langmuir450461c2015-06-29 22:16:39 +0000198 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000199#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000200 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000201#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000202 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000203#endif
Peter Collingbourne881ba102018-06-13 18:03:14 +0000204 Out.close();
Douglas Gregor7039e352012-01-29 20:15:10 +0000205
206 if (Out.has_error()) {
Bob Haarman9ce2d032017-10-24 01:26:22 +0000207 // We failed to write out PID, so report the error, remove the
Douglas Gregor7039e352012-01-29 20:15:10 +0000208 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000209 std::string S("failed to write to ");
Benjamin Krameradcd0262020-01-28 20:23:46 +0100210 S.append(std::string(UniqueLockFileName.str()));
Bob Haarman9ce2d032017-10-24 01:26:22 +0000211 setError(Out.error(), S);
Peter Collingbourne881ba102018-06-13 18:03:14 +0000212 sys::fs::remove(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000213 return;
214 }
215 }
216
Peter Collingbourne881ba102018-06-13 18:03:14 +0000217 // Clean up the unique file on signal, which also releases the lock if it is
218 // held since the .lock symlink will point to a nonexistent file.
219 RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
220
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000221 while (true) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000222 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000223 std::error_code EC =
Peter Collingbourne881ba102018-06-13 18:03:14 +0000224 sys::fs::create_link(UniqueLockFileName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000225 if (!EC) {
Peter Collingbourne881ba102018-06-13 18:03:14 +0000226 RemoveUniqueFile.lockAcquired();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000227 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000228 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000229
Rafael Espindola2a826e42014-06-13 17:20:48 +0000230 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000231 std::string S("failed to create link ");
232 raw_string_ostream OSS(S);
Peter Collingbourne881ba102018-06-13 18:03:14 +0000233 OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000234 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000235 return;
236 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000237
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000238 // Someone else managed to create the lock file first. Read the process ID
239 // from the lock file.
Peter Collingbourne881ba102018-06-13 18:03:14 +0000240 if ((Owner = readLockFile(LockFileName))) {
241 // Wipe out our unique lock file (it's useless now)
242 sys::fs::remove(UniqueLockFileName);
243 return;
244 }
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000245
Yaron Keren92e1b622015-03-18 10:17:07 +0000246 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000247 // The previous owner released the lock file before we could read it.
248 // Try to get ownership again.
249 continue;
250 }
251
252 // There is a lock file that nobody owns; try to clean it up and get
253 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000254 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000255 std::string S("failed to remove lockfile ");
Benjamin Krameradcd0262020-01-28 20:23:46 +0100256 S.append(std::string(UniqueLockFileName.str()));
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000257 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000258 return;
259 }
260 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000261}
262
263LockFileManager::LockFileState LockFileManager::getState() const {
264 if (Owner)
265 return LFS_Shared;
266
Rafael Espindola8c42d322017-11-13 23:32:19 +0000267 if (ErrorCode)
Douglas Gregor7039e352012-01-29 20:15:10 +0000268 return LFS_Error;
269
270 return LFS_Owned;
271}
272
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000273std::string LockFileManager::getErrorMessage() const {
Rafael Espindola8c42d322017-11-13 23:32:19 +0000274 if (ErrorCode) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000275 std::string Str(ErrorDiagMsg);
Rafael Espindola8c42d322017-11-13 23:32:19 +0000276 std::string ErrCodeMsg = ErrorCode.message();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000277 raw_string_ostream OSS(Str);
278 if (!ErrCodeMsg.empty())
Rafael Espindolac8434102017-11-13 23:06:54 +0000279 OSS << ": " << ErrCodeMsg;
280 return OSS.str();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000281 }
282 return "";
283}
284
Douglas Gregor7039e352012-01-29 20:15:10 +0000285LockFileManager::~LockFileManager() {
286 if (getState() != LFS_Owned)
287 return;
288
289 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000290 sys::fs::remove(LockFileName);
Peter Collingbourne881ba102018-06-13 18:03:14 +0000291 sys::fs::remove(UniqueLockFileName);
292 // The unique file is now gone, so remove it from the signal handler. This
293 // matches a sys::RemoveFileOnSignal() in LockFileManager().
294 sys::DontRemoveFileOnSignal(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000295}
296
Vedant Kumare05e2192020-01-10 15:24:30 -0800297LockFileManager::WaitForUnlockResult
298LockFileManager::waitForUnlock(const unsigned MaxSeconds) {
Douglas Gregor7039e352012-01-29 20:15:10 +0000299 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000300 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000301
Ladd Van Tola2086232020-03-23 14:16:55 -0700302 // Since we don't yet have an event-based method to wait for the lock file,
303 // implement randomized exponential backoff, similar to Ethernet collision
304 // algorithm. This improves performance on machines with high core counts
305 // when the file lock is heavily contended by multiple clang processes
306 const unsigned long MinWaitDurationMS = 10;
307 const unsigned long MaxWaitMultiplier = 50; // 500ms max wait
308 unsigned long WaitMultiplier = 1;
309 unsigned long ElapsedTimeSeconds = 0;
310
311 std::random_device Device;
312 std::default_random_engine Engine(Device());
313
314 auto StartTime = std::chrono::steady_clock::now();
315
Douglas Gregor7039e352012-01-29 20:15:10 +0000316 do {
Ladd Van Tola2086232020-03-23 14:16:55 -0700317 // FIXME: implement event-based waiting
318
Douglas Gregor7039e352012-01-29 20:15:10 +0000319 // Sleep for the designated interval, to allow the owning process time to
320 // finish up and remove the lock file.
Ladd Van Tola2086232020-03-23 14:16:55 -0700321 std::uniform_int_distribution<unsigned long> Distribution(1,
322 WaitMultiplier);
323 unsigned long WaitDurationMS = MinWaitDurationMS * Distribution(Engine);
324 std::this_thread::sleep_for(std::chrono::milliseconds(WaitDurationMS));
Douglas Gregor0cb68462013-04-05 20:53:57 +0000325
Ben Langmuir08970912015-02-19 18:22:35 +0000326 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
327 errc::no_such_file_or_directory) {
328 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000329 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000330 return Res_OwnerDied;
331 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000332 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000333
Ben Langmuir08970912015-02-19 18:22:35 +0000334 // If the process owning the lock died without cleaning up, just bail out.
335 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000336 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000337
Ladd Van Tola2086232020-03-23 14:16:55 -0700338 WaitMultiplier *= 2;
339 if (WaitMultiplier > MaxWaitMultiplier) {
340 WaitMultiplier = MaxWaitMultiplier;
Douglas Gregor7039e352012-01-29 20:15:10 +0000341 }
Ladd Van Tola2086232020-03-23 14:16:55 -0700342
343 ElapsedTimeSeconds = std::chrono::duration_cast<std::chrono::seconds>(
344 std::chrono::steady_clock::now() - StartTime)
345 .count();
346
347 } while (ElapsedTimeSeconds < MaxSeconds);
Douglas Gregor7039e352012-01-29 20:15:10 +0000348
349 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000350 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000351}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000352
353std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000354 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000355}