blob: b050e5de8d48720982dc2ce8da6c3930ff7fac35 [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"
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"
Argyrios Kyrtzidis531a5be2014-03-21 02:31:56 +000014#include "llvm/Support/Path.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000015#include "llvm/Support/raw_ostream.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
24using namespace llvm;
25
26/// \brief Attempt to read the lock file with the given name, if it exists.
27///
28/// \param LockFileName The name of the lock file to read.
29///
30/// \returns The process ID of the process that owns this lock file
31Optional<std::pair<std::string, int> >
32LockFileManager::readLockFile(StringRef LockFileName) {
Douglas Gregor7039e352012-01-29 20:15:10 +000033 // Read the owning host and PID out of the lock file. If it appears that the
34 // owning process is dead, the lock file is invalid.
Ahmed Charles56440fd2014-03-06 05:51:42 +000035 std::unique_ptr<MemoryBuffer> MB;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000036 if (MemoryBuffer::getFile(LockFileName, MB)) {
37 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000038 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000039 }
Reid Kleckner7de8ea32013-08-07 01:22:04 +000040
41 StringRef Hostname;
42 StringRef PIDStr;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +000043 std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000044 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
45 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000046 if (!PIDStr.getAsInteger(10, PID)) {
47 auto Owner = std::make_pair(std::string(Hostname), PID);
48 if (processStillExecuting(Owner.first, Owner.second))
49 return Owner;
50 }
Douglas Gregor7039e352012-01-29 20:15:10 +000051
52 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000053 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000054 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000055}
56
57bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +000058#if LLVM_ON_UNIX && !defined(__ANDROID__)
Douglas Gregor7039e352012-01-29 20:15:10 +000059 char MyHostname[256];
60 MyHostname[255] = 0;
61 MyHostname[0] = 0;
62 gethostname(MyHostname, 255);
63 // Check whether the process is dead. If so, we're done.
64 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
65 return false;
66#endif
67
68 return true;
69}
70
71LockFileManager::LockFileManager(StringRef FileName)
72{
Douglas Gregor056eafd2013-01-10 02:01:35 +000073 this->FileName = FileName;
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +000074 if (error_code EC = sys::fs::make_absolute(this->FileName)) {
75 Error = EC;
76 return;
77 }
78 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +000079 LockFileName += ".lock";
80
81 // If the lock file already exists, don't bother to try to create our own
82 // lock file; it won't work anyway. Just figure out who owns this lock file.
83 if ((Owner = readLockFile(LockFileName)))
84 return;
85
86 // Create a lock file that is unique to this instance.
87 UniqueLockFileName = LockFileName;
88 UniqueLockFileName += "-%%%%%%%%";
89 int UniqueLockFileID;
90 if (error_code EC
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +000091 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
92 UniqueLockFileID,
93 UniqueLockFileName)) {
Douglas Gregor7039e352012-01-29 20:15:10 +000094 Error = EC;
95 return;
96 }
97
98 // Write our process ID to our unique lock file.
99 {
100 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
101
102#if LLVM_ON_UNIX
103 // FIXME: move getpid() call into LLVM
104 char hostname[256];
105 hostname[255] = 0;
106 hostname[0] = 0;
107 gethostname(hostname, 255);
108 Out << hostname << ' ' << getpid();
109#else
110 Out << "localhost 1";
111#endif
112 Out.close();
113
114 if (Out.has_error()) {
115 // We failed to write out PID, so make up an excuse, remove the
116 // unique lock file, and fail.
Rafael Espindolaed6882b2014-06-12 11:58:49 +0000117 Error = std::make_error_code(std::errc::no_space_on_device);
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000118 sys::fs::remove(UniqueLockFileName.c_str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000119 return;
120 }
121 }
122
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000123 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000124 // Create a link from the lock file name. If this succeeds, we're done.
125 error_code EC =
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +0000126 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
Rafael Espindolaa3f2e3f2014-05-31 03:21:04 +0000127 if (!EC)
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000128 return;
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000129
Rafael Espindola5c4f8292014-06-11 19:05:50 +0000130 if (EC != std::errc::file_exists) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000131 Error = EC;
132 return;
133 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000134
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000135 // Someone else managed to create the lock file first. Read the process ID
136 // from the lock file.
137 if ((Owner = readLockFile(LockFileName))) {
138 // Wipe out our unique lock file (it's useless now)
139 sys::fs::remove(UniqueLockFileName.str());
140 return;
141 }
142
143 if (!sys::fs::exists(LockFileName.str())) {
144 // The previous owner released the lock file before we could read it.
145 // Try to get ownership again.
146 continue;
147 }
148
149 // There is a lock file that nobody owns; try to clean it up and get
150 // ownership.
151 if ((EC = sys::fs::remove(LockFileName.str()))) {
152 Error = EC;
153 return;
154 }
155 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000156}
157
158LockFileManager::LockFileState LockFileManager::getState() const {
159 if (Owner)
160 return LFS_Shared;
161
162 if (Error)
163 return LFS_Error;
164
165 return LFS_Owned;
166}
167
168LockFileManager::~LockFileManager() {
169 if (getState() != LFS_Owned)
170 return;
171
172 // Since we own the lock, remove the lock file and our own unique lock file.
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000173 sys::fs::remove(LockFileName.str());
174 sys::fs::remove(UniqueLockFileName.str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000175}
176
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000177LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000178 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000179 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000180
181#if LLVM_ON_WIN32
182 unsigned long Interval = 1;
183#else
184 struct timespec Interval;
185 Interval.tv_sec = 0;
186 Interval.tv_nsec = 1000000;
187#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000188 // Don't wait more than five minutes for the file to appear.
189 unsigned MaxSeconds = 300;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000190 bool LockFileGone = false;
Douglas Gregor7039e352012-01-29 20:15:10 +0000191 do {
192 // Sleep for the designated interval, to allow the owning process time to
193 // finish up and remove the lock file.
194 // FIXME: Should we hook in to system APIs to get a notification when the
195 // lock file is deleted?
196#if LLVM_ON_WIN32
197 Sleep(Interval);
198#else
Craig Topperc10719f2014-04-07 04:17:22 +0000199 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000200#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000201 bool LockFileJustDisappeared = false;
202
203 // If the lock file is still expected to be there, check whether it still
204 // is.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000205 if (!LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000206 bool Exists;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000207 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
208 LockFileGone = true;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000209 LockFileJustDisappeared = true;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000210 }
211 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000212
213 // If the lock file is no longer there, check if the original file is
214 // available now.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000215 if (LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000216 if (sys::fs::exists(FileName.str())) {
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000217 return Res_Success;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000218 }
219
220 // The lock file is gone, so now we're waiting for the original file to
221 // show up. If this just happened, reset our waiting intervals and keep
222 // waiting.
223 if (LockFileJustDisappeared) {
224 MaxSeconds = 5;
225
226#if LLVM_ON_WIN32
227 Interval = 1;
228#else
229 Interval.tv_sec = 0;
230 Interval.tv_nsec = 1000000;
231#endif
232 continue;
233 }
Douglas Gregor056eafd2013-01-10 02:01:35 +0000234 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000235
Douglas Gregor0cb68462013-04-05 20:53:57 +0000236 // If we're looking for the lock file to disappear, but the process
237 // owning the lock died without cleaning up, just bail out.
238 if (!LockFileGone &&
239 !processStillExecuting((*Owner).first, (*Owner).second)) {
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000240 return Res_OwnerDied;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000241 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000242
243 // Exponentially increase the time we wait for the lock to be removed.
244#if LLVM_ON_WIN32
245 Interval *= 2;
246#else
247 Interval.tv_sec *= 2;
248 Interval.tv_nsec *= 2;
249 if (Interval.tv_nsec >= 1000000000) {
250 ++Interval.tv_sec;
251 Interval.tv_nsec -= 1000000000;
252 }
253#endif
254 } while (
255#if LLVM_ON_WIN32
256 Interval < MaxSeconds * 1000
257#else
258 Interval.tv_sec < (time_t)MaxSeconds
259#endif
260 );
261
262 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000263 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000264}