codekingpro/portable-devtools
114k
1"""Provides a mechanism for not competing with other processes interacting with an MSAL cache."""2import os3import sys4import errno5import time6import logging7 8import portalocker9from packaging.version import Version10 11 12logger = logging.getLogger(__name__)13 14 15class CrossPlatLock(object):16 """Offers a mechanism for waiting until another process is finished interacting with a shared17 resource. This is specifically written to interact with a class of the same name in the .NET18 extensions library.19 """20 def __init__(self, lockfile_path):21 self._lockpath = lockfile_path22 # Support for passing through arguments to the open syscall was added in v1.4.023 open_kwargs = ({'buffering': 0}24 if Version(portalocker.__version__) >= Version("1.4.0") else {})25 self._lock = portalocker.Lock(26 lockfile_path,27 mode='wb+',28 # In posix systems, we HAVE to use LOCK_EX(exclusive lock) bitwise ORed29 # with LOCK_NB(non-blocking) to avoid blocking on lock acquisition.30 # More information here:31 # https://docs.python.org/3/library/fcntl.html#fcntl.lockf32 flags=portalocker.LOCK_EX | portalocker.LOCK_NB,33 **open_kwargs)34 35 def _try_to_create_lock_file(self):36 timeout = 537 check_interval = 0.2538 current_time = getattr(time, "monotonic", time.time)39 timeout_end = current_time() + timeout40 pid = os.getpid()41 while timeout_end > current_time():42 try:43 with open(self._lockpath, 'x'): # pylint: disable=unspecified-encoding44 return True45 except ValueError: # This needs to be the first clause, for Python 2 to hit it46 logger.warning("Python 2 does not support atomic creation of file")47 return False48 except FileExistsError: # Only Python 3 will reach this clause49 logger.debug(50 "Process %d found existing lock file, will retry after %f second",51 pid, check_interval)52 time.sleep(check_interval)53 return False54 55 def __enter__(self):56 pid = os.getpid()57 if not self._try_to_create_lock_file():58 logger.warning("Process %d failed to create lock file", pid)59 file_handle = self._lock.__enter__()60 file_handle.write('{} {}'.format(pid, sys.argv[0]).encode('utf-8')) # pylint: disable=consider-using-f-string61 return file_handle62 63 def __exit__(self, *args):64 self._lock.__exit__(*args)65 try:66 # Attempt to delete the lockfile. In either of the failure cases enumerated below, it is67 # likely that another process has raced this one and ended up clearing or locking the68 # file for itself.69 os.remove(self._lockpath)70 except OSError as ex: # pylint: disable=invalid-name71 if ex.errno not in (errno.ENOENT, errno.EACCES):72 raise73 