blob: d8c81f9d49c3ff1c1e77f3b04acefa9dbfbf93e5 [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001#!/usr/bin/env python
2
3import sys
4from threading import currentThread
5from SocketServer import BaseRequestHandler, TCPServer
6from code import InteractiveConsole
7
8_locals = None
9
10class DebugLogger(object):
11 def do_print(self, *args):
12 for i in args:
13 print i,
14 print
15 info = do_print
16 warn = do_print
17 debug = do_print
18_log = DebugLogger()
19
20
21class DebugConsole(InteractiveConsole):
22 def __init__(self, request):
23 self.request = request
24 InteractiveConsole.__init__(self, _locals)
25
26 def raw_input(self, prompt):
27 self.request.send(prompt)
28 data = self.request.recv(10000).rstrip()
29 if len(data) == 1 and ord(data[0]) == 4:
30 sys.exit()
31 return data
32
33 def write(self, data):
34 self.request.send(str(data))
35
36 def write_nl(self, data):
37 self.write(str(data)+"\r\n")
38
39class DebugServerHandler(BaseRequestHandler):
40 def __init__(self, request, client_address, server):
41 currentThread()._thread.setName("debugserver-%s:%d" % client_address)
42 _log.debug('Open connection to DebugServer from %s:%d' % client_address)
43 BaseRequestHandler.__init__(self, request, client_address, server)
44
45 def handle(self):
46 console = DebugConsole(self.request)
47 sys.displayhook = console.write_nl
48 console.interact('DebugServer')
49 self.request.close()
50
51class DebugServer(TCPServer):
52 daemon_threads = True
53 allow_reuse_address = True
54
55 def handle_error(self, request, client_address):
56 _log.debug('Closing connection to DebugServer from %s:%d' % client_address)
57 request.close()
58
59def run_server(port=6655, host='0.0.0.0', locals=locals()):
60 currentThread()._thread.setName("debugserver-main")
61
62 global _locals
63 _locals = locals
64 if "log" in locals.keys():
65 global _log
66 _log = locals["log"]
67
68 _log.info("Starting DebugServer on port %d" % port)
69 server = DebugServer(('', port), DebugServerHandler)
70 try:
71 server.serve_forever()
72 except KeyboardInterrupt:
73 pass
74
75if __name__ == "__main__":
76 run_server()