blob: 611f94a9709bc2af9b2abfddcd6d24294a441d17 [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//===----------------------------------------------------------------------===//
9#include "llvm/Support/LockFileManager.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000010#include "llvm/ADT/StringExtras.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000011#include "llvm/Support/Errc.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000012#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000013#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000014#include "llvm/Support/raw_ostream.h"
Ben Langmuir63aa8c52015-06-29 17:08:41 +000015#include "llvm/Support/Signals.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000016#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include <sys/types.h>
Douglas Gregor7039e352012-01-29 20:15:10 +000018#if LLVM_ON_WIN32
19#include <windows.h>
20#endif
21#if LLVM_ON_UNIX
22#include <unistd.h>
23#endif
Ben Langmuir450461c2015-06-29 22:16:39 +000024
25#if defined(__APPLE__) && defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (__MAC_OS_X_VERSION_MIN_REQUIRED > 1050)
26#define USE_OSX_GETHOSTUUID 1
27#else
28#define USE_OSX_GETHOSTUUID 0
29#endif
30
31#if USE_OSX_GETHOSTUUID
32#include <uuid/uuid.h>
33#endif
Douglas Gregor7039e352012-01-29 20:15:10 +000034using namespace llvm;
35
36/// \brief Attempt to read the lock file with the given name, if it exists.
37///
38/// \param LockFileName The name of the lock file to read.
39///
40/// \returns The process ID of the process that owns this lock file
41Optional<std::pair<std::string, int> >
42LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000043 // Read the owning host and PID out of the lock file. If it appears that the
44 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000045 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
46 MemoryBuffer::getFile(LockFileName);
47 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000048 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000049 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000050 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000051 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000052
53 StringRef Hostname;
54 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000055 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000056 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
57 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000058 if (!PIDStr.getAsInteger(10, PID)) {
59 auto Owner = std::make_pair(std::string(Hostname), PID);
60 if (processStillExecuting(Owner.first, Owner.second))
61 return Owner;
62 }
Douglas Gregor7039e352012-01-29 20:15:10 +000063
64 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000065 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000066 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000067}
68
Ben Langmuir450461c2015-06-29 22:16:39 +000069static std::error_code getHostID(SmallVectorImpl<char> &HostID) {
70 HostID.clear();
71
72#if USE_OSX_GETHOSTUUID
73 // On OS X, use the more stable hardware UUID instead of hostname.
74 struct timespec wait = {1, 0}; // 1 second.
75 uuid_t uuid;
76 if (gethostuuid(uuid, &wait) != 0)
77 return std::error_code(errno, std::system_category());
78
79 uuid_string_t UUIDStr;
80 uuid_unparse(uuid, UUIDStr);
81 StringRef UUIDRef(UUIDStr);
82 HostID.append(UUIDRef.begin(), UUIDRef.end());
83
84#elif LLVM_ON_UNIX
85 char HostName[256];
86 HostName[255] = 0;
87 HostName[0] = 0;
88 gethostname(HostName, 255);
89 StringRef HostNameRef(HostName);
90 HostID.append(HostNameRef.begin(), HostNameRef.end());
91
92#else
93 StringRef Dummy("localhost");
94 HostID.append(Dummy.begin(), Dummy.end());
95#endif
96
97 return std::error_code();
98}
99
100bool LockFileManager::processStillExecuting(StringRef HostID, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +0000101#if LLVM_ON_UNIX && !defined(__ANDROID__)
Ben Langmuir450461c2015-06-29 22:16:39 +0000102 SmallString<256> StoredHostID;
103 if (getHostID(StoredHostID))
104 return true; // Conservatively assume it's executing on error.
105
Douglas Gregor7039e352012-01-29 20:15:10 +0000106 // Check whether the process is dead. If so, we're done.
Ben Langmuir450461c2015-06-29 22:16:39 +0000107 if (StoredHostID == HostID && getsid(PID) == -1 && errno == ESRCH)
Douglas Gregor7039e352012-01-29 20:15:10 +0000108 return false;
109#endif
110
111 return true;
112}
113
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000114namespace {
115/// An RAII helper object ensure that the unique lock file is removed.
116///
117/// Ensures that if there is an error or a signal before we finish acquiring the
118/// lock, the unique file will be removed. And if we successfully take the lock,
119/// the signal handler is left in place so that signals while the lock is held
120/// will remove the unique lock file. The caller should ensure there is a
121/// matching call to sys::DontRemoveFileOnSignal when the lock is released.
122class RemoveUniqueLockFileOnSignal {
123 StringRef Filename;
124 bool RemoveImmediately;
125public:
126 RemoveUniqueLockFileOnSignal(StringRef Name)
127 : Filename(Name), RemoveImmediately(true) {
128 sys::RemoveFileOnSignal(Filename, nullptr);
129 }
130 ~RemoveUniqueLockFileOnSignal() {
131 if (!RemoveImmediately) {
132 // Leave the signal handler enabled. It will be removed when the lock is
133 // released.
134 return;
135 }
136 sys::fs::remove(Filename);
137 sys::DontRemoveFileOnSignal(Filename);
138 }
139 void lockAcquired() { RemoveImmediately = false; }
140};
141} // end anonymous namespace
142
Douglas Gregor7039e352012-01-29 20:15:10 +0000143LockFileManager::LockFileManager(StringRef FileName)
144{
Douglas Gregor056eafd2013-01-10 02:01:35 +0000145 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000146 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000147 std::string S("failed to obtain absolute path for ");
148 S.append(this->FileName.str());
149 setError(EC, S);
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000150 return;
151 }
152 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +0000153 LockFileName += ".lock";
154
155 // If the lock file already exists, don't bother to try to create our own
156 // lock file; it won't work anyway. Just figure out who owns this lock file.
157 if ((Owner = readLockFile(LockFileName)))
158 return;
159
160 // Create a lock file that is unique to this instance.
161 UniqueLockFileName = LockFileName;
162 UniqueLockFileName += "-%%%%%%%%";
163 int UniqueLockFileID;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000164 if (std::error_code EC = sys::fs::createUniqueFile(
Yaron Keren92e1b622015-03-18 10:17:07 +0000165 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000166 std::string S("failed to create unique file ");
167 S.append(UniqueLockFileName.str());
168 setError(EC, S);
Douglas Gregor7039e352012-01-29 20:15:10 +0000169 return;
170 }
171
172 // Write our process ID to our unique lock file.
173 {
Ben Langmuir450461c2015-06-29 22:16:39 +0000174 SmallString<256> HostID;
175 if (auto EC = getHostID(HostID)) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000176 setError(EC, "failed to get host id");
Ben Langmuir450461c2015-06-29 22:16:39 +0000177 return;
178 }
Ben Langmuir5123eec2015-06-29 21:56:03 +0000179
Ben Langmuir450461c2015-06-29 22:16:39 +0000180 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
181 Out << HostID << ' ';
Douglas Gregor7039e352012-01-29 20:15:10 +0000182#if LLVM_ON_UNIX
Ben Langmuir450461c2015-06-29 22:16:39 +0000183 Out << getpid();
Douglas Gregor7039e352012-01-29 20:15:10 +0000184#else
Ben Langmuir450461c2015-06-29 22:16:39 +0000185 Out << "1";
Douglas Gregor7039e352012-01-29 20:15:10 +0000186#endif
187 Out.close();
188
189 if (Out.has_error()) {
190 // We failed to write out PID, so make up an excuse, remove the
191 // unique lock file, and fail.
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000192 auto EC = make_error_code(errc::no_space_on_device);
193 std::string S("failed to write to ");
194 S.append(UniqueLockFileName.str());
195 setError(EC, S);
Yaron Keren92e1b622015-03-18 10:17:07 +0000196 sys::fs::remove(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000197 return;
198 }
199 }
200
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000201 // Clean up the unique file on signal, which also releases the lock if it is
202 // held since the .lock symlink will point to a nonexistent file.
203 RemoveUniqueLockFileOnSignal RemoveUniqueFile(UniqueLockFileName);
204
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000205 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000206 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000207 std::error_code EC =
Yaron Keren92e1b622015-03-18 10:17:07 +0000208 sys::fs::create_link(UniqueLockFileName, LockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000209 if (!EC) {
210 RemoveUniqueFile.lockAcquired();
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000211 return;
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000212 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000213
Rafael Espindola2a826e42014-06-13 17:20:48 +0000214 if (EC != errc::file_exists) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000215 std::string S("failed to create link ");
216 raw_string_ostream OSS(S);
217 OSS << LockFileName.str() << " to " << UniqueLockFileName.str();
218 setError(EC, OSS.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000219 return;
220 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000221
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000222 // Someone else managed to create the lock file first. Read the process ID
223 // from the lock file.
224 if ((Owner = readLockFile(LockFileName))) {
225 // Wipe out our unique lock file (it's useless now)
Yaron Keren92e1b622015-03-18 10:17:07 +0000226 sys::fs::remove(UniqueLockFileName);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000227 return;
228 }
229
Yaron Keren92e1b622015-03-18 10:17:07 +0000230 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000231 // The previous owner released the lock file before we could read it.
232 // Try to get ownership again.
233 continue;
234 }
235
236 // There is a lock file that nobody owns; try to clean it up and get
237 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000238 if ((EC = sys::fs::remove(LockFileName))) {
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000239 std::string S("failed to remove lockfile ");
240 S.append(UniqueLockFileName.str());
241 setError(EC, S);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000242 return;
243 }
244 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000245}
246
247LockFileManager::LockFileState LockFileManager::getState() const {
248 if (Owner)
249 return LFS_Shared;
250
251 if (Error)
252 return LFS_Error;
253
254 return LFS_Owned;
255}
256
Bruno Cardoso Lopes42b1f652016-06-04 00:34:00 +0000257std::string LockFileManager::getErrorMessage() const {
258 if (Error) {
259 std::string Str(ErrorDiagMsg);
260 std::string ErrCodeMsg = Error->message();
261 raw_string_ostream OSS(Str);
262 if (!ErrCodeMsg.empty())
263 OSS << ": " << Error->message();
264 OSS.flush();
265 return Str;
266 }
267 return "";
268}
269
Douglas Gregor7039e352012-01-29 20:15:10 +0000270LockFileManager::~LockFileManager() {
271 if (getState() != LFS_Owned)
272 return;
273
274 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000275 sys::fs::remove(LockFileName);
276 sys::fs::remove(UniqueLockFileName);
Ben Langmuir63aa8c52015-06-29 17:08:41 +0000277 // The unique file is now gone, so remove it from the signal handler. This
278 // matches a sys::RemoveFileOnSignal() in LockFileManager().
279 sys::DontRemoveFileOnSignal(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000280}
281
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000282LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000283 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000284 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000285
286#if LLVM_ON_WIN32
287 unsigned long Interval = 1;
288#else
289 struct timespec Interval;
290 Interval.tv_sec = 0;
291 Interval.tv_nsec = 1000000;
292#endif
Argyrios Kyrtzidisdc8f9792015-03-04 22:54:38 +0000293 // Don't wait more than five minutes per iteration. Total timeout for the file
294 // to appear is ~8.5 mins.
295 const unsigned MaxSeconds = 5*60;
Douglas Gregor7039e352012-01-29 20:15:10 +0000296 do {
297 // Sleep for the designated interval, to allow the owning process time to
298 // finish up and remove the lock file.
299 // FIXME: Should we hook in to system APIs to get a notification when the
300 // lock file is deleted?
301#if LLVM_ON_WIN32
302 Sleep(Interval);
303#else
Craig Topperc10719f2014-04-07 04:17:22 +0000304 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000305#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000306
Ben Langmuir08970912015-02-19 18:22:35 +0000307 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
308 errc::no_such_file_or_directory) {
309 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000310 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000311 return Res_OwnerDied;
312 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000313 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000314
Ben Langmuir08970912015-02-19 18:22:35 +0000315 // If the process owning the lock died without cleaning up, just bail out.
316 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000317 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000318
319 // Exponentially increase the time we wait for the lock to be removed.
320#if LLVM_ON_WIN32
321 Interval *= 2;
322#else
323 Interval.tv_sec *= 2;
324 Interval.tv_nsec *= 2;
325 if (Interval.tv_nsec >= 1000000000) {
326 ++Interval.tv_sec;
327 Interval.tv_nsec -= 1000000000;
328 }
329#endif
330 } while (
331#if LLVM_ON_WIN32
332 Interval < MaxSeconds * 1000
333#else
334 Interval.tv_sec < (time_t)MaxSeconds
335#endif
336 );
337
338 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000339 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000340}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000341
342std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000343 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000344}