3 # © Copyright 2021-2022, Scott Gasch
5 """File-based locking helper."""
7 from __future__ import annotations
16 from dataclasses import dataclass
17 from typing import Literal, Optional
21 import decorator_utils
23 cfg = config.add_commandline_args(f'Lockfile ({__file__})', 'Args related to lockfiles')
25 '--lockfile_held_duration_warning_threshold_sec',
29 help='If a lock is held for longer than this threshold we log a warning',
31 logger = logging.getLogger(__name__)
34 class LockFileException(Exception):
35 """An exception related to lock files."""
41 class LockFileContents:
42 """The contents we'll write to each lock file."""
46 expiration_timestamp: Optional[float]
49 class LockFile(contextlib.AbstractContextManager):
50 """A file locking mechanism that has context-manager support so you
51 can use it in a with statement. e.g.
53 with LockFile('./foo.lock'):
54 # do a bunch of stuff... if the process dies we have a signal
55 # handler to do cleanup. Other code (in this process or another)
56 # that tries to take the same lockfile will block. There is also
57 # some logic for detecting stale locks.
65 do_signal_cleanup: bool = True,
66 expiration_timestamp: Optional[float] = None,
67 override_command: Optional[str] = None,
69 self.is_locked: bool = False
70 self.lockfile: str = lockfile_path
71 self.locktime: Optional[int] = None
72 self.override_command: Optional[str] = override_command
74 signal.signal(signal.SIGINT, self._signal)
75 signal.signal(signal.SIGTERM, self._signal)
76 self.expiration_timestamp = expiration_timestamp
82 return not os.path.exists(self.lockfile)
84 def try_acquire_lock_once(self) -> bool:
85 logger.debug("Trying to acquire %s.", self.lockfile)
87 # Attempt to create the lockfile. These flags cause
88 # os.open to raise an OSError if the file already
90 fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
91 with os.fdopen(fd, "a") as f:
92 contents = self._get_lockfile_contents()
93 logger.debug(contents)
95 logger.debug('Success; I own %s.', self.lockfile)
100 logger.warning('Couldn\'t acquire %s.', self.lockfile)
103 def acquire_with_retries(
106 initial_delay: float = 1.0,
107 backoff_factor: float = 2.0,
110 @decorator_utils.retry_if_false(
111 tries=max_attempts, delay_sec=initial_delay, backoff=backoff_factor
113 def _try_acquire_lock_with_retries() -> bool:
114 success = self.try_acquire_lock_once()
115 if not success and os.path.exists(self.lockfile):
116 self._detect_stale_lockfile()
119 if os.path.exists(self.lockfile):
120 self._detect_stale_lockfile()
121 return _try_acquire_lock_with_retries()
125 os.unlink(self.lockfile)
126 except Exception as e:
128 self.is_locked = False
131 if self.acquire_with_retries():
132 self.locktime = datetime.datetime.now().timestamp()
134 msg = f"Couldn't acquire {self.lockfile}; giving up."
136 raise LockFileException(msg)
138 def __exit__(self, _, value, traceback) -> Literal[False]:
140 ts = datetime.datetime.now().timestamp()
141 duration = ts - self.locktime
142 if duration >= config.config['lockfile_held_duration_warning_threshold_sec']:
143 # Note: describe duration briefly only does 1s granularity...
144 str_duration = datetime_utils.describe_duration_briefly(int(duration))
145 msg = f'Held {self.lockfile} for {str_duration}'
147 warnings.warn(msg, stacklevel=2)
155 def _signal(self, *args):
159 def _get_lockfile_contents(self) -> str:
160 if self.override_command:
161 cmd = self.override_command
163 cmd = ' '.join(sys.argv)
164 contents = LockFileContents(
167 expiration_timestamp=self.expiration_timestamp,
169 return json.dumps(contents.__dict__)
171 def _detect_stale_lockfile(self) -> None:
173 with open(self.lockfile, 'r') as rf:
174 lines = rf.readlines()
177 line_dict = json.loads(line)
178 contents = LockFileContents(**line_dict)
179 logger.debug('Blocking lock contents="%s"', contents)
181 # Does the PID exist still?
183 os.kill(contents.pid, 0)
186 'Lockfile %s\'s pid (%d) is stale; force acquiring...',
192 # Has the lock expiration expired?
193 if contents.expiration_timestamp is not None:
194 now = datetime.datetime.now().timestamp()
195 if now > contents.expiration_timestamp:
197 'Lockfile %s\'s expiration time has passed; force acquiring',
202 pass # If the lockfile doesn't exist or disappears, good.