3 """File-based locking helper."""
12 from dataclasses import dataclass
13 from typing import Optional
17 import decorator_utils
19 cfg = config.add_commandline_args(f'Lockfile ({__file__})', 'Args related to lockfiles')
21 '--lockfile_held_duration_warning_threshold_sec',
25 help='If a lock is held for longer than this threshold we log a warning',
27 logger = logging.getLogger(__name__)
30 class LockFileException(Exception):
31 """An exception related to lock files."""
37 class LockFileContents:
38 """The contents we'll write to each lock file."""
42 expiration_timestamp: Optional[float]
45 class LockFile(object):
46 """A file locking mechanism that has context-manager support so you
47 can use it in a with statement. e.g.
49 with LockFile('./foo.lock'):
50 # do a bunch of stuff... if the process dies we have a signal
51 # handler to do cleanup. Other code (in this process or another)
52 # that tries to take the same lockfile will block. There is also
53 # some logic for detecting stale locks.
61 do_signal_cleanup: bool = True,
62 expiration_timestamp: Optional[float] = None,
63 override_command: Optional[str] = None,
65 self.is_locked: bool = False
66 self.lockfile: str = lockfile_path
67 self.locktime: Optional[int] = None
68 self.override_command: Optional[str] = override_command
70 signal.signal(signal.SIGINT, self._signal)
71 signal.signal(signal.SIGTERM, self._signal)
72 self.expiration_timestamp = expiration_timestamp
78 return not os.path.exists(self.lockfile)
80 def try_acquire_lock_once(self) -> bool:
81 logger.debug("Trying to acquire %s.", self.lockfile)
83 # Attempt to create the lockfile. These flags cause
84 # os.open to raise an OSError if the file already
86 fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
87 with os.fdopen(fd, "a") as f:
88 contents = self._get_lockfile_contents()
89 logger.debug(contents)
91 logger.debug('Success; I own %s.', self.lockfile)
96 logger.warning('Couldn\'t acquire %s.', self.lockfile)
99 def acquire_with_retries(
102 initial_delay: float = 1.0,
103 backoff_factor: float = 2.0,
106 @decorator_utils.retry_if_false(
107 tries=max_attempts, delay_sec=initial_delay, backoff=backoff_factor
109 def _try_acquire_lock_with_retries() -> bool:
110 success = self.try_acquire_lock_once()
111 if not success and os.path.exists(self.lockfile):
112 self._detect_stale_lockfile()
115 if os.path.exists(self.lockfile):
116 self._detect_stale_lockfile()
117 return _try_acquire_lock_with_retries()
121 os.unlink(self.lockfile)
122 except Exception as e:
124 self.is_locked = False
127 if self.acquire_with_retries():
128 self.locktime = datetime.datetime.now().timestamp()
130 msg = f"Couldn't acquire {self.lockfile}; giving up."
132 raise LockFileException(msg)
134 def __exit__(self, _, value, traceback):
136 ts = datetime.datetime.now().timestamp()
137 duration = ts - self.locktime
138 if duration >= config.config['lockfile_held_duration_warning_threshold_sec']:
139 str_duration = datetime_utils.describe_duration_briefly(duration)
140 msg = f'Held {self.lockfile} for {str_duration}'
142 warnings.warn(msg, stacklevel=2)
149 def _signal(self, *args):
153 def _get_lockfile_contents(self) -> str:
154 if self.override_command:
155 cmd = self.override_command
157 cmd = ' '.join(sys.argv)
158 contents = LockFileContents(
161 expiration_timestamp=self.expiration_timestamp,
163 return json.dumps(contents.__dict__)
165 def _detect_stale_lockfile(self) -> None:
167 with open(self.lockfile, 'r') as rf:
168 lines = rf.readlines()
171 line_dict = json.loads(line)
172 contents = LockFileContents(**line_dict)
173 logger.debug('Blocking lock contents="%s"', contents)
175 # Does the PID exist still?
177 os.kill(contents.pid, 0)
179 msg = f'Lockfile {self.lockfile}\'s pid ({contents.pid}) is stale; force acquiring'
183 # Has the lock expiration expired?
184 if contents.expiration_timestamp is not None:
185 now = datetime.datetime.now().timestamp()
186 if now > contents.expiration_timestamp:
187 msg = f'Lockfile {self.lockfile} expiration time has passed; force acquiring'