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.__name__)
76 self.services = dict()
79 log.debug(u'ProcessManager()')
81 def register(self, name, command, 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 assert not self.has(name)
86 pi = ProcessInfo(name, command, callback, persist, max_errors,
88 self.services[name] = pi
91 def unregister(self, name):
92 log.debug(u'ProcessManager.unregister(%s)', name)
93 pi = self.services[name]
94 del self.services[name]
99 self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
101 def once(self, name, command, callback=None, persist=False,
102 max_errors=3, *args, **kwargs):
103 log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
104 name, command, callback, persist, max_errors, args, kwargs)
105 assert not self.has(name)
106 pi = ProcessInfo(name, command, callback, persist, max_errors,
111 def start(self, name):
112 log.debug(u'ProcessManager.start(%s)', name)
113 assert name not in self.namemap
114 self._call(self.services[name])
116 def stop(self, name):
117 log.debug(u'ProcessManager.stop(%s)', name)
118 assert name in self.namemap
119 self.namemap[name].stop()
121 def restart(self, name):
122 log.debug(u'ProcessManager.restart(%s)', name)
123 # we have to check first in namemap in case is an unregistered
124 # process (added with once())
125 if name in self.namemap:
126 pi = self.namemap[name]
127 # the process will change its PID, so we delete it while we know it
128 del self.pidmap[pi.process.pid]
133 self.pidmap[pi.process.pid] = pi
137 def kill(self, name, signum):
138 log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
139 assert name in self.namemap
140 self.namemap[name].kill(name, stop)
142 def sigchild_handler(self, signum, stack_frame=None):
143 log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
145 (pid, status) = os.waitpid(-1, os.WNOHANG)
147 log.debug(u'ProcessManager.sigchild_handler(): OSError')
148 if e.errno is errno.ECHILD:
149 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
152 log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
155 if pid in self.pidmap:
157 p.process.returncode = status
158 if p.callback is not None:
159 log.debug(u'ProcessManager.sigchild_handler: '
160 u'calling %s(%s)', p.callback.__name__, p)
162 if (p._dont_run or not p.persist
163 or p._error_count >= p.max_errors):
164 log.debug(u"ProcessManager.sigchild_handler: can't "
165 u'persist, dont_run=%s, persist=%s, error_cout=%s, '
166 u'max_errors=%s', p._dont_run, p.persist,
167 p._error_count, p.max_errors)
168 del self.namemap[p.name]
172 log.debug(u'ProcessManager.sigchild_handler: persist')
173 if p.process.returncode == 0:
175 log.debug(u'ProcessManager.sigchild_handler: '
176 u'return OK, resetting error_count')
179 log.debug(u'ProcessManager.sigchild_handler: return'
180 u'not 0, error_count + 1 = %s', p._error_count)
183 self.pidmap[p.process.pid] = p
185 (pid, status) = os.waitpid(-1, os.WNOHANG)
187 if e.errno == errno.ECHILD:
192 if isinstance(name, basestring): # is a name
193 if name in self.namemap:
194 return self.namemap[name]
195 if name in self.services:
196 return self.services[name]
198 if name in self.pidmap:
199 return self.pidmap[name]
201 # Syntax sugar for self[name]
205 if isinstance(name, basestring): # is a name
206 if name in self.namemap:
208 if name in self.services:
211 if name in self.pidmap:
214 # Syntax sugar for name in self
218 if __name__ == '__main__':
220 level = logging.DEBUG,
221 format = '%(asctime)s %(levelname)-8s %(message)s',
222 datefmt = '%H:%M:%S',
227 manager = ProcessManager()
228 register = manager.register
229 unregister = manager.unregister
231 start = manager.start
233 restart = manager.restart
237 sigchild_handler = manager.sigchild_handler
240 if __name__ == '__main__':
248 def SIGCHLD_handler(signum, stacktrace):
251 print 'SIGCHLD', signum
255 if pi.name == 'test-service':
256 print 'test-service count =', count
259 print 'set test-service non-persistent, start test-service-2'
261 assert 'test-service-2' not in manager.namemap
262 pm.start('test-service-2')
263 assert 'test-service-2' in manager.namemap
264 assert get('test-service-2').running
265 print 'died:', pi.name, pi.command
267 register('test-service', ('sleep', '2'), notify, True)
268 assert 'test-service' in manager.services
269 assert 'test-service' not in manager.namemap
270 assert not get('test-service').running
271 assert manager['test-service'] == get('test-service')
272 assert has('test-service')
273 assert 'test-service' in manager
275 register('test-service-2', ('sleep', '3'), notify, False)
276 assert 'test-service-2' in manager.services
277 assert 'test-service-2' not in manager.namemap
278 assert not get('test-service-2').running
280 signal.signal(signal.SIGCHLD, SIGCHLD_handler)
282 once('test-once', ('sleep', '5'), notify)
283 assert 'test-once' not in manager.services
284 assert 'test-once' in manager.namemap
285 assert get('test-once').running
286 assert get('test-once').process.pid
287 pid = get('test-once').process.pid
289 assert pid != get('test-once').process.pid
290 assert pid != manager.pidmap[get('test-once').process.pid].process.pid
292 start('test-service')
293 assert 'test-service' in manager.namemap
294 assert get('test-service').running
295 assert get('test-service').process.pid
296 pid = get('test-service').process.pid
297 restart('test-service')
298 assert pid != get('test-service').process.pid
299 assert pid != manager.pidmap[get('test-service').process.pid].process.pid
301 print "Known processes:", manager.services.keys()
302 print "Waiting...", manager.namemap.keys()
303 print "------------------------------------------------------------------"
304 while manager.pidmap:
306 if sig == signal.SIGCHLD:
307 sigchild_handler(sig)
309 print "Known processes:", manager.services.keys()
310 print "Waiting...", manager.namemap.keys()
311 print "------------------------------------------------------------------"
312 assert 'test-service' not in manager.namemap
313 assert 'test-service-2' not in manager.namemap
314 assert 'test-once' not in manager.services
315 assert 'test-once' not in manager.namemap
317 restart('test-service')
318 assert get('test-service').process.pid
319 assert manager.pidmap[get('test-service').process.pid].process.pid
321 once('test-wait', ('sleep', '2'))
322 print 'test-wait running?', get('test-wait').running
323 assert get('test-wait').running
324 print 'Waiting test-wait to return...'
325 ret = get('test-wait').process.wait()
326 print 'Done! returned:', ret