Skip to content

prefect.locking.filesystem

FileSystemLockManager

Bases: LockManager

A lock manager that implements locking using local files.

Attributes:

Name Type Description
lock_files_directory

the directory where lock files are stored

Source code in src/prefect/locking/filesystem.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
class FileSystemLockManager(LockManager):
    """
    A lock manager that implements locking using local files.

    Attributes:
        lock_files_directory: the directory where lock files are stored
    """

    def __init__(self, lock_files_directory: Path):
        self.lock_files_directory = lock_files_directory.expanduser().resolve()
        self._locks: Dict[str, _LockInfo] = {}

    def _ensure_lock_files_directory_exists(self):
        self.lock_files_directory.mkdir(parents=True, exist_ok=True)

    def _lock_path_for_key(self, key: str) -> Path:
        if (lock_info := self._locks.get(key)) is not None:
            return lock_info["path"]
        return self.lock_files_directory.joinpath(key).with_suffix(".lock")

    def _get_lock_info(self, key: str, use_cache=True) -> Optional[_LockInfo]:
        if use_cache:
            if (lock_info := self._locks.get(key)) is not None:
                return lock_info

        lock_path = self._lock_path_for_key(key)

        try:
            with open(lock_path, "rb") as lock_file:
                lock_info = pydantic_core.from_json(lock_file.read())
                lock_info["path"] = lock_path
                expiration = lock_info.get("expiration")
                lock_info["expiration"] = (
                    pendulum.parse(expiration) if expiration is not None else None
                )
            self._locks[key] = lock_info
            return lock_info
        except FileNotFoundError:
            return None

    async def _aget_lock_info(
        self, key: str, use_cache: bool = True
    ) -> Optional[_LockInfo]:
        if use_cache:
            if (lock_info := self._locks.get(key)) is not None:
                return lock_info

        lock_path = self._lock_path_for_key(key)

        try:
            lock_info_bytes = await anyio.Path(lock_path).read_bytes()
            lock_info = pydantic_core.from_json(lock_info_bytes)
            lock_info["path"] = lock_path
            expiration = lock_info.get("expiration")
            lock_info["expiration"] = (
                pendulum.parse(expiration) if expiration is not None else None
            )
            self._locks[key] = lock_info
            return lock_info
        except FileNotFoundError:
            return None

    def acquire_lock(
        self,
        key: str,
        holder: str,
        acquire_timeout: Optional[float] = None,
        hold_timeout: Optional[float] = None,
    ) -> bool:
        self._ensure_lock_files_directory_exists()
        lock_path = self._lock_path_for_key(key)

        if self.is_locked(key) and not self.is_lock_holder(key, holder):
            lock_free = self.wait_for_lock(key, acquire_timeout)
            if not lock_free:
                return False

        try:
            Path(lock_path).touch(exist_ok=False)
        except FileExistsError:
            if not self.is_lock_holder(key, holder):
                logger.debug(
                    f"Another actor acquired the lock for record with key {key}. Trying again."
                )
                return self.acquire_lock(key, holder, acquire_timeout, hold_timeout)
        expiration = (
            pendulum.now("utc") + pendulum.duration(seconds=hold_timeout)
            if hold_timeout is not None
            else None
        )

        with open(Path(lock_path), "wb") as lock_file:
            lock_file.write(
                pydantic_core.to_json(
                    {
                        "holder": holder,
                        "expiration": str(expiration)
                        if expiration is not None
                        else None,
                    },
                )
            )

        self._locks[key] = {
            "holder": holder,
            "expiration": expiration,
            "path": lock_path,
        }

        return True

    async def aacquire_lock(
        self,
        key: str,
        holder: str,
        acquire_timeout: Optional[float] = None,
        hold_timeout: Optional[float] = None,
    ) -> bool:
        await anyio.Path(self.lock_files_directory).mkdir(parents=True, exist_ok=True)
        lock_path = self._lock_path_for_key(key)

        if self.is_locked(key) and not self.is_lock_holder(key, holder):
            lock_free = await self.await_for_lock(key, acquire_timeout)
            if not lock_free:
                return False

        try:
            await anyio.Path(lock_path).touch(exist_ok=False)
        except FileExistsError:
            if not self.is_lock_holder(key, holder):
                logger.debug(
                    f"Another actor acquired the lock for record with key {key}. Trying again."
                )
                return self.acquire_lock(key, holder, acquire_timeout, hold_timeout)
        expiration = (
            pendulum.now("utc") + pendulum.duration(seconds=hold_timeout)
            if hold_timeout is not None
            else None
        )

        async with await anyio.Path(lock_path).open("wb") as lock_file:
            await lock_file.write(
                pydantic_core.to_json(
                    {
                        "holder": holder,
                        "expiration": str(expiration)
                        if expiration is not None
                        else None,
                    },
                )
            )

        self._locks[key] = {
            "holder": holder,
            "expiration": expiration,
            "path": lock_path,
        }

        return True

    def release_lock(self, key: str, holder: str) -> None:
        lock_path = self._lock_path_for_key(key)
        if not self.is_locked(key):
            ValueError(f"No lock for transaction with key {key}")
        if self.is_lock_holder(key, holder):
            Path(lock_path).unlink(missing_ok=True)
            self._locks.pop(key, None)
        else:
            raise ValueError(f"No lock held by {holder} for transaction with key {key}")

    def is_locked(self, key: str, use_cache: bool = False) -> bool:
        if (lock_info := self._get_lock_info(key, use_cache=use_cache)) is None:
            return False

        if (expiration := lock_info.get("expiration")) is None:
            return True

        expired = expiration < pendulum.now("utc")
        if expired:
            Path(lock_info["path"]).unlink()
            self._locks.pop(key, None)
            return False
        else:
            return True

    def is_lock_holder(self, key: str, holder: str) -> bool:
        if not self.is_locked(key):
            return False

        if not self.is_locked(key):
            return False
        if (lock_info := self._get_lock_info(key)) is None:
            return False
        return lock_info["holder"] == holder

    def wait_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
        seconds_waited = 0
        while self.is_locked(key, use_cache=False):
            if timeout and seconds_waited >= timeout:
                return False
            seconds_waited += 0.1
            time.sleep(0.1)
        return True

    async def await_for_lock(self, key: str, timeout: Optional[float] = None) -> bool:
        seconds_waited = 0
        while self.is_locked(key, use_cache=False):
            if timeout and seconds_waited >= timeout:
                return False
            seconds_waited += 0.1
            await anyio.sleep(0.1)
        return True