-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlockfile.py
More file actions
103 lines (79 loc) · 3.08 KB
/
lockfile.py
File metadata and controls
103 lines (79 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
import subprocess
import os
import socket
import datetime
class LockFile(object):
def __init__(self, lockfile_type):
hostname = socket.gethostname()
self._lockfile_name = f"Lockfile.{lockfile_type}.{hostname}"
self._tmp_lockfile_name = f"/tmp/Lockfile.{lockfile_type}.{hostname}"
self._process_ids = []
def log(self, msg):
f = None
x = datetime.datetime.now()
try:
f = open(self._tmp_lockfile_name, "a")
f.write(f'{x.strftime("%Y-%m-%d:%H:%M:%S")}: {msg}\n')
finally:
if f:
f.close()
def run_ps(self):
# this only works in python2.7
# print "running ps"
self.log("Getting list of system PIDs ...")
x = subprocess.check_output(['ps', 'aux'], stderr=subprocess.STDOUT)
lines = x.split('\n')
for line in lines:
if not line:
continue
# print "LINE", line
parts = line.split()
# print parts
if parts[0] == 'USER':
continue
self._process_ids.append(int(parts[1]))
self.log(f"Read {len(self._process_ids)} system PIDs")
def get_lock_pid(self):
result = None
try:
f = open(self._lockfile_name)
if f:
for line in f:
if line:
result = int(line)
f.close()
except Exception:
result = None
self.log("get_lock_pid({self._lockfile_name}): returning: {repr(result)}")
return result
def set_lock_pid(self, my_pid):
f = open(self._lockfile_name, "w")
f.write("%d\n" % my_pid)
f.close()
def acquire(self):
pid = self.get_lock_pid()
if pid is None:
self.log("No lockfile found")
my_pid = int(os.getpid())
self.set_lock_pid(my_pid)
pid = self.get_lock_pid()
if my_pid == pid:
self.log("Created new lockfile with PID: %d; starting" % my_pid)
return
self.log("Failed to create new lockfile with PID: %d; not starting" % my_pid)
raise ValueError("Failed to create lockfile: %s: %d != %d; not starting" % (self._lockfile_name, my_pid, pid))
self.log("Found existing PID: %d" % pid)
self.run_ps()
if pid in self._process_ids:
self.log("Lockfile PID %d in list of running PIDs; not starting" % pid)
raise ValueError("Detected process with PID: %d (%s)" % (pid, self._lockfile_name))
self.log("removing stale lockfile for PID: %d" % pid)
os.remove(self._lockfile_name)
my_pid = int(os.getpid())
self.set_lock_pid(my_pid)
pid = self.get_lock_pid()
if my_pid == pid:
self.log("Created new lockfile with PID: %d; starting" % my_pid)
return
self.log("Failed to create new lockfile with PID: %d; not starting" % my_pid)
raise ValueError("Failed to create lockfile: %s: %d != %d" % (self._lockfile_name, my_pid, pid))