|
58 | 58 | import os |
59 | 59 | import shutil |
60 | 60 | import tempfile |
| 61 | +import time |
| 62 | +import traceback |
61 | 63 | from pathlib import Path |
62 | 64 | from typing import IO, TYPE_CHECKING, cast |
63 | 65 | from urllib import parse |
|
79 | 81 | # advisory file locking for posix |
80 | 82 | import fcntl |
81 | 83 |
|
82 | | - def _lock_file(f: IO) -> None: |
83 | | - if f.writable(): |
| 84 | + @contextlib.contextmanager |
| 85 | + def _lock_file(path: str) -> Iterator[IO]: |
| 86 | + with open(path, "wb") as f: |
84 | 87 | fcntl.lockf(f, fcntl.LOCK_EX) |
| 88 | + yield f |
85 | 89 |
|
86 | 90 | except ModuleNotFoundError: |
87 | 91 | # Windows file locking |
88 | 92 | import msvcrt |
89 | 93 |
|
90 | | - def _lock_file(f: IO) -> None: |
91 | | - # On Windows we lock a byte range and file must not be empty |
92 | | - f.write(b"\0") |
93 | | - f.flush() |
94 | | - f.seek(0) |
| 94 | + @contextlib.contextmanager |
| 95 | + def _lock_file(path: str) -> Iterator[IO]: |
| 96 | + err = None |
| 97 | + locked = False |
| 98 | + for i in range(100): |
| 99 | + try: |
| 100 | + with open(path, "wb") as f: |
| 101 | + # file must not be empty |
| 102 | + f.write(b"\0") |
| 103 | + f.flush() |
| 104 | + f.seek(0) |
| 105 | + msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1) |
| 106 | + locked = True |
| 107 | + yield f |
| 108 | + return |
| 109 | + except OSError as e: |
| 110 | + if locked: |
| 111 | + # yield raised |
| 112 | + raise e |
| 113 | + err = e |
| 114 | + logger.warning( |
| 115 | + "Unsuccessful lock attempt %d for %s: %s", i, path, e |
| 116 | + ) |
| 117 | + logger.warning(traceback.format_exc()) |
| 118 | + time.sleep(0.3) |
95 | 119 |
|
96 | | - msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1) |
| 120 | + if err: |
| 121 | + raise err |
97 | 122 |
|
98 | 123 |
|
99 | 124 | class Updater: |
@@ -171,9 +196,9 @@ def _lock_metadata(self) -> Iterator[None]: |
171 | 196 | # Ensure the whole metadata directory structure exists |
172 | 197 | rootdir = Path(self._dir, "root_history") |
173 | 198 | rootdir.mkdir(exist_ok=True, parents=True) |
| 199 | + |
174 | 200 | logger.debug("Getting metadata lock...") |
175 | | - with open(os.path.join(self._dir, ".lock"), "wb") as f: |
176 | | - _lock_file(f) |
| 201 | + with _lock_file(os.path.join(self._dir, ".lock")): |
177 | 202 | yield |
178 | 203 | logger.debug("Released metadata lock") |
179 | 204 |
|
@@ -336,8 +361,7 @@ def download_target( |
336 | 361 | targetinfo.verify_length_and_hashes(target_file) |
337 | 362 |
|
338 | 363 | target_file.seek(0) |
339 | | - with open(filepath, "wb") as destination_file: |
340 | | - _lock_file(destination_file) |
| 364 | + with _lock_file(filepath) as destination_file: |
341 | 365 | shutil.copyfileobj(target_file, destination_file) |
342 | 366 |
|
343 | 367 | logger.debug("Downloaded target %s", targetinfo.path) |
|
0 commit comments