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