1 //===--- LockFileManager.h - File-level locking utility ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_SUPPORT_LOCKFILEMANAGER_H
10 #define LLVM_SUPPORT_LOCKFILEMANAGER_H
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/Support/FileSystem.h"
15 #include <system_error>
16 #include <utility> // for std::pair
21 /// \brief Class that manages the creation of a lock file to aid
22 /// implicit coordination between different processes.
24 /// The implicit coordination works by creating a ".lock" file alongside
25 /// the file that we're coordinating for, using the atomicity of the file
26 /// system to ensure that only a single process can create that ".lock" file.
27 /// When the lock file is removed, the owning process has finished the
29 class LockFileManager {
31 /// \brief Describes the state of a lock file.
33 /// \brief The lock file has been created and is owned by this instance
36 /// \brief The lock file already exists and is owned by some other
39 /// \brief An error occurred while trying to create or find the lock
44 /// \brief Describes the result of waiting for the owner to release the lock.
45 enum WaitForUnlockResult {
46 /// \brief The lock was released successfully.
48 /// \brief Owner died while holding the lock.
50 /// \brief Reached timeout while waiting for the owner to release the lock.
55 SmallString<128> FileName;
56 SmallString<128> LockFileName;
57 Optional<sys::fs::TempFile> UniqueLockFile;
59 Optional<std::pair<std::string, int> > Owner;
60 std::error_code ErrorCode;
61 std::string ErrorDiagMsg;
63 LockFileManager(const LockFileManager &) = delete;
64 LockFileManager &operator=(const LockFileManager &) = delete;
66 static Optional<std::pair<std::string, int> >
67 readLockFile(StringRef LockFileName);
69 static bool processStillExecuting(StringRef Hostname, int PID);
73 LockFileManager(StringRef FileName);
76 /// \brief Determine the state of the lock file.
77 LockFileState getState() const;
79 operator LockFileState() const { return getState(); }
81 /// \brief For a shared lock, wait until the owner releases the lock.
82 WaitForUnlockResult waitForUnlock();
84 /// \brief Remove the lock file. This may delete a different lock file than
85 /// the one previously read if there is a race.
86 std::error_code unsafeRemoveLockFile();
88 /// \brief Get error message, or "" if there is no error.
89 std::string getErrorMessage() const;
91 /// \brief Set error and error message
92 void setError(const std::error_code &EC, StringRef ErrorMsg = "") {
94 ErrorDiagMsg = ErrorMsg.str();
98 } // end namespace llvm
100 #endif // LLVM_SUPPORT_LOCKFILEMANAGER_H