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, *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
60 if self.process is not None:
61 pid = self.process.pid
62 return 'ProcessInfo(name=%s, pid=%s command=%s, persist=%s, cb=%s)' % (
63 self.name, pid, self.command, self.persist,
64 self.callback.__name__)
69 self.services = dict()
72 log.debug(u'ProcessManager()')
74 def register(self, name, command, callback=None, persist=False,
75 max_errors=3, *args, **kwargs):
76 log.debug(u'ProcessManager.register(%s, %s, %s, %s, %s, %s, %s)',
77 name, command, callback, persist, max_errors, args, kwargs)
78 assert not self.has(name)
79 self.services[name] = ProcessInfo(name, command, callback, persist,
80 max_errors, args, kwargs)
82 def unregister(self, name):
83 log.debug(u'ProcessManager.unregister(%s)', name)
84 del self.services[name]
88 self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
90 def once(self, name, command, callback=None, persist=False,
91 max_errors=3, *args, **kwargs):
92 log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
93 name, command, callback, persist, max_errors, args, kwargs)
94 assert not self.has(name)
95 pi = ProcessInfo(name, command, callback, persist, max_errors,
99 def start(self, name):
100 log.debug(u'ProcessManager.start(%s)', name)
101 assert name not in self.namemap
102 self._call(self.services[name])
104 def stop(self, name):
105 log.debug(u'ProcessManager.stop(%s)', name)
106 assert name in self.namemap
107 self.namemap[name].stop()
109 def restart(self, name):
110 log.debug(u'ProcessManager.restart(%s)', name)
111 # we have to check first in namemap in case is an unregistered
112 # process (added with once())
113 if name in self.namemap:
114 pi = self.namemap[name]
119 self.services[name].start()
121 def kill(self, name, signum):
122 log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
123 assert name in self.namemap
124 self.namemap[name].kill(name, stop)
126 def sigchild_handler(self, signum, stack_frame=None):
127 log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
129 (pid, status) = os.waitpid(-1, os.WNOHANG)
131 log.debug(u'ProcessManager.sigchild_handler(): OSError')
132 if e.errno is errno.ECHILD:
133 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
136 log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
139 if pid in self.pidmap:
141 p.process.returncode = status
142 if p.callback is not None:
143 log.debug(u'ProcessManager.sigchild_handler: '
144 u'calling %s(%s)', p.callback.__name__, p)
146 if p._dont_run or not p.persist or p.error_count >= p.max_errors:
147 log.debug(u"ProcessManager.sigchild_handler: can't "
148 u'persist, dont_run=%s, persist=%s, error_cout=%s, '
149 u'max_errors=%s', p._dont_run, p.persist,
150 p.error_count, p.max_errors)
151 del self.namemap[p.name]
155 log.debug(u'ProcessManager.sigchild_handler: persist')
156 if p.process.returncode == 0:
158 log.debug(u'ProcessManager.sigchild_handler: '
159 u'return OK, resetting error_count')
162 log.debug(u'ProcessManager.sigchild_handler: return'
163 u'not 0, error_count + 1 = %s', p.error_count)
166 self.pidmap[p.process.pid] = p
168 (pid, status) = os.waitpid(-1, os.WNOHANG)
170 if e.errno == errno.ECHILD:
175 if isinstance(name, basestring): # is a name
176 if name in self.namemap:
177 return self.namemap[name]
178 if name in self.services:
179 return self.services[name]
181 if name in self.pidmap:
182 return self.pidmap[name]
186 if isinstance(name, basestring): # is a name
187 if name in self.namemap:
189 if name in self.services:
192 if name in self.pidmap:
196 def __getitem__(self, name):
197 return self.get(name)
199 def __contains__(self, name):
200 return self.has(name)
203 if __name__ == '__main__':
205 level = logging.DEBUG,
206 format = '%(asctime)s %(levelname)-8s %(message)s',
207 datefmt = '%H:%M:%S',
212 manager = ProcessManager()
213 register = manager.register
214 unregister = manager.unregister
216 start = manager.start
218 restart = manager.restart
222 sigchild_handler = manager.sigchild_handler
225 if __name__ == '__main__':
233 def SIGCHLD_handler(signum, stacktrace):
236 print 'SIGCHLD', signum
240 if pi.name == 'test-service':
241 print 'test-service count =', count
244 print 'set test-service non-persistent, start test-service-2'
246 assert 'test-service-2' not in manager.namemap
247 pm.start('test-service-2')
248 assert 'test-service-2' in manager.namemap
249 assert get('test-service-2').running
250 print 'died:', pi.name, pi.command
252 register('test-service', ('sleep', '2'), notify, True)
253 assert 'test-service' in manager.services
254 assert 'test-service' not in manager.namemap
255 assert not get('test-service').running
257 register('test-service-2', ('sleep', '3'), notify, False)
258 assert 'test-service-2' in manager.services
259 assert 'test-service-2' not in manager.namemap
260 assert not get('test-service-2').running
262 signal.signal(signal.SIGCHLD, SIGCHLD_handler)
264 once('test-once', ('sleep', '5'), notify)
265 assert 'test-once' not in manager.services
266 assert 'test-once' in manager.namemap
267 assert get('test-once').running
269 start('test-service')
270 assert 'test-service' in manager.namemap
271 assert get('test-service').running
273 print "Known processes:", manager.services.keys()
274 print "Waiting...", manager.namemap.keys()
275 print "------------------------------------------------------------------"
276 while manager.pidmap:
278 if sig == signal.SIGCHLD:
279 sigchild_handler(sig)
281 print "Known processes:", manager.services.keys()
282 print "Waiting...", manager.namemap.keys()
283 print "------------------------------------------------------------------"
284 assert 'test-service' not in manager.namemap
285 assert 'test-service-2' not in manager.namemap
286 assert 'test-once' not in manager.services
287 assert 'test-once' not in manager.namemap
289 once('test-wait', ('sleep', '2'))
290 print 'test-wait returned?', get('test-wait').process.poll()
291 assert get('test-wait').running
292 print 'Waiting test-wait to return...'
293 ret = get('test-wait').process.wait()
294 print 'Done! returned:', ret