blob: d97452d08c075d359d618b2aecfd321513a8cfc8 [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"
Benjamin Kramer92387a82018-02-18 16:05:40 +000012#include "llvm/ADT/ScopeExit.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000013#include "llvm/ADT/SmallVector.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000014#include "llvm/ADT/StringExtras.h"
Nico Weber432a3882018-04-30 14:59:11 +000015#include "llvm/Config/llvm-config.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000016#include "llvm/Support/Errc.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000017#include "llvm/Support/ErrorOr.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000018#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000019#include "llvm/Support/MemoryBuffer.h"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000020#include "llvm/Support/Signals.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include <cerrno>
23#include <ctime>
24#include <memory>
Douglas Gregor7039e352012-01-29 20:15:10 +000025#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include <sys/types.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include <system_error>
28#include <tuple>
Nico Weber712e8d22018-04-29 00:45:03 +000029#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +000030#include <windows.h>
31#endif
32#if LLVM_ON_UNIX
33#include <unistd.h>
34#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000035
36#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
37#define USE_OSX_GETHOSTUUID 1
38#else
39#define USE_OSX_GETHOSTUUID 0
40#endif
41
42#if USE_OSX_GETHOSTUUID
43#include <uuid/uuid.h>
44#endif
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045
Douglas Gregor7039e352012-01-29 20:15:10 +000046using namespace llvm;
47
48/// \brief Attempt to read the lock file with the given name, if it exists.
49///
50/// \param LockFileName The name of the lock file to read.
51///
52/// \returns The process ID of the process that owns this lock file
53Optional<std::pair<std::string, int> >
54LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000055 // Read the owning host and PID out of the lock file. If it appears that the
56 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000057 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
58 MemoryBuffer::getFile(LockFileName);
59 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000060 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000061 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000062 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000063 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000064
65 StringRef Hostname;
66 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000067 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000068 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
69 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000070 if (!PIDStr.getAsInteger(10, PID)) {
71 auto Owner = std::make_pair(std::string(Hostname), PID);
72 if (processStillExecuting(Owner.first, Owner.second))
73 return Owner;
74 }
Douglas Gregor7039e352012-01-29 20:15:10 +000075
76 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000077 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000078 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000079}
80
Ben Langmuir450461c2015-06-29 22:16:39 +000081static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
82 HostID.clear();
83
84#if USE_OSX_GETHOSTUUID
85 // On OS X, use the more stable hardware UUID instead of hostname.
86 struct timespec wait = {1, 0}; // 1 second.
87 uuid_t uuid;
88 if (gethostuuid(uuid, &wait) != 0)
89 return std::error_code(errno, std::system_category());
90
91 uuid_string_t UUIDStr;
92 uuid_unparse(uuid, UUIDStr);
93 StringRef UUIDRef(UUIDStr);
94 HostID.append(UUIDRef.begin(), UUIDRef.end());
95
96#elif LLVM_ON_UNIX
97 char HostName[256];
98 HostName[255] = 0;
99 HostName[0] = 0;
100 gethostname(HostName, 255);
101 StringRef HostNameRef(HostName);
102 HostID.append(HostNameRef.begin(), HostNameRef.end());
103
104#else
105 StringRef Dummy("localhost");
106 HostID.append(Dummy.begin(), Dummy.end());
107#endif
108
109 return std::error_code();
110}
111
112bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000113#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000114 SmallString<256> StoredHostID;
115 if (getHostID(StoredHostID))
116 return true; // Conservatively assume it's executing on error.
117
Douglas Gregor7039e352012-01-29 20:15:10 +0000118 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000119 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000120 return false;
121#endif
122
123 return true;
124}
125
126LockFileManager::LockFileManager(StringRef FileName)
127{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000128 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000129 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000130 std::string S("failed to obtain absolute path for ");
131 S.append(this->FileName.str());
132 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000133 return;
134 }
135 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000136 LockFileName += ".lock";
137
138 // If the lock file already exists, don't bother to try to create our own
139 // lock file; it won't work anyway. Just figure out who owns this lock file.
140 if ((Owner = readLockFile(LockFileName)))
141 return;
142
143 // Create a lock file that is unique to this instance.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000144 Expected<sys::fs::TempFile> Temp =
145 sys::fs::TempFile::create(LockFileName + "-%%%%%%%%");
146 if (!Temp) {
147 std::error_code EC = errorToErrorCode(Temp.takeError());
148 std::string S("failed to create unique file with prefix ");
149 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000150 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000151 return;
152 }
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000153 UniqueLockFile = std::move(*Temp);
154
155 // Make sure we discard the temporary file on exit.
Benjamin Kramer92387a82018-02-18 16:05:40 +0000156 auto RemoveTempFile = llvm::make_scope_exit([&]() {
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000157 if (Error E = UniqueLockFile->discard())
158 setError(errorToErrorCode(std::move(E)));
159 });
Douglas Gregor7039e352012-01-29 20:15:10 +0000160
161 // Write our process ID to our unique lock file.
162 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000163 SmallString<256> HostID;
164 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000165 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000166 return;
167 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000168
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000169 raw_fd_ostream Out(UniqueLockFile->FD, /*shouldClose=*/false);
Ben Langmuir450461c2015-06-29 22:16:39 +0000170 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000171#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000172 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000173#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000174 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000175#endif
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000176 Out.flush();
Douglas Gregor7039e352012-01-29 20:15:10 +0000177
178 if (Out.has_error()) {
Bob Haarman9ce2d032017-10-24 01:26:22 +0000179 // We failed to write out PID, so report the error, remove the
Douglas Gregor7039e352012-01-29 20:15:10 +0000180 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000181 std::string S("failed to write to ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000182 S.append(UniqueLockFile->TmpName);
Bob Haarman9ce2d032017-10-24 01:26:22 +0000183 setError(Out.error(), S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000184 return;
185 }
186 }
187
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000188 while (true) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000189 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000190 std::error_code EC =
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000191 sys::fs::create_link(UniqueLockFile->TmpName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000192 if (!EC) {
Benjamin Kramer92387a82018-02-18 16:05:40 +0000193 RemoveTempFile.release();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000194 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000195 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000196
Rafael Espindola2a826e42014-06-13 17:20:48 +0000197 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000198 std::string S("failed to create link ");
199 raw_string_ostream OSS(S);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000200 OSS << LockFileName.str() << " to " << UniqueLockFile->TmpName;
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000201 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000202 return;
203 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000204
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000205 // Someone else managed to create the lock file first. Read the process ID
206 // from the lock file.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000207 if ((Owner = readLockFile(LockFileName)))
208 return; // RemoveTempFile will delete out our unique lock file.
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000209
Yaron Keren92e1b622015-03-18 10:17:07 +0000210 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000211 // The previous owner released the lock file before we could read it.
212 // Try to get ownership again.
213 continue;
214 }
215
216 // There is a lock file that nobody owns; try to clean it up and get
217 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000218 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000219 std::string S("failed to remove lockfile ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000220 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000221 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000222 return;
223 }
224 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000225}
226
227LockFileManager::LockFileState LockFileManager::getState() const {
228 if (Owner)
229 return LFS_Shared;
230
Rafael Espindola8c42d322017-11-13 23:32:19 +0000231 if (ErrorCode)
Douglas Gregor7039e352012-01-29 20:15:10 +0000232 return LFS_Error;
233
234 return LFS_Owned;
235}
236
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000237std::string LockFileManager::getErrorMessage() const {
Rafael Espindola8c42d322017-11-13 23:32:19 +0000238 if (ErrorCode) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000239 std::string Str(ErrorDiagMsg);
Rafael Espindola8c42d322017-11-13 23:32:19 +0000240 std::string ErrCodeMsg = ErrorCode.message();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000241 raw_string_ostream OSS(Str);
242 if (!ErrCodeMsg.empty())
Rafael Espindolac8434102017-11-13 23:06:54 +0000243 OSS << ": " << ErrCodeMsg;
244 return OSS.str();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000245 }
246 return "";
247}
248
Douglas Gregor7039e352012-01-29 20:15:10 +0000249LockFileManager::~LockFileManager() {
250 if (getState() != LFS_Owned)
251 return;
252
253 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000254 sys::fs::remove(LockFileName);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000255 consumeError(UniqueLockFile->discard());
Douglas Gregor7039e352012-01-29 20:15:10 +0000256}
257
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000258LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000259 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000260 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000261
Nico Weber712e8d22018-04-29 00:45:03 +0000262#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000263 unsigned long Interval = 1;
264#else
265 struct timespec Interval;
266 Interval.tv_sec = 0;
267 Interval.tv_nsec = 1000000;
268#endif
Bruno Cardoso Lopes8fef5552017-03-18 00:32:34 +0000269 // Don't wait more than 40s per iteration. Total timeout for the file
270 // to appear is ~1.5 minutes.
271 const unsigned MaxSeconds = 40;
Douglas Gregor7039e352012-01-29 20:15:10 +0000272 do {
273 // Sleep for the designated interval, to allow the owning process time to
274 // finish up and remove the lock file.
275 // FIXME: Should we hook in to system APIs to get a notification when the
276 // lock file is deleted?
Nico Weber712e8d22018-04-29 00:45:03 +0000277#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000278 Sleep(Interval);
279#else
Craig Topperc10719f2014-04-07 04:17:22 +0000280 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000281#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000282
Ben Langmuir08970912015-02-19 18:22:35 +0000283 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
284 errc::no_such_file_or_directory) {
285 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000286 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000287 return Res_OwnerDied;
288 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000289 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000290
Ben Langmuir08970912015-02-19 18:22:35 +0000291 // If the process owning the lock died without cleaning up, just bail out.
292 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000293 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000294
295 // Exponentially increase the time we wait for the lock to be removed.
Nico Weber712e8d22018-04-29 00:45:03 +0000296#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000297 Interval *= 2;
298#else
299 Interval.tv_sec *= 2;
300 Interval.tv_nsec *= 2;
301 if (Interval.tv_nsec >= 1000000000) {
302 ++Interval.tv_sec;
303 Interval.tv_nsec -= 1000000000;
304 }
305#endif
306 } while (
Nico Weber712e8d22018-04-29 00:45:03 +0000307#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000308 Interval < MaxSeconds * 1000
309#else
310 Interval.tv_sec < (time_t)MaxSeconds
311#endif
312 );
313
314 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000315 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000316}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000317
318std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000319 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000320}