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