A bunch of changes...
[python_utils.git] / lockfile.py
1 #!/usr/bin/env python3
2
3 from dataclasses import dataclass
4 import datetime
5 import json
6 import logging
7 import os
8 import signal
9 import sys
10 from typing import Optional
11
12 import config
13 import decorator_utils
14
15
16 cfg = config.add_commandline_args(
17     f'Lockfile ({__file__})',
18     'Args related to lockfiles')
19 cfg.add_argument(
20     '--lockfile_held_duration_warning_threshold_sec',
21     type=float,
22     default=10.0,
23     metavar='SECONDS',
24     help='If a lock is held for longer than this threshold we log a warning'
25 )
26 logger = logging.getLogger(__name__)
27
28
29 class LockFileException(Exception):
30     pass
31
32
33 @dataclass
34 class LockFileContents:
35     pid: int
36     commandline: str
37     expiration_timestamp: float
38
39
40 class LockFile(object):
41     """A file locking mechanism that has context-manager support so you
42     can use it in a with statement.  e.g.
43
44     with LockFile('./foo.lock'):
45         # do a bunch of stuff... if the process dies we have a signal
46         # handler to do cleanup.  Other code (in this process or another)
47         # that tries to take the same lockfile will block.  There is also
48         # some logic for detecting stale locks.
49
50     """
51     def __init__(
52             self,
53             lockfile_path: str,
54             *,
55             do_signal_cleanup: bool = True,
56             expiration_timestamp: Optional[float] = None,
57             override_command: Optional[str] = None,
58     ) -> None:
59         self.is_locked = False
60         self.lockfile = lockfile_path
61         self.override_command = override_command
62         if do_signal_cleanup:
63             signal.signal(signal.SIGINT, self._signal)
64             signal.signal(signal.SIGTERM, self._signal)
65         self.expiration_timestamp = expiration_timestamp
66
67     def locked(self):
68         return self.is_locked
69
70     def available(self):
71         return not os.path.exists(self.lockfile)
72
73     def try_acquire_lock_once(self) -> bool:
74         logger.debug(f"Trying to acquire {self.lockfile}.")
75         try:
76             # Attempt to create the lockfile.  These flags cause
77             # os.open to raise an OSError if the file already
78             # exists.
79             fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
80             with os.fdopen(fd, "a") as f:
81                 contents = self._get_lockfile_contents()
82                 logger.debug(contents)
83                 f.write(contents)
84             logger.debug(f'Success; I own {self.lockfile}.')
85             self.is_locked = True
86             return True
87         except OSError:
88             pass
89         logger.warning(f'Could not acquire {self.lockfile}.')
90         return False
91
92     def acquire_with_retries(
93             self,
94             *,
95             initial_delay: float = 1.0,
96             backoff_factor: float = 2.0,
97             max_attempts = 5
98     ) -> bool:
99
100         @decorator_utils.retry_if_false(tries = max_attempts,
101                                         delay_sec = initial_delay,
102                                         backoff = backoff_factor)
103         def _try_acquire_lock_with_retries() -> bool:
104             success = self.try_acquire_lock_once()
105             if not success and os.path.exists(self.lockfile):
106                 self._detect_stale_lockfile()
107             return success
108
109         if os.path.exists(self.lockfile):
110             self._detect_stale_lockfile()
111         return _try_acquire_lock_with_retries()
112
113     def release(self):
114         try:
115             os.unlink(self.lockfile)
116         except Exception as e:
117             logger.exception(e)
118         self.is_locked = False
119
120     def __enter__(self):
121         if self.acquire_with_retries():
122             self.locktime = datetime.datetime.now().timestamp()
123             return self
124         msg = f"Couldn't acquire {self.lockfile}; giving up."
125         logger.warning(msg)
126         raise LockFileException(msg)
127
128     def __exit__(self, type, value, traceback):
129         if self.locktime:
130             ts = datetime.datetime.now().timestamp()
131             duration = ts - self.locktime
132             if duration >= config.config['lockfile_held_duration_warning_threshold_sec']:
133                 str_duration = datetime_utils.describe_duration_briefly(duration)
134                 logger.warning(f'Held {self.lockfile} for {str_duration}')
135         self.release()
136
137     def __del__(self):
138         if self.is_locked:
139             self.release()
140
141     def _signal(self, *args):
142         if self.is_locked:
143             self.release()
144
145     def _get_lockfile_contents(self) -> str:
146         if self.override_command:
147             cmd = self.override_command
148         else:
149             cmd = ' '.join(sys.argv)
150         print(cmd)
151         contents = LockFileContents(
152             pid = os.getpid(),
153             commandline = cmd,
154             expiration_timestamp = self.expiration_timestamp,
155         )
156         return json.dumps(contents.__dict__)
157
158     def _detect_stale_lockfile(self) -> None:
159         try:
160             with open(self.lockfile, 'r') as rf:
161                 lines = rf.readlines()
162                 if len(lines) == 1:
163                     line = lines[0]
164                     line_dict = json.loads(line)
165                     contents = LockFileContents(**line_dict)
166                     logger.debug(f'Blocking lock contents="{contents}"')
167
168                     # Does the PID exist still?
169                     try:
170                         os.kill(contents.pid, 0)
171                     except OSError:
172                         logger.warning(f'Lockfile {self.lockfile}\'s pid ({contents.pid}) is stale; ' +
173                                        'force acquiring')
174                         self.release()
175
176                     # Has the lock expiration expired?
177                     if contents.expiration_timestamp is not None:
178                         now = datetime.datetime.now().timestamp()
179                         if now > contents.expiration_datetime:
180                             logger.warning(f'Lockfile {self.lockfile} expiration time has passed; ' +
181                                            'force acquiring')
182                             self.release()
183         except Exception:
184             pass