forked from BrewPi/brewpi-script
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BrewPiProcess.py
297 lines (257 loc) · 10.1 KB
/
BrewPiProcess.py
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# Copyright 2013 BrewPi
# This file is part of BrewPi.
# BrewPi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# BrewPi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with BrewPi. If not, see <http://www.gnu.org/licenses/>.
import pprint
import os
import sys
from time import sleep
from distutils.version import LooseVersion
try:
import psutil
if LooseVersion(psutil.__version__) < LooseVersion("2.0"):
print >> sys.stderr, "Your version of pstuil is %s \n" \
"BrewPi requires psutil 2.0 or higher, please upgrade your version of psutil.\n" \
"This can best be done via pip, please run:\n" \
" sudo apt-get install build-essential python-dev python-pip\n" \
" sudo pip install psutil --upgrade\n" % psutil.__version__
sys.exit(1)
except ImportError:
print "BrewPi requires psutil to run, please install it via pip: 'sudo pip install psutil --upgrade"
sys.exit(1)
import BrewPiSocket
import BrewPiUtil as util
class BrewPiProcess:
"""
This class represents a running BrewPi process.
It allows other instances of BrewPi to see if there would be conflicts between them.
It can also use the socket to send a quit signal or the pid to kill the other instance.
"""
def __init__(self):
self.pid = None # pid of process
self.cfg = None # config file of process, full path
self.port = None # serial port the process is connected to
self.sock = None # BrewPiSocket object which the process is connected to
def as_dict(self):
"""
Returns: member variables as a dictionary
"""
return self.__dict__
def quit(self):
"""
Sends a friendly quit message to this BrewPi process over its socket to aks the process to exit.
"""
if self.sock is not None:
conn = self.sock.connect()
if conn:
conn.send('quit')
conn.close() # do not shutdown the socket, other processes are still connected to it.
print "Quit message sent to BrewPi instance with pid %s!" % self.pid
return True
else:
print "Could not connect to socket of BrewPi process, maybe it just started and is not listening yet."
print "Could not send quit message to BrewPi instance with pid %d!" % self.pid
print "Killing it instead!"
self.kill()
return False
def kill(self):
"""
Kills this BrewPiProcess with force, use when quit fails.
"""
process = psutil.Process(self.pid) # get psutil process my pid
try:
process.kill()
print "SIGKILL sent to BrewPi instance with pid %d!" % self.pid
except psutil.AccessDenied:
print >> sys.stderr, "Cannot kill process %d, you need root permission to do that." % self.pid
print >> sys.stderr, "Is the process running under the same user?"
def conflict(self, otherProcess):
if self.pid == otherProcess.pid:
return 0 # this is me! I don't have a conflict with myself
if otherProcess.cfg == self.cfg:
print "Conflict: same config file as another BrewPi instance already running."
return 1
if otherProcess.port == self.port:
print "Conflict: same serial port as another BrewPi instance already running."
return 1
if [otherProcess.sock.type, otherProcess.sock.file, otherProcess.sock.host, otherProcess.sock.port] == \
[self.sock.type, self.sock.file, self.sock.host, self.sock.port]:
print "Conflict: same socket as another BrewPi instance already running."
return 1
return 0
class BrewPiProcesses():
"""
This class can get all running BrewPi instances on the system as a list of BrewPiProcess objects.
"""
def __init__(self):
self.list = []
def update(self):
"""
Update the list of BrewPi processes by receiving them from the system with psutil.
Returns: list of BrewPiProcess objects
"""
bpList = []
matching = []
# some OS's (OS X) do not allow processes to read info from other processes.
try:
matching = [p for p in psutil.process_iter() if any('python' in p.name() and 'brewpi.py'in s for s in p.cmdline())]
except psutil.AccessDenied:
pass
for p in matching:
bp = self.parseProcess(p)
if bp:
bpList.append(bp)
self.list = bpList
return self.list
def parseProcess(self, process):
"""
Converts a psutil process into a BrewPiProcess object by parsing the config file it has been called with.
Params: a psutil.Process object
Returns: BrewPiProcess object
"""
bp = BrewPiProcess()
try:
bp.pid = process._pid
cfg = [s for s in process.cmdline() if '.cfg' in s] # get config file argument
except psutil.NoSuchProcess:
# process no longer exists
return None
if cfg:
cfg = cfg[0] # add full path to config file
else:
# use default config file location
cfg = util.scriptPath() + "/settings/config.cfg"
bp.cfg = util.readCfgWithDefaults(cfg)
bp.port = bp.cfg['port']
bp.sock = BrewPiSocket.BrewPiSocket(bp.cfg)
return bp
def get(self):
"""
Returns a non-updated list of BrewPiProcess objects
"""
return self.list
def me(self):
"""
Get a BrewPiProcess object of the process this function is called from
"""
myPid = os.getpid()
myProcess = psutil.Process(myPid)
return self.parseProcess(myProcess)
def findConflicts(self, process):
"""
Finds out if the process given as argument will conflict with other running instances of BrewPi
Always returns a conflict if a firmware update is running
Params:
process: a BrewPiProcess object that will be compared with other running instances
Returns:
bool: True means there are conflicts, False means no conflict
"""
# some OS's (OS X) do not allow processes to read info from other processes.
matching = []
try:
matching = [p for p in psutil.process_iter() if any('python' in p.name() and 'flashDfu.py'in s for s in p.cmdline())]
except psutil.AccessDenied:
pass
if len(matching) > 0:
return 1
try:
matching = [p for p in psutil.process_iter() if any('python' in p.name() and 'updateFirmware.py'in s for s in p.cmdline())]
except psutil.AccessDenied:
pass
if len(matching) > 0:
return 1
for p in self.list:
if process.pid == p.pid: # skip the process itself
continue
elif process.conflict(p):
return 1
return 0
def as_dict(self):
"""
Returns the list of BrewPiProcesses as a list of dicts, except for the process calling this function
"""
outputList = []
myPid = os.getpid()
self.update()
for p in self.list:
if p.pid == myPid: # do not send quit message to myself
continue
outputList.append(p.as_dict())
return outputList
def __repr__(self):
"""
Print BrewPiProcesses as a dict when passed to a print statement
"""
return repr(self.as_dict())
def quitAll(self):
"""
Ask all running BrewPi processes to exit
"""
myPid = os.getpid()
self.update()
for p in self.list:
if p.pid == myPid: # do not send quit message to myself
continue
else:
p.quit()
def stopAll(self, dontRunFilePath):
"""
Ask all running Brewpi processes to exit, and prevent restarting by writing
the do_not_run file
"""
if not os.path.exists(dontRunFilePath):
# if do not run file does not exist, create it
dontrunfile = open(dontRunFilePath, "w")
dontrunfile.write("1")
dontrunfile.close()
myPid = os.getpid()
self.update()
for p in self.list:
if p.pid == myPid: # do not send quit message to myself
continue
else:
p.quit()
def killAll(self):
"""
Kill all running BrewPi processes with force by sending a sigkill signal.
"""
myPid = os.getpid()
self.update()
for p in self.list:
if p.pid == myPid: # do not commit suicide
continue
else:
p.kill()
def testKillAll():
"""
Test function that prints the process list, sends a kill signal to all processes and prints the updated list again.
"""
allScripts = BrewPiProcesses()
allScripts.update()
print ("Running instances of BrewPi before killing them:")
pprint.pprint(allScripts)
allScripts.killAll()
allScripts.update()
print ("Running instances of BrewPi before after them:")
pprint.pprint(allScripts)
def testQuitAll():
"""
Test function that prints the process list, sends a quit signal to all processes and prints the updated list again.
"""
allScripts = BrewPiProcesses()
allScripts.update()
print ("Running instances of BrewPi before asking them to quit:")
pprint.pprint(allScripts)
allScripts.quitAll()
sleep(2)
allScripts.update()
print ("Running instances of BrewPi after asking them to quit:")
pprint.pprint(allScripts)