blob: ba1047b88ac2ee6516859aa1306535ea334f18c5 [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"
Douglas Gregor7039e352012-01-29 20:15:10 +000014#include "llvm/Support/raw_ostream.h"
Douglas Gregor7039e352012-01-29 20:15:10 +000015#include <sys/stat.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include <sys/types.h>
Douglas Gregor7039e352012-01-29 20:15:10 +000017#if LLVM_ON_WIN32
18#include <windows.h>
19#endif
20#if LLVM_ON_UNIX
21#include <unistd.h>
22#endif
23using namespace llvm;
24
25/// \brief Attempt to read the lock file with the given name, if it exists.
26///
27/// \param LockFileName The name of the lock file to read.
28///
29/// \returns The process ID of the process that owns this lock file
30Optional<std::pair<std::string, int> >
31LockFileManager::readLockFile(StringRef LockFileName) {
32 // Check whether the lock file exists. If not, clearly there's nothing
33 // to read, so we just return.
Rafael Espindola9e7a6382014-02-13 04:00:35 +000034 if (!sys::fs::exists(LockFileName))
David Blaikieef045932013-02-21 00:27:28 +000035 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000036
37 // Read the owning host and PID out of the lock file. If it appears that the
38 // owning process is dead, the lock file is invalid.
Ahmed Charles56440fd2014-03-06 05:51:42 +000039 std::unique_ptr<MemoryBuffer> MB;
Reid Kleckner7de8ea32013-08-07 01:22:04 +000040 if (MemoryBuffer::getFile(LockFileName, MB))
41 return None;
42
43 StringRef Hostname;
44 StringRef PIDStr;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +000045 std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000046 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
47 int PID;
48 if (!PIDStr.getAsInteger(10, PID))
49 return std::make_pair(std::string(Hostname), PID);
Douglas Gregor7039e352012-01-29 20:15:10 +000050
51 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000052 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000053 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000054}
55
56bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +000057#if LLVM_ON_UNIX && !defined(__ANDROID__)
Douglas Gregor7039e352012-01-29 20:15:10 +000058 char MyHostname[256];
59 MyHostname[255] = 0;
60 MyHostname[0] = 0;
61 gethostname(MyHostname, 255);
62 // Check whether the process is dead. If so, we're done.
63 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
64 return false;
65#endif
66
67 return true;
68}
69
70LockFileManager::LockFileManager(StringRef FileName)
71{
Douglas Gregor056eafd2013-01-10 02:01:35 +000072 this->FileName = FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +000073 LockFileName = FileName;
74 LockFileName += ".lock";
75
76 // If the lock file already exists, don't bother to try to create our own
77 // lock file; it won't work anyway. Just figure out who owns this lock file.
78 if ((Owner = readLockFile(LockFileName)))
79 return;
80
81 // Create a lock file that is unique to this instance.
82 UniqueLockFileName = LockFileName;
83 UniqueLockFileName += "-%%%%%%%%";
84 int UniqueLockFileID;
85 if (error_code EC
Rafael Espindolac9d2e5b2013-07-05 21:01:08 +000086 = sys::fs::createUniqueFile(UniqueLockFileName.str(),
87 UniqueLockFileID,
88 UniqueLockFileName)) {
Douglas Gregor7039e352012-01-29 20:15:10 +000089 Error = EC;
90 return;
91 }
92
93 // Write our process ID to our unique lock file.
94 {
95 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
96
97#if LLVM_ON_UNIX
98 // FIXME: move getpid() call into LLVM
99 char hostname[256];
100 hostname[255] = 0;
101 hostname[0] = 0;
102 gethostname(hostname, 255);
103 Out << hostname << ' ' << getpid();
104#else
105 Out << "localhost 1";
106#endif
107 Out.close();
108
109 if (Out.has_error()) {
110 // We failed to write out PID, so make up an excuse, remove the
111 // unique lock file, and fail.
112 Error = make_error_code(errc::no_space_on_device);
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000113 sys::fs::remove(UniqueLockFileName.c_str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000114 return;
115 }
116 }
117
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000118 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000119 // Create a link from the lock file name. If this succeeds, we're done.
120 error_code EC =
121 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str());
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000122 if (EC == errc::success)
123 return;
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000124
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000125 if (EC != errc::file_exists) {
126 Error = EC;
127 return;
128 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000129
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000130 // Someone else managed to create the lock file first. Read the process ID
131 // from the lock file.
132 if ((Owner = readLockFile(LockFileName))) {
133 // Wipe out our unique lock file (it's useless now)
134 sys::fs::remove(UniqueLockFileName.str());
135 return;
136 }
137
138 if (!sys::fs::exists(LockFileName.str())) {
139 // The previous owner released the lock file before we could read it.
140 // Try to get ownership again.
141 continue;
142 }
143
144 // There is a lock file that nobody owns; try to clean it up and get
145 // ownership.
146 if ((EC = sys::fs::remove(LockFileName.str()))) {
147 Error = EC;
148 return;
149 }
150 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000151}
152
153LockFileManager::LockFileState LockFileManager::getState() const {
154 if (Owner)
155 return LFS_Shared;
156
157 if (Error)
158 return LFS_Error;
159
160 return LFS_Owned;
161}
162
163LockFileManager::~LockFileManager() {
164 if (getState() != LFS_Owned)
165 return;
166
167 // Since we own the lock, remove the lock file and our own unique lock file.
Rafael Espindola81e7fd02014-01-10 21:40:29 +0000168 sys::fs::remove(LockFileName.str());
169 sys::fs::remove(UniqueLockFileName.str());
Douglas Gregor7039e352012-01-29 20:15:10 +0000170}
171
172void LockFileManager::waitForUnlock() {
173 if (getState() != LFS_Shared)
174 return;
175
176#if LLVM_ON_WIN32
177 unsigned long Interval = 1;
178#else
179 struct timespec Interval;
180 Interval.tv_sec = 0;
181 Interval.tv_nsec = 1000000;
182#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000183 // Don't wait more than five minutes for the file to appear.
184 unsigned MaxSeconds = 300;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000185 bool LockFileGone = false;
Douglas Gregor7039e352012-01-29 20:15:10 +0000186 do {
187 // Sleep for the designated interval, to allow the owning process time to
188 // finish up and remove the lock file.
189 // FIXME: Should we hook in to system APIs to get a notification when the
190 // lock file is deleted?
191#if LLVM_ON_WIN32
192 Sleep(Interval);
193#else
194 nanosleep(&Interval, NULL);
195#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000196 bool LockFileJustDisappeared = false;
197
198 // If the lock file is still expected to be there, check whether it still
199 // is.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000200 if (!LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000201 bool Exists;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000202 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) {
203 LockFileGone = true;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000204 LockFileJustDisappeared = true;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000205 }
206 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000207
208 // If the lock file is no longer there, check if the original file is
209 // available now.
Douglas Gregor056eafd2013-01-10 02:01:35 +0000210 if (LockFileGone) {
Rafael Espindola9e7a6382014-02-13 04:00:35 +0000211 if (sys::fs::exists(FileName.str())) {
Douglas Gregor056eafd2013-01-10 02:01:35 +0000212 return;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000213 }
214
215 // The lock file is gone, so now we're waiting for the original file to
216 // show up. If this just happened, reset our waiting intervals and keep
217 // waiting.
218 if (LockFileJustDisappeared) {
219 MaxSeconds = 5;
220
221#if LLVM_ON_WIN32
222 Interval = 1;
223#else
224 Interval.tv_sec = 0;
225 Interval.tv_nsec = 1000000;
226#endif
227 continue;
228 }
Douglas Gregor056eafd2013-01-10 02:01:35 +0000229 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000230
Douglas Gregor0cb68462013-04-05 20:53:57 +0000231 // If we're looking for the lock file to disappear, but the process
232 // owning the lock died without cleaning up, just bail out.
233 if (!LockFileGone &&
234 !processStillExecuting((*Owner).first, (*Owner).second)) {
Douglas Gregor7039e352012-01-29 20:15:10 +0000235 return;
Douglas Gregor0cb68462013-04-05 20:53:57 +0000236 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000237
238 // Exponentially increase the time we wait for the lock to be removed.
239#if LLVM_ON_WIN32
240 Interval *= 2;
241#else
242 Interval.tv_sec *= 2;
243 Interval.tv_nsec *= 2;
244 if (Interval.tv_nsec >= 1000000000) {
245 ++Interval.tv_sec;
246 Interval.tv_nsec -= 1000000000;
247 }
248#endif
249 } while (
250#if LLVM_ON_WIN32
251 Interval < MaxSeconds * 1000
252#else
253 Interval.tv_sec < (time_t)MaxSeconds
254#endif
255 );
256
257 // Give up.
258}