]> git.llucax.com Git - software/pymin.git/blob - pymin/procman.py
554fdbada88629222e889b77d6b01b180caeab63
[software/pymin.git] / pymin / procman.py
1 # vim: set encoding=utf-8 et sw=4 sts=4 :
2
3 import os
4 import errno
5 import signal
6 import subprocess
7 import logging ; log = logging.getLogger('pymin.procman')
8
9 __all__ = ('ProcessManager', 'manager', 'register', 'unregister', 'once',
10            'start', 'stop', 'restart', 'kill', 'get', 'has', 'sigchild_handler')
11
12 class ProcessInfo:
13     def __init__(self, name, command, callback=None, persist=False,
14                  max_errors=3, args=None, kwargs=None):
15         self._name = name
16         self.command = command
17         self.callback = callback
18         if args is None: args = list()
19         self.args = args
20         if kwargs is None: kwargs = dict()
21         self.kwargs = kwargs
22         self.persist = persist
23         self.max_errors = max_errors
24         self.clear()
25     def clear(self):
26         self._dont_run = False
27         self._signal = None
28         self._process = None
29         self.error_count = 0
30     def start(self):
31         assert self.process is None
32         self.restart()
33     def restart(self):
34         self.clear()
35         log.debug(u'ProcessInfo.restart(): executing %s', self.command)
36         self._process = subprocess.Popen(self.command,
37                                          *self.args, **self.kwargs)
38     def stop(self):
39         assert self.process is not None
40         self._dont_run = True
41         if self._signal == signal.SIGTERM or self._signal == signal.SIGKILL:
42             # Allready stopped, kill it
43             self.kill(signal.SIGKILL)
44         else:
45             # Stop it
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)
52         self._signal = signum
53     @property
54     def running(self):
55         return self.process is not None and self.process.poll() is None
56     @property
57     def name(self):
58         return self._name
59     @property
60     def process(self):
61         return self._process
62     def __repr__(self):
63         pid = None
64         if self.process is not None:
65             pid = self.process.pid
66         return 'ProcessInfo(name=%s, pid=%s command=%s, persist=%s, cb=%s)' % (
67                     self.name, pid, self.command, self.persist,
68                     self.callback.__name__)
69
70 class ProcessManager:
71
72     def __init__(self):
73         self.services = dict()
74         self.namemap = dict()
75         self.pidmap = dict()
76         log.debug(u'ProcessManager()')
77
78     def register(self, name, command, callback=None, persist=False,
79                 max_errors=3, *args, **kwargs):
80         log.debug(u'ProcessManager.register(%s, %s, %s, %s, %s, %s, %s)',
81                   name, command, callback, persist, max_errors, args, kwargs)
82         assert not self.has(name)
83         self.services[name] = ProcessInfo(name, command, callback, persist,
84                                           max_errors, args, kwargs)
85
86     def unregister(self, name):
87         log.debug(u'ProcessManager.unregister(%s)', name)
88         del self.services[name]
89
90     def _call(self, pi):
91         pi.start()
92         self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
93
94     def once(self, name, command, callback=None, persist=False,
95                 max_errors=3, *args, **kwargs):
96         log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
97                   name, command, callback, persist, max_errors, args, kwargs)
98         assert not self.has(name)
99         pi = ProcessInfo(name, command, callback, persist, max_errors,
100                          args, kwargs)
101         self._call(pi)
102
103     def start(self, name):
104         log.debug(u'ProcessManager.start(%s)', name)
105         assert name not in self.namemap
106         self._call(self.services[name])
107
108     def stop(self, name):
109         log.debug(u'ProcessManager.stop(%s)', name)
110         assert name in self.namemap
111         self.namemap[name].stop()
112
113     def restart(self, name):
114         log.debug(u'ProcessManager.restart(%s)', name)
115         # we have to check first in namemap in case is an unregistered
116         # process (added with once())
117         if name in self.namemap:
118             pi = self.namemap[name]
119             pi.stop()
120             pi.process.wait()
121             pi.restart()
122         else:
123             self.services[name].start()
124
125     def kill(self, name, signum):
126         log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
127         assert name in self.namemap
128         self.namemap[name].kill(name, stop)
129
130     def sigchild_handler(self, signum, stack_frame=None):
131         log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
132         try:
133             (pid, status) = os.waitpid(-1, os.WNOHANG)
134         except OSError, e:
135             log.debug(u'ProcessManager.sigchild_handler(): OSError')
136             if e.errno is errno.ECHILD:
137                 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
138                 return
139             raise
140         log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
141                       pid, status)
142         while pid:
143             if pid in self.pidmap:
144                 p = self.pidmap[pid]
145                 p.process.returncode = status
146                 if p.callback is not None:
147                     log.debug(u'ProcessManager.sigchild_handler: '
148                                   u'calling %s(%s)', p.callback.__name__, p)
149                     p.callback(self, p)
150                 if p._dont_run or not p.persist or p.error_count >= p.max_errors:
151                     log.debug(u"ProcessManager.sigchild_handler: can't "
152                             u'persist, dont_run=%s, persist=%s, error_cout=%s, '
153                             u'max_errors=%s', p._dont_run, p.persist,
154                             p.error_count, p.max_errors)
155                     del self.namemap[p.name]
156                     del self.pidmap[pid]
157                     p.clear()
158                 else:
159                     log.debug(u'ProcessManager.sigchild_handler: persist')
160                     if p.process.returncode == 0:
161                         p.error_count = 0
162                         log.debug(u'ProcessManager.sigchild_handler: '
163                                 u'return OK, resetting error_count')
164                     else:
165                         p.error_count += 1
166                         log.debug(u'ProcessManager.sigchild_handler: return'
167                                 u'not 0, error_count + 1 = %s', p.error_count)
168                     del self.pidmap[pid]
169                     p.restart()
170                     self.pidmap[p.process.pid] = p
171             try:
172                 (pid, status) = os.waitpid(-1, os.WNOHANG)
173             except OSError, e:
174                 if e.errno == errno.ECHILD:
175                     return
176                 raise
177
178     def get(self, name):
179         if isinstance(name, basestring): # is a name
180             if name in self.namemap:
181                 return self.namemap[name]
182             if name in self.services:
183                 return self.services[name]
184         else: # is a pid
185             if name in self.pidmap:
186                 return self.pidmap[name]
187         raise KeyError, name
188     # Syntax sugar for self[name]
189     __getitem__ = get
190
191     def has(self, name):
192         if isinstance(name, basestring): # is a name
193             if name in self.namemap:
194                 return True
195             if name in self.services:
196                 return True
197         else: # is a pid
198             if name in self.pidmap:
199                 return True
200         return False
201     # Syntax sugar for name in self
202     __contains__ = has
203
204
205 if __name__ == '__main__':
206     logging.basicConfig(
207         level   = logging.DEBUG,
208         format  = '%(asctime)s %(levelname)-8s %(message)s',
209         datefmt = '%H:%M:%S',
210     )
211
212
213 # Globals
214 manager = ProcessManager()
215 register = manager.register
216 unregister = manager.unregister
217 once = manager.once
218 start = manager.start
219 stop = manager.stop
220 restart = manager.restart
221 kill = manager.kill
222 get = manager.get
223 has = manager.has
224 sigchild_handler = manager.sigchild_handler
225
226
227 if __name__ == '__main__':
228
229     import signal
230     import time
231
232     sig = None
233     count = 0
234
235     def SIGCHLD_handler(signum, stacktrace):
236         global sig
237         sig = signum
238         print 'SIGCHLD', signum
239
240     def notify(pm, pi):
241         global count
242         if pi.name == 'test-service':
243             print 'test-service count =', count
244             count += 1
245             if count > 4:
246                 print 'set test-service non-persistent, start test-service-2'
247                 pi.persist = False
248                 assert 'test-service-2' not in manager.namemap
249                 pm.start('test-service-2')
250                 assert 'test-service-2' in manager.namemap
251                 assert get('test-service-2').running
252         print 'died:', pi.name, pi.command
253
254     register('test-service', ('sleep', '2'), notify, True)
255     assert 'test-service' in manager.services
256     assert 'test-service' not in manager.namemap
257     assert not get('test-service').running
258     assert manager['test-service'] == get('test-service')
259     assert has('test-service')
260     assert 'test-service' in manager
261
262     register('test-service-2', ('sleep', '3'), notify, False)
263     assert 'test-service-2' in manager.services
264     assert 'test-service-2' not in manager.namemap
265     assert not get('test-service-2').running
266
267     signal.signal(signal.SIGCHLD, SIGCHLD_handler)
268
269     once('test-once', ('sleep', '5'), notify)
270     assert 'test-once' not in manager.services
271     assert 'test-once' in manager.namemap
272     assert get('test-once').running
273
274     start('test-service')
275     assert 'test-service' in manager.namemap
276     assert get('test-service').running
277
278     print "Known processes:", manager.services.keys()
279     print "Waiting...", manager.namemap.keys()
280     print "------------------------------------------------------------------"
281     while manager.pidmap:
282         signal.pause()
283         if sig == signal.SIGCHLD:
284             sigchild_handler(sig)
285             sig = None
286         print "Known processes:", manager.services.keys()
287         print "Waiting...", manager.namemap.keys()
288         print "------------------------------------------------------------------"
289     assert 'test-service' not in manager.namemap
290     assert 'test-service-2' not in manager.namemap
291     assert 'test-once' not in manager.services
292     assert 'test-once' not in manager.namemap
293
294     once('test-wait', ('sleep', '2'))
295     print 'test-wait returned?', get('test-wait').process.poll()
296     assert get('test-wait').running
297     print 'Waiting test-wait to return...'
298     ret = get('test-wait').process.wait()
299     print 'Done! returned:', ret
300