-
Notifications
You must be signed in to change notification settings - Fork 245
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
Improvements around test_pidfile_contents #1328
Draft
exarkun
wants to merge
12
commits into
tahoe-lafs:master
Choose a base branch
from
exarkun:4058.test_pidfile_contents
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
c579f28
check_pid_process is not a context manager
exarkun 4cde6ac
Further constrain the test and the implementation
exarkun 145910d
news fragments
exarkun 2493f67
handle line-break related characters too
exarkun c2868e3
the re escape for "whitespace" is "\s" not "\w" :(
exarkun aae73ba
Merge remote-tracking branch 'origin/master' into 4058.test_pidfile_c…
exarkun dd33519
module docstring and __future__.annotations
exarkun 9750e54
some more type annotations
exarkun 18fe33e
fix the mypy error about the lambda
exarkun 85e06f6
fix more errors from mypy
exarkun f978f9c
define the function before using it
exarkun b744c76
remove unused import
exarkun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
Empty file.
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,18 @@ | ||
""" | ||
Process IDentification-related helpers. | ||
""" | ||
|
||
from __future__ import annotations | ||
|
||
import psutil | ||
from attrs import frozen | ||
|
||
# the docs are a little misleading, but this is either WindowsFileLock | ||
# or UnixFileLock depending upon the platform we're currently on | ||
from filelock import FileLock, Timeout | ||
|
||
from twisted.python.filepath import FilePath | ||
|
||
|
||
class ProcessInTheWay(Exception): | ||
""" | ||
|
@@ -23,36 +32,40 @@ class CannotRemovePidFile(Exception): | |
""" | ||
|
||
|
||
def _pidfile_to_lockpath(pidfile): | ||
def _pidfile_to_lockpath(pidfile: FilePath) -> FilePath: | ||
""" | ||
internal helper. | ||
:returns FilePath: a path to use for file-locking the given pidfile | ||
:returns: a path to use for file-locking the given pidfile | ||
""" | ||
return pidfile.sibling("{}.lock".format(pidfile.basename())) | ||
|
||
|
||
def parse_pidfile(pidfile): | ||
def parse_pidfile(pidfile: FilePath) -> tuple[int, float]: | ||
""" | ||
:param FilePath pidfile: | ||
:returns tuple: 2-tuple of pid, creation-time as int, float | ||
:param pidfile: The path to the file to parse. | ||
|
||
:return: 2-tuple of pid, creation-time as int, float | ||
|
||
:raises InvalidPidFile: on error | ||
""" | ||
with pidfile.open("r") as f: | ||
content = f.read().decode("utf8").strip() | ||
try: | ||
pid, starttime = content.split() | ||
pid = int(pid) | ||
starttime = float(starttime) | ||
pid_str, starttime_str = content.split() | ||
pid = int(pid_str) | ||
starttime = float(starttime_str) | ||
except ValueError: | ||
raise InvalidPidFile( | ||
"found invalid PID file in {}".format( | ||
pidfile | ||
) | ||
) | ||
if pid <= 0 or starttime < 0: | ||
raise InvalidPidFile(f"Found value out of bounds: pid={pid} time={starttime}") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. even though these values pass through our simple parser above, we know that they are semantically nonsensical so we can exclude them here rather than letting them reach other parts of the system. |
||
return pid, starttime | ||
|
||
|
||
def check_pid_process(pidfile): | ||
def check_pid_process(pidfile: FilePath) -> None: | ||
""" | ||
If another instance appears to be running already, raise an | ||
exception. Otherwise, write our PID + start time to the pidfile | ||
|
@@ -68,7 +81,7 @@ def check_pid_process(pidfile): | |
# a short timeout is fine, this lock should only be active | ||
# while someone is reading or deleting the pidfile .. and | ||
# facilitates testing the locking itself. | ||
with FileLock(lock_path.path, timeout=2): | ||
with FileLock(_CouldBeBytesPath(lock_path.path), timeout=2): | ||
# check if we have another instance running already | ||
if pidfile.exists(): | ||
pid, starttime = parse_pidfile(pidfile) | ||
|
@@ -85,7 +98,7 @@ def check_pid_process(pidfile): | |
except psutil.NoSuchProcess: | ||
print( | ||
"'{pidpath}' refers to {pid} that isn't running".format( | ||
pidpath=pidfile.path, | ||
pidpath=pidfile.asTextMode().path, | ||
pid=pid, | ||
) | ||
) | ||
|
@@ -98,23 +111,35 @@ def check_pid_process(pidfile): | |
f.write("{} {}\n".format(proc.pid, proc.create_time()).encode("utf8")) | ||
except Timeout: | ||
raise ProcessInTheWay( | ||
"Another process is still locking {}".format(pidfile.path) | ||
"Another process is still locking {}".format(pidfile.asTextMode().path) | ||
) | ||
|
||
|
||
def cleanup_pidfile(pidfile): | ||
def cleanup_pidfile(pidfile: FilePath) -> None: | ||
""" | ||
Remove the pidfile specified (respecting locks). If anything at | ||
all goes wrong, `CannotRemovePidFile` is raised. | ||
""" | ||
lock_path = _pidfile_to_lockpath(pidfile) | ||
with FileLock(lock_path.path): | ||
with FileLock(_CouldBeBytesPath(lock_path.path)): | ||
try: | ||
pidfile.remove() | ||
except Exception as e: | ||
raise CannotRemovePidFile( | ||
"Couldn't remove '{pidfile}': {err}.".format( | ||
pidfile=pidfile.path, | ||
pidfile=pidfile.asTextMode().path, | ||
err=e, | ||
) | ||
) | ||
|
||
@frozen | ||
class _CouldBeBytesPath(object): | ||
""" | ||
Sneak bytes past `FileLock.__init__`. | ||
|
||
See https://github.com/tox-dev/py-filelock/issues/258 | ||
""" | ||
_path: str | bytes | ||
|
||
def __fspath__(self) -> str | bytes: | ||
return self._path |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I greatly elaborated this regular expression and removed some subtle inconsistencies with the real parser but note that apart from getting much longer a significant change here is going from
\w
("word character") to\s
("whitespace character") - a pretty dramatic inconsistency, I think.