Skip to content
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

Lock cache file with python #168

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
19 changes: 18 additions & 1 deletion lib/id3c/cli/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
import pickle
import logging
from functools import wraps
from typing import Optional
from typing import IO, Any
from cachetools import TTLCache
from contextlib import contextmanager
from fcntl import flock, LOCK_EX, LOCK_UN, LOCK_NB
from id3c.db.session import DatabaseSession


Expand Down Expand Up @@ -125,7 +126,9 @@ def pickled_cache(filename: str = None) -> TTLCache:
LOG.info(f"Loading cache from «{filename}»")
try:
with open(filename, "rb") as file:
lock_file(file)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't comment on the implementation of lock_file() yet, but I think the usage here isn't doing what you expect because it's not being called as a context manager. It should be called as:

with lock_file(file):
    …

cache = pickle.load(file)

except FileNotFoundError:
LOG.warning(f"Cache file «{filename}» does not exist; starting with empty cache.")
cache = empty_cache
Expand All @@ -142,3 +145,17 @@ def pickled_cache(filename: str = None) -> TTLCache:
if filename:
with open(filename, "wb") as file:
pickle.dump(cache, file)


@contextmanager
def lock_file(file_object: IO[Any]):
"""
Context manager for locking/unlocking a given :class:`IOBase` *file_object*.
"""
# Apply POSIX-style, exclusive lock
flock(file_object, LOCK_EX)

yield

# Remove the lock
flock(file_object, LOCK_UN)