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,
41 self.is_locked = False
42 self.lockfile = lockfile_path
44 signal.signal(signal.SIGINT, self._signal)
45 signal.signal(signal.SIGTERM, self._signal)
46 self.expiration_timestamp = expiration_timestamp
52 return not os.path.exists(self.lockfile)
54 def try_acquire_lock_once(self) -> bool:
55 logger.debug(f"Trying to acquire {self.lockfile}.")
57 # Attempt to create the lockfile. These flags cause
58 # os.open to raise an OSError if the file already
60 fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
61 with os.fdopen(fd, "a") as f:
62 contents = self._get_lockfile_contents()
63 logger.debug(contents)
65 logger.debug(f'Success; I own {self.lockfile}.')
70 logger.debug(f'Failed; I could not acquire {self.lockfile}.')
73 def acquire_with_retries(
76 initial_delay: float = 1.0,
77 backoff_factor: float = 2.0,
81 @decorator_utils.retry_if_false(tries = max_attempts,
82 delay_sec = initial_delay,
83 backoff = backoff_factor)
84 def _try_acquire_lock_with_retries() -> bool:
85 success = self.try_acquire_lock_once()
86 if not success and os.path.exists(self.lockfile):
87 self._detect_stale_lockfile()
90 if os.path.exists(self.lockfile):
91 self._detect_stale_lockfile()
92 return _try_acquire_lock_with_retries()
96 os.unlink(self.lockfile)
97 except Exception as e:
99 self.is_locked = False
102 if self.acquire_with_retries():
104 msg = f"Couldn't acquire {self.lockfile}; giving up."
106 raise LockFileException(msg)
108 def __exit__(self, type, value, traceback):
115 def _signal(self, *args):
119 def _get_lockfile_contents(self) -> str:
120 contents = LockFileContents(
122 commandline = ' '.join(sys.argv),
123 expiration_timestamp = self.expiration_timestamp
125 return json.dumps(contents.__dict__)
127 def _detect_stale_lockfile(self) -> None:
129 with open(self.lockfile, 'r') as rf:
130 lines = rf.readlines()
133 line_dict = json.loads(line)
134 contents = LockFileContents(**line_dict)
135 logger.debug(f'Blocking lock contents="{contents}"')
137 # Does the PID exist still?
139 os.kill(contents.pid, 0)
141 logger.debug('The pid seems stale; killing the lock.')
144 # Has the lock expiration expired?
145 if contents.expiration_timestamp is not None:
146 now = datetime.datetime.now().timestamp()
147 if now > contents.expiration_datetime:
148 logger.debug('The expiration time has passed; ' +