Skip to content

Commit 5d22932

Browse files
authored
Adding explicit unlocking using portalocker (#43)
1 parent 8a45dbb commit 5d22932

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

msal_extensions/cache_lock.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,23 @@ class CrossPlatLock(object):
1212
"""
1313
def __init__(self, lockfile_path):
1414
self._lockpath = lockfile_path
15-
self._fh = None
15+
self._lock = portalocker.Lock(
16+
lockfile_path,
17+
mode='wb+',
18+
# In posix systems, we HAVE to use LOCK_EX(exclusive lock) bitwise ORed
19+
# with LOCK_NB(non-blocking) to avoid blocking on lock acquisition.
20+
# More information here:
21+
# https://docs.python.org/3/library/fcntl.html#fcntl.lockf
22+
flags=portalocker.LOCK_EX | portalocker.LOCK_NB,
23+
buffering=0)
1624

1725
def __enter__(self):
18-
pid = os.getpid()
19-
20-
self._fh = open(self._lockpath, 'wb+', buffering=0)
21-
portalocker.lock(self._fh, portalocker.LOCK_EX)
22-
self._fh.write('{} {}'.format(pid, sys.argv[0]).encode('utf-8'))
26+
file_handle = self._lock.__enter__()
27+
file_handle.write('{} {}'.format(os.getpid(), sys.argv[0]).encode('utf-8'))
28+
return file_handle
2329

2430
def __exit__(self, *args):
25-
self._fh.close()
31+
self._lock.__exit__(*args)
2632
try:
2733
# Attempt to delete the lockfile. In either of the failure cases enumerated below, it is
2834
# likely that another process has raced this one and ended up clearing or locking the

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
package_data={'': ['LICENSE']},
1919
install_requires=[
2020
'msal>=0.4.1,<2.0.0',
21-
'portalocker~=1.0',
21+
'portalocker~=1.6',
2222
],
2323
tests_require=['pytest'],
2424
)

0 commit comments

Comments
 (0)