blob: 4f7ebd408fe230d68ba34f89befab32b5e4f39d6 [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"
Rafael Espindola2a826e42014-06-13 17:20:48 +000015#include "llvm/Support/Errc.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000016#include "llvm/Support/ErrorOr.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000017#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000018#include "llvm/Support/MemoryBuffer.h"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000019#include "llvm/Support/Signals.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000021#include <cerrno>
22#include <ctime>
23#include <memory>
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>
27#include <tuple>
Nico Weber712e8d22018-04-29 00:45:03 +000028#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +000029#include <windows.h>
30#endif
31#if LLVM_ON_UNIX
32#include <unistd.h>
33#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000034
35#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
36#define USE_OSX_GETHOSTUUID 1
37#else
38#define USE_OSX_GETHOSTUUID 0
39#endif
40
41#if USE_OSX_GETHOSTUUID
42#include <uuid/uuid.h>
43#endif
Eugene Zelenko33d7b762016-08-23 17:14:32 +000044
Douglas Gregor7039e352012-01-29 20:15:10 +000045using namespace llvm;
46
47/// \brief Attempt to read the lock file with the given name, if it exists.
48///
49/// \param LockFileName The name of the lock file to read.
50///
51/// \returns The process ID of the process that owns this lock file
52Optional<std::pair<std::string, int> >
53LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000054 // Read the owning host and PID out of the lock file. If it appears that the
55 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000056 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
57 MemoryBuffer::getFile(LockFileName);
58 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000059 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000060 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000061 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000062 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000063
64 StringRef Hostname;
65 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000066 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000067 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
68 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000069 if (!PIDStr.getAsInteger(10, PID)) {
70 auto Owner = std::make_pair(std::string(Hostname), PID);
71 if (processStillExecuting(Owner.first, Owner.second))
72 return Owner;
73 }
Douglas Gregor7039e352012-01-29 20:15:10 +000074
75 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000076 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000077 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000078}
79
Ben Langmuir450461c2015-06-29 22:16:39 +000080static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
81 HostID.clear();
82
83#if USE_OSX_GETHOSTUUID
84 // On OS X, use the more stable hardware UUID instead of hostname.
85 struct timespec wait = {1, 0}; // 1 second.
86 uuid_t uuid;
87 if (gethostuuid(uuid, &wait) != 0)
88 return std::error_code(errno, std::system_category());
89
90 uuid_string_t UUIDStr;
91 uuid_unparse(uuid, UUIDStr);
92 StringRef UUIDRef(UUIDStr);
93 HostID.append(UUIDRef.begin(), UUIDRef.end());
94
95#elif LLVM_ON_UNIX
96 char HostName[256];
97 HostName[255] = 0;
98 HostName[0] = 0;
99 gethostname(HostName, 255);
100 StringRef HostNameRef(HostName);
101 HostID.append(HostNameRef.begin(), HostNameRef.end());
102
103#else
104 StringRef Dummy("localhost");
105 HostID.append(Dummy.begin(), Dummy.end());
106#endif
107
108 return std::error_code();
109}
110
111bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000112#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000113 SmallString<256> StoredHostID;
114 if (getHostID(StoredHostID))
115 return true; // Conservatively assume it's executing on error.
116
Douglas Gregor7039e352012-01-29 20:15:10 +0000117 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000118 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000119 return false;
120#endif
121
122 return true;
123}
124
125LockFileManager::LockFileManager(StringRef FileName)
126{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000127 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000128 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000129 std::string S("failed to obtain absolute path for ");
130 S.append(this->FileName.str());
131 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000132 return;
133 }
134 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000135 LockFileName += ".lock";
136
137 // If the lock file already exists, don't bother to try to create our own
138 // lock file; it won't work anyway. Just figure out who owns this lock file.
139 if ((Owner = readLockFile(LockFileName)))
140 return;
141
142 // Create a lock file that is unique to this instance.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000143 Expected<sys::fs::TempFile> Temp =
144 sys::fs::TempFile::create(LockFileName + "-%%%%%%%%");
145 if (!Temp) {
146 std::error_code EC = errorToErrorCode(Temp.takeError());
147 std::string S("failed to create unique file with prefix ");
148 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000149 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000150 return;
151 }
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000152 UniqueLockFile = std::move(*Temp);
153
154 // Make sure we discard the temporary file on exit.
Benjamin Kramer92387a82018-02-18 16:05:40 +0000155 auto RemoveTempFile = llvm::make_scope_exit([&]() {
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000156 if (Error E = UniqueLockFile->discard())
157 setError(errorToErrorCode(std::move(E)));
158 });
Douglas Gregor7039e352012-01-29 20:15:10 +0000159
160 // Write our process ID to our unique lock file.
161 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000162 SmallString<256> HostID;
163 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000164 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000165 return;
166 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000167
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000168 raw_fd_ostream Out(UniqueLockFile->FD, /*shouldClose=*/false);
Ben Langmuir450461c2015-06-29 22:16:39 +0000169 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000170#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000171 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000172#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000173 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000174#endif
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000175 Out.flush();
Douglas Gregor7039e352012-01-29 20:15:10 +0000176
177 if (Out.has_error()) {
Bob Haarman9ce2d032017-10-24 01:26:22 +0000178 // We failed to write out PID, so report the error, remove the
Douglas Gregor7039e352012-01-29 20:15:10 +0000179 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000180 std::string S("failed to write to ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000181 S.append(UniqueLockFile->TmpName);
Bob Haarman9ce2d032017-10-24 01:26:22 +0000182 setError(Out.error(), S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000183 return;
184 }
185 }
186
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000187 while (true) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000188 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000189 std::error_code EC =
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000190 sys::fs::create_link(UniqueLockFile->TmpName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000191 if (!EC) {
Benjamin Kramer92387a82018-02-18 16:05:40 +0000192 RemoveTempFile.release();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000193 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000194 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000195
Rafael Espindola2a826e42014-06-13 17:20:48 +0000196 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000197 std::string S("failed to create link ");
198 raw_string_ostream OSS(S);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000199 OSS << LockFileName.str() << " to " << UniqueLockFile->TmpName;
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000200 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000201 return;
202 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000203
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000204 // Someone else managed to create the lock file first. Read the process ID
205 // from the lock file.
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000206 if ((Owner = readLockFile(LockFileName)))
207 return; // RemoveTempFile will delete out our unique lock file.
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000208
Yaron Keren92e1b622015-03-18 10:17:07 +0000209 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000210 // The previous owner released the lock file before we could read it.
211 // Try to get ownership again.
212 continue;
213 }
214
215 // There is a lock file that nobody owns; try to clean it up and get
216 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000217 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000218 std::string S("failed to remove lockfile ");
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000219 S.append(LockFileName.str());
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000220 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000221 return;
222 }
223 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000224}
225
226LockFileManager::LockFileState LockFileManager::getState() const {
227 if (Owner)
228 return LFS_Shared;
229
Rafael Espindola8c42d322017-11-13 23:32:19 +0000230 if (ErrorCode)
Douglas Gregor7039e352012-01-29 20:15:10 +0000231 return LFS_Error;
232
233 return LFS_Owned;
234}
235
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000236std::string LockFileManager::getErrorMessage() const {
Rafael Espindola8c42d322017-11-13 23:32:19 +0000237 if (ErrorCode) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000238 std::string Str(ErrorDiagMsg);
Rafael Espindola8c42d322017-11-13 23:32:19 +0000239 std::string ErrCodeMsg = ErrorCode.message();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000240 raw_string_ostream OSS(Str);
241 if (!ErrCodeMsg.empty())
Rafael Espindolac8434102017-11-13 23:06:54 +0000242 OSS << ": " << ErrCodeMsg;
243 return OSS.str();
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000244 }
245 return "";
246}
247
Douglas Gregor7039e352012-01-29 20:15:10 +0000248LockFileManager::~LockFileManager() {
249 if (getState() != LFS_Owned)
250 return;
251
252 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000253 sys::fs::remove(LockFileName);
Rafael Espindola51c63bb2017-11-17 20:06:41 +0000254 consumeError(UniqueLockFile->discard());
Douglas Gregor7039e352012-01-29 20:15:10 +0000255}
256
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000257LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000258 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000259 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000260
Nico Weber712e8d22018-04-29 00:45:03 +0000261#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000262 unsigned long Interval = 1;
263#else
264 struct timespec Interval;
265 Interval.tv_sec = 0;
266 Interval.tv_nsec = 1000000;
267#endif
Bruno Cardoso Lopes8fef5552017-03-18 00:32:34 +0000268 // Don't wait more than 40s per iteration. Total timeout for the file
269 // to appear is ~1.5 minutes.
270 const unsigned MaxSeconds = 40;
Douglas Gregor7039e352012-01-29 20:15:10 +0000271 do {
272 // Sleep for the designated interval, to allow the owning process time to
273 // finish up and remove the lock file.
274 // FIXME: Should we hook in to system APIs to get a notification when the
275 // lock file is deleted?
Nico Weber712e8d22018-04-29 00:45:03 +0000276#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000277 Sleep(Interval);
278#else
Craig Topperc10719f2014-04-07 04:17:22 +0000279 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000280#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000281
Ben Langmuir08970912015-02-19 18:22:35 +0000282 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
283 errc::no_such_file_or_directory) {
284 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000285 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000286 return Res_OwnerDied;
287 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000288 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000289
Ben Langmuir08970912015-02-19 18:22:35 +0000290 // If the process owning the lock died without cleaning up, just bail out.
291 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000292 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000293
294 // Exponentially increase the time we wait for the lock to be removed.
Nico Weber712e8d22018-04-29 00:45:03 +0000295#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000296 Interval *= 2;
297#else
298 Interval.tv_sec *= 2;
299 Interval.tv_nsec *= 2;
300 if (Interval.tv_nsec >= 1000000000) {
301 ++Interval.tv_sec;
302 Interval.tv_nsec -= 1000000000;
303 }
304#endif
305 } while (
Nico Weber712e8d22018-04-29 00:45:03 +0000306#if _WIN32
Douglas Gregor7039e352012-01-29 20:15:10 +0000307 Interval < MaxSeconds * 1000
308#else
309 Interval.tv_sec < (time_t)MaxSeconds
310#endif
311 );
312
313 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000314 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000315}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000316
317std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000318 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000319}