source: trunk/docs/check_running.py

Last change on this file was a7398e1, checked in by GitHub <noreply@…>, at 2022-09-28T15:35:17Z

Update docs/check_running.py

Co-authored-by: Jean-Paul Calderone <exarkun@…>

  • Property mode set to 100644
File size: 1.4 KB
Line 
1
2import psutil
3import filelock
4
5
6def can_spawn_tahoe(pidfile):
7    """
8    Determine if we can spawn a Tahoe-LAFS for the given pidfile. That
9    pidfile may be deleted if it is stale.
10
11    :param pathlib.Path pidfile: the file to check, that is the Path
12        to "running.process" in a Tahoe-LAFS configuration directory
13
14    :returns bool: True if we can spawn `tahoe run` here
15    """
16    lockpath = pidfile.parent / (pidfile.name + ".lock")
17    with filelock.FileLock(lockpath):
18        try:
19            with pidfile.open("r") as f:
20                pid, create_time = f.read().strip().split(" ", 1)
21        except FileNotFoundError:
22            return True
23
24        # somewhat interesting: we have a pidfile
25        pid = int(pid)
26        create_time = float(create_time)
27
28        try:
29            proc = psutil.Process(pid)
30            # most interesting case: there _is_ a process running at the
31            # recorded PID -- but did it just happen to get that PID, or
32            # is it the very same one that wrote the file?
33            if create_time == proc.create_time():
34                # _not_ stale! another intance is still running against
35                # this configuration
36                return False
37
38        except psutil.NoSuchProcess:
39            pass
40
41        # the file is stale
42        pidfile.unlink()
43        return True
44
45
46from pathlib import Path
47print("can spawn?", can_spawn_tahoe(Path("running.process")))
Note: See TracBrowser for help on using the repository browser.