blob: ec951f33a36a757cb559348eb25e705e2a703b33 [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"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000018#include "llvm/Support/Signals.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include <cerrno>
21#include <ctime>
22#include <memory>
Douglas Gregor7039e352012-01-29 20:15:10 +000023#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <sys/types.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include <system_error>
26#include <tuple>
Douglas Gregor7039e352012-01-29 20:15:10 +000027#if LLVM_ON_WIN32
28#include <windows.h>
29#endif
30#if LLVM_ON_UNIX
31#include <unistd.h>
32#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000033
34#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
35#define USE_OSX_GETHOSTUUID 1
36#else
37#define USE_OSX_GETHOSTUUID 0
38#endif
39
40#if USE_OSX_GETHOSTUUID
41#include <uuid/uuid.h>
42#endif
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043
Douglas Gregor7039e352012-01-29 20:15:10 +000044using namespace llvm;
45
46/// \brief Attempt to read the lock file with the given name, if it exists.
47///
48/// \param LockFileName The name of the lock file to read.
49///
50/// \returns The process ID of the process that owns this lock file
51Optional<std::pair<std::string, int> >
52LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000053 // Read the owning host and PID out of the lock file. If it appears that the
54 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000055 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
56 MemoryBuffer::getFile(LockFileName);
57 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000058 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000059 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000060 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000061 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000062
63 StringRef Hostname;
64 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000065 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000066 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
67 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000068 if (!PIDStr.getAsInteger(10, PID)) {
69 auto Owner = std::make_pair(std::string(Hostname), PID);
70 if (processStillExecuting(Owner.first, Owner.second))
71 return Owner;
72 }
Douglas Gregor7039e352012-01-29 20:15:10 +000073
74 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000075 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000076 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000077}
78
Ben Langmuir450461c2015-06-29 22:16:39 +000079static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
80 HostID.clear();
81
82#if USE_OSX_GETHOSTUUID
83 // On OS X, use the more stable hardware UUID instead of hostname.
84 struct timespec wait = {1, 0}; // 1 second.
85 uuid_t uuid;
86 if (gethostuuid(uuid, &wait) != 0)
87 return std::error_code(errno, std::system_category());
88
89 uuid_string_t UUIDStr;
90 uuid_unparse(uuid, UUIDStr);
91 StringRef UUIDRef(UUIDStr);
92 HostID.append(UUIDRef.begin(), UUIDRef.end());
93
94#elif LLVM_ON_UNIX
95 char HostName[256];
96 HostName[255] = 0;
97 HostName[0] = 0;
98 gethostname(HostName, 255);
99 StringRef HostNameRef(HostName);
100 HostID.append(HostNameRef.begin(), HostNameRef.end());
101
102#else
103 StringRef Dummy("localhost");
104 HostID.append(Dummy.begin(), Dummy.end());
105#endif
106
107 return std::error_code();
108}
109
110bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000111#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000112 SmallString<256> StoredHostID;
113 if (getHostID(StoredHostID))
114 return true; // Conservatively assume it's executing on error.
115
Douglas Gregor7039e352012-01-29 20:15:10 +0000116 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000117 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000118 return false;
119#endif
120
121 return true;
122}
123
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000124namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000125
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000126/// An RAII helper object for cleanups.
127class RAIICleanup {
128 std::function<void()> Fn;
129 bool Canceled = false;
130
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000131public:
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000132 RAIICleanup(std::function<void()> Fn) : Fn(Fn) {}
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000133
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000134 ~RAIICleanup() {
135 if (Canceled)
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000136 return;
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000137 Fn();
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000138 }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000139
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000140 void cancel() { Canceled = true; }
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000141};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000142
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000143} // end anonymous namespace
144
Douglas Gregor7039e352012-01-29 20:15:10 +0000145LockFileManager::LockFileManager(StringRef FileName)
146{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000147 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000148 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000149 std::string S("failed to obtain absolute path for ");
150 S.append(this->FileName.str());
151 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000152 return;
153 }
154 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000155 LockFileName += ".lock";
156
157 // If the lock file already exists, don't bother to try to create our own
158 // lock file; it won't work anyway. Just figure out who owns this lock file.
159 if ((Owner = readLockFile(LockFileName)))
160 return;
161
162 // Create a lock file that is unique to this instance.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000163 Expected<sys::fs::TempFile> Temp =
164 sys::fs::TempFile::create(LockFileName + "-%%%%%%%%");
165 if (!Temp) {
166 std::error_code EC = errorToErrorCode(Temp.takeError());
167 std::string S("failed to create unique file with prefix ");
168 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000169 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000170 return;
171 }
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000172 UniqueLockFile = std::move(*Temp);
173
174 // Make sure we discard the temporary file on exit.
175 RAIICleanup RemoveTempFile([&]() {
176 if (Error E = UniqueLockFile->discard())
177 setError(errorToErrorCode(std::move(E)));
178 });
Douglas Gregor7039e352012-01-29 20:15:10 +0000179
180 // Write our process ID to our unique lock file.
181 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000182 SmallString<256> HostID;
183 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000184 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000185 return;
186 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000187
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000188 raw_fd_ostream Out(UniqueLockFile->FD, /*shouldClose=*/false);
Ben Langmuir450461c2015-06-29 22:16:39 +0000189 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000190#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000191 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000192#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000193 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000194#endif
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000195 Out.flush();
Douglas Gregor7039e352012-01-29 20:15:10 +0000196
197 if (Out.has_error()) {
Bob Haarman9ce2d032017-10-24 01:26:22 +0000198 // We failed to write out PID, so report the error, remove the
Douglas Gregor7039e352012-01-29 20:15:10 +0000199 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000200 std::string S("failed to write to ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000201 S.append(UniqueLockFile->TmpName);
Bob Haarman9ce2d032017-10-24 01:26:22 +0000202 setError(Out.error(), S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000203 return;
204 }
205 }
206
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000207 while (true) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000208 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000209 std::error_code EC =
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000210 sys::fs::create_link(UniqueLockFile->TmpName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000211 if (!EC) {
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000212 RemoveTempFile.cancel();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000213 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000214 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000215
Rafael Espindola2a826e42014-06-13 17:20:48 +0000216 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000217 std::string S("failed to create link ");
218 raw_string_ostream OSS(S);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000219 OSS << LockFileName.str() << " to " << UniqueLockFile->TmpName;
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000220 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000221 return;
222 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000223
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000224 // Someone else managed to create the lock file first. Read the process ID
225 // from the lock file.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000226 if ((Owner = readLockFile(LockFileName)))
227 return; // RemoveTempFile will delete out our unique lock file.
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000228
Yaron Keren92e1b622015-03-18 10:17:07 +0000229 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000230 // The previous owner released the lock file before we could read it.
231 // Try to get ownership again.
232 continue;
233 }
234
235 // There is a lock file that nobody owns; try to clean it up and get
236 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000237 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000238 std::string S("failed to remove lockfile ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000239 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000240 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000241 return;
242 }
243 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000244}
245
246LockFileManager::LockFileState LockFileManager::getState() const {
247 if (Owner)
248 return LFS_Shared;
249
Rafael Espindola8c42d322017-11-13 23:32:19 +0000250 if (ErrorCode)
Douglas Gregor7039e352012-01-29 20:15:10 +0000251 return LFS_Error;
252
253 return LFS_Owned;
254}
255
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000256std::string LockFileManager::getErrorMessage() const {
Rafael Espindola8c42d322017-11-13 23:32:19 +0000257 if (ErrorCode) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000258 std::string Str(ErrorDiagMsg);
Rafael Espindola8c42d322017-11-13 23:32:19 +0000259 std::string ErrCodeMsg = ErrorCode.message();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000260 raw_string_ostream OSS(Str);
261 if (!ErrCodeMsg.empty())
Rafael Espindolac8434102017-11-13 23:06:54 +0000262 OSS << ": " << ErrCodeMsg;
263 return OSS.str();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000264 }
265 return "";
266}
267
Douglas Gregor7039e352012-01-29 20:15:10 +0000268LockFileManager::~LockFileManager() {
269 if (getState() != LFS_Owned)
270 return;
271
272 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000273 sys::fs::remove(LockFileName);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000274 consumeError(UniqueLockFile->discard());
Douglas Gregor7039e352012-01-29 20:15:10 +0000275}
276
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000277LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000278 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000279 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000280
281#if LLVM_ON_WIN32
282 unsigned long Interval = 1;
283#else
284 struct timespec Interval;
285 Interval.tv_sec = 0;
286 Interval.tv_nsec = 1000000;
287#endif
Bruno Cardoso Lopes8fef5552017-03-18 00:32:34 +0000288 // Don't wait more than 40s per iteration. Total timeout for the file
289 // to appear is ~1.5 minutes.
290 const unsigned MaxSeconds = 40;
Douglas Gregor7039e352012-01-29 20:15:10 +0000291 do {
292 // Sleep for the designated interval, to allow the owning process time to
293 // finish up and remove the lock file.
294 // FIXME: Should we hook in to system APIs to get a notification when the
295 // lock file is deleted?
296#if LLVM_ON_WIN32
297 Sleep(Interval);
298#else
Craig Topperc10719f2014-04-07 04:17:22 +0000299 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000300#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000301
Ben Langmuir08970912015-02-19 18:22:35 +0000302 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
303 errc::no_such_file_or_directory) {
304 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000305 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000306 return Res_OwnerDied;
307 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000308 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000309
Ben Langmuir08970912015-02-19 18:22:35 +0000310 // If the process owning the lock died without cleaning up, just bail out.
311 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000312 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000313
314 // Exponentially increase the time we wait for the lock to be removed.
315#if LLVM_ON_WIN32
316 Interval *= 2;
317#else
318 Interval.tv_sec *= 2;
319 Interval.tv_nsec *= 2;
320 if (Interval.tv_nsec >= 1000000000) {
321 ++Interval.tv_sec;
322 Interval.tv_nsec -= 1000000000;
323 }
324#endif
325 } while (
326#if LLVM_ON_WIN32
327 Interval < MaxSeconds * 1000
328#else
329 Interval.tv_sec < (time_t)MaxSeconds
330#endif
331 );
332
333 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000334 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000335}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000336
337std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000338 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000339}