3 from dataclasses import dataclass
10 from typing import Optional
12 import decorator_utils
15 logger = logging.getLogger(__name__)
18 class LockFileException(Exception):
23 class LockFileContents:
26 expiration_timestamp: float
29 class LockFile(object):
30 """A file locking mechanism that has context-manager support so you
31 can use it in a with statement.
38 do_signal_cleanup: bool = True,
39 expiration_timestamp: Optional[float] = None,
40 override_command: Optional[str] = None,
42 self.is_locked = False
43 self.lockfile = lockfile_path
44 self.override_command = override_command
46 signal.signal(signal.SIGINT, self._signal)
47 signal.signal(signal.SIGTERM, self._signal)
48 self.expiration_timestamp = expiration_timestamp
54 return not os.path.exists(self.lockfile)
56 def try_acquire_lock_once(self) -> bool:
57 logger.debug(f"Trying to acquire {self.lockfile}.")
59 # Attempt to create the lockfile. These flags cause
60 # os.open to raise an OSError if the file already
62 fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
63 with os.fdopen(fd, "a") as f:
64 contents = self._get_lockfile_contents()
65 logger.debug(contents)
67 logger.debug(f'Success; I own {self.lockfile}.')
72 logger.debug(f'Failed; I could not acquire {self.lockfile}.')
75 def acquire_with_retries(
78 initial_delay: float = 1.0,
79 backoff_factor: float = 2.0,
83 @decorator_utils.retry_if_false(tries = max_attempts,
84 delay_sec = initial_delay,
85 backoff = backoff_factor)
86 def _try_acquire_lock_with_retries() -> bool:
87 success = self.try_acquire_lock_once()
88 if not success and os.path.exists(self.lockfile):
89 self._detect_stale_lockfile()
92 if os.path.exists(self.lockfile):
93 self._detect_stale_lockfile()
94 return _try_acquire_lock_with_retries()
98 os.unlink(self.lockfile)
99 except Exception as e:
101 self.is_locked = False
104 if self.acquire_with_retries():
106 msg = f"Couldn't acquire {self.lockfile}; giving up."
108 raise LockFileException(msg)
110 def __exit__(self, type, value, traceback):
117 def _signal(self, *args):
121 def _get_lockfile_contents(self) -> str:
122 if self.override_command:
123 cmd = self.override_command
125 cmd = ' '.join(sys.argv)
126 contents = LockFileContents(
129 expiration_timestamp = self.expiration_timestamp,
131 return json.dumps(contents.__dict__)
133 def _detect_stale_lockfile(self) -> None:
135 with open(self.lockfile, 'r') as rf:
136 lines = rf.readlines()
139 line_dict = json.loads(line)
140 contents = LockFileContents(**line_dict)
141 logger.debug(f'Blocking lock contents="{contents}"')
143 # Does the PID exist still?
145 os.kill(contents.pid, 0)
147 logger.debug('The pid seems stale; killing the lock.')
150 # Has the lock expiration expired?
151 if contents.expiration_timestamp is not None:
152 now = datetime.datetime.now().timestamp()
153 if now > contents.expiration_datetime:
154 logger.debug('The expiration time has passed; ' +