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 from dispatcher import Dispatcher
14 from eventloop import EventLoop, LoopInterruptedError
16 class PyminDaemon(EventLoop):
17 r"""PyminDaemon(bind_addr, routes) -> PyminDaemon instance
19 This class is well suited to run as a single process. It handles
20 signals for controlled termination (SIGINT and SIGTERM), as well as
21 a user signal to reload the configuration files (SIGUSR1).
23 bind_addr - is a tuple of (ip, port) where to bind the UDP socket to.
25 routes - is a dictionary where the key is a command string and the value
26 is the command handler. This is passed directly to the Dispatcher.
28 Here is a simple usage example:
30 >>> def test_handler(*args): print 'test:', args
31 >>> PyminDaemon(('', 9999), dict(test=test_handler)).run()
34 def __init__(self, bind_addr, routes):
35 r"""Initialize the PyminDaemon object.
37 See PyminDaemon class documentation for more info.
39 # Create and bind socket
40 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
41 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
44 EventLoop.__init__(self, sock)
46 self.dispatcher = Dispatcher(routes)
48 def quit(signum, frame):
49 print "Shuting down ..."
50 self.stop() # tell main event loop to stop
51 def reload_config(signum, frame):
52 print "Reloading configuration..."
53 # TODO iterate handlers list propagating reload action
54 signal.signal(signal.SIGINT, quit)
55 signal.signal(signal.SIGTERM, quit)
56 signal.signal(signal.SIGUSR1, reload_config)
59 r"handle() -> None :: Handle incoming events using the dispatcher."
60 (msg, addr) = self.file.recvfrom(65535)
62 result = self.dispatcher.dispatch(msg)
70 response += '%d\n%s' % (len(str(result)), result)
71 self.file.sendto(response, addr)
74 r"run() -> None :: Run the event loop (shortcut to loop())"
77 except LoopInterruptedError, e:
80 if __name__ == '__main__':
83 def test_handler(*args):
86 PyminDaemon(('', 9999), dict(test=test_handler)).run()