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 import eventloop
15 from pymin import serializer
17 class PyminDaemon(eventloop.EventLoop):
18 r"""PyminDaemon(bind_addr, routes) -> PyminDaemon instance
20 This class is well suited to run as a single process. It handles
21 signals for controlled termination (SIGINT and SIGTERM), as well as
22 a user signal to reload the configuration files (SIGUSR1).
24 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
26 routes - is a dictionary where the key is a command string and the value
27 is the command handler. This is passed directly to the Dispatcher.
29 Here is a simple usage example:
31 >>> def test_handler(*args): print 'test:', args
32 >>> PyminDaemon(('', 9999), dict(test=test_handler)).run()
35 def __init__(self, routes=dict(), bind_addr=('', 9999)):
36 r"""Initialize the PyminDaemon object.
38 See PyminDaemon class documentation for more info.
40 # Create and bind socket
41 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
42 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
45 eventloop.EventLoop.__init__(self, sock)
47 self.dispatcher = Dispatcher(routes)
49 def quit(signum, frame):
50 print "Shuting down ..."
51 self.stop() # tell main event loop to stop
52 def reload_config(signum, frame):
53 print "Reloading configuration..."
54 # TODO iterate handlers list propagating reload action
55 signal.signal(signal.SIGINT, quit)
56 signal.signal(signal.SIGTERM, quit)
57 signal.signal(signal.SIGUSR1, reload_config)
60 r"handle() -> None :: Handle incoming events using the dispatcher."
61 (msg, addr) = self.file.recvfrom(65535)
63 result = self.dispatcher.dispatch(msg)
64 if result is not None:
65 result = serializer.serialize(result)
67 except dispatcher.Error, e:
68 result = unicode(e) + u'\n'
72 result = u'Internal server error\n'
73 traceback.print_exc() # TODO logging!
78 response += u'%d\n%s' % (len(result), result)
79 self.file.sendto(response, addr)
82 r"run() -> None :: Run the event loop (shortcut to loop())"
85 except eventloop.LoopInterruptedError, e:
88 if __name__ == '__main__':
90 @handler(u"Print all the arguments, return nothing.")
91 def test_handler(*args):
94 @handler(u"Echo the message passed as argument.")
95 def echo_handler(message):
96 print 'echo:', message
99 PyminDaemon(dict(test=test_handler, echo=echo_handler)).run()