blob: d07c5f0f682f447736c91f2025a02c35847fcace [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"
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) {
Douglas Gregor7039e352012-01-29 20:15:10 +000032 // Read the owning host and PID out of the lock file. If it appears that the
33 // owning process is dead, the lock file is invalid.
Rafael Espindolaadf21f22014-07-06 17:43:13 +000034 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
35 MemoryBuffer::getFile(LockFileName);
36 if (!MBOrErr) {
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000037 sys::fs::remove(LockFileName);
Reid Kleckner7de8ea32013-08-07 01:22:04 +000038 return None;
Argyrios Kyrtzidis37575692014-03-21 01:25:37 +000039 }
Rafael Espindola3f6481d2014-08-01 14:31:55 +000040 MemoryBuffer &MB = *MBOrErr.get();
Reid Kleckner7de8ea32013-08-07 01:22:04 +000041
42 StringRef Hostname;
43 StringRef PIDStr;
Rafael Espindola3f6481d2014-08-01 14:31:55 +000044 std::tie(Hostname, PIDStr) = getToken(MB.getBuffer(), " ");
Reid Kleckner7de8ea32013-08-07 01:22:04 +000045 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" "));
46 int PID;
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +000047 if (!PIDStr.getAsInteger(10, PID)) {
48 auto Owner = std::make_pair(std::string(Hostname), PID);
49 if (processStillExecuting(Owner.first, Owner.second))
50 return Owner;
51 }
Douglas Gregor7039e352012-01-29 20:15:10 +000052
53 // Delete the lock file. It's invalid anyway.
Reid Klecknerd78273f2013-08-06 22:51:21 +000054 sys::fs::remove(LockFileName);
David Blaikieef045932013-02-21 00:27:28 +000055 return None;
Douglas Gregor7039e352012-01-29 20:15:10 +000056}
57
58bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) {
Evgeniy Stepanovc439a422012-09-04 09:14:45 +000059#if LLVM_ON_UNIX && !defined(__ANDROID__)
Douglas Gregor7039e352012-01-29 20:15:10 +000060 char MyHostname[256];
61 MyHostname[255] = 0;
62 MyHostname[0] = 0;
63 gethostname(MyHostname, 255);
64 // Check whether the process is dead. If so, we're done.
65 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH)
66 return false;
67#endif
68
69 return true;
70}
71
72LockFileManager::LockFileManager(StringRef FileName)
73{
Douglas Gregor056eafd2013-01-10 02:01:35 +000074 this->FileName = FileName;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000075 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) {
Argyrios Kyrtzidis900e9a32014-03-21 21:45:07 +000076 Error = EC;
77 return;
78 }
79 LockFileName = this->FileName;
Douglas Gregor7039e352012-01-29 20:15:10 +000080 LockFileName += ".lock";
81
82 // If the lock file already exists, don't bother to try to create our own
83 // lock file; it won't work anyway. Just figure out who owns this lock file.
84 if ((Owner = readLockFile(LockFileName)))
85 return;
86
87 // Create a lock file that is unique to this instance.
88 UniqueLockFileName = LockFileName;
89 UniqueLockFileName += "-%%%%%%%%";
90 int UniqueLockFileID;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +000091 if (std::error_code EC = sys::fs::createUniqueFile(
Yaron Keren92e1b622015-03-18 10:17:07 +000092 UniqueLockFileName, UniqueLockFileID, UniqueLockFileName)) {
Douglas Gregor7039e352012-01-29 20:15:10 +000093 Error = EC;
94 return;
95 }
96
97 // Write our process ID to our unique lock file.
98 {
99 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true);
100
101#if LLVM_ON_UNIX
102 // FIXME: move getpid() call into LLVM
103 char hostname[256];
104 hostname[255] = 0;
105 hostname[0] = 0;
106 gethostname(hostname, 255);
107 Out << hostname << ' ' << getpid();
108#else
109 Out << "localhost 1";
110#endif
111 Out.close();
112
113 if (Out.has_error()) {
114 // We failed to write out PID, so make up an excuse, remove the
115 // unique lock file, and fail.
Rafael Espindola2a826e42014-06-13 17:20:48 +0000116 Error = make_error_code(errc::no_space_on_device);
Yaron Keren92e1b622015-03-18 10:17:07 +0000117 sys::fs::remove(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000118 return;
119 }
120 }
121
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000122 while (1) {
Rafael Espindola83f858e2014-03-11 18:40:24 +0000123 // Create a link from the lock file name. If this succeeds, we're done.
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000124 std::error_code EC =
Yaron Keren92e1b622015-03-18 10:17:07 +0000125 sys::fs::create_link(UniqueLockFileName, LockFileName);
Rafael Espindolaa3f2e3f2014-05-31 03:21:04 +0000126 if (!EC)
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000127 return;
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000128
Rafael Espindola2a826e42014-06-13 17:20:48 +0000129 if (EC != errc::file_exists) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000130 Error = EC;
131 return;
132 }
Argyrios Kyrtzidis62a979c2014-03-06 17:37:10 +0000133
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000134 // Someone else managed to create the lock file first. Read the process ID
135 // from the lock file.
136 if ((Owner = readLockFile(LockFileName))) {
137 // Wipe out our unique lock file (it's useless now)
Yaron Keren92e1b622015-03-18 10:17:07 +0000138 sys::fs::remove(UniqueLockFileName);
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000139 return;
140 }
141
Yaron Keren92e1b622015-03-18 10:17:07 +0000142 if (!sys::fs::exists(LockFileName)) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000143 // The previous owner released the lock file before we could read it.
144 // Try to get ownership again.
145 continue;
146 }
147
148 // There is a lock file that nobody owns; try to clean it up and get
149 // ownership.
Yaron Keren92e1b622015-03-18 10:17:07 +0000150 if ((EC = sys::fs::remove(LockFileName))) {
Argyrios Kyrtzidis41479782014-03-06 20:53:58 +0000151 Error = EC;
152 return;
153 }
154 }
Douglas Gregor7039e352012-01-29 20:15:10 +0000155}
156
157LockFileManager::LockFileState LockFileManager::getState() const {
158 if (Owner)
159 return LFS_Shared;
160
161 if (Error)
162 return LFS_Error;
163
164 return LFS_Owned;
165}
166
167LockFileManager::~LockFileManager() {
168 if (getState() != LFS_Owned)
169 return;
170
171 // Since we own the lock, remove the lock file and our own unique lock file.
Yaron Keren92e1b622015-03-18 10:17:07 +0000172 sys::fs::remove(LockFileName);
173 sys::fs::remove(UniqueLockFileName);
Douglas Gregor7039e352012-01-29 20:15:10 +0000174}
175
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000176LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() {
Douglas Gregor7039e352012-01-29 20:15:10 +0000177 if (getState() != LFS_Shared)
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000178 return Res_Success;
Douglas Gregor7039e352012-01-29 20:15:10 +0000179
180#if LLVM_ON_WIN32
181 unsigned long Interval = 1;
182#else
183 struct timespec Interval;
184 Interval.tv_sec = 0;
185 Interval.tv_nsec = 1000000;
186#endif
Argyrios Kyrtzidisdc8f9792015-03-04 22:54:38 +0000187 // Don't wait more than five minutes per iteration. Total timeout for the file
188 // to appear is ~8.5 mins.
189 const unsigned MaxSeconds = 5*60;
Douglas Gregor7039e352012-01-29 20:15:10 +0000190 do {
191 // Sleep for the designated interval, to allow the owning process time to
192 // finish up and remove the lock file.
193 // FIXME: Should we hook in to system APIs to get a notification when the
194 // lock file is deleted?
195#if LLVM_ON_WIN32
196 Sleep(Interval);
197#else
Craig Topperc10719f2014-04-07 04:17:22 +0000198 nanosleep(&Interval, nullptr);
Douglas Gregor7039e352012-01-29 20:15:10 +0000199#endif
Douglas Gregor0cb68462013-04-05 20:53:57 +0000200
Ben Langmuir08970912015-02-19 18:22:35 +0000201 if (sys::fs::access(LockFileName.c_str(), sys::fs::AccessMode::Exist) ==
202 errc::no_such_file_or_directory) {
203 // If the original file wasn't created, somone thought the lock was dead.
Yaron Keren92e1b622015-03-18 10:17:07 +0000204 if (!sys::fs::exists(FileName))
Ben Langmuir08970912015-02-19 18:22:35 +0000205 return Res_OwnerDied;
206 return Res_Success;
Douglas Gregor056eafd2013-01-10 02:01:35 +0000207 }
Douglas Gregor0cb68462013-04-05 20:53:57 +0000208
Ben Langmuir08970912015-02-19 18:22:35 +0000209 // If the process owning the lock died without cleaning up, just bail out.
210 if (!processStillExecuting((*Owner).first, (*Owner).second))
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000211 return Res_OwnerDied;
Douglas Gregor7039e352012-01-29 20:15:10 +0000212
213 // Exponentially increase the time we wait for the lock to be removed.
214#if LLVM_ON_WIN32
215 Interval *= 2;
216#else
217 Interval.tv_sec *= 2;
218 Interval.tv_nsec *= 2;
219 if (Interval.tv_nsec >= 1000000000) {
220 ++Interval.tv_sec;
221 Interval.tv_nsec -= 1000000000;
222 }
223#endif
224 } while (
225#if LLVM_ON_WIN32
226 Interval < MaxSeconds * 1000
227#else
228 Interval.tv_sec < (time_t)MaxSeconds
229#endif
230 );
231
232 // Give up.
Argyrios Kyrtzidis44ec0a72014-04-06 03:19:31 +0000233 return Res_Timeout;
Douglas Gregor7039e352012-01-29 20:15:10 +0000234}
Ben Langmuird2d52de2015-02-09 20:34:24 +0000235
236std::error_code LockFileManager::unsafeRemoveLockFile() {
Yaron Keren92e1b622015-03-18 10:17:07 +0000237 return sys::fs::remove(LockFileName);
Ben Langmuird2d52de2015-02-09 20:34:24 +0000238}