blob: 2a0178bcc5b7b157a54aad05505190290a71e866 [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/STLExtras.h"
11#include "llvm/ADT/StringExtras.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000012#include "llvm/Support/Errc.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000013#include "llvm/Support/FileSystem.h"
Reid Klecknerd78273f2013-08-06 22:51:21 +000014#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidis531a5be2014-03-21 02:31:56 +000015#include "llvm/Support/Path.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000016#include "llvm/Support/raw_ostream.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000017#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <sys/types.h>
Douglas Gregor7039e352012-01-29 20:15:10 +000019#if LLVM_ON_WIN32
20#include <windows.h>
21#endif
22#if LLVM_ON_UNIX
23#include <unistd.h>
24#endif
25using namespace llvm;
26
27/// \brief Attempt to read the lock file with the given name, if it exists.
28///
29/// \param LockFileName The name of the lock file to read.
30///
31/// \returns The process ID of the process that owns this lock file
32Optional<std::pair<std::string, int> >
33LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000034 // Read the owning host and PID out of the lock file. If it appears that the
35 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000036 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
37 MemoryBuffer::getFile(LockFileName);
38 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000039 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000040 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000041 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000042 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000043
44 StringRef Hostname;
45 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000046 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000047 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
48 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000049 if (!PIDStr.getAsInteger(10, PID)) {
50 auto Owner = std::make_pair(std::string(Hostname), PID);
51 if (processStillExecuting(Owner.first, Owner.second))
52 return Owner;
53 }
Douglas Gregor7039e352012-01-29 20:15:10 +000054
55 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000056 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000057 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000058}
59
60bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +000061#if LLVM_ON_UNIX && !defined(__ANDROID__)
Douglas Gregor7039e352012-01-29 20:15:10 +000062 char MyHostname[256];
63 MyHostname[255] = 0;
64 MyHostname[0] = 0;
65 gethostname(MyHostname, 255);
66 // Check whether the process is dead. If so, we're done.
67 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
68 return false;
69#endif
70
71 return true;
72}
73
74LockFileManager::LockFileManager(StringRef FileName)
75{
Douglas Gregor056eafd2013-01-10 02:01:35 +000076 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000077 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +000078 Error = EC;
79 return;
80 }
81 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +000082 LockFileName += ".lock";
83
84 // If the lock file already exists, don't bother to try to create our own
85 // lock file; it won't work anyway. Just figure out who owns this lock file.
86 if ((Owner = readLockFile(LockFileName)))
87 return;
88
89 // Create a lock file that is unique to this instance.
90 UniqueLockFileName = LockFileName;
91 UniqueLockFileName += "-%%%%%%%%";
92 int UniqueLockFileID;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000093 if (std::error_code EC = sys::fs::createUniqueFile(
94 UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) {
Douglas Gregor7039e352012-01-29 20:15:10 +000095 Error = EC;
96 return;
97 }
98
99 // Write our process ID to our unique lock file.
100 {
101 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
102
103#if LLVM_ON_UNIX
104 // FIXME: move getpid() call into LLVM
105 char hostname[256];
106 hostname[255] = 0;
107 hostname[0] = 0;
108 gethostname(hostname, 255);
109 Out << hostname << ' ' << getpid();
110#else
111 Out << "localhost 1";
112#endif
113 Out.close();
114
115 if (Out.has_error()) {
116 // We failed to write out PID, so make up an excuse, remove the
117 // unique lock file, and fail.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000118 Error = make_error_code(errc::no_space_on_device);
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000119 sys::fs::remove(UniqueLockFileName.c_str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000120 return;
121 }
122 }
123
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000124 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000125 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000126 std::error_code EC =
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000127 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
Rafael Espindolaa3f2e3f2014-05-31 03:21:04 +0000128 if (!EC)
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000129 return;
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000130
Rafael Espindola2a826e42014-06-13 17:20:48 +0000131 if (EC != errc::file_exists) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000132 Error = EC;
133 return;
134 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000135
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000136 // Someone else managed to create the lock file first. Read the process ID
137 // from the lock file.
138 if ((Owner = readLockFile(LockFileName))) {
139 // Wipe out our unique lock file (it's useless now)
140 sys::fs::remove(UniqueLockFileName.str());
141 return;
142 }
143
144 if (!sys::fs::exists(LockFileName.str())) {
145 // The previous owner released the lock file before we could read it.
146 // Try to get ownership again.
147 continue;
148 }
149
150 // There is a lock file that nobody owns; try to clean it up and get
151 // ownership.
152 if ((EC = sys::fs::remove(LockFileName.str()))) {
153 Error = EC;
154 return;
155 }
156 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000157}
158
159LockFileManager::LockFileState LockFileManager::getState() const {
160 if (Owner)
161 return LFS_Shared;
162
163 if (Error)
164 return LFS_Error;
165
166 return LFS_Owned;
167}
168
169LockFileManager::~LockFileManager() {
170 if (getState() != LFS_Owned)
171 return;
172
173 // Since we own the lock, remove the lock file and our own unique lock file.
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000174 sys::fs::remove(LockFileName.str());
175 sys::fs::remove(UniqueLockFileName.str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000176}
177
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000178LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000179 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000180 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000181
182#if LLVM_ON_WIN32
183 unsigned long Interval = 1;
184#else
185 struct timespec Interval;
186 Interval.tv_sec = 0;
187 Interval.tv_nsec = 1000000;
188#endif
Argyrios Kyrtzidisdc8f9792015-03-04 22:54:38 +0000189 // Don't wait more than five minutes per iteration. Total timeout for the file
190 // to appear is ~8.5 mins.
191 const unsigned MaxSeconds = 5*60;
Douglas Gregor7039e352012-01-29 20:15:10 +0000192 do {
193 // Sleep for the designated interval, to allow the owning process time to
194 // finish up and remove the lock file.
195 // FIXME: Should we hook in to system APIs to get a notification when the
196 // lock file is deleted?
197#if LLVM_ON_WIN32
198 Sleep(Interval);
199#else
Craig Topperc10719f2014-04-07 04:17:22 +0000200 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000201#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000202
Ben Langmuir08970912015-02-19 18:22:35 +0000203 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
204 errc::no_such_file_or_directory) {
205 // If the original file wasn't created, somone thought the lock was dead.
206 if (!sys::fs::exists(FileName.str()))
207 return Res_OwnerDied;
208 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000209 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000210
Ben Langmuir08970912015-02-19 18:22:35 +0000211 // If the process owning the lock died without cleaning up, just bail out.
212 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000213 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000214
215 // Exponentially increase the time we wait for the lock to be removed.
216#if LLVM_ON_WIN32
217 Interval *= 2;
218#else
219 Interval.tv_sec *= 2;
220 Interval.tv_nsec *= 2;
221 if (Interval.tv_nsec >= 1000000000) {
222 ++Interval.tv_sec;
223 Interval.tv_nsec -= 1000000000;
224 }
225#endif
226 } while (
227#if LLVM_ON_WIN32
228 Interval < MaxSeconds * 1000
229#else
230 Interval.tv_sec < (time_t)MaxSeconds
231#endif
232 );
233
234 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000235 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000236}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000237
238std::error_code LockFileManager::unsafeRemoveLockFile() {
239 return sys::fs::remove(LockFileName.str());
240}