Skip to content

Commit 7a8417e

Browse files
committed
fix: windows locker
1 parent b6fd793 commit 7a8417e

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

Diff for: qiniu/http/regions_provider.py

+38-7
Original file line numberDiff line numberDiff line change
@@ -208,46 +208,73 @@ def _file_path(self):
208208
class _FileLocker:
209209
def __init__(self, fd):
210210
self._fd = fd
211+
self._lock_fd = None
212+
self._already_locked = False
211213

212214
def __enter__(self):
213215
try:
214-
msvcrt.locking(self._fd.fileno(), msvcrt.LK_LOCK | msvcrt.LK_NBLCK, 1)
216+
self._lock_fd = open(self._lock_file_path, 'w')
217+
msvcrt.locking(self._lock_fd.fileno(), msvcrt.LK_LOCK | msvcrt.LK_NBLCK, 1)
215218
except OSError:
219+
self._already_locked = True
216220
raise FileAlreadyLocked('File {0} already locked'.format(self._file_path))
217221

218222
def __exit__(self, exc_type, exc_val, exc_tb):
219-
msvcrt.locking(self._fd.fileno(), msvcrt.LK_UNLCK, 1)
223+
if self._already_locked:
224+
if self._lock_fd:
225+
self._lock_fd.close()
226+
return
227+
228+
try:
229+
msvcrt.locking(self._lock_fd.fileno(), msvcrt.LK_UNLCK, 1)
230+
finally:
231+
self._lock_fd.close()
232+
os.remove(self._lock_file_path)
233+
220234

221235
@property
222236
def _file_path(self):
223237
return self._fd.name
224238

239+
@property
240+
def _lock_file_path(self):
241+
"""
242+
Returns
243+
-------
244+
str
245+
"""
246+
return self._file_path + '.lock'
247+
225248
else:
226249
class _FileLocker:
227250
def __init__(self, fd):
228251
self._fd = fd
252+
self._already_locked = False
229253

230254
def __enter__(self):
231255
try:
232256
# Atomic file creation
233257
open_flags = os.O_EXCL | os.O_RDWR | os.O_CREAT
234-
fd = os.open(self.lock_file_path, open_flags)
258+
fd = os.open(self._lock_file_path, open_flags)
235259
os.close(fd)
236-
except IOError:
260+
except OSError:
261+
self._already_locked = True
237262
raise FileAlreadyLocked('File {0} already locked'.format(self._file_path))
238263

239264
def __exit__(self, exc_type, exc_val, exc_tb):
265+
if self._already_locked:
266+
return
240267
try:
241-
os.remove(self.lock_file_path)
242-
except IOError:
268+
os.remove(self._lock_file_path)
269+
except OSError:
243270
pass
244271

245272
@property
246273
def _file_path(self):
247274
return self._fd.name
248275

249276
@property
250-
def lock_file_path(self):
277+
def _lock_file_path(self):
251278
"""
252279
Returns
253280
-------
@@ -770,6 +797,10 @@ def __shrink_cache(self):
770797
os.chmod(shrink_file_path, 0o666)
771798

772799
# rename file
800+
if is_windows:
801+
# windows must close first, or will raise permission error
802+
# be careful to do something with the file after this
803+
f.close()
773804
shutil.move(shrink_file_path, self._cache_scope.persist_path)
774805

775806
# update last shrink time

0 commit comments

Comments
 (0)