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
31 assert self.process is None
35 log.debug(u'ProcessInfo.restart(): executing %s', self.command)
36 self.process = subprocess.Popen(self.command, *self.args, **self.kwargs)
38 assert self.process is not None
40 if self.signal == signal.SIGTERM or self.signal == signal.SIGKILL:
41 # Allready stopped, kill it
42 self.kill(signal.SIGKILL)
45 self.kill(signal.SIGTERM)
46 def kill(self, signum):
47 log.debug(u'ProcessInfo.kill(): killing pid %s with signal %s',
48 self.process.pid, signum)
49 assert self.process is not None
50 os.kill(self.process.pid, signum)
54 return self.process is not None and self.process.poll() is None
57 if self.process is not None:
58 pid = self.process.pid
59 return 'ProcessInfo(name=%s, pid=%s command=%s, persist=%s, cb=%s)' % (
60 self.name, pid, self.command, self.persist,
61 self.callback.__name__)
66 self.services = dict()
69 log.debug(u'ProcessManager()')
71 def register(self, name, command, callback=None, persist=False,
72 max_errors=3, *args, **kwargs):
73 log.debug(u'ProcessManager.register(%s, %s, %s, %s, %s, %s, %s)',
74 name, command, callback, persist, max_errors, args, kwargs)
75 assert not self.has(name)
76 self.services[name] = ProcessInfo(name, command, callback, persist,
77 max_errors, args, kwargs)
79 def unregister(self, name):
80 log.debug(u'ProcessManager.unregister(%s)', name)
81 del self.services[name]
85 self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
87 def once(self, name, command, callback=None, persist=False,
88 max_errors=3, *args, **kwargs):
89 log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
90 name, command, callback, persist, max_errors, args, kwargs)
91 assert not self.has(name)
92 pi = ProcessInfo(name, command, callback, persist, max_errors,
96 def start(self, name):
97 log.debug(u'ProcessManager.start(%s)', name)
98 assert name not in self.namemap
99 self._call(self.services[name])
101 def stop(self, name):
102 log.debug(u'ProcessManager.stop(%s)', name)
103 assert name in self.namemap
104 self.namemap[name].stop()
106 def restart(self, name):
107 log.debug(u'ProcessManager.restart(%s)', name)
108 # we have to check first in namemap in case is an unregistered
109 # process (added with once())
110 if name in self.namemap:
111 pi = self.namemap[name]
116 self.services[name].start()
118 def kill(self, name, signum):
119 log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
120 assert name in self.namemap
121 self.namemap[name].kill(name, stop)
123 def sigchild_handler(self, signum, stack_frame=None):
124 log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
126 (pid, status) = os.waitpid(-1, os.WNOHANG)
128 log.debug(u'ProcessManager.sigchild_handler(): OSError')
129 if e.errno is errno.ECHILD:
130 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
133 log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
136 if pid in self.pidmap:
138 p.process.returncode = status
139 if p.callback is not None:
140 log.debug(u'ProcessManager.sigchild_handler: '
141 u'calling %s(%s)', p.callback.__name__, p)
143 if p.dont_run or not p.persist or p.error_count >= p.max_errors:
144 log.debug(u"ProcessManager.sigchild_handler: can't "
145 u'persist, dont_run=%s, persist=%s, error_cout=%s, '
146 u'max_errors=%s', p.dont_run, p.persist,
147 p.error_count, p.max_errors)
148 del self.namemap[p.name]
152 log.debug(u'ProcessManager.sigchild_handler: persist')
153 if p.process.returncode == 0:
155 log.debug(u'ProcessManager.sigchild_handler: '
156 u'return OK, resetting error_count')
159 log.debug(u'ProcessManager.sigchild_handler: return'
160 u'not 0, error_count + 1 = %s', p.error_count)
163 self.pidmap[p.process.pid] = p
165 (pid, status) = os.waitpid(-1, os.WNOHANG)
167 if e.errno == errno.ECHILD:
172 if isinstance(name, basestring): # is a name
173 if name in self.namemap:
174 return self.namemap[name]
175 if name in self.services:
176 return self.services[name]
178 if name in self.pidmap:
179 return self.pidmap[name]
183 if isinstance(name, basestring): # is a name
184 if name in self.namemap:
186 if name in self.services:
189 if name in self.pidmap:
193 def __getitem__(self, name):
194 return self.get(name)
196 def __contains__(self, name):
197 return self.has(name)
200 if __name__ == '__main__':
202 level = logging.DEBUG,
203 format = '%(asctime)s %(levelname)-8s %(message)s',
204 datefmt = '%H:%M:%S',
209 manager = ProcessManager()
210 register = manager.register
211 unregister = manager.unregister
213 start = manager.start
215 restart = manager.restart
219 sigchild_handler = manager.sigchild_handler
222 if __name__ == '__main__':
230 def SIGCHLD_handler(signum, stacktrace):
233 print 'SIGCHLD', signum
237 if pi.name == 'test-service':
238 print 'test-service count =', count
241 print 'set test-service non-persistent, start test-service-2'
243 assert 'test-service-2' not in manager.namemap
244 pm.start('test-service-2')
245 assert 'test-service-2' in manager.namemap
246 assert get('test-service-2').running
247 print 'died:', pi.name, pi.command
249 register('test-service', ('sleep', '2'), notify, True)
250 assert 'test-service' in manager.services
251 assert 'test-service' not in manager.namemap
252 assert not get('test-service').running
254 register('test-service-2', ('sleep', '3'), notify, False)
255 assert 'test-service-2' in manager.services
256 assert 'test-service-2' not in manager.namemap
257 assert not get('test-service-2').running
259 signal.signal(signal.SIGCHLD, SIGCHLD_handler)
261 once('test-once', ('sleep', '5'), notify)
262 assert 'test-once' not in manager.services
263 assert 'test-once' in manager.namemap
264 assert get('test-once').running
266 start('test-service')
267 assert 'test-service' in manager.namemap
268 assert get('test-service').running
270 print "Known processes:", manager.services.keys()
271 print "Waiting...", manager.namemap.keys()
272 print "------------------------------------------------------------------"
273 while manager.pidmap:
275 if sig == signal.SIGCHLD:
276 sigchild_handler(sig)
278 print "Known processes:", manager.services.keys()
279 print "Waiting...", manager.namemap.keys()
280 print "------------------------------------------------------------------"
281 assert 'test-service' not in manager.namemap
282 assert 'test-service-2' not in manager.namemap
283 assert 'test-once' not in manager.services
284 assert 'test-once' not in manager.namemap
286 once('test-wait', ('sleep', '2'))
287 print 'test-wait returned?', get('test-wait').process.poll()
288 assert get('test-wait').running
289 print 'Waiting test-wait to return...'
290 ret = get('test-wait').process.wait()
291 print 'Done! returned:', ret