blob: 9fbe0e9a4a8dbdd54c8e9676b6d81bc4092ee4d4 [file] [log] [blame]
Chui Tey5d2af632002-05-26 13:36:41 +00001import sys
Kurt B. Kaisera00050f2003-05-08 20:26:55 +00002import os
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +00003import linecache
Kurt B. Kaiserb4179362002-07-26 00:06:42 +00004import time
5import socket
Kurt B. Kaiser86bc4642003-02-27 23:04:17 +00006import traceback
Kurt B. Kaiser93e8e542003-06-13 22:03:43 +00007import thread
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +00008import threading
9import Queue
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +000010
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000011from idlelib import CallTips
12from idlelib import AutoComplete
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000013
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +000014from idlelib import RemoteDebugger
15from idlelib import RemoteObjectBrowser
16from idlelib import StackViewer
17from idlelib import rpc
Chui Tey5d2af632002-05-26 13:36:41 +000018
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +000019import __main__
20
Kurt B. Kaiser24d7e0c2003-06-05 23:51:29 +000021LOCALHOST = '127.0.0.1'
22
Kurt B. Kaiser49a5fe12004-07-04 01:25:56 +000023try:
24 import warnings
25except ImportError:
26 pass
27else:
28 def idle_formatwarning_subproc(message, category, filename, lineno):
29 """Format warnings the IDLE way"""
30 s = "\nWarning (from warnings module):\n"
31 s += ' File \"%s\", line %s\n' % (filename, lineno)
32 line = linecache.getline(filename, lineno).strip()
33 if line:
34 s += " %s\n" % line
35 s += "%s: %s\n" % (category.__name__, message)
36 return s
37 warnings.formatwarning = idle_formatwarning_subproc
38
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000039# Thread shared globals: Establish a queue between a subthread (which handles
40# the socket) and the main thread (which runs user code), plus global
Guido van Rossum8ce8a782007-11-01 19:42:39 +000041# completion, exit and interruptable (the main thread) flags:
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000042
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +000043exit_now = False
44quitting = False
Guido van Rossum8ce8a782007-11-01 19:42:39 +000045interruptable = False
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000046
Kurt B. Kaiser62df0442003-05-28 01:47:46 +000047def main(del_exitfunc=False):
Kurt B. Kaiserb4179362002-07-26 00:06:42 +000048 """Start the Python execution server in a subprocess
49
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +000050 In the Python subprocess, RPCServer is instantiated with handlerclass
51 MyHandler, which inherits register/unregister methods from RPCHandler via
52 the mix-in class SocketIO.
Kurt B. Kaiserb4179362002-07-26 00:06:42 +000053
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000054 When the RPCServer 'server' is instantiated, the TCPServer initialization
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +000055 creates an instance of run.MyHandler and calls its handle() method.
56 handle() instantiates a run.Executive object, passing it a reference to the
57 MyHandler object. That reference is saved as attribute rpchandler of the
58 Executive instance. The Executive methods have access to the reference and
59 can pass it on to entities that they command
60 (e.g. RemoteDebugger.Debugger.start_debugger()). The latter, in turn, can
61 call MyHandler(SocketIO) register/unregister methods via the reference to
62 register and unregister themselves.
Kurt B. Kaiserb4179362002-07-26 00:06:42 +000063
64 """
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +000065 global exit_now
66 global quitting
Kurt B. Kaiser62df0442003-05-28 01:47:46 +000067 global no_exitfunc
68 no_exitfunc = del_exitfunc
Chui Tey5d2af632002-05-26 13:36:41 +000069 port = 8833
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +000070 #time.sleep(15) # test subprocess not responding
Chui Tey5d2af632002-05-26 13:36:41 +000071 if sys.argv[1:]:
72 port = int(sys.argv[1])
73 sys.argv[:] = [""]
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000074 sockthread = threading.Thread(target=manage_socket,
75 name='SockThread',
Kurt B. Kaiser24d7e0c2003-06-05 23:51:29 +000076 args=((LOCALHOST, port),))
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +000077 sockthread.setDaemon(True)
78 sockthread.start()
79 while 1:
80 try:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +000081 if exit_now:
82 try:
Kurt B. Kaiser62df0442003-05-28 01:47:46 +000083 exit()
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +000084 except KeyboardInterrupt:
85 # exiting but got an extra KBI? Try again!
86 continue
Kurt B. Kaisera00050f2003-05-08 20:26:55 +000087 try:
Kurt B. Kaiser20345fb2005-05-05 23:29:54 +000088 seq, request = rpc.request_queue.get(block=True, timeout=0.05)
Kurt B. Kaisera00050f2003-05-08 20:26:55 +000089 except Queue.Empty:
Kurt B. Kaisera00050f2003-05-08 20:26:55 +000090 continue
91 method, args, kwargs = request
92 ret = method(*args, **kwargs)
93 rpc.response_queue.put((seq, ret))
Kurt B. Kaiseraa6b8562003-05-14 18:15:40 +000094 except KeyboardInterrupt:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +000095 if quitting:
96 exit_now = True
Kurt B. Kaiseraa6b8562003-05-14 18:15:40 +000097 continue
Kurt B. Kaisera2792be2003-05-17 21:04:10 +000098 except SystemExit:
99 raise
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000100 except:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000101 type, value, tb = sys.exc_info()
Kurt B. Kaisera2792be2003-05-17 21:04:10 +0000102 try:
103 print_exception()
104 rpc.response_queue.put((seq, None))
105 except:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000106 # Link didn't work, print same exception to __stderr__
107 traceback.print_exception(type, value, tb, file=sys.__stderr__)
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000108 exit()
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000109 else:
110 continue
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000111
112def manage_socket(address):
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000113 for i in range(3):
Kurt B. Kaiserb4179362002-07-26 00:06:42 +0000114 time.sleep(i)
115 try:
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000116 server = MyRPCServer(address, MyHandler)
Kurt B. Kaiserb4179362002-07-26 00:06:42 +0000117 break
Guido van Rossumb940e112007-01-10 16:19:56 +0000118 except socket.error as err:
Georg Brandl6464d472007-10-22 16:16:13 +0000119 print("IDLE Subprocess: socket error: " + err.args[1] +
120 ", retrying....", file=sys.__stderr__)
Kurt B. Kaiserb4179362002-07-26 00:06:42 +0000121 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000122 print("IDLE Subprocess: Connection to "\
123 "IDLE GUI failed, exiting.", file=sys.__stderr__)
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000124 show_socket_error(err, address)
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000125 global exit_now
126 exit_now = True
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000127 return
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000128 server.handle_request() # A single request only
129
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000130def show_socket_error(err, address):
131 import Tkinter
132 import tkMessageBox
133 root = Tkinter.Tk()
134 root.withdraw()
Georg Brandl6464d472007-10-22 16:16:13 +0000135 if err.args[0] == 61: # connection refused
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000136 msg = "IDLE's subprocess can't connect to %s:%d. This may be due "\
137 "to your personal firewall configuration. It is safe to "\
138 "allow this internal connection because no data is visible on "\
139 "external ports." % address
140 tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
141 else:
Georg Brandl6464d472007-10-22 16:16:13 +0000142 tkMessageBox.showerror("IDLE Subprocess Error",
143 "Socket Error: %s" % err.args[1])
Kurt B. Kaiseraf3eb872004-01-21 18:54:30 +0000144 root.destroy()
145
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000146def print_exception():
Kurt B. Kaisere9802a32004-01-02 04:04:04 +0000147 import linecache
148 linecache.checkcache()
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000149 flush_stdout()
150 efile = sys.stderr
Kurt B. Kaiser924f6162003-11-19 04:52:32 +0000151 typ, val, tb = excinfo = sys.exc_info()
152 sys.last_type, sys.last_value, sys.last_traceback = excinfo
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000153 tbe = traceback.extract_tb(tb)
Guido van Rossum33d26892007-08-05 15:29:28 +0000154 print('Traceback (most recent call last):', file=efile)
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000155 exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
156 "RemoteDebugger.py", "bdb.py")
157 cleanup_traceback(tbe, exclude)
158 traceback.print_list(tbe, file=efile)
159 lines = traceback.format_exception_only(typ, val)
160 for line in lines:
Guido van Rossum33d26892007-08-05 15:29:28 +0000161 print(line, end='', file=efile)
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000162
163def cleanup_traceback(tb, exclude):
164 "Remove excluded traces from beginning/end of tb; get cached lines"
165 orig_tb = tb[:]
166 while tb:
167 for rpcfile in exclude:
168 if tb[0][0].count(rpcfile):
169 break # found an exclude, break for: and delete tb[0]
170 else:
171 break # no excludes, have left RPC code, break while:
172 del tb[0]
173 while tb:
174 for rpcfile in exclude:
175 if tb[-1][0].count(rpcfile):
176 break
177 else:
178 break
179 del tb[-1]
180 if len(tb) == 0:
181 # exception was in IDLE internals, don't prune!
182 tb[:] = orig_tb[:]
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000183 print("** IDLE Internal Exception: ", file=sys.stderr)
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000184 rpchandler = rpc.objecttable['exec'].rpchandler
185 for i in range(len(tb)):
186 fn, ln, nm, line = tb[i]
187 if nm == '?':
188 nm = "-toplevel-"
189 if not line and fn.startswith("<pyshell#"):
190 line = rpchandler.remotecall('linecache', 'getline',
191 (fn, ln), {})
192 tb[i] = fn, ln, nm, line
193
194def flush_stdout():
Guido van Rossum79139b22007-02-09 23:20:19 +0000195 """XXX How to do this now?"""
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000196
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000197def exit():
Guido van Rossumc76a2502007-08-09 14:26:58 +0000198 """Exit subprocess, possibly after first clearing exit functions.
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000199
200 If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any
Guido van Rossumc76a2502007-08-09 14:26:58 +0000201 functions registered with atexit will be removed before exiting.
202 (VPython support)
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000203
204 """
205 if no_exitfunc:
Guido van Rossumc76a2502007-08-09 14:26:58 +0000206 import atexit
207 atexit._clear()
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000208 sys.exit(0)
Chui Tey5d2af632002-05-26 13:36:41 +0000209
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000210class MyRPCServer(rpc.RPCServer):
211
212 def handle_error(self, request, client_address):
213 """Override RPCServer method for IDLE
214
215 Interrupt the MainThread and exit server if link is dropped.
216
217 """
Kurt B. Kaisere9535112004-11-19 15:46:49 +0000218 global quitting
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000219 try:
220 raise
221 except SystemExit:
222 raise
223 except EOFError:
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000224 global exit_now
225 exit_now = True
Kurt B. Kaiser93e8e542003-06-13 22:03:43 +0000226 thread.interrupt_main()
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000227 except:
228 erf = sys.__stderr__
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000229 print('\n' + '-'*40, file=erf)
230 print('Unhandled server exception!', file=erf)
231 print('Thread: %s' % threading.currentThread().getName(), file=erf)
232 print('Client Address: ', client_address, file=erf)
233 print('Request: ', repr(request), file=erf)
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000234 traceback.print_exc(file=erf)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000235 print('\n*** Unrecoverable, server exiting!', file=erf)
236 print('-'*40, file=erf)
Kurt B. Kaisere9535112004-11-19 15:46:49 +0000237 quitting = True
238 thread.interrupt_main()
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000239
240
Chui Tey5d2af632002-05-26 13:36:41 +0000241class MyHandler(rpc.RPCHandler):
242
243 def handle(self):
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000244 """Override base method"""
Chui Tey5d2af632002-05-26 13:36:41 +0000245 executive = Executive(self)
246 self.register("exec", executive)
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000247 sys.stdin = self.console = self.get_remote_proxy("stdin")
Chui Tey5d2af632002-05-26 13:36:41 +0000248 sys.stdout = self.get_remote_proxy("stdout")
249 sys.stderr = self.get_remote_proxy("stderr")
Kurt B. Kaiser2d7f6a02007-08-22 23:01:33 +0000250 from idlelib import IOBinding
Martin v. Löwisbcc651a2003-06-22 07:52:56 +0000251 sys.stdin.encoding = sys.stdout.encoding = \
252 sys.stderr.encoding = IOBinding.encoding
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000253 self.interp = self.get_remote_proxy("interp")
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000254 rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
255
256 def exithook(self):
257 "override SocketIO method - wait for MainThread to shut us down"
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000258 time.sleep(10)
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000259
260 def EOFhook(self):
261 "Override SocketIO method - terminate wait on callback and exit thread"
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000262 global quitting
263 quitting = True
Kurt B. Kaiser93e8e542003-06-13 22:03:43 +0000264 thread.interrupt_main()
Kurt B. Kaisera00050f2003-05-08 20:26:55 +0000265
266 def decode_interrupthook(self):
267 "interrupt awakened thread"
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000268 global quitting
269 quitting = True
Kurt B. Kaiser93e8e542003-06-13 22:03:43 +0000270 thread.interrupt_main()
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000271
Chui Tey5d2af632002-05-26 13:36:41 +0000272
Kurt B. Kaiserdcba6622004-12-21 22:10:32 +0000273class Executive(object):
Chui Tey5d2af632002-05-26 13:36:41 +0000274
275 def __init__(self, rpchandler):
Kurt B. Kaiserffd3a422002-06-26 02:32:09 +0000276 self.rpchandler = rpchandler
Kurt B. Kaiseradc63842002-08-25 14:08:07 +0000277 self.locals = __main__.__dict__
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000278 self.calltip = CallTips.CallTips()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000279 self.autocomplete = AutoComplete.AutoComplete()
Chui Tey5d2af632002-05-26 13:36:41 +0000280
281 def runcode(self, code):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000282 global interruptable
Kurt B. Kaiser86bc4642003-02-27 23:04:17 +0000283 try:
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000284 self.usr_exc_info = None
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000285 interruptable = True
286 try:
287 exec(code, self.locals)
288 finally:
289 interruptable = False
Kurt B. Kaiser86bc4642003-02-27 23:04:17 +0000290 except:
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000291 self.usr_exc_info = sys.exc_info()
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000292 if quitting:
Kurt B. Kaiser62df0442003-05-28 01:47:46 +0000293 exit()
Kurt B. Kaiser67fd0ea2003-05-24 20:59:15 +0000294 # even print a user code SystemExit exception, continue
295 print_exception()
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000296 jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>")
297 if jit:
298 self.rpchandler.interp.open_remote_stack_viewer()
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000299 else:
Kurt B. Kaiser9ec454e2003-05-12 02:33:47 +0000300 flush_stdout()
Chui Tey5d2af632002-05-26 13:36:41 +0000301
Kurt B. Kaiser003091c2003-02-17 18:57:16 +0000302 def interrupt_the_server(self):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000303 if interruptable:
304 thread.interrupt_main()
Kurt B. Kaiser11c53e22003-03-22 19:40:19 +0000305
Kurt B. Kaiser0e3a5772002-06-16 03:32:24 +0000306 def start_the_debugger(self, gui_adap_oid):
Kurt B. Kaiserffd3a422002-06-26 02:32:09 +0000307 return RemoteDebugger.start_debugger(self.rpchandler, gui_adap_oid)
308
309 def stop_the_debugger(self, idb_adap_oid):
310 "Unregister the Idb Adapter. Link objects and Idb then subject to GC"
311 self.rpchandler.unregister(idb_adap_oid)
Chui Tey5d2af632002-05-26 13:36:41 +0000312
Kurt B. Kaiser5afa1df2002-10-10 08:25:24 +0000313 def get_the_calltip(self, name):
314 return self.calltip.fetch_tip(name)
315
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000316 def get_the_completion_list(self, what, mode):
317 return self.autocomplete.fetch_completions(what, mode)
318
Chui Tey5d2af632002-05-26 13:36:41 +0000319 def stackviewer(self, flist_oid=None):
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000320 if self.usr_exc_info:
321 typ, val, tb = self.usr_exc_info
322 else:
Chui Tey5d2af632002-05-26 13:36:41 +0000323 return None
324 flist = None
325 if flist_oid is not None:
Kurt B. Kaiserffd3a422002-06-26 02:32:09 +0000326 flist = self.rpchandler.get_remote_proxy(flist_oid)
Chui Tey5d2af632002-05-26 13:36:41 +0000327 while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]:
328 tb = tb.tb_next
Kurt B. Kaiser9f366092003-06-02 01:50:19 +0000329 sys.last_type = typ
330 sys.last_value = val
Chui Tey5d2af632002-05-26 13:36:41 +0000331 item = StackViewer.StackTreeItem(flist, tb)
332 return RemoteObjectBrowser.remote_object_tree_item(item)