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.
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, timer=timer)
52 #TODO root.pymin = PyminHandler()
53 self.dispatcher = dispatcher.Dispatcher(root)
55 def quit(signum, frame):
56 print "Shuting down ..."
57 self.stop() # tell main event loop to stop
58 def reload_config(signum, frame):
59 print "Reloading configuration..."
60 # TODO iterate handlers list propagating reload action
61 signal.signal(signal.SIGINT, quit)
62 signal.signal(signal.SIGTERM, quit)
63 signal.signal(signal.SIGUSR1, reload_config)
66 r"handle() -> None :: Handle incoming events using the dispatcher."
67 (msg, addr) = self.file.recvfrom(65535)
69 result = self.dispatcher.dispatch(unicode(msg, 'utf-8'))
70 if result is not None:
71 result = serializer.serialize(result)
73 except dispatcher.Error, e:
74 result = unicode(e) + u'\n'
78 result = u'Internal server error\n'
79 traceback.print_exc() # TODO logging!
84 response += u'%d\n%s' % (len(result), result)
85 self.file.sendto(response.encode('utf-8'), addr)
87 def handle_timer(self):
88 r"handle_timer() -> None :: Call handle_timer() on handlers."
89 self.dispatcher.root.handle_timer()
92 r"run() -> None :: Run the event loop (shortcut to loop())"
95 except eventloop.LoopInterruptedError, e:
98 if __name__ == '__main__':
100 class Root(dispatcher.Handler):
101 @handler(u"Print all the arguments, return nothing.")
102 def test(self, *args):
104 @handler(u"Echo the message passed as argument.")
105 def echo(self, message):
106 print 'echo:', message
109 PyminDaemon(Root()).run()