Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/filelock/_unix.py: 45%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

143 statements  

1from __future__ import annotations 

2 

3__lazy_modules__ = ["contextlib", "filelock._util", "pathlib", "typing", "warnings"] 

4 

5import os 

6import sys 

7import warnings 

8from contextlib import suppress 

9from errno import EACCES, EAGAIN, ENOSYS, EWOULDBLOCK 

10from pathlib import Path 

11from typing import Final, cast 

12 

13from filelock._api import BaseFileLock 

14from filelock._util import remove_own_file 

15 

16has_fcntl = False 

17if sys.platform == "win32": # pragma: win32 cover 

18 

19 class UnixFileLock(BaseFileLock): 

20 """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems.""" 

21 

22 def _acquire(self) -> None: 

23 raise NotImplementedError 

24 

25 def _release(self) -> None: 

26 raise NotImplementedError 

27 

28else: # pragma: win32 no cover 

29 try: 

30 import fcntl 

31 

32 _ = (fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_NB, fcntl.LOCK_UN) 

33 except (ImportError, AttributeError): 

34 _FCNTL_UNAVAILABLE: Final[str] = "fcntl is unavailable" 

35 

36 def _lock_fd_nonblocking(_fd: int) -> bool: 

37 raise OSError(ENOSYS, _FCNTL_UNAVAILABLE) 

38 

39 def _unlock_fd(_fd: int) -> None: 

40 raise OSError(ENOSYS, _FCNTL_UNAVAILABLE) 

41 

42 else: 

43 has_fcntl = True 

44 # Contention errnos for a nonblocking flock. EAGAIN/EWOULDBLOCK are the usual "held elsewhere" codes; some 

45 # filesystems report EACCES instead, so treat it as contention too rather than a permanent error. 

46 _CONTENTION_ERRNOS: Final[frozenset[int]] = frozenset({EACCES, EAGAIN, EWOULDBLOCK}) 

47 

48 def _lock_fd_nonblocking(fd: int) -> bool: 

49 # One nonblocking exclusive flock attempt shared by UnixFileLock and lock_descriptor, so both contend on 

50 # the same lock and classify errors identically. The caller owns fd; this never closes it. 

51 try: 

52 fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) 

53 except OSError as exception: 

54 if exception.errno in _CONTENTION_ERRNOS: 

55 return False 

56 raise 

57 return True 

58 

59 def _unlock_fd(fd: int) -> None: 

60 fcntl.flock(fd, fcntl.LOCK_UN) 

61 

62 def _flock_is_missing(fd: int) -> bool: 

63 try: 

64 _lock_fd_nonblocking(fd) 

65 except OSError as exception: 

66 return exception.errno == ENOSYS 

67 return False # a flock the probe won is released when the caller closes fd 

68 

69 class UnixFileLock(BaseFileLock): 

70 """ 

71 Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems. 

72 

73 We leave the lock file in place after release. Unlinking a locked file on Unix splits 

74 waiters across inodes and breaks mutual exclusion for processes that coordinate via the 

75 same path. 

76 """ 

77 

78 def _acquire(self) -> None: 

79 if (missing_flock := self._acquire_native()) is not None: 

80 fd, exception, created = missing_flock 

81 self._switch_to_soft_lock(fd, exception, created=created) 

82 

83 def _acquire_native(self) -> tuple[int, OSError, bool] | None: 

84 if (opened := self._open_lock_file()) is None: 

85 return None 

86 fd, created = opened 

87 self._mark_descriptor_pending(fd) 

88 if created: 

89 # Before the flock: a peer may win it first, and only the creator may set the mode. Outside the flock 

90 # handler below: an fchmod that answers ENOSYS says nothing about flock. 

91 try: 

92 self._apply_explicit_mode(fd) 

93 except BaseException: 

94 self._mark_descriptor_released() 

95 os.close(fd) 

96 raise 

97 # One guard covers the flock through the recording of the hold. A signal handler that raises in between 

98 # would otherwise leave an unreferenced descriptor, and its flock, open until the process exits. 

99 locked = False 

100 try: 

101 locked = _lock_fd_nonblocking(fd) 

102 if locked and self._finalize_locked_fd(fd): 

103 return None 

104 except BaseException as exception: 

105 if not locked and isinstance(exception, OSError) and exception.errno == ENOSYS: 

106 return fd, exception, created 

107 # Contention returns False from _lock_fd_nonblocking, so a raise here is a failure. 

108 self._mark_descriptor_released() 

109 os.close(fd) 

110 raise 

111 self._mark_descriptor_released() 

112 os.close(fd) # contention or an unlinked inode; let the retry loop try again 

113 return None 

114 

115 def _open_lock_file(self) -> tuple[int, bool] | None: 

116 # No O_TRUNC: a contender that loses the flock must not truncate the holder's file (#591), and neither may 

117 # the winner, since a file renamed or hard-linked to the lock path is indistinguishable from a lock file. 

118 # O_EXCL tells whether this attempt created the inode: only then does it get the explicit mode, and the 

119 # ENOSYS fallback removes only its own placeholder. O_NONBLOCK: a lease (Linux F_SETLEASE) on the file would 

120 # otherwise block the open for up to fs.lease-break-time, beyond timeout, blocking=False and cancel_check. 

121 open_flags = os.O_RDWR | os.O_NONBLOCK 

122 if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None: 

123 open_flags |= o_nofollow 

124 open_mode = self._open_mode() 

125 try: 

126 return os.open(self._lock_path, open_flags | os.O_CREAT | os.O_EXCL, open_mode), True 

127 except FileExistsError: 

128 pass 

129 except FileNotFoundError: 

130 # On FUSE/NFS a split LOOKUP + CREATE lets a concurrent unlink() race the create, so ENOENT is transient 

131 # contention. An empty or separator-terminated path (Path() strips the separator) fails this way on 

132 # every attempt on macOS, so re-raise rather than retry forever. 

133 if self._lock_path and not self._lock_path.endswith(os.sep) and Path(self._lock_path).parent.exists(): 

134 return None 

135 raise 

136 except PermissionError: 

137 # Sticky-bit dirs (e.g. /tmp): O_CREAT fails if another user owns the file (#317). 

138 if not Path(self._lock_path).exists(): 

139 raise 

140 return self._open_existing_lock_file(open_flags, open_mode) 

141 

142 def _open_existing_lock_file(self, open_flags: int, open_mode: int) -> tuple[int, bool] | None: 

143 try: 

144 return os.open(self._lock_path, open_flags, open_mode), False 

145 except FileNotFoundError: 

146 return None # unlinked since the create attempt; let the retry loop start over 

147 except BlockingIOError: 

148 return None # a lease is breaking: contention, so the retry loop keeps the deadline 

149 except PermissionError: 

150 # A marker another account left is readable but not writable. Without flock, waiting on it only needs 

151 # reading it; with flock the lock writes its file, so the denial stands. 

152 try: 

153 fd = os.open(self._lock_path, open_flags & ~os.O_RDWR | os.O_RDONLY) 

154 except (FileNotFoundError, BlockingIOError): 

155 return None # unlinked, or leased: the kernel checks permission before the lease 

156 if _flock_is_missing(fd): 

157 return fd, False 

158 os.close(fd) 

159 raise 

160 

161 def _switch_to_soft_lock(self, fd: int, missing_flock: OSError, *, created: bool) -> None: 

162 # The filesystem does not implement flock. Fail closed when the caller opted out of existence-lock 

163 # semantics (#603), asked to preserve the pathname (#605), or set an on_acquired hook (#607), none of which 

164 # a soft lock can honor. 

165 falls_back: Final = self._fallback_to_soft and not self._preserve_lock_file and self._on_acquired is None 

166 try: 

167 # A file this attempt did not create may be a peer's live marker, so it stays. Our own placeholder goes 

168 # before the close: the open descriptor keeps its inode number from a peer's marker, and an exchange 

169 # puts back a peer's marker that replaced it. 

170 if created and falls_back: 

171 with suppress(OSError): 

172 remove_own_file(self._lock_path, fd) 

173 finally: 

174 self._mark_descriptor_released() 

175 os.close(fd) 

176 if not falls_back: 

177 raise missing_flock 

178 self._fallback_to_soft_lock() 

179 self._acquire() 

180 

181 def _finalize_locked_fd(self, fd: int) -> bool: 

182 # Runs with the flock held; the caller closes fd on failure. A concurrent _release() may have unlinked 

183 # the file between our open() and flock(), which st_nlink 0 shows. That lock guards no name, so report 

184 # it and let the retry loop start over. 

185 if (stat_result := os.fstat(fd)).st_nlink == 0: 

186 return False 

187 self._mark_descriptor_owned(fd, (stat_result.st_dev, stat_result.st_ino)) 

188 return True 

189 

190 def _apply_explicit_mode(self, fd: int) -> None: 

191 if self.has_explicit_mode: 

192 with suppress(PermissionError): 

193 os.fchmod(fd, self._context.mode) 

194 

195 def _fallback_to_soft_lock(self: BaseFileLock) -> None: 

196 # Import lazily: this runs only on the rare flock fallback, and asyncio imports _unix, so a 

197 # module-level import of it here would cycle. 

198 from filelock._soft import SoftFileLock # ruff:ignore[import-outside-top-level] 

199 

200 warnings.warn("flock not supported on this filesystem, falling back to SoftFileLock", stacklevel=2) 

201 from filelock.asyncio import AsyncSoftFileLock, BaseAsyncFileLock # ruff:ignore[import-outside-top-level] 

202 

203 self.__class__ = AsyncSoftFileLock if isinstance(self, BaseAsyncFileLock) else SoftFileLock 

204 

205 def _release(self) -> None: 

206 fd = cast("int", self._context.lock_file_fd) 

207 # Retain the descriptor until flock succeeds: a failed unlock leaves the kernel lock held, so is_locked 

208 # must keep reporting held for a retry. Once flock commits, clear held state and close as post-unlock 

209 # cleanup; a close failure (EIO on FUSE/Docker bind mounts) does not make the kernel lock held again. 

210 _unlock_fd(fd) 

211 self._mark_descriptor_released() 

212 self._close_released_fd(fd, default_suppresses=True) 

213 

214 

215if sys.platform == "win32": # pragma: win32 cover 

216 __all__ = ["UnixFileLock", "has_fcntl"] 

217else: # pragma: win32 no cover 

218 __all__ = ["UnixFileLock", "_lock_fd_nonblocking", "_unlock_fd", "has_fcntl"]