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 auto Owner = std::make_pair(std::string(Hostname), PID); 48 if (processStillExecuting(Owner.first, Owner.second)) 49 return Owner; 50 } 51 52 // Delete the lock file. It's invalid anyway. 53 sys::fs::remove(LockFileName); 54 return None; 55 } 56 57 bool LockFileManager::processStillExecuting(StringRef Hostname, int PID) { 58 #if LLVM_ON_UNIX && !defined(__ANDROID__) 59 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 71 LockFileManager::LockFileManager(StringRef FileName) 72 { 73 this->FileName = FileName; 74 if (std::error_code EC = sys::fs::make_absolute(this->FileName)) { 75 Error = EC; 76 return; 77 } 78 LockFileName = this->FileName; 79 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 (std::error_code EC = sys::fs::createUniqueFile( 91 UniqueLockFileName.str(), UniqueLockFileID, UniqueLockFileName)) { 92 Error = EC; 93 return; 94 } 95 96 // Write our process ID to our unique lock file. 97 { 98 raw_fd_ostream Out(UniqueLockFileID, /*shouldClose=*/true); 99 100 #if LLVM_ON_UNIX 101 // FIXME: move getpid() call into LLVM 102 char hostname[256]; 103 hostname[255] = 0; 104 hostname[0] = 0; 105 gethostname(hostname, 255); 106 Out << hostname << ' ' << getpid(); 107 #else 108 Out << "localhost 1"; 109 #endif 110 Out.close(); 111 112 if (Out.has_error()) { 113 // We failed to write out PID, so make up an excuse, remove the 114 // unique lock file, and fail. 115 Error = std::make_error_code(std::errc::no_space_on_device); 116 sys::fs::remove(UniqueLockFileName.c_str()); 117 return; 118 } 119 } 120 121 while (1) { 122 // Create a link from the lock file name. If this succeeds, we're done. 123 std::error_code EC = 124 sys::fs::create_link(UniqueLockFileName.str(), LockFileName.str()); 125 if (!EC) 126 return; 127 128 if (EC != std::errc::file_exists) { 129 Error = EC; 130 return; 131 } 132 133 // Someone else managed to create the lock file first. Read the process ID 134 // from the lock file. 135 if ((Owner = readLockFile(LockFileName))) { 136 // Wipe out our unique lock file (it's useless now) 137 sys::fs::remove(UniqueLockFileName.str()); 138 return; 139 } 140 141 if (!sys::fs::exists(LockFileName.str())) { 142 // The previous owner released the lock file before we could read it. 143 // Try to get ownership again. 144 continue; 145 } 146 147 // There is a lock file that nobody owns; try to clean it up and get 148 // ownership. 149 if ((EC = sys::fs::remove(LockFileName.str()))) { 150 Error = EC; 151 return; 152 } 153 } 154 } 155 156 LockFileManager::LockFileState LockFileManager::getState() const { 157 if (Owner) 158 return LFS_Shared; 159 160 if (Error) 161 return LFS_Error; 162 163 return LFS_Owned; 164 } 165 166 LockFileManager::~LockFileManager() { 167 if (getState() != LFS_Owned) 168 return; 169 170 // Since we own the lock, remove the lock file and our own unique lock file. 171 sys::fs::remove(LockFileName.str()); 172 sys::fs::remove(UniqueLockFileName.str()); 173 } 174 175 LockFileManager::WaitForUnlockResult LockFileManager::waitForUnlock() { 176 if (getState() != LFS_Shared) 177 return Res_Success; 178 179 #if LLVM_ON_WIN32 180 unsigned long Interval = 1; 181 #else 182 struct timespec Interval; 183 Interval.tv_sec = 0; 184 Interval.tv_nsec = 1000000; 185 #endif 186 // Don't wait more than five minutes for the file to appear. 187 unsigned MaxSeconds = 300; 188 bool LockFileGone = false; 189 do { 190 // Sleep for the designated interval, to allow the owning process time to 191 // finish up and remove the lock file. 192 // FIXME: Should we hook in to system APIs to get a notification when the 193 // lock file is deleted? 194 #if LLVM_ON_WIN32 195 Sleep(Interval); 196 #else 197 nanosleep(&Interval, nullptr); 198 #endif 199 bool LockFileJustDisappeared = false; 200 201 // If the lock file is still expected to be there, check whether it still 202 // is. 203 if (!LockFileGone) { 204 bool Exists; 205 if (!sys::fs::exists(LockFileName.str(), Exists) && !Exists) { 206 LockFileGone = true; 207 LockFileJustDisappeared = true; 208 } 209 } 210 211 // If the lock file is no longer there, check if the original file is 212 // available now. 213 if (LockFileGone) { 214 if (sys::fs::exists(FileName.str())) { 215 return Res_Success; 216 } 217 218 // The lock file is gone, so now we're waiting for the original file to 219 // show up. If this just happened, reset our waiting intervals and keep 220 // waiting. 221 if (LockFileJustDisappeared) { 222 MaxSeconds = 5; 223 224 #if LLVM_ON_WIN32 225 Interval = 1; 226 #else 227 Interval.tv_sec = 0; 228 Interval.tv_nsec = 1000000; 229 #endif 230 continue; 231 } 232 } 233 234 // If we're looking for the lock file to disappear, but the process 235 // owning the lock died without cleaning up, just bail out. 236 if (!LockFileGone && 237 !processStillExecuting((*Owner).first, (*Owner).second)) { 238 return Res_OwnerDied; 239 } 240 241 // Exponentially increase the time we wait for the lock to be removed. 242 #if LLVM_ON_WIN32 243 Interval *= 2; 244 #else 245 Interval.tv_sec *= 2; 246 Interval.tv_nsec *= 2; 247 if (Interval.tv_nsec >= 1000000000) { 248 ++Interval.tv_sec; 249 Interval.tv_nsec -= 1000000000; 250 } 251 #endif 252 } while ( 253 #if LLVM_ON_WIN32 254 Interval < MaxSeconds * 1000 255 #else 256 Interval.tv_sec < (time_t)MaxSeconds 257 #endif 258 ); 259 260 // Give up. 261 return Res_Timeout; 262 } 263