Skip to content

Commit bd930e8

Browse files
authored
Cache resiliency (#63)
1 parent 0d47dad commit bd930e8

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

msal_extensions/cache_lock.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22
import os
33
import sys
44
import errno
5+
import time
6+
import logging
7+
8+
logger = logging.getLogger(__name__)
9+
510
import portalocker
611
from distutils.version import LooseVersion
712

@@ -25,7 +30,26 @@ def __init__(self, lockfile_path):
2530
flags=portalocker.LOCK_EX | portalocker.LOCK_NB,
2631
**open_kwargs)
2732

33+
def try_to_create_lock_file(self):
34+
timeout = 5
35+
check_interval = 0.25
36+
current_time = getattr(time, "monotonic", time.time)
37+
timeout_end = current_time() + timeout
38+
while timeout_end > current_time():
39+
try:
40+
with open(self._lockpath, 'x'):
41+
return True
42+
except ValueError: # This needs to be the first clause, for Python 2 to hit it
43+
logger.warning("Python 2 does not support atomic creation of file")
44+
return False
45+
except FileExistsError: # Only Python 3 will reach this clause
46+
logger.warning("Lock file exists, trying again after some time")
47+
time.sleep(check_interval)
48+
return False
49+
2850
def __enter__(self):
51+
if not self.try_to_create_lock_file():
52+
logger.warning("Failed to create lock file")
2953
file_handle = self._lock.__enter__()
3054
file_handle.write('{} {}'.format(os.getpid(), sys.argv[0]).encode('utf-8'))
3155
return file_handle

tests/test_cache_lock_file_perf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def test_lock_for_high_workload(temp_location):
6767

6868

6969
def test_lock_for_timeout(temp_location):
70-
num_of_processes = 10
70+
num_of_processes = 30
7171
sleep_interval = 1
7272
_run_multiple_processes(num_of_processes, temp_location, sleep_interval)
7373
count = _validate_result_in_cache(temp_location)

0 commit comments

Comments
 (0)