1 //===--- 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" 10 #include "llvm/ADT/STLExtras.h" 11 #include "llvm/ADT/StringExtras.h" 12 #include "llvm/Support/FileSystem.h" 13 #include "llvm/Support/MemoryBuffer.h" 14 #include "llvm/Support/Path.h" 15 #include "llvm/Support/raw_ostream.h" 16 #include <sys/stat.h> 17 #include <sys/types.h> 18 #if LLVM_ON_WIN32 19 #include <windows.h> 20 #endif 21 #if LLVM_ON_UNIX 22 #include <unistd.h> 23 #endif 24 using 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 31 Optional<std::pair<std::string, int> > 32 LockFileManager::readLockFile(StringRef LockFileName) { 33 // 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. 35 std::unique_ptr<MemoryBuffer> MB; 36 if (MemoryBuffer::getFile(LockFileName, MB)) { 37 sys::fs::remove(LockFileName); 38 return None; 39 } 40 41 StringRef Hostname; 42 StringRef PIDStr; 43 std::tie(Hostname, PIDStr) = getToken(MB->getBuffer(), " "); 44 PIDStr = PIDStr.substr(PIDStr.find_first_not_of(" ")); 45 int PID; 46 if (!PIDStr.getAsInteger(10, PID)) 47 return std::make_pair(std::string(Hostname), PID); 48 49 // Delete the lock file. It's invalid anyway. 50 sys::fs::remove(LockFileName); 51 return None; 52 } 53 54 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) { 55 #if LLVM_ON_UNIX && !defined(__ANDROID__) 56 char MyHostname[256]; 57 MyHostname[255] = 0; 58 MyHostname[0] = 0; 59 gethostname(MyHostname, 255); 60 // Check whether the process is dead. If so, we're done. 61 if (MyHostname == Hostname && getsid(PID) == -1 && errno == ESRCH) 62 return false; 63 #endif 64 65 return true; 66 } 67 68 LockFileManager::LockFileManager(StringRef FileName) 69 { 70 this->FileName = FileName; 71 LockFileName = FileName; 72 LockFileName += ".lock"; 73 74 // If the lock file already exists, don't bother to try to create our own 75 // lock file; it won't work anyway. Just figure out who owns this lock file. 76 if ((Owner = readLockFile(LockFileName))) 77 return; 78 79 // Create a lock file that is unique to this instance. 80 UniqueLockFileName = LockFileName; 81 UniqueLockFileName += "-%%%%%%%%"; 82 int UniqueLockFileID; 83 if (error_code EC 84 = sys::fs::createUniqueFile(UniqueLockFileName.str(), 85 UniqueLockFileID, 86 UniqueLockFileName)) { 87 Error = EC; 88 return; 89 } 90 91 // Write our process ID to our unique lock file. 92 { 93 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true); 94 95 #if LLVM_ON_UNIX 96 // FIXME: move getpid() call into LLVM 97 char hostname[256]; 98 hostname[255] = 0; 99 hostname[0] = 0; 100 gethostname(hostname, 255); 101 Out << hostname << ' ' << getpid(); 102 #else 103 Out << "localhost 1"; 104 #endif 105 Out.close(); 106 107 if (Out.has_error()) { 108 // We failed to write out PID, so make up an excuse, remove the 109 // unique lock file, and fail. 110 Error = make_error_code(errc::no_space_on_device); 111 sys::fs::remove(UniqueLockFileName.c_str()); 112 return; 113 } 114 } 115 116 while (1) { 117 // Create a link from the lock file name. If this succeeds, we're done. 118 error_code EC = 119 sys::fs::create_link(sys::path::filename(UniqueLockFileName.str()), 120 LockFileName.str()); 121 if (EC == errc::success) 122 return; 123 124 if (EC != errc::file_exists) { 125 Error = EC; 126 return; 127 } 128 129 // Someone else managed to create the lock file first. Read the process ID 130 // from the lock file. 131 if ((Owner = readLockFile(LockFileName))) { 132 // Wipe out our unique lock file (it's useless now) 133 sys::fs::remove(UniqueLockFileName.str()); 134 return; 135 } 136 137 if (!sys::fs::exists(LockFileName.str())) { 138 // The previous owner released the lock file before we could read it. 139 // Try to get ownership again. 140 continue; 141 } 142 143 // There is a lock file that nobody owns; try to clean it up and get 144 // ownership. 145 if ((EC = sys::fs::remove(LockFileName.str()))) { 146 Error = EC; 147 return; 148 } 149 } 150 } 151 152 LockFileManager::LockFileState LockFileManager::getState() const { 153 if (Owner) 154 return LFS_Shared; 155 156 if (Error) 157 return LFS_Error; 158 159 return LFS_Owned; 160 } 161 162 LockFileManager::~LockFileManager() { 163 if (getState() != LFS_Owned) 164 return; 165 166 // Since we own the lock, remove the lock file and our own unique lock file. 167 sys::fs::remove(LockFileName.str()); 168 sys::fs::remove(UniqueLockFileName.str()); 169 } 170 171 void LockFileManager::waitForUnlock() { 172 if (getState() != LFS_Shared) 173 return; 174 175 #if LLVM_ON_WIN32 176 unsigned long Interval = 1; 177 #else 178 struct timespec Interval; 179 Interval.tv_sec = 0; 180 Interval.tv_nsec = 1000000; 181 #endif 182 // Don't wait more than five minutes for the file to appear. 183 unsigned MaxSeconds = 300; 184 bool LockFileGone = false; 185 do { 186 // Sleep for the designated interval, to allow the owning process time to 187 // finish up and remove the lock file. 188 // FIXME: Should we hook in to system APIs to get a notification when the 189 // lock file is deleted? 190 #if LLVM_ON_WIN32 191 Sleep(Interval); 192 #else 193 nanosleep(&Interval, NULL); 194 #endif 195 bool LockFileJustDisappeared = false; 196 197 // If the lock file is still expected to be there, check whether it still 198 // is. 199 if (!LockFileGone) { 200 bool Exists; 201 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) { 202 LockFileGone = true; 203 LockFileJustDisappeared = true; 204 } 205 } 206 207 // If the lock file is no longer there, check if the original file is 208 // available now. 209 if (LockFileGone) { 210 if (sys::fs::exists(FileName.str())) { 211 return; 212 } 213 214 // The lock file is gone, so now we're waiting for the original file to 215 // show up. If this just happened, reset our waiting intervals and keep 216 // waiting. 217 if (LockFileJustDisappeared) { 218 MaxSeconds = 5; 219 220 #if LLVM_ON_WIN32 221 Interval = 1; 222 #else 223 Interval.tv_sec = 0; 224 Interval.tv_nsec = 1000000; 225 #endif 226 continue; 227 } 228 } 229 230 // If we're looking for the lock file to disappear, but the process 231 // owning the lock died without cleaning up, just bail out. 232 if (!LockFileGone && 233 !processStillExecuting((*Owner).first, (*Owner).second)) { 234 return; 235 } 236 237 // Exponentially increase the time we wait for the lock to be removed. 238 #if LLVM_ON_WIN32 239 Interval *= 2; 240 #else 241 Interval.tv_sec *= 2; 242 Interval.tv_nsec *= 2; 243 if (Interval.tv_nsec >= 1000000000) { 244 ++Interval.tv_sec; 245 Interval.tv_nsec -= 1000000000; 246 } 247 #endif 248 } while ( 249 #if LLVM_ON_WIN32 250 Interval < MaxSeconds * 1000 251 #else 252 Interval.tv_sec < (time_t)MaxSeconds 253 #endif 254 ); 255 256 // Give up. 257 } 258