| 1 |
"""The :class:`~._protocol.Files` implementation over :mod:`os`.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import os |
| 6 |
import stat |
| 7 |
import sys |
| 8 |
import time |
| 9 |
from contextlib import suppress |
| 10 |
from errno import ENOENT, ESTALE |
| 11 |
from pathlib import Path |
| 12 |
from typing import Final |
| 13 |
|
| 14 |
from filelock._strict import _link_no_follow, _raise_if_hard_links_unsupported |
| 15 |
from filelock._util import ensure_directory_exists, write_all |
| 16 |
|
| 17 |
from ._protocol import _GENERATIONS_DIRECTORY, _HOLDERS_DIRECTORY, _MAX_RECORD_SIZE |
| 18 |
|
| 19 |
_O_NOFOLLOW: Final[int] = getattr(os, "O_NOFOLLOW", 0) |
| 20 |
#: Windows opens descriptors in text mode by default, which rewrites newlines; every record here is exact bytes. |
| 21 |
_O_BINARY: Final[int] = getattr(os, "O_BINARY", 0) |
| 22 |
#: ESTALE is what an NFS client reports for a file a peer unlinked out from under its cached handle: gone, not broken. |
| 23 |
_MISSING_ERRNOS: Final[frozenset[int]] = frozenset({ENOENT, ESTALE}) |
| 24 |
#: Windows refuses an open with EACCES while another process is deleting the file or holds it open without sharing; |
| 25 |
#: both clear within moments, so an open is retried this long before the refusal is taken as real. |
| 26 |
_WINDOWS_OPEN_GRACE: Final[float] = 0.5 |
| 27 |
|
| 28 |
|
| 29 |
class OsFiles: |
| 30 |
"""Record files under a lock's protocol root, opened without following symlinks and owned by this UID alone.""" |
| 31 |
|
| 32 |
def __init__(self, lock_file: str) -> None: |
| 33 |
self._lock_file = lock_file |
| 34 |
|
| 35 |
@staticmethod |
| 36 |
def read(path: str) -> bytes | None: |
| 37 |
# O_NONBLOCK keeps an open of a FIFO planted at the path from blocking; the regular-file check below rejects it. |
| 38 |
if (fd := _open(path, os.O_RDONLY | _O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0) | _O_BINARY)) is None: |
| 39 |
return None |
| 40 |
try: |
| 41 |
if not stat.S_ISREG(os.fstat(fd).st_mode): |
| 42 |
return b"" |
| 43 |
chunks: list[bytes] = [] |
| 44 |
remaining = _MAX_RECORD_SIZE + 1 |
| 45 |
while remaining > 0 and (chunk := os.read(fd, remaining)): |
| 46 |
chunks.append(chunk) |
| 47 |
remaining -= len(chunk) |
| 48 |
return b"".join(chunks) |
| 49 |
finally: |
| 50 |
os.close(fd) |
| 51 |
|
| 52 |
@classmethod |
| 53 |
def create(cls, path: str, data: bytes) -> None: |
| 54 |
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW | _O_BINARY, 0o600) |
| 55 |
try: |
| 56 |
write_all(fd, data) |
| 57 |
except BaseException: |
| 58 |
os.close(fd) |
| 59 |
# The name is unique to this call, so removing it cannot take a record from anyone else. |
| 60 |
cls.unlink(path) |
| 61 |
raise |
| 62 |
os.close(fd) |
| 63 |
|
| 64 |
def link(self, source: str, target: str) -> bool: |
| 65 |
failure: NotImplementedError | OSError | None = None |
| 66 |
try: |
| 67 |
_link_no_follow(source, target) |
| 68 |
except FileExistsError: |
| 69 |
pass |
| 70 |
except (NotImplementedError, OSError) as error: |
| 71 |
_raise_if_hard_links_unsupported(self._lock_file, error) |
| 72 |
failure = error |
| 73 |
# Whatever the call reported, the file's identity decides: an NFS retransmit can turn a link that landed into |
| 74 |
# an error, and an EEXIST can be this very link answered twice. Any other error on a link that did not land is |
| 75 |
# a real fault, not a peer winning the race, and retrying it would spin. |
| 76 |
if (identity := _identity(source)) is not None and identity == _identity(target): |
| 77 |
return True |
| 78 |
if failure is not None: |
| 79 |
raise failure |
| 80 |
return False |
| 81 |
|
| 82 |
@staticmethod |
| 83 |
def overwrite(path: str, data: bytes) -> bool: |
| 84 |
if (fd := _open(path, os.O_WRONLY | _O_NOFOLLOW | _O_BINARY)) is None: |
| 85 |
return False |
| 86 |
try: |
| 87 |
write_all(fd, data) |
| 88 |
finally: |
| 89 |
os.close(fd) |
| 90 |
return True |
| 91 |
|
| 92 |
@staticmethod |
| 93 |
def unlink(path: str) -> None: |
| 94 |
try: |
| 95 |
Path(path).unlink() |
| 96 |
except OSError as error: |
| 97 |
# Windows refuses to remove a file another process holds open; the record then outlives its owner until |
| 98 |
# that process exits, which only delays the cleanup a later participant repeats. |
| 99 |
if error.errno not in _MISSING_ERRNOS and not isinstance(error, PermissionError): |
| 100 |
raise |
| 101 |
|
| 102 |
@staticmethod |
| 103 |
def listdir(path: str) -> list[str]: |
| 104 |
try: |
| 105 |
return [entry.name for entry in Path(path).iterdir()] |
| 106 |
except FileNotFoundError: |
| 107 |
return [] |
| 108 |
|
| 109 |
@staticmethod |
| 110 |
def prepare(root: str) -> None: |
| 111 |
ensure_directory_exists(root) |
| 112 |
for directory in (Path(root), Path(root, _GENERATIONS_DIRECTORY), Path(root, _HOLDERS_DIRECTORY)): |
| 113 |
with suppress(FileExistsError): |
| 114 |
directory.mkdir(mode=0o700) |
| 115 |
# mkdir has no O_NOFOLLOW, so check what the name resolves to before anything is created inside it. |
| 116 |
mode = directory.lstat().st_mode |
| 117 |
if stat.S_ISLNK(mode) or not stat.S_ISDIR(mode): |
| 118 |
msg = f"{directory} exists but is not a directory or is a symlink; refusing to use it" |
| 119 |
raise RuntimeError(msg) |
| 120 |
|
| 121 |
|
| 122 |
def _open(path: str, flags: int) -> int | None: |
| 123 |
# Missing is the one answer a caller acts on without raising. A refused open is real on POSIX, where nothing this |
| 124 |
# lock does makes its own records unreadable; on Windows it is usually another process mid-delete or holding the |
| 125 |
# file without sharing, so it is retried through a short grace before it counts, and a file still refusing after |
| 126 |
# that has been in delete-pending for longer than any deletion takes, so it is on its way out: missing. |
| 127 |
deadline: float | None = None |
| 128 |
while True: |
| 129 |
if isinstance(opened := _attempt_open(path, flags), int): |
| 130 |
return opened |
| 131 |
if opened.errno in _MISSING_ERRNOS: |
| 132 |
return None |
| 133 |
if not isinstance(opened, PermissionError) or sys.platform != "win32": |
| 134 |
raise opened |
| 135 |
if deadline is None: # pragma: win32 cover |
| 136 |
deadline = time.monotonic() + _WINDOWS_OPEN_GRACE |
| 137 |
elif time.monotonic() >= deadline: # pragma: win32 cover |
| 138 |
return None |
| 139 |
time.sleep(0.002) # pragma: win32 cover |
| 140 |
|
| 141 |
|
| 142 |
def _attempt_open(path: str, flags: int) -> int | OSError: |
| 143 |
try: |
| 144 |
return os.open(path, flags) |
| 145 |
except OSError as error: |
| 146 |
return error |
| 147 |
|
| 148 |
|
| 149 |
def _identity(path: str) -> tuple[int, int] | None: |
| 150 |
try: |
| 151 |
st = os.lstat(path) |
| 152 |
except OSError: |
| 153 |
return None |
| 154 |
return st.st_dev, st.st_ino |
| 155 |
|
| 156 |
|
| 157 |
__all__ = [ |
| 158 |
"OsFiles", |
| 159 |
] |