Debian Codegraph @

ansible_collections/community/proxmox/plugins/module_utils/_filelock.py

raw
1 # Copyright (c) 2018, Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 # NOTE:
6 # This has been vendored from ansible.module_utils.common.file. This code has been removed from there for ansible-core 2.16.
7
8
9 import fcntl
10 import os
11 import stat
12 import time
13 from contextlib import contextmanager
14
15
16 class LockTimeout(Exception):
17 pass
18
19
20 class FileLock:
21 """
22 Implementation uses fcntl.flock on a lock file; behaviour may change in the future.
23
24 Avoid mixing lock types fcntl.flock, fcntl.lockf and module_utils.common.file.FileLock
25 as it will certainly cause unwanted and/or unexpected behaviour.
26 """
27
28 def __init__(self):
29 self.lockfd = None
30
31 @contextmanager
32 def lock_file(self, path, tmpdir, lock_timeout=None):
33 """Context for lock acquisition."""
34 try:
35 self.set_lock(path, tmpdir, lock_timeout)
36 yield
37 finally:
38 self.unlock()
39
40 def set_lock(self, path, tmpdir, lock_timeout=None):
41 """
42 Create a lock file based on path with flock to prevent other processes using given path.
43
44 Please note that currently file locking only works when it is executed by
45 the same user, for example single user scenarios.
46
47 :kw path: Path (file) to lock
48 :kw tmpdir: Path where to place the temporary .lock file
49 :kw lock_timeout:
50 Wait n seconds for lock acquisition, fail if timeout is reached.
51 0 = Do not wait, fail if lock cannot be acquired immediately,
52 Default is None, wait indefinitely until lock is released.
53 :returns: True
54 """
55 lock_path = os.path.join(tmpdir, f"ansible-{os.path.basename(path)}.lock")
56 l_wait = 0.1
57 r_exception = BlockingIOError
58
59 self.lockfd = open(lock_path, "w") # noqa: SIM115 - open is used to create a lock file
60
61 if lock_timeout <= 0:
62 fcntl.flock(self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
63 os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)
64 return True
65
66 if lock_timeout:
67 e_secs = 0
68 while e_secs < lock_timeout:
69 try:
70 fcntl.flock(self.lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
71 os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)
72 return True
73 except r_exception:
74 time.sleep(l_wait)
75 e_secs += l_wait
76 continue
77
78 self.lockfd.close()
79 raise LockTimeout(f"{lock_timeout} sec")
80
81 fcntl.flock(self.lockfd, fcntl.LOCK_EX)
82 os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)
83
84 return True
85
86 def unlock(self):
87 """
88 Make sure lock file is available for everyone and unlock the file descriptor locked by set_lock.
89
90 :returns: True
91 """
92 if not self.lockfd:
93 return True
94
95 try:
96 fcntl.flock(self.lockfd, fcntl.LOCK_UN)
97 self.lockfd.close()
98 except ValueError: # file wasn't opened, let context manager fail gracefully
99 pass
100
101 return True