|
4 | 4 | import logging |
5 | 5 | from os import remove |
6 | 6 | from os.path import basename |
| 7 | +import sys |
| 8 | +from tenacity import Retrying, stop_after_attempt, wait_exponential |
| 9 | + |
| 10 | +logger = logging.getLogger("django") |
7 | 11 |
|
8 | 12 |
|
9 | 13 | class BaseCommand(DjangoBaseCommand): |
10 | 14 | """ |
11 | | - Django BaseCommand wrapper that adds file locks to management commands |
| 15 | + Django BaseCommand wrapper that adds |
| 16 | + - file locks |
| 17 | + - up to 5 retries with exponential backoff |
12 | 18 | """ |
13 | 19 |
|
| 20 | + def __init__(self, *args, **options): |
| 21 | + super().__init__(*args, **options) |
| 22 | + self.name = basename(inspect.getfile(self.__class__)) |
| 23 | + self.status = 0 |
| 24 | + |
| 25 | + def retry_log(self, retry_state): |
| 26 | + logger.warning(f"{self.name} attempt {retry_state.attempt_number} failed") |
| 27 | + |
14 | 28 | def handle(self, *args, **options): |
15 | | - lockname = basename(inspect.getfile(self.__class__)) |
16 | 29 | # Use a lockfile to prevent overruns. |
17 | | - lockfile = "/tmp/{}.lock".format(lockname) |
| 30 | + logger.info(f"Executing {self.name}") |
| 31 | + lockfile = f"/tmp/{self.name}.lock" |
18 | 32 | lock = FileLock(lockfile) |
19 | 33 | lock.acquire() |
20 | 34 | try: |
21 | | - self._handle(*args, **options) |
22 | | - finally: |
23 | | - lock.release() |
24 | | - remove(lockfile) |
| 35 | + for attempt in Retrying( |
| 36 | + after=self.retry_log, |
| 37 | + reraise=True, |
| 38 | + stop=stop_after_attempt(5), |
| 39 | + wait=wait_exponential(multiplier=1, min=60, max=300), |
| 40 | + ): |
| 41 | + with attempt: |
| 42 | + self._handle(*args, **options) |
| 43 | + except Exception as e: |
| 44 | + logger.warning(f"Retries exhausted for {self.name}") |
| 45 | + logger.error(e) |
| 46 | + self.status = 1 |
| 47 | + lock.release() |
| 48 | + remove(lockfile) |
| 49 | + sys.exit(self.status) |
0 commit comments