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), timer=1):
41 r"""Initialize the PyminDaemon object.
43 See PyminDaemon class documentation for more info.
47 # Create and bind socket
48 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
49 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
52 def quit(loop, signum):
53 print "Shuting down ..."
54 loop.stop() # tell main event loop to stop
55 def reload_config(loop, signum):
56 print "Reloading configuration..."
57 # TODO iterate handlers list propagating reload action
58 def timer(loop, signum):
60 signal.alarm(loop.timer)
62 eventloop.EventLoop.__init__(self, sock, signals={
65 signal.SIGUSR1: reload_config,
66 signal.SIGALRM: timer,
69 #TODO root.pymin = PyminHandler()
70 self.dispatcher = dispatcher.Dispatcher(root)
73 r"handle() -> None :: Handle incoming events using the dispatcher."
74 (msg, addr) = self.file.recvfrom(65535)
76 result = self.dispatcher.dispatch(unicode(msg, 'utf-8'))
77 if result is not None:
78 result = serializer.serialize(result)
80 except dispatcher.Error, e:
81 result = unicode(e) + u'\n'
85 result = u'Internal server error\n'
86 traceback.print_exc() # TODO logging!
91 response += u'%d\n%s' % (len(result), result)
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())"
102 signal.alarm(self.timer)
106 except eventloop.LoopInterruptedError, e:
109 if __name__ == '__main__':
111 class Root(dispatcher.Handler):
112 @handler(u"Print all the arguments, return nothing.")
113 def test(self, *args):
115 @handler(u"Echo the message passed as argument.")
116 def echo(self, message):
117 print 'echo:', message
120 PyminDaemon(Root()).run()