]> git.llucax.com Git - software/pymin.git/blob - pymin/procman.py
Make some procman.ProcessManager's methods return the ProcessInfo instance.
[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         pi = ProcessInfo(name, command, callback, persist, max_errors,
84                         args, kwargs)
85         self.services[name] = pi
86         return pi
87
88     def unregister(self, name):
89         log.debug(u'ProcessManager.unregister(%s)', name)
90         pi = self.services[name]
91         del self.services[name]
92         return pi
93
94     def _call(self, pi):
95         pi.start()
96         self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
97
98     def once(self, name, command, callback=None, persist=False,
99                 max_errors=3, *args, **kwargs):
100         log.debug(u'ProcessManager.once(%s, %s, %s, %s, %s, %s, %s)',
101                   name, command, callback, persist, max_errors, args, kwargs)
102         assert not self.has(name)
103         pi = ProcessInfo(name, command, callback, persist, max_errors,
104                          args, kwargs)
105         self._call(pi)
106         return pi
107
108     def start(self, name):
109         log.debug(u'ProcessManager.start(%s)', name)
110         assert name not in self.namemap
111         self._call(self.services[name])
112
113     def stop(self, name):
114         log.debug(u'ProcessManager.stop(%s)', name)
115         assert name in self.namemap
116         self.namemap[name].stop()
117
118     def restart(self, name):
119         log.debug(u'ProcessManager.restart(%s)', name)
120         # we have to check first in namemap in case is an unregistered
121         # process (added with once())
122         if name in self.namemap:
123             pi = self.namemap[name]
124             pi.stop()
125             pi.process.wait()
126             pi.restart()
127         else:
128             self.services[name].start()
129
130     def kill(self, name, signum):
131         log.debug(u'ProcessManager.kill(%s, %s)', name, signum)
132         assert name in self.namemap
133         self.namemap[name].kill(name, stop)
134
135     def sigchild_handler(self, signum, stack_frame=None):
136         log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
137         try:
138             (pid, status) = os.waitpid(-1, os.WNOHANG)
139         except OSError, e:
140             log.debug(u'ProcessManager.sigchild_handler(): OSError')
141             if e.errno is errno.ECHILD:
142                 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
143                 return
144             raise
145         log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
146                       pid, status)
147         while pid:
148             if pid in self.pidmap:
149                 p = self.pidmap[pid]
150                 p.process.returncode = status
151                 if p.callback is not None:
152                     log.debug(u'ProcessManager.sigchild_handler: '
153                                   u'calling %s(%s)', p.callback.__name__, p)
154                     p.callback(self, p)
155                 if p._dont_run or not p.persist or p.error_count >= p.max_errors:
156                     log.debug(u"ProcessManager.sigchild_handler: can't "
157                             u'persist, dont_run=%s, persist=%s, error_cout=%s, '
158                             u'max_errors=%s', p._dont_run, p.persist,
159                             p.error_count, p.max_errors)
160                     del self.namemap[p.name]
161                     del self.pidmap[pid]
162                     p.clear()
163                 else:
164                     log.debug(u'ProcessManager.sigchild_handler: persist')
165                     if p.process.returncode == 0:
166                         p.error_count = 0
167                         log.debug(u'ProcessManager.sigchild_handler: '
168                                 u'return OK, resetting error_count')
169                     else:
170                         p.error_count += 1
171                         log.debug(u'ProcessManager.sigchild_handler: return'
172                                 u'not 0, error_count + 1 = %s', p.error_count)
173                     del self.pidmap[pid]
174                     p.restart()
175                     self.pidmap[p.process.pid] = p
176             try:
177                 (pid, status) = os.waitpid(-1, os.WNOHANG)
178             except OSError, e:
179                 if e.errno == errno.ECHILD:
180                     return
181                 raise
182
183     def get(self, name):
184         if isinstance(name, basestring): # is a name
185             if name in self.namemap:
186                 return self.namemap[name]
187             if name in self.services:
188                 return self.services[name]
189         else: # is a pid
190             if name in self.pidmap:
191                 return self.pidmap[name]
192         raise KeyError, name
193     # Syntax sugar for self[name]
194     __getitem__ = get
195
196     def has(self, name):
197         if isinstance(name, basestring): # is a name
198             if name in self.namemap:
199                 return True
200             if name in self.services:
201                 return True
202         else: # is a pid
203             if name in self.pidmap:
204                 return True
205         return False
206     # Syntax sugar for name in self
207     __contains__ = has
208
209
210 if __name__ == '__main__':
211     logging.basicConfig(
212         level   = logging.DEBUG,
213         format  = '%(asctime)s %(levelname)-8s %(message)s',
214         datefmt = '%H:%M:%S',
215     )
216
217
218 # Globals
219 manager = ProcessManager()
220 register = manager.register
221 unregister = manager.unregister
222 once = manager.once
223 start = manager.start
224 stop = manager.stop
225 restart = manager.restart
226 kill = manager.kill
227 get = manager.get
228 has = manager.has
229 sigchild_handler = manager.sigchild_handler
230
231
232 if __name__ == '__main__':
233
234     import signal
235     import time
236
237     sig = None
238     count = 0
239
240     def SIGCHLD_handler(signum, stacktrace):
241         global sig
242         sig = signum
243         print 'SIGCHLD', signum
244
245     def notify(pm, pi):
246         global count
247         if pi.name == 'test-service':
248             print 'test-service count =', count
249             count += 1
250             if count > 4:
251                 print 'set test-service non-persistent, start test-service-2'
252                 pi.persist = False
253                 assert 'test-service-2' not in manager.namemap
254                 pm.start('test-service-2')
255                 assert 'test-service-2' in manager.namemap
256                 assert get('test-service-2').running
257         print 'died:', pi.name, pi.command
258
259     register('test-service', ('sleep', '2'), notify, True)
260     assert 'test-service' in manager.services
261     assert 'test-service' not in manager.namemap
262     assert not get('test-service').running
263     assert manager['test-service'] == get('test-service')
264     assert has('test-service')
265     assert 'test-service' in manager
266
267     register('test-service-2', ('sleep', '3'), notify, False)
268     assert 'test-service-2' in manager.services
269     assert 'test-service-2' not in manager.namemap
270     assert not get('test-service-2').running
271
272     signal.signal(signal.SIGCHLD, SIGCHLD_handler)
273
274     once('test-once', ('sleep', '5'), notify)
275     assert 'test-once' not in manager.services
276     assert 'test-once' in manager.namemap
277     assert get('test-once').running
278
279     start('test-service')
280     assert 'test-service' in manager.namemap
281     assert get('test-service').running
282
283     print "Known processes:", manager.services.keys()
284     print "Waiting...", manager.namemap.keys()
285     print "------------------------------------------------------------------"
286     while manager.pidmap:
287         signal.pause()
288         if sig == signal.SIGCHLD:
289             sigchild_handler(sig)
290             sig = None
291         print "Known processes:", manager.services.keys()
292         print "Waiting...", manager.namemap.keys()
293         print "------------------------------------------------------------------"
294     assert 'test-service' not in manager.namemap
295     assert 'test-service-2' not in manager.namemap
296     assert 'test-once' not in manager.services
297     assert 'test-once' not in manager.namemap
298
299     once('test-wait', ('sleep', '2'))
300     print 'test-wait returned?', get('test-wait').process.poll()
301     assert get('test-wait').running
302     print 'Waiting test-wait to return...'
303     ret = get('test-wait').process.wait()
304     print 'Done! returned:', ret
305