Skip to content

Use a lock file to avoid exceptions due to concurrenct symlink creation #2851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions tuf/ngclient/file_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright 2025, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0

"""Minimal file locking implementation.

Source: https://stackoverflow.com/questions/489861/locking-a-file-in-python
"""

try:
# Posix based file locking (Linux, Ubuntu, MacOS, etc.)
# Only allows locking on writable files, might cause
# strange results for reading.
import fcntl
def lock_file(f):
if f.writable(): fcntl.lockf(f, fcntl.LOCK_EX)
except ModuleNotFoundError:
# Windows file locking
import msvcrt
def file_size(f):
return os.path.getsize( os.path.realpath(f.name) )
def lock_file(f):
msvcrt.locking(f.fileno(), msvcrt.LK_RLCK, file_size(f))
10 changes: 7 additions & 3 deletions tuf/ngclient/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
from tuf.api.metadata import Root, Snapshot, TargetFile, Targets, Timestamp
from tuf.ngclient._internal.trusted_metadata_set import TrustedMetadataSet
from tuf.ngclient.config import EnvelopeType, UpdaterConfig
from tuf.ngclient.file_lock import lock_file
from tuf.ngclient.urllib3_fetcher import Urllib3Fetcher

if TYPE_CHECKING:
Expand Down Expand Up @@ -362,9 +363,12 @@ def _update_root_symlink(self) -> None:
linkname = os.path.join(self._dir, "root.json")
version = self._trusted_set.root.version
current = os.path.join("root_history", f"{version}.root.json")
with contextlib.suppress(FileNotFoundError):
os.remove(linkname)
os.symlink(current, linkname)

with open(os.path.join(self._dir, current + ".lck"), "wb") as f:
lock_file(f)
with contextlib.suppress(FileNotFoundError):
os.remove(linkname)
os.symlink(current, linkname)

def _load_root(self) -> None:
"""Load root metadata.
Expand Down