]> git.llucax.com Git - software/pymin.git/blob - pymin/procman.py
Make procman.ProcessInfo.error_count a read-only property.
[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     @property
63     def error_count(self):
64         return self._error_count
65     def __repr__(self):
66         pid = None
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__)
72
73 class ProcessManager:
74
75     def __init__(self):
76         self.services = dict()
77         self.namemap = dict()
78         self.pidmap = dict()
79         log.debug(u'ProcessManager()')
80
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,
87                         args, kwargs)
88         self.services[name] = pi
89         return pi
90
91     def unregister(self, name):
92         log.debug(u'ProcessManager.unregister(%s)', name)
93         pi = self.services[name]
94         del self.services[name]
95         return pi
96
97     def _call(self, pi):
98         pi.start()
99         self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
100
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,
107                          args, kwargs)
108         self._call(pi)
109         return pi
110
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])
115
116     def stop(self, name):
117         log.debug(u'ProcessManager.stop(%s)', name)
118         assert name in self.namemap
119         self.namemap[name].stop()
120
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]
129             pi.stop()
130             pi.process.wait()
131             pi.restart()
132             # add the new PID
133             self.pidmap[pi.process.pid] = pi
134         else:
135             self.start(name)
136
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)
141
142     def sigchild_handler(self, signum, stack_frame=None):
143         log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
144         try:
145             (pid, status) = os.waitpid(-1, os.WNOHANG)
146         except OSError, e:
147             log.debug(u'ProcessManager.sigchild_handler(): OSError')
148             if e.errno is errno.ECHILD:
149                 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
150                 return
151             raise
152         log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
153                       pid, status)
154         while pid:
155             if pid in self.pidmap:
156                 p = self.pidmap[pid]
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)
161                     p.callback(self, 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]
169                     del self.pidmap[pid]
170                     p.clear()
171                 else:
172                     log.debug(u'ProcessManager.sigchild_handler: persist')
173                     if p.process.returncode == 0:
174                         p._error_count = 0
175                         log.debug(u'ProcessManager.sigchild_handler: '
176                                 u'return OK, resetting error_count')
177                     else:
178                         p._error_count += 1
179                         log.debug(u'ProcessManager.sigchild_handler: return'
180                                 u'not 0, error_count + 1 = %s', p._error_count)
181                     del self.pidmap[pid]
182                     p.restart()
183                     self.pidmap[p.process.pid] = p
184             try:
185                 (pid, status) = os.waitpid(-1, os.WNOHANG)
186             except OSError, e:
187                 if e.errno == errno.ECHILD:
188                     return
189                 raise
190
191     def get(self, name):
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]
197         else: # is a pid
198             if name in self.pidmap:
199                 return self.pidmap[name]
200         raise KeyError, name
201     # Syntax sugar for self[name]
202     __getitem__ = get
203
204     def has(self, name):
205         if isinstance(name, basestring): # is a name
206             if name in self.namemap:
207                 return True
208             if name in self.services:
209                 return True
210         else: # is a pid
211             if name in self.pidmap:
212                 return True
213         return False
214     # Syntax sugar for name in self
215     __contains__ = has
216
217
218 if __name__ == '__main__':
219     logging.basicConfig(
220         level   = logging.DEBUG,
221         format  = '%(asctime)s %(levelname)-8s %(message)s',
222         datefmt = '%H:%M:%S',
223     )
224
225
226 # Globals
227 manager = ProcessManager()
228 register = manager.register
229 unregister = manager.unregister
230 once = manager.once
231 start = manager.start
232 stop = manager.stop
233 restart = manager.restart
234 kill = manager.kill
235 get = manager.get
236 has = manager.has
237 sigchild_handler = manager.sigchild_handler
238
239
240 if __name__ == '__main__':
241
242     import signal
243     import time
244
245     sig = None
246     count = 0
247
248     def SIGCHLD_handler(signum, stacktrace):
249         global sig
250         sig = signum
251         print 'SIGCHLD', signum
252
253     def notify(pm, pi):
254         global count
255         if pi.name == 'test-service':
256             print 'test-service count =', count
257             count += 1
258             if count > 4:
259                 print 'set test-service non-persistent, start test-service-2'
260                 pi.persist = False
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
266
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
274
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
279
280     signal.signal(signal.SIGCHLD, SIGCHLD_handler)
281
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
288     restart('test-once')
289     assert pid != get('test-once').process.pid
290     assert pid != manager.pidmap[get('test-once').process.pid].process.pid
291
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
300
301     print "Known processes:", manager.services.keys()
302     print "Waiting...", manager.namemap.keys()
303     print "------------------------------------------------------------------"
304     while manager.pidmap:
305         signal.pause()
306         if sig == signal.SIGCHLD:
307             sigchild_handler(sig)
308             sig = None
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
316
317     restart('test-service')
318     assert get('test-service').process.pid
319     assert manager.pidmap[get('test-service').process.pid].process.pid
320
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
327