1 # vim: set encoding=utf-8 et sw=4 sts=4 :
4 Python Administration Daemon.
6 Python Administration Daemon is an modular, extensible administration tool
7 to administrate a set of services remotely (or localy) throw a simple
13 import logging ; log = logging.getLogger('pymin.pymindaemon')
15 from pymin.dispatcher import handler
16 from pymin import dispatcher
17 from pymin import eventloop
18 from pymin import serializer
19 from pymin import procman
21 class PyminDaemon(eventloop.EventLoop):
22 r"""PyminDaemon(root, bind_addr) -> PyminDaemon instance
24 This class is well suited to run as a single process. It handles
25 signals for controlled termination (SIGINT and SIGTERM), as well as
26 a user signal to reload the configuration files (SIGUSR1).
28 root - the root handler. This is passed directly to the Dispatcher.
30 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
32 Here is a simple usage example:
34 >>> from pymin import dispatcher
35 >>> class Root(dispatcher.Handler):
36 @handler('Test command.')
37 def test(self, *args):
39 >>> PyminDaemon(Root(), ('', 9999)).run()
42 def __init__(self, root, bind_addr=('', 9999), timer=1):
43 r"""Initialize the PyminDaemon object.
45 See PyminDaemon class documentation for more info.
47 log.debug(u'PyminDaemon(%r, %r, %r)', root, bind_addr, timer)
50 # Create and bind socket
51 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
52 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
55 def quit(loop, signum):
56 log.debug(u'PyminDaemon quit() handler: signal %r', signum)
57 log.info(u'Shutting down...')
58 loop.stop() # tell main event loop to stop
59 def reload_config(loop, signum):
60 log.debug(u'PyminDaemon reload_config() handler: signal %r', signum)
61 log.info(u'Reloading configuration...')
62 # TODO iterate handlers list propagating reload action
63 def timer(loop, signum):
65 signal.alarm(loop.timer)
66 def child(loop, signum):
67 procman.sigchild_handler(signum)
69 eventloop.EventLoop.__init__(self, sock, signals={
72 signal.SIGUSR1: reload_config,
73 signal.SIGALRM: timer,
74 signal.SIGCHLD: child,
77 #TODO root.pymin = PyminHandler()
78 self.dispatcher = dispatcher.Dispatcher(root)
81 r"handle() -> None :: Handle incoming events using the dispatcher."
82 (msg, addr) = self.file.recvfrom(65535)
83 log.debug(u'PyminDaemon.handle: message %r from %r', msg, addr)
85 result = self.dispatcher.dispatch(unicode(msg, 'utf-8'))
86 if result is not None:
87 result = serializer.serialize(result)
89 except dispatcher.Error, e:
90 result = unicode(e) + u'\n'
94 result = u'Internal server error\n'
96 log.exception(u'PyminDaemon.handle: unhandled exception')
100 response += u'%d\n%s' % (len(result), result)
101 log.debug(u'PyminDaemon.handle: response %r to %r', response, addr)
102 self.file.sendto(response.encode('utf-8'), addr)
104 def handle_timer(self):
105 r"handle_timer() -> None :: Call handle_timer() on handlers."
106 self.dispatcher.root.handle_timer()
109 r"run() -> None :: Run the event loop (shortcut to loop())"
110 log.debug(u'PyminDaemon.loop()')
113 signal.alarm(self.timer)
117 except eventloop.LoopInterruptedError, e:
118 log.debug(u'PyminDaemon.loop: interrupted')
121 if __name__ == '__main__':
124 level = logging.DEBUG,
125 format = '%(asctime)s %(levelname)-8s %(message)s',
126 datefmt = '%H:%M:%S',
129 class Root(dispatcher.Handler):
130 @handler(u"Print all the arguments, return nothing.")
131 def test(self, *args):
133 @handler(u"Echo the message passed as argument.")
134 def echo(self, message):
135 print 'echo:', message
138 PyminDaemon(Root()).run()