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
18 class PyminDaemon(eventloop.EventLoop):
19 r"""PyminDaemon(bind_addr, routes) -> PyminDaemon instance
21 This class is well suited to run as a single process. It handles
22 signals for controlled termination (SIGINT and SIGTERM), as well as
23 a user signal to reload the configuration files (SIGUSR1).
25 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
27 routes - is a dictionary where the key is a command string and the value
28 is the command handler. This is passed directly to the Dispatcher.
30 Here is a simple usage example:
32 >>> def test_handler(*args): print 'test:', args
33 >>> PyminDaemon(('', 9999), dict(test=test_handler)).run()
36 def __init__(self, routes=dict(), bind_addr=('', 9999)):
37 r"""Initialize the PyminDaemon object.
39 See PyminDaemon class documentation for more info.
41 # Create and bind socket
42 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
43 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
46 eventloop.EventLoop.__init__(self, sock)
48 self.dispatcher = dispatcher.Dispatcher(routes)
50 def quit(signum, frame):
51 print "Shuting down ..."
52 self.stop() # tell main event loop to stop
53 def reload_config(signum, frame):
54 print "Reloading configuration..."
55 # TODO iterate handlers list propagating reload action
56 signal.signal(signal.SIGINT, quit)
57 signal.signal(signal.SIGTERM, quit)
58 signal.signal(signal.SIGUSR1, reload_config)
61 r"handle() -> None :: Handle incoming events using the dispatcher."
62 (msg, addr) = self.file.recvfrom(65535)
64 result = self.dispatcher.dispatch(msg)
65 if result is not None:
66 result = serializer.serialize(result)
68 except dispatcher.Error, e:
69 result = unicode(e) + u'\n'
73 result = u'Internal server error\n'
74 traceback.print_exc() # TODO logging!
79 response += u'%d\n%s' % (len(result), result)
80 self.file.sendto(response, addr)
83 r"run() -> None :: Run the event loop (shortcut to loop())"
86 except eventloop.LoopInterruptedError, e:
89 if __name__ == '__main__':
91 @handler(u"Print all the arguments, return nothing.")
92 def test_handler(*args):
95 @handler(u"Echo the message passed as argument.")
96 def echo_handler(message):
97 print 'echo:', message
100 PyminDaemon(dict(test=test_handler, echo=echo_handler)).run()