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
14 from pymin.dispatcher import handler
15 from pymin import dispatcher
16 from pymin import eventloop
17 from pymin import serializer
19 class PyminDaemon(eventloop.EventLoop):
20 r"""PyminDaemon(root, bind_addr) -> PyminDaemon instance
22 This class is well suited to run as a single process. It handles
23 signals for controlled termination (SIGINT and SIGTERM), as well as
24 a user signal to reload the configuration files (SIGUSR1).
26 root - the root handler. This is passed directly to the Dispatcher.
28 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
30 Here is a simple usage example:
32 >>> from pymin import dispatcher
33 >>> class Root(dispatcher.Handler):
34 @handler('Test command.')
35 def test(self, *args):
37 >>> PyminDaemon(Root(), ('', 9999)).run()
40 def __init__(self, root, bind_addr=('', 9999)):
41 r"""Initialize the PyminDaemon object.
43 See PyminDaemon class documentation for more info.
45 # Create and bind socket
46 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
47 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
50 eventloop.EventLoop.__init__(self, sock)
52 self.dispatcher = dispatcher.Dispatcher(root)
54 def quit(signum, frame):
55 print "Shuting down ..."
56 self.stop() # tell main event loop to stop
57 def reload_config(signum, frame):
58 print "Reloading configuration..."
59 # TODO iterate handlers list propagating reload action
60 signal.signal(signal.SIGINT, quit)
61 signal.signal(signal.SIGTERM, quit)
62 signal.signal(signal.SIGUSR1, reload_config)
65 r"handle() -> None :: Handle incoming events using the dispatcher."
66 (msg, addr) = self.file.recvfrom(65535)
68 result = self.dispatcher.dispatch(msg)
69 if result is not None:
70 result = serializer.serialize(result)
72 except dispatcher.Error, e:
73 result = unicode(e) + u'\n'
77 result = u'Internal server error\n'
78 traceback.print_exc() # TODO logging!
83 response += u'%d\n%s' % (len(result), result)
84 self.file.sendto(response, addr)
87 r"run() -> None :: Run the event loop (shortcut to loop())"
90 except eventloop.LoopInterruptedError, e:
93 if __name__ == '__main__':
95 class Root(dispatcher.Handler):
96 @handler(u"Print all the arguments, return nothing.")
97 def test(self, *args):
99 @handler(u"Echo the message passed as argument.")
100 def echo(self, message):
101 print 'echo:', message
104 PyminDaemon(Root()).run()