From c9b63b00c74ef619719aa9d1ddb41a4f83dab1a6 Mon Sep 17 00:00:00 2001 From: yw07 Date: Thu, 5 Dec 2024 10:00:02 +0800 Subject: [PATCH] fix: improve file locking mechanism with atomic creation --- qiniu/http/regions_provider.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/qiniu/http/regions_provider.py b/qiniu/http/regions_provider.py index 13d1800a..3e07a7cd 100644 --- a/qiniu/http/regions_provider.py +++ b/qiniu/http/regions_provider.py @@ -142,13 +142,19 @@ def __init__(self, origin_file): self._origin_file = origin_file def __enter__(self): - if os.access(self.lock_file_path, os.R_OK | os.W_OK): + try: + # Atomic file creation + open_flags = os.O_EXCL | os.O_RDWR | os.O_CREAT + fd = os.open(self.lock_file_path, open_flags) + os.close(fd) + except FileExistsError: raise FileAlreadyLocked('File {0} already locked'.format(self._origin_file)) - with open(self.lock_file_path, 'w'): - pass def __exit__(self, exc_type, exc_val, exc_tb): - os.remove(self.lock_file_path) + try: + os.remove(self.lock_file_path) + except FileNotFoundError: + pass # Lock file might have been removed @property def lock_file_path(self):