]> git.llucax.com Git - software/pymin.git/blob - pymin/procman.py
Add an example of process waiting to testcase.
[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', 'call',
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         self.running = False
31     def start(self):
32         assert self.process is None
33         self.restart()
34     def restart(self):
35         self.clear()
36         log.debug(u'ProcessInfo.restart(): executing %s', self.command)
37         self.process = subprocess.Popen(self.command, *self.args, **self.kwargs)
38         self.running = True
39     def stop(self):
40         assert self.process is not None
41         self.dont_run = True
42         if self.signal == signal.SIGTERM or self.signal == signal.SIGKILL:
43             # Allready stopped, kill it
44             self.kill(signal.SIGKILL)
45         else:
46             # Stop it
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)
53         self.signal = signum
54     def __repr__(self):
55         pid = None
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__)
61
62 class ProcessManager:
63
64     def __init__(self):
65         self.services = dict()
66         self.namemap = dict()
67         self.pidmap = dict()
68         log.debug(u'ProcessManager()')
69
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)
76
77     def unregister(self, name):
78         log.debug(u'ProcessManager.unregister(%s)', name)
79         del self.services[name]
80
81     def _call(self, pi):
82         pi.start()
83         self.namemap[pi.name] = self.pidmap[pi.process.pid] = pi
84
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,
90                          args, kwargs)
91         self._call(pi)
92
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])
97
98     def stop(self, name):
99         log.debug(u'ProcessManager.stop(%s)', name)
100         assert name in self.namemap
101         self.namemap[name].stop()
102
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]
109             pi.stop()
110             pi.process.wait()
111             pi.restart()
112         else:
113             self.services[name].start()
114
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)
119
120     def sigchild_handler(self, signum, stack_frame=None):
121         log.debug(u'ProcessManager.sigchild_handler(%s)', signum)
122         try:
123             (pid, status) = os.waitpid(-1, os.WNOHANG)
124         except OSError, e:
125             log.debug(u'ProcessManager.sigchild_handler(): OSError')
126             if e.errno is errno.ECHILD:
127                 log.debug(u'ProcessManager.sigchild_handler(): OSError ECHILD')
128                 return
129             raise
130         log.debug(u'ProcessManager.sigchild_handler: pid=%s, status=%s',
131                       pid, status)
132         while pid:
133             if pid in self.pidmap:
134                 p = self.pidmap[pid]
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)
139                     p.callback(self, 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]
146                     del self.pidmap[pid]
147                     p.clear()
148                 else:
149                     log.debug(u'ProcessManager.sigchild_handler: persist')
150                     if p.process.returncode == 0:
151                         p.error_count = 0
152                         log.debug(u'ProcessManager.sigchild_handler: '
153                                 u'return OK, resetting error_count')
154                     else:
155                         p.error_count += 1
156                         log.debug(u'ProcessManager.sigchild_handler: return'
157                                 u'not 0, error_count + 1 = %s', p.error_count)
158                     del self.pidmap[pid]
159                     p.restart()
160                     self.pidmap[p.process.pid] = p
161             try:
162                 (pid, status) = os.waitpid(-1, os.WNOHANG)
163             except OSError, e:
164                 if e.errno == errno.ECHILD:
165                     return
166                 raise
167
168     def get(self, name):
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]
174         else: # is a pid
175             if name in self.pidmap:
176                 return self.pidmap[name]
177         raise KeyError, name
178
179     def has(self, name):
180         if isinstance(name, basestring): # is a name
181             if name in self.namemap:
182                 return True
183             if name in self.services:
184                 return True
185         else: # is a pid
186             if name in self.pidmap:
187                 return True
188         return False
189
190     def __getitem__(self, name):
191         return self.get(name)
192
193     def __contains__(self, name):
194         return self.has(name)
195
196
197 if __name__ == '__main__':
198     logging.basicConfig(
199         level   = logging.DEBUG,
200         format  = '%(asctime)s %(levelname)-8s %(message)s',
201         datefmt = '%H:%M:%S',
202     )
203
204
205 # Globals
206 manager = ProcessManager()
207 register = manager.register
208 unregister = manager.unregister
209 call = manager.call
210 start = manager.start
211 stop = manager.stop
212 restart = manager.restart
213 kill = manager.kill
214 get = manager.get
215 has = manager.has
216 sigchild_handler = manager.sigchild_handler
217
218
219 if __name__ == '__main__':
220
221     import signal
222     import time
223
224     sig = None
225     count = 0
226
227     def SIGCHLD_handler(signum, stacktrace):
228         global sig
229         sig = signum
230         print 'SIGCHLD', signum
231
232     def notify(pm, pi):
233         global count
234         if pi.name == 'test-service':
235             print 'test-service count =', count
236             count += 1
237             if count > 4:
238                 print 'set test-service non-persistent, start test-service-2'
239                 pi.persist = False
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
244
245     register('test-service', ('sleep', '2'), notify, True)
246     assert 'test-service' in manager.services
247     assert 'test-service' not in manager.namemap
248
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
252
253     signal.signal(signal.SIGCHLD, SIGCHLD_handler)
254
255     call('test-once', ('sleep', '5'), notify)
256     assert 'test-once' not in manager.services
257     assert 'test-once' in manager.namemap
258
259     start('test-service')
260     assert 'test-service' in manager.namemap
261
262     print "Known processes:", manager.services.keys()
263     print "Waiting...", manager.namemap.keys()
264     print "------------------------------------------------------------------"
265     while manager.pidmap:
266         signal.pause()
267         if sig == signal.SIGCHLD:
268             sigchild_handler(sig)
269             sig = None
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
277
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
283