diff options
| author | Scott Gasch <[email protected]> | 2022-02-08 20:21:02 -0800 |
|---|---|---|
| committer | Scott Gasch <[email protected]> | 2022-02-08 20:21:02 -0800 |
| commit | 2f5b47c8b30d1b7d86443391332be2f3805cdafd (patch) | |
| tree | 181f08770989ed65f859d8c6772d1d71336c77c7 /lockfile.py | |
| parent | 4b04fd1d5a14c5c4c7e0985e5376b4e2f879ef06 (diff) | |
Cleanup more contextlib.AbstractContextManagers and Literal[False]s.
Diffstat (limited to 'lockfile.py')
| -rw-r--r-- | lockfile.py | 28 |
1 files changed, 19 insertions, 9 deletions
diff --git a/lockfile.py b/lockfile.py index 6993cb8..10fe10d 100644 --- a/lockfile.py +++ b/lockfile.py @@ -2,6 +2,9 @@ """File-based locking helper.""" +from __future__ import annotations + +import contextlib import datetime import json import logging @@ -10,7 +13,7 @@ import signal import sys import warnings from dataclasses import dataclass -from typing import Optional +from typing import Literal, Optional import config import datetime_utils @@ -42,7 +45,7 @@ class LockFileContents: expiration_timestamp: Optional[float] -class LockFile(object): +class LockFile(contextlib.AbstractContextManager): """A file locking mechanism that has context-manager support so you can use it in a with statement. e.g. @@ -131,16 +134,18 @@ class LockFile(object): logger.warning(msg) raise LockFileException(msg) - def __exit__(self, _, value, traceback): + def __exit__(self, _, value, traceback) -> Literal[False]: if self.locktime: ts = datetime.datetime.now().timestamp() duration = ts - self.locktime if duration >= config.config['lockfile_held_duration_warning_threshold_sec']: - str_duration = datetime_utils.describe_duration_briefly(duration) + # Note: describe duration briefly only does 1s granularity... + str_duration = datetime_utils.describe_duration_briefly(int(duration)) msg = f'Held {self.lockfile} for {str_duration}' logger.warning(msg) warnings.warn(msg, stacklevel=2) self.release() + return False def __del__(self): if self.is_locked: @@ -176,16 +181,21 @@ class LockFile(object): try: os.kill(contents.pid, 0) except OSError: - msg = f'Lockfile {self.lockfile}\'s pid ({contents.pid}) is stale; force acquiring' - logger.warning(msg) + logger.warning( + 'Lockfile %s\'s pid (%d) is stale; force acquiring...', + self.lockfile, + contents.pid, + ) self.release() # Has the lock expiration expired? if contents.expiration_timestamp is not None: now = datetime.datetime.now().timestamp() if now > contents.expiration_timestamp: - msg = f'Lockfile {self.lockfile} expiration time has passed; force acquiring' - logger.warning(msg) + logger.warning( + 'Lockfile %s\'s expiration time has passed; force acquiring', + self.lockfile, + ) self.release() except Exception: - pass + pass # If the lockfile doesn't exist or disappears, good. |
