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(%s.%s, %s, %s)', root.__class__.__module__,
47 root.__class__.__name__, bind_addr, timer)
48 # Create and bind socket
49 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
50 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
53 eventloop.EventLoop.__init__(self, sock, timer=timer)
55 #TODO root.pymin = PyminHandler()
56 self.dispatcher = dispatcher.Dispatcher(root)
58 def quit(signum, frame):
59 log.debug(u'PyminDaemon quit() handler: signal %s', signum)
60 log.info(u'Shutting down...')
61 self.stop() # tell main event loop to stop
62 def reload_config(signum, frame):
63 log.debug(u'PyminDaemon reload_config() handler: signal %s', signum)
64 log.info(u'Reloading configuration...')
65 # TODO iterate handlers list propagating reload action
66 signal.signal(signal.SIGINT, quit)
67 signal.signal(signal.SIGTERM, quit)
68 signal.signal(signal.SIGUSR1, reload_config)
71 r"handle() -> None :: Handle incoming events using the dispatcher."
72 (msg, addr) = self.file.recvfrom(65535)
73 log.debug(u'PyminDaemon.handle: message %r from %s', msg, addr)
75 result = self.dispatcher.dispatch(unicode(msg, 'utf-8'))
76 if result is not None:
77 result = serializer.serialize(result)
79 except dispatcher.Error, e:
80 result = unicode(e) + u'\n'
84 result = u'Internal server error\n'
86 log.exception(u'PyminDaemon.handle: unhandled exception')
90 response += u'%d\n%s' % (len(result), result)
91 log.debug(u'PyminDaemon.handle: response %r to %s', response, addr)
92 self.file.sendto(response.encode('utf-8'), addr)
94 def handle_timer(self):
95 r"handle_timer() -> None :: Call handle_timer() on handlers."
96 self.dispatcher.root.handle_timer()
99 r"run() -> None :: Run the event loop (shortcut to loop())"
100 log.debug(u'PyminDaemon.loop()')
103 except eventloop.LoopInterruptedError, e:
104 log.debug(u'PyminDaemon.loop: interrupted')
107 if __name__ == '__main__':
110 level = logging.DEBUG,
111 format = '%(asctime)s %(levelname)-8s %(message)s',
112 datefmt = '%H:%M:%S',
115 class Root(dispatcher.Handler):
116 @handler(u"Print all the arguments, return nothing.")
117 def test(self, *args):
119 @handler(u"Echo the message passed as argument.")
120 def echo(self, message):
121 print 'echo:', message
124 PyminDaemon(Root()).run()