1 # vim: set encoding=utf-8 et sw=4 sts=4 :
7 import logging ; log = logging.getLogger('pymin.procman')
9 __all__ = ('ProcessManager', 'manager', 'register', 'unregister', 'once',
10 'start', 'stop', 'restart', 'kill', 'get', 'has', 'sigchild_handler')
13 def __init__(self, name, command, callback=None, persist=False,
14 max_errors=3, args=None, kwargs=None):
16 self.command = command
17 self.callback = callback
18 if args is None: args = list()
20 if kwargs is None: kwargs = dict()
22 self.persist = persist
23 self.max_errors = max_errors
26 self._dont_run = False
31 assert self.process is None
35 log.debug(u'ProcessInfo.restart(): executing %s', self.command)
36 self._process = subprocess.Popen(self.command,
37 *self.args, **self.kwargs)
39 assert self.process is not None
41 if self._signal == signal.SIGTERM or self._signal == signal.SIGKILL:
42 # Allready stopped, kill it
43 self.kill(signal.SIGKILL)
46 self.kill(signal.SIGTERM)
47 def kill(self, signum):
48 log.debug(u'ProcessInfo.kill(): killing pid %s with signal %s',
49 self.process.pid, signum)
50 assert self.process is not None
51 os.kill(self.process.pid, signum)
55 return self.process is not None and self.process.poll() is None
63 def error_count(self):
64 return self._error_count
67 if self.process is not None:
68 pid = self.process.pid
69 return 'ProcessInfo(name=%s, pid=%s command=%s, persist=%s, cb=%s)' % (
70 self.name, pid, self.command, self.persist,
71 self.callback and self.callback.__name__ or None)
76 self.services = dict()
79 log.debug(u'ProcessManager()')
81 def register(self, name, command=None, callback=None, persist=False,
82 max_errors=3, *args, **kwargs):
83 log.debug(u'ProcessManager.register(%s, %s, %s, %s, %s, %s, %s)',
84 name, command, callback, persist, max_errors, args, kwargs)
85 if not isinstance(name, ProcessInfo):
86 pi = ProcessInfo(name, command, callback, persist, max_errors,
91 assert not self.has(name)
92 self.services[name] = pi
95 def unregister(self, name):
96 log.debug(u'ProcessManager.unregister(%s)', name)
97 if isinstance(name, ProcessInfo):
101 pi = self.services[name]
102 del self.services[name]
107 self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
109 def once(self, name, command=None, callback=None, persist=False,
110 max_errors=3, *args, **kwargs):
111 log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
112 name, command, callback, persist, max_errors, args, kwargs)
113 if not isinstance(name, ProcessInfo):
114 pi = ProcessInfo(name, command, callback, persist, max_errors,
119 assert not self.has(name)
123 def start(self, name):
124 log.debug(u'ProcessManager.start(%s)', name)
125 if isinstance(name, ProcessInfo):
127 if name not in self.namemap:
128 self._call(self.services[name])
132 def stop(self, name):
133 log.debug(u'ProcessManager.stop(%s)', name)
134 if isinstance(name, ProcessInfo):
136 if name in self.namemap:
137 self.namemap[name].stop()
141 def restart(self, name):
142 log.debug(u'ProcessManager.restart(%s)', name)
143 if isinstance(name, ProcessInfo):
145 # we have to check first in namemap in case is an unregistered
146 # process (added with once())
147 if name in self.namemap:
148 pi = self.namemap[name]
149 # the process will change its PID, so we delete it while we know it
150 del self.pidmap[pi.process.pid]
155 self.pidmap[pi.process.pid] = pi
161 def kill(self, name, signum):
162 log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
163 if isinstance(name, ProcessInfo):
165 if name in self.namemap:
166 self.namemap[name].kill(name, stop)
170 def sigchild_handler(self, signum, stack_frame=None):
171 log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
173 (pid, status) = os.waitpid(-1, os.WNOHANG)
175 log.debug(u'ProcessManager.sigchild_handler(): OSError')
176 if e.errno is errno.ECHILD:
177 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
180 log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
183 if pid in self.pidmap:
185 p.process.returncode = status
186 if p.callback is not None:
187 log.debug(u'ProcessManager.sigchild_handler: '
188 u'calling %s(%s)', p.callback.__name__, p)
190 if (p._dont_run or not p.persist
191 or p._error_count >= p.max_errors):
192 log.debug(u"ProcessManager.sigchild_handler: can't "
193 u'persist, dont_run=%s, persist=%s, error_cout=%s, '
194 u'max_errors=%s', p._dont_run, p.persist,
195 p._error_count, p.max_errors)
196 del self.namemap[p.name]
200 log.debug(u'ProcessManager.sigchild_handler: persist')
201 if p.process.returncode == 0:
203 log.debug(u'ProcessManager.sigchild_handler: '
204 u'return OK, resetting error_count')
207 log.debug(u'ProcessManager.sigchild_handler: return'
208 u'not 0, error_count + 1 = %s', p._error_count)
211 self.pidmap[p.process.pid] = p
213 (pid, status) = os.waitpid(-1, os.WNOHANG)
215 if e.errno == errno.ECHILD:
220 if isinstance(name, basestring): # is a name
221 if name in self.namemap:
222 return self.namemap[name]
223 if name in self.services:
224 return self.services[name]
226 if name in self.pidmap:
227 return self.pidmap[name]
229 # Syntax sugar for self[name]
233 if isinstance(name, basestring): # is a name
234 if name in self.namemap:
236 if name in self.services:
239 if name in self.pidmap:
242 # Syntax sugar for name in self
246 if __name__ == '__main__':
248 level = logging.DEBUG,
249 format = '%(asctime)s %(levelname)-8s %(message)s',
250 datefmt = '%H:%M:%S',
255 manager = ProcessManager()
256 register = manager.register
257 unregister = manager.unregister
259 start = manager.start
261 restart = manager.restart
265 sigchild_handler = manager.sigchild_handler
268 if __name__ == '__main__':
276 def SIGCHLD_handler(signum, stacktrace):
279 print 'SIGCHLD', signum
283 if pi.name == 'test-service':
284 print 'test-service count =', count
287 print 'set test-service non-persistent, start test-service-2'
289 assert 'test-service-2' not in manager.namemap
290 pm.start('test-service-2')
291 assert 'test-service-2' in manager.namemap
292 assert get('test-service-2').running
293 print 'died:', pi.name, pi.command
295 register('test-service', ('sleep', '2'), notify, True)
296 assert 'test-service' in manager.services
297 assert 'test-service' not in manager.namemap
298 assert not get('test-service').running
299 assert manager['test-service'] == get('test-service')
300 assert has('test-service')
301 assert 'test-service' in manager
303 register('test-service-2', ('sleep', '3'), notify, False)
304 assert 'test-service-2' in manager.services
305 assert 'test-service-2' not in manager.namemap
306 assert not get('test-service-2').running
308 signal.signal(signal.SIGCHLD, SIGCHLD_handler)
310 once('test-once', ('sleep', '5'), notify)
311 assert 'test-once' not in manager.services
312 assert 'test-once' in manager.namemap
313 assert get('test-once').running
314 assert get('test-once').process.pid
315 pid = get('test-once').process.pid
317 assert pid != get('test-once').process.pid
318 assert pid != manager.pidmap[get('test-once').process.pid].process.pid
320 start('test-service')
321 assert 'test-service' in manager.namemap
322 assert get('test-service').running
323 assert get('test-service').process.pid
324 pid = get('test-service').process.pid
325 restart('test-service')
326 assert pid != get('test-service').process.pid
327 assert pid != manager.pidmap[get('test-service').process.pid].process.pid
329 print "Known processes:", manager.services.keys()
330 print "Waiting...", manager.namemap.keys()
331 print "------------------------------------------------------------------"
332 while manager.pidmap:
334 if sig == signal.SIGCHLD:
335 sigchild_handler(sig)
337 print "Known processes:", manager.services.keys()
338 print "Waiting...", manager.namemap.keys()
339 print "------------------------------------------------------------------"
340 assert 'test-service' not in manager.namemap
341 assert 'test-service-2' not in manager.namemap
342 assert 'test-once' not in manager.services
343 assert 'test-once' not in manager.namemap
345 restart('test-service')
346 assert get('test-service').process.pid
347 assert manager.pidmap[get('test-service').process.pid].process.pid
349 once('test-wait', ('sleep', '2'))
350 print 'test-wait running?', get('test-wait').running
351 assert get('test-wait').running
352 print 'Waiting test-wait to return...'
353 ret = get('test-wait').process.wait()
354 print 'Done! returned:', ret