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
20 class PyminDaemon(eventloop.EventLoop):
21 r"""PyminDaemon(root, bind_addr) -> PyminDaemon instance
23 This class is well suited to run as a single process. It handles
24 signals for controlled termination (SIGINT and SIGTERM), as well as
25 a user signal to reload the configuration files (SIGUSR1).
27 root - the root handler. This is passed directly to the Dispatcher.
29 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
31 Here is a simple usage example:
33 >>> from pymin import dispatcher
34 >>> class Root(dispatcher.Handler):
35 @handler('Test command.')
36 def test(self, *args):
38 >>> PyminDaemon(Root(), ('', 9999)).run()
41 def __init__(self, root, bind_addr=('', 9999), timer=1):
42 r"""Initialize the PyminDaemon object.
44 See PyminDaemon class documentation for more info.
46 log.debug(u'PyminDaemon(%r, %r, %r)', root, bind_addr, timer)
47 # Create and bind socket
48 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
49 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
52 eventloop.EventLoop.__init__(self, sock, timer=timer)
54 #TODO root.pymin = PyminHandler()
55 self.dispatcher = dispatcher.Dispatcher(root)
57 def quit(signum, frame):
58 log.debug(u'PyminDaemon quit() handler: signal %r', signum)
59 log.info(u'Shutting down...')
60 self.stop() # tell main event loop to stop
61 def reload_config(signum, frame):
62 log.debug(u'PyminDaemon reload_config() handler: signal %r', signum)
63 log.info(u'Reloading configuration...')
64 # TODO iterate handlers list propagating reload action
65 signal.signal(signal.SIGINT, quit)
66 signal.signal(signal.SIGTERM, quit)
67 signal.signal(signal.SIGUSR1, reload_config)
70 r"handle() -> None :: Handle incoming events using the dispatcher."
71 (msg, addr) = self.file.recvfrom(65535)
72 log.debug(u'PyminDaemon.handle: message %r from %r', msg, addr)
74 result = self.dispatcher.dispatch(unicode(msg, 'utf-8'))
75 if result is not None:
76 result = serializer.serialize(result)
78 except dispatcher.Error, e:
79 result = unicode(e) + u'\n'
83 result = u'Internal server error\n'
85 log.exception(u'PyminDaemon.handle: unhandled exception')
89 response += u'%d\n%s' % (len(result), result)
90 log.debug(u'PyminDaemon.handle: response %r to %r', response, addr)
91 self.file.sendto(response.encode('utf-8'), addr)
93 def handle_timer(self):
94 r"handle_timer() -> None :: Call handle_timer() on handlers."
95 self.dispatcher.root.handle_timer()
98 r"run() -> None :: Run the event loop (shortcut to loop())"
99 log.debug(u'PyminDaemon.loop()')
102 except eventloop.LoopInterruptedError, e:
103 log.debug(u'PyminDaemon.loop: interrupted')
106 if __name__ == '__main__':
109 level = logging.DEBUG,
110 format = '%(asctime)s %(levelname)-8s %(message)s',
111 datefmt = '%H:%M:%S',
114 class Root(dispatcher.Handler):
115 @handler(u"Print all the arguments, return nothing.")
116 def test(self, *args):
118 @handler(u"Echo the message passed as argument.")
119 def echo(self, message):
120 print 'echo:', message
123 PyminDaemon(Root()).run()