rpc.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. """RPC Implementation, originally written for the Python Idle IDE
  2. For security reasons, GvR requested that Idle's Python execution server process
  3. connect to the Idle process, which listens for the connection. Since Idle has
  4. only one client per server, this was not a limitation.
  5. +---------------------------------+ +-------------+
  6. | socketserver.BaseRequestHandler | | SocketIO |
  7. +---------------------------------+ +-------------+
  8. ^ | register() |
  9. | | unregister()|
  10. | +-------------+
  11. | ^ ^
  12. | | |
  13. | + -------------------+ |
  14. | | |
  15. +-------------------------+ +-----------------+
  16. | RPCHandler | | RPCClient |
  17. | [attribute of RPCServer]| | |
  18. +-------------------------+ +-----------------+
  19. The RPCServer handler class is expected to provide register/unregister methods.
  20. RPCHandler inherits the mix-in class SocketIO, which provides these methods.
  21. See the Idle run.main() docstring for further information on how this was
  22. accomplished in Idle.
  23. """
  24. import builtins
  25. import copyreg
  26. import io
  27. import marshal
  28. import os
  29. import pickle
  30. import queue
  31. import select
  32. import socket
  33. import socketserver
  34. import struct
  35. import sys
  36. import threading
  37. import traceback
  38. import types
  39. def unpickle_code(ms):
  40. "Return code object from marshal string ms."
  41. co = marshal.loads(ms)
  42. assert isinstance(co, types.CodeType)
  43. return co
  44. def pickle_code(co):
  45. "Return unpickle function and tuple with marshalled co code object."
  46. assert isinstance(co, types.CodeType)
  47. ms = marshal.dumps(co)
  48. return unpickle_code, (ms,)
  49. def dumps(obj, protocol=None):
  50. "Return pickled (or marshalled) string for obj."
  51. # IDLE passes 'None' to select pickle.DEFAULT_PROTOCOL.
  52. f = io.BytesIO()
  53. p = CodePickler(f, protocol)
  54. p.dump(obj)
  55. return f.getvalue()
  56. class CodePickler(pickle.Pickler):
  57. dispatch_table = {types.CodeType: pickle_code, **copyreg.dispatch_table}
  58. BUFSIZE = 8*1024
  59. LOCALHOST = '127.0.0.1'
  60. class RPCServer(socketserver.TCPServer):
  61. def __init__(self, addr, handlerclass=None):
  62. if handlerclass is None:
  63. handlerclass = RPCHandler
  64. socketserver.TCPServer.__init__(self, addr, handlerclass)
  65. def server_bind(self):
  66. "Override TCPServer method, no bind() phase for connecting entity"
  67. pass
  68. def server_activate(self):
  69. """Override TCPServer method, connect() instead of listen()
  70. Due to the reversed connection, self.server_address is actually the
  71. address of the Idle Client to which we are connecting.
  72. """
  73. self.socket.connect(self.server_address)
  74. def get_request(self):
  75. "Override TCPServer method, return already connected socket"
  76. return self.socket, self.server_address
  77. def handle_error(self, request, client_address):
  78. """Override TCPServer method
  79. Error message goes to __stderr__. No error message if exiting
  80. normally or socket raised EOF. Other exceptions not handled in
  81. server code will cause os._exit.
  82. """
  83. try:
  84. raise
  85. except SystemExit:
  86. raise
  87. except:
  88. erf = sys.__stderr__
  89. print('\n' + '-'*40, file=erf)
  90. print('Unhandled server exception!', file=erf)
  91. print('Thread: %s' % threading.current_thread().name, file=erf)
  92. print('Client Address: ', client_address, file=erf)
  93. print('Request: ', repr(request), file=erf)
  94. traceback.print_exc(file=erf)
  95. print('\n*** Unrecoverable, server exiting!', file=erf)
  96. print('-'*40, file=erf)
  97. os._exit(0)
  98. #----------------- end class RPCServer --------------------
  99. objecttable = {}
  100. request_queue = queue.Queue(0)
  101. response_queue = queue.Queue(0)
  102. class SocketIO:
  103. nextseq = 0
  104. def __init__(self, sock, objtable=None, debugging=None):
  105. self.sockthread = threading.current_thread()
  106. if debugging is not None:
  107. self.debugging = debugging
  108. self.sock = sock
  109. if objtable is None:
  110. objtable = objecttable
  111. self.objtable = objtable
  112. self.responses = {}
  113. self.cvars = {}
  114. def close(self):
  115. sock = self.sock
  116. self.sock = None
  117. if sock is not None:
  118. sock.close()
  119. def exithook(self):
  120. "override for specific exit action"
  121. os._exit(0)
  122. def debug(self, *args):
  123. if not self.debugging:
  124. return
  125. s = self.location + " " + str(threading.current_thread().name)
  126. for a in args:
  127. s = s + " " + str(a)
  128. print(s, file=sys.__stderr__)
  129. def register(self, oid, object):
  130. self.objtable[oid] = object
  131. def unregister(self, oid):
  132. try:
  133. del self.objtable[oid]
  134. except KeyError:
  135. pass
  136. def localcall(self, seq, request):
  137. self.debug("localcall:", request)
  138. try:
  139. how, (oid, methodname, args, kwargs) = request
  140. except TypeError:
  141. return ("ERROR", "Bad request format")
  142. if oid not in self.objtable:
  143. return ("ERROR", f"Unknown object id: {oid!r}")
  144. obj = self.objtable[oid]
  145. if methodname == "__methods__":
  146. methods = {}
  147. _getmethods(obj, methods)
  148. return ("OK", methods)
  149. if methodname == "__attributes__":
  150. attributes = {}
  151. _getattributes(obj, attributes)
  152. return ("OK", attributes)
  153. if not hasattr(obj, methodname):
  154. return ("ERROR", f"Unsupported method name: {methodname!r}")
  155. method = getattr(obj, methodname)
  156. try:
  157. if how == 'CALL':
  158. ret = method(*args, **kwargs)
  159. if isinstance(ret, RemoteObject):
  160. ret = remoteref(ret)
  161. return ("OK", ret)
  162. elif how == 'QUEUE':
  163. request_queue.put((seq, (method, args, kwargs)))
  164. return("QUEUED", None)
  165. else:
  166. return ("ERROR", "Unsupported message type: %s" % how)
  167. except SystemExit:
  168. raise
  169. except KeyboardInterrupt:
  170. raise
  171. except OSError:
  172. raise
  173. except Exception as ex:
  174. return ("CALLEXC", ex)
  175. except:
  176. msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
  177. " Object: %s \n Method: %s \n Args: %s\n"
  178. print(msg % (oid, method, args), file=sys.__stderr__)
  179. traceback.print_exc(file=sys.__stderr__)
  180. return ("EXCEPTION", None)
  181. def remotecall(self, oid, methodname, args, kwargs):
  182. self.debug("remotecall:asynccall: ", oid, methodname)
  183. seq = self.asynccall(oid, methodname, args, kwargs)
  184. return self.asyncreturn(seq)
  185. def remotequeue(self, oid, methodname, args, kwargs):
  186. self.debug("remotequeue:asyncqueue: ", oid, methodname)
  187. seq = self.asyncqueue(oid, methodname, args, kwargs)
  188. return self.asyncreturn(seq)
  189. def asynccall(self, oid, methodname, args, kwargs):
  190. request = ("CALL", (oid, methodname, args, kwargs))
  191. seq = self.newseq()
  192. if threading.current_thread() != self.sockthread:
  193. cvar = threading.Condition()
  194. self.cvars[seq] = cvar
  195. self.debug(("asynccall:%d:" % seq), oid, methodname, args, kwargs)
  196. self.putmessage((seq, request))
  197. return seq
  198. def asyncqueue(self, oid, methodname, args, kwargs):
  199. request = ("QUEUE", (oid, methodname, args, kwargs))
  200. seq = self.newseq()
  201. if threading.current_thread() != self.sockthread:
  202. cvar = threading.Condition()
  203. self.cvars[seq] = cvar
  204. self.debug(("asyncqueue:%d:" % seq), oid, methodname, args, kwargs)
  205. self.putmessage((seq, request))
  206. return seq
  207. def asyncreturn(self, seq):
  208. self.debug("asyncreturn:%d:call getresponse(): " % seq)
  209. response = self.getresponse(seq, wait=0.05)
  210. self.debug(("asyncreturn:%d:response: " % seq), response)
  211. return self.decoderesponse(response)
  212. def decoderesponse(self, response):
  213. how, what = response
  214. if how == "OK":
  215. return what
  216. if how == "QUEUED":
  217. return None
  218. if how == "EXCEPTION":
  219. self.debug("decoderesponse: EXCEPTION")
  220. return None
  221. if how == "EOF":
  222. self.debug("decoderesponse: EOF")
  223. self.decode_interrupthook()
  224. return None
  225. if how == "ERROR":
  226. self.debug("decoderesponse: Internal ERROR:", what)
  227. raise RuntimeError(what)
  228. if how == "CALLEXC":
  229. self.debug("decoderesponse: Call Exception:", what)
  230. raise what
  231. raise SystemError(how, what)
  232. def decode_interrupthook(self):
  233. ""
  234. raise EOFError
  235. def mainloop(self):
  236. """Listen on socket until I/O not ready or EOF
  237. pollresponse() will loop looking for seq number None, which
  238. never comes, and exit on EOFError.
  239. """
  240. try:
  241. self.getresponse(myseq=None, wait=0.05)
  242. except EOFError:
  243. self.debug("mainloop:return")
  244. return
  245. def getresponse(self, myseq, wait):
  246. response = self._getresponse(myseq, wait)
  247. if response is not None:
  248. how, what = response
  249. if how == "OK":
  250. response = how, self._proxify(what)
  251. return response
  252. def _proxify(self, obj):
  253. if isinstance(obj, RemoteProxy):
  254. return RPCProxy(self, obj.oid)
  255. if isinstance(obj, list):
  256. return list(map(self._proxify, obj))
  257. # XXX Check for other types -- not currently needed
  258. return obj
  259. def _getresponse(self, myseq, wait):
  260. self.debug("_getresponse:myseq:", myseq)
  261. if threading.current_thread() is self.sockthread:
  262. # this thread does all reading of requests or responses
  263. while True:
  264. response = self.pollresponse(myseq, wait)
  265. if response is not None:
  266. return response
  267. else:
  268. # wait for notification from socket handling thread
  269. cvar = self.cvars[myseq]
  270. cvar.acquire()
  271. while myseq not in self.responses:
  272. cvar.wait()
  273. response = self.responses[myseq]
  274. self.debug("_getresponse:%s: thread woke up: response: %s" %
  275. (myseq, response))
  276. del self.responses[myseq]
  277. del self.cvars[myseq]
  278. cvar.release()
  279. return response
  280. def newseq(self):
  281. self.nextseq = seq = self.nextseq + 2
  282. return seq
  283. def putmessage(self, message):
  284. self.debug("putmessage:%d:" % message[0])
  285. try:
  286. s = dumps(message)
  287. except pickle.PicklingError:
  288. print("Cannot pickle:", repr(message), file=sys.__stderr__)
  289. raise
  290. s = struct.pack("<i", len(s)) + s
  291. while len(s) > 0:
  292. try:
  293. r, w, x = select.select([], [self.sock], [])
  294. n = self.sock.send(s[:BUFSIZE])
  295. except (AttributeError, TypeError):
  296. raise OSError("socket no longer exists")
  297. s = s[n:]
  298. buff = b''
  299. bufneed = 4
  300. bufstate = 0 # meaning: 0 => reading count; 1 => reading data
  301. def pollpacket(self, wait):
  302. self._stage0()
  303. if len(self.buff) < self.bufneed:
  304. r, w, x = select.select([self.sock.fileno()], [], [], wait)
  305. if len(r) == 0:
  306. return None
  307. try:
  308. s = self.sock.recv(BUFSIZE)
  309. except OSError:
  310. raise EOFError
  311. if len(s) == 0:
  312. raise EOFError
  313. self.buff += s
  314. self._stage0()
  315. return self._stage1()
  316. def _stage0(self):
  317. if self.bufstate == 0 and len(self.buff) >= 4:
  318. s = self.buff[:4]
  319. self.buff = self.buff[4:]
  320. self.bufneed = struct.unpack("<i", s)[0]
  321. self.bufstate = 1
  322. def _stage1(self):
  323. if self.bufstate == 1 and len(self.buff) >= self.bufneed:
  324. packet = self.buff[:self.bufneed]
  325. self.buff = self.buff[self.bufneed:]
  326. self.bufneed = 4
  327. self.bufstate = 0
  328. return packet
  329. def pollmessage(self, wait):
  330. packet = self.pollpacket(wait)
  331. if packet is None:
  332. return None
  333. try:
  334. message = pickle.loads(packet)
  335. except pickle.UnpicklingError:
  336. print("-----------------------", file=sys.__stderr__)
  337. print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
  338. traceback.print_stack(file=sys.__stderr__)
  339. print("-----------------------", file=sys.__stderr__)
  340. raise
  341. return message
  342. def pollresponse(self, myseq, wait):
  343. """Handle messages received on the socket.
  344. Some messages received may be asynchronous 'call' or 'queue' requests,
  345. and some may be responses for other threads.
  346. 'call' requests are passed to self.localcall() with the expectation of
  347. immediate execution, during which time the socket is not serviced.
  348. 'queue' requests are used for tasks (which may block or hang) to be
  349. processed in a different thread. These requests are fed into
  350. request_queue by self.localcall(). Responses to queued requests are
  351. taken from response_queue and sent across the link with the associated
  352. sequence numbers. Messages in the queues are (sequence_number,
  353. request/response) tuples and code using this module removing messages
  354. from the request_queue is responsible for returning the correct
  355. sequence number in the response_queue.
  356. pollresponse() will loop until a response message with the myseq
  357. sequence number is received, and will save other responses in
  358. self.responses and notify the owning thread.
  359. """
  360. while True:
  361. # send queued response if there is one available
  362. try:
  363. qmsg = response_queue.get(0)
  364. except queue.Empty:
  365. pass
  366. else:
  367. seq, response = qmsg
  368. message = (seq, ('OK', response))
  369. self.putmessage(message)
  370. # poll for message on link
  371. try:
  372. message = self.pollmessage(wait)
  373. if message is None: # socket not ready
  374. return None
  375. except EOFError:
  376. self.handle_EOF()
  377. return None
  378. except AttributeError:
  379. return None
  380. seq, resq = message
  381. how = resq[0]
  382. self.debug("pollresponse:%d:myseq:%s" % (seq, myseq))
  383. # process or queue a request
  384. if how in ("CALL", "QUEUE"):
  385. self.debug("pollresponse:%d:localcall:call:" % seq)
  386. response = self.localcall(seq, resq)
  387. self.debug("pollresponse:%d:localcall:response:%s"
  388. % (seq, response))
  389. if how == "CALL":
  390. self.putmessage((seq, response))
  391. elif how == "QUEUE":
  392. # don't acknowledge the 'queue' request!
  393. pass
  394. continue
  395. # return if completed message transaction
  396. elif seq == myseq:
  397. return resq
  398. # must be a response for a different thread:
  399. else:
  400. cv = self.cvars.get(seq, None)
  401. # response involving unknown sequence number is discarded,
  402. # probably intended for prior incarnation of server
  403. if cv is not None:
  404. cv.acquire()
  405. self.responses[seq] = resq
  406. cv.notify()
  407. cv.release()
  408. continue
  409. def handle_EOF(self):
  410. "action taken upon link being closed by peer"
  411. self.EOFhook()
  412. self.debug("handle_EOF")
  413. for key in self.cvars:
  414. cv = self.cvars[key]
  415. cv.acquire()
  416. self.responses[key] = ('EOF', None)
  417. cv.notify()
  418. cv.release()
  419. # call our (possibly overridden) exit function
  420. self.exithook()
  421. def EOFhook(self):
  422. "Classes using rpc client/server can override to augment EOF action"
  423. pass
  424. #----------------- end class SocketIO --------------------
  425. class RemoteObject:
  426. # Token mix-in class
  427. pass
  428. def remoteref(obj):
  429. oid = id(obj)
  430. objecttable[oid] = obj
  431. return RemoteProxy(oid)
  432. class RemoteProxy:
  433. def __init__(self, oid):
  434. self.oid = oid
  435. class RPCHandler(socketserver.BaseRequestHandler, SocketIO):
  436. debugging = False
  437. location = "#S" # Server
  438. def __init__(self, sock, addr, svr):
  439. svr.current_handler = self ## cgt xxx
  440. SocketIO.__init__(self, sock)
  441. socketserver.BaseRequestHandler.__init__(self, sock, addr, svr)
  442. def handle(self):
  443. "handle() method required by socketserver"
  444. self.mainloop()
  445. def get_remote_proxy(self, oid):
  446. return RPCProxy(self, oid)
  447. class RPCClient(SocketIO):
  448. debugging = False
  449. location = "#C" # Client
  450. nextseq = 1 # Requests coming from the client are odd numbered
  451. def __init__(self, address, family=socket.AF_INET, type=socket.SOCK_STREAM):
  452. self.listening_sock = socket.socket(family, type)
  453. self.listening_sock.bind(address)
  454. self.listening_sock.listen(1)
  455. def accept(self):
  456. working_sock, address = self.listening_sock.accept()
  457. if self.debugging:
  458. print("****** Connection request from ", address, file=sys.__stderr__)
  459. if address[0] == LOCALHOST:
  460. SocketIO.__init__(self, working_sock)
  461. else:
  462. print("** Invalid host: ", address, file=sys.__stderr__)
  463. raise OSError
  464. def get_remote_proxy(self, oid):
  465. return RPCProxy(self, oid)
  466. class RPCProxy:
  467. __methods = None
  468. __attributes = None
  469. def __init__(self, sockio, oid):
  470. self.sockio = sockio
  471. self.oid = oid
  472. def __getattr__(self, name):
  473. if self.__methods is None:
  474. self.__getmethods()
  475. if self.__methods.get(name):
  476. return MethodProxy(self.sockio, self.oid, name)
  477. if self.__attributes is None:
  478. self.__getattributes()
  479. if name in self.__attributes:
  480. value = self.sockio.remotecall(self.oid, '__getattribute__',
  481. (name,), {})
  482. return value
  483. else:
  484. raise AttributeError(name)
  485. def __getattributes(self):
  486. self.__attributes = self.sockio.remotecall(self.oid,
  487. "__attributes__", (), {})
  488. def __getmethods(self):
  489. self.__methods = self.sockio.remotecall(self.oid,
  490. "__methods__", (), {})
  491. def _getmethods(obj, methods):
  492. # Helper to get a list of methods from an object
  493. # Adds names to dictionary argument 'methods'
  494. for name in dir(obj):
  495. attr = getattr(obj, name)
  496. if callable(attr):
  497. methods[name] = 1
  498. if isinstance(obj, type):
  499. for super in obj.__bases__:
  500. _getmethods(super, methods)
  501. def _getattributes(obj, attributes):
  502. for name in dir(obj):
  503. attr = getattr(obj, name)
  504. if not callable(attr):
  505. attributes[name] = 1
  506. class MethodProxy:
  507. def __init__(self, sockio, oid, name):
  508. self.sockio = sockio
  509. self.oid = oid
  510. self.name = name
  511. def __call__(self, /, *args, **kwargs):
  512. value = self.sockio.remotecall(self.oid, self.name, args, kwargs)
  513. return value
  514. # XXX KBK 09Sep03 We need a proper unit test for this module. Previously
  515. # existing test code was removed at Rev 1.27 (r34098).
  516. def displayhook(value):
  517. """Override standard display hook to use non-locale encoding"""
  518. if value is None:
  519. return
  520. # Set '_' to None to avoid recursion
  521. builtins._ = None
  522. text = repr(value)
  523. try:
  524. sys.stdout.write(text)
  525. except UnicodeEncodeError:
  526. # let's use ascii while utf8-bmp codec doesn't present
  527. encoding = 'ascii'
  528. bytes = text.encode(encoding, 'backslashreplace')
  529. text = bytes.decode(encoding, 'strict')
  530. sys.stdout.write(text)
  531. sys.stdout.write("\n")
  532. builtins._ = value
  533. if __name__ == '__main__':
  534. from unittest import main
  535. main('idlelib.idle_test.test_rpc', verbosity=2,)