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