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', 'call',
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
32 assert self.process is None
36 log.debug(u'ProcessInfo.restart(): executing %s', self.command)
37 self.process = subprocess.Popen(self.command, *self.args, **self.kwargs)
40 assert self.process is not None
42 if self.signal == signal.SIGTERM or self.signal == signal.SIGKILL:
43 # Allready stopped, kill it
44 self.kill(signal.SIGKILL)
47 self.kill(signal.SIGTERM)
48 def kill(self, signum):
49 log.debug(u'ProcessInfo.kill(): killing pid %s with signal %s',
50 self.process.pid, signum)
51 assert self.process is not None
52 os.kill(self.process.pid, signum)
56 if self.process is not None:
57 pid = self.process.pid
58 return 'ProcessInfo(name=%s, pid=%s command=%s, persist=%s, cb=%s)' % (
59 self.name, pid, self.command, self.persist,
60 self.callback.__name__)
65 self.services = dict()
68 log.debug(u'ProcessManager()')
70 def register(self, name, command, callback=None, persist=False,
71 max_errors=3, *args, **kwargs):
72 log.debug(u'ProcessManager.register(%s, %s, %s, %s, %s, %s, %s)',
73 name, command, callback, persist, max_errors, args, kwargs)
74 self.services[name] = ProcessInfo(name, command, callback, persist,
75 max_errors, args, kwargs)
77 def unregister(self, name):
78 log.debug(u'ProcessManager.unregister(%s)', name)
79 del self.services[name]
83 self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
85 def call(self, name, command, callback=None, persist=False,
86 max_errors=3, *args, **kwargs):
87 log.debug(u'ProcessManager.call(%s, %s, %s, %s, %s, %s, %s)',
88 name, command, callback, persist, max_errors, args, kwargs)
89 pi = ProcessInfo(name, command, callback, persist, max_errors,
93 def start(self, name):
94 log.debug(u'ProcessManager.start(%s)', name)
95 assert name not in self.namemap
96 self._call(self.services[name])
99 log.debug(u'ProcessManager.stop(%s)', name)
100 assert name in self.namemap
101 self.namemap[name].stop()
103 def restart(self, name):
104 log.debug(u'ProcessManager.restart(%s)', name)
105 # we have to check first in namemap in case is an unregistered
106 # process (added with call())
107 if name in self.namemap:
108 pi = self.namemap[name]
113 self.services[name].start()
115 def kill(self, name, signum):
116 log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
117 assert name in self.namemap
118 self.namemap[name].kill(name, stop)
120 def sigchild_handler(self, signum, stack_frame=None):
121 log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
123 (pid, status) = os.waitpid(-1, os.WNOHANG)
125 log.debug(u'ProcessManager.sigchild_handler(): OSError')
126 if e.errno is errno.ECHILD:
127 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
130 log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
133 if pid in self.pidmap:
135 p.process.returncode = status
136 if p.callback is not None:
137 log.debug(u'ProcessManager.sigchild_handler: '
138 u'calling %s(%s)', p.callback.__name__, p)
140 if p.dont_run or not p.persist or p.error_count >= p.max_errors:
141 log.debug(u"ProcessManager.sigchild_handler: can't "
142 u'persist, dont_run=%s, persist=%s, error_cout=%s, '
143 u'max_errors=%s', p.dont_run, p.persist,
144 p.error_count, p.max_errors)
145 del self.namemap[p.name]
149 log.debug(u'ProcessManager.sigchild_handler: persist')
150 if p.process.returncode == 0:
152 log.debug(u'ProcessManager.sigchild_handler: '
153 u'return OK, resetting error_count')
156 log.debug(u'ProcessManager.sigchild_handler: return'
157 u'not 0, error_count + 1 = %s', p.error_count)
160 self.pidmap[p.process.pid] = p
162 (pid, status) = os.waitpid(-1, os.WNOHANG)
164 if e.errno == errno.ECHILD:
169 if isinstance(name, basestring): # is a name
170 if name in self.namemap:
171 return self.namemap[name]
172 if name in self.services:
173 return self.services[name]
175 if name in self.pidmap:
176 return self.pidmap[name]
180 if isinstance(name, basestring): # is a name
181 if name in self.namemap:
183 if name in self.services:
186 if name in self.pidmap:
190 def __getitem__(self, name):
191 return self.get(name)
193 def __contains__(self, name):
194 return self.has(name)
197 if __name__ == '__main__':
199 level = logging.DEBUG,
200 format = '%(asctime)s %(levelname)-8s %(message)s',
201 datefmt = '%H:%M:%S',
206 manager = ProcessManager()
207 register = manager.register
208 unregister = manager.unregister
210 start = manager.start
212 restart = manager.restart
216 sigchild_handler = manager.sigchild_handler
219 if __name__ == '__main__':
227 def SIGCHLD_handler(signum, stacktrace):
230 print 'SIGCHLD', signum
234 if pi.name == 'test-service':
235 print 'test-service count =', count
238 print 'set test-service non-persistent, start test-service-2'
240 assert 'test-service-2' not in manager.namemap
241 pm.start('test-service-2')
242 assert 'test-service-2' in manager.namemap
243 print 'died:', pi.name, pi.command
245 register('test-service', ('sleep', '2'), notify, True)
246 assert 'test-service' in manager.services
247 assert 'test-service' not in manager.namemap
249 register('test-service-2', ('sleep', '3'), notify, False)
250 assert 'test-service-2' in manager.services
251 assert 'test-service-2' not in manager.namemap
253 signal.signal(signal.SIGCHLD, SIGCHLD_handler)
255 call('test-once', ('sleep', '5'), notify)
256 assert 'test-once' not in manager.services
257 assert 'test-once' in manager.namemap
259 start('test-service')
260 assert 'test-service' in manager.namemap
262 print "Known processes:", manager.services.keys()
263 print "Waiting...", manager.namemap.keys()
264 print "------------------------------------------------------------------"
265 while manager.pidmap:
267 if sig == signal.SIGCHLD:
268 sigchild_handler(sig)
270 print "Known processes:", manager.services.keys()
271 print "Waiting...", manager.namemap.keys()
272 print "------------------------------------------------------------------"
273 assert 'test-service' not in manager.namemap
274 assert 'test-service-2' not in manager.namemap
275 assert 'test-once' not in manager.services
276 assert 'test-once' not in manager.namemap
278 call('test-wait', ('sleep', '2'))
279 print 'test-wait returned?', get('test-wait').process.poll()
280 print 'Waiting test-wait to return...'
281 ret = get('test-wait').process.wait()
282 print 'Done! returned:', ret