Debian Codegraph @

Pyro5/client.py

raw
1 """
2 Client related classes (Proxy, mostly)
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5 """
6
7 import sys
8 import time
9 import logging
10 import serpent
11 import contextlib
12 from . import config, core, serializers, protocol, errors, socketutil
13 from .callcontext import current_context
14 try:
15 from greenlet import getcurrent as get_ident
16 except ImportError:
17 from threading import get_ident
18
19
20 log = logging.getLogger("Pyro5.client")
21
22 __all__ = ["Proxy", "BatchProxy", "SerializedBlob"]
23
24
25 class Proxy(object):
26 """
27 Pyro proxy for a remote object. Intercepts method calls and dispatches them to the remote object.
28
29 .. automethod:: _pyroBind
30 .. automethod:: _pyroRelease
31 .. automethod:: _pyroReconnect
32 .. automethod:: _pyroValidateHandshake
33 .. autoattribute:: _pyroTimeout
34 .. attribute:: _pyroMaxRetries
35
36 Number of retries to perform on communication calls by this proxy, allows you to override the default setting.
37
38 .. attribute:: _pyroSerializer
39
40 Name of the serializer to use by this proxy, allows you to override the default setting.
41
42 .. attribute:: _pyroHandshake
43
44 The data object that should be sent in the initial connection handshake message. Can be any serializable object.
45
46 .. attribute:: _pyroLocalSocket
47
48 The socket that is used locally to connect to the remote daemon.
49 The format depends on the address family used for the connection, but usually
50 for IPV4 connections it is the familiar (hostname, port) tuple.
51 Consult the Python documentation on `socket families <https://docs.python.org/3/library/socket.html#socket-families>`_
52 for more details
53 """
54 __pyroAttributes = frozenset(
55 ["__getnewargs__", "__getnewargs_ex__", "__getinitargs__", "_pyroConnection", "_pyroUri",
56 "_pyroOneway", "_pyroMethods", "_pyroAttrs", "_pyroTimeout", "_pyroSeq", "_pyroLocalSocket",
57 "_pyroRawWireResponse", "_pyroHandshake", "_pyroMaxRetries", "_pyroSerializer",
58 "_Proxy__pyroTimeout", "_Proxy__pyroOwnerThread"])
59
60 def __init__(self, uri, connected_socket=None):
61 if connected_socket:
62 uri = core.URI("PYRO:" + uri + "@<<connected-socket>>:0")
63 if isinstance(uri, str):
64 uri = core.URI(uri)
65 elif not isinstance(uri, core.URI):
66 raise TypeError("expected Pyro URI")
67 self._pyroUri = uri
68 self._pyroConnection = None
69 self._pyroSerializer = None # can be set to the name of a serializer to override the global one per-proxy
70 self._pyroMethods = set() # all methods of the remote object, gotten from meta-data
71 self._pyroAttrs = set() # attributes of the remote object, gotten from meta-data
72 self._pyroOneway = set() # oneway-methods of the remote object, gotten from meta-data
73 self._pyroSeq = 0 # message sequence number
74 self._pyroRawWireResponse = False # internal switch to enable wire level responses
75 self._pyroHandshake = "hello" # the data object that should be sent in the initial connection handshake message
76 self._pyroMaxRetries = config.MAX_RETRIES
77 self.__pyroTimeout = config.COMMTIMEOUT
78 self.__pyroOwnerThread = get_ident() # the thread that owns this proxy
79 if config.SERIALIZER not in serializers.serializers:
80 raise ValueError("unknown serializer configured")
81 # note: we're not clearing the client annotations dict here.
82 # that is because otherwise it will be wiped if a new proxy is needed to connect PYRONAME uris.
83 # clearing the response annotations is okay.
84 current_context.response_annotations = {}
85 if connected_socket:
86 self.__pyroCreateConnection(False, connected_socket)
87
88 def __del__(self):
89 if hasattr(self, "_pyroConnection"):
90 try:
91 self._pyroRelease()
92 except Exception:
93 pass
94
95 def __getattr__(self, name):
96 if name in Proxy.__pyroAttributes:
97 # allows it to be safely pickled
98 raise AttributeError(name)
99 # get metadata if it's not there yet
100 if not self._pyroMethods and not self._pyroAttrs:
101 self._pyroGetMetadata()
102 if name in self._pyroAttrs:
103 return self._pyroInvoke("__getattr__", (name,), None)
104 if name not in self._pyroMethods:
105 # client side check if the requested attr actually exists
106 raise AttributeError("remote object '%s' has no exposed attribute or method '%s'" % (self._pyroUri, name))
107 return _RemoteMethod(self._pyroInvoke, name, self._pyroMaxRetries)
108
109 def __setattr__(self, name, value):
110 if name in Proxy.__pyroAttributes:
111 return super(Proxy, self).__setattr__(name, value) # one of the special pyro attributes
112 # get metadata if it's not there yet
113 if not self._pyroMethods and not self._pyroAttrs:
114 self._pyroGetMetadata()
115 if name in self._pyroAttrs:
116 return self._pyroInvoke("__setattr__", (name, value), None) # remote attribute
117 # client side validation if the requested attr actually exists
118 raise AttributeError("remote object '%s' has no exposed attribute '%s'" % (self._pyroUri, name))
119
120 def __repr__(self):
121 if self._pyroConnection:
122 connected = "connected " + self._pyroConnection.family()
123 else:
124 connected = "not connected"
125 return "<%s.%s at 0x%x; %s; for %s; owner %s>" % (self.__class__.__module__, self.__class__.__name__,
126 id(self), connected, self._pyroUri, self.__pyroOwnerThread)
127
128 def __getstate__(self):
129 # make sure a tuple of just primitive types are used to allow for proper serialization
130 return str(self._pyroUri), tuple(self._pyroOneway), tuple(self._pyroMethods), \
131 tuple(self._pyroAttrs), self._pyroHandshake, self._pyroSerializer
132
133 def __setstate__(self, state):
134 self._pyroUri = core.URI(state[0])
135 self._pyroOneway = set(state[1])
136 self._pyroMethods = set(state[2])
137 self._pyroAttrs = set(state[3])
138 self._pyroHandshake = state[4]
139 self._pyroSerializer = state[5]
140 self.__pyroTimeout = config.COMMTIMEOUT
141 self._pyroMaxRetries = config.MAX_RETRIES
142 self._pyroConnection = None
143 self._pyroLocalSocket = None
144 self._pyroSeq = 0
145 self._pyroRawWireResponse = False
146 self.__pyroOwnerThread = get_ident()
147
148 def __copy__(self):
149 p = object.__new__(type(self))
150 p.__setstate__(self.__getstate__())
151 p._pyroTimeout = self._pyroTimeout
152 p._pyroRawWireResponse = self._pyroRawWireResponse
153 p._pyroMaxRetries = self._pyroMaxRetries
154 return p
155
156 def __enter__(self):
157 return self
158
159 def __exit__(self, exc_type, exc_value, traceback):
160 self._pyroRelease()
161
162 def __eq__(self, other):
163 if other is self:
164 return True
165 return isinstance(other, Proxy) and other._pyroUri == self._pyroUri
166
167 def __ne__(self, other):
168 if other and isinstance(other, Proxy):
169 return other._pyroUri != self._pyroUri
170 return True
171
172 def __hash__(self):
173 return hash(self._pyroUri)
174
175 def __dir__(self):
176 result = dir(self.__class__) + list(self.__dict__.keys())
177 return sorted(set(result) | self._pyroMethods | self._pyroAttrs)
178
179 # When special methods are invoked via special syntax (e.g. obj[index] calls
180 # obj.__getitem__(index)), the special methods are not looked up via __getattr__
181 # for efficiency reasons; instead, their presence is checked directly.
182 # Thus we need to define them here to force (remote) lookup through __getitem__.
183 def __bool__(self): return True
184 def __len__(self): return self.__getattr__('__len__')()
185 def __getitem__(self, index): return self.__getattr__('__getitem__')(index)
186 def __setitem__(self, index, val): return self.__getattr__('__setitem__')(index, val)
187 def __delitem__(self, index): return self.__getattr__('__delitem__')(index)
188
189 def __iter__(self):
190 try:
191 # use remote iterator if it exists
192 yield from self.__getattr__('__iter__')()
193 except AttributeError:
194 # fallback to indexed based iteration
195 try:
196 yield from (self[index] for index in range(sys.maxsize))
197 except (StopIteration, IndexError):
198 return
199
200 def _pyroRelease(self):
201 """release the connection to the pyro daemon"""
202 self.__check_owner()
203 if self._pyroConnection is not None:
204 self._pyroConnection.close()
205 self._pyroConnection = None
206 self._pyroLocalSocket = None
207
208 def _pyroBind(self):
209 """
210 Bind this proxy to the exact object from the uri. That means that the proxy's uri
211 will be updated with a direct PYRO uri, if it isn't one yet.
212 If the proxy is already bound, it will not bind again.
213 """
214 return self.__pyroCreateConnection(True)
215
216 def __pyroGetTimeout(self):
217 return self.__pyroTimeout
218
219 def __pyroSetTimeout(self, timeout):
220 self.__pyroTimeout = timeout
221 if self._pyroConnection is not None:
222 self._pyroConnection.timeout = timeout
223
224 _pyroTimeout = property(__pyroGetTimeout, __pyroSetTimeout, doc="""
225 The timeout in seconds for calls on this proxy. Defaults to ``None``.
226 If the timeout expires before the remote method call returns,
227 Pyro will raise a :exc:`Pyro5.errors.TimeoutError`""")
228
229 def _pyroInvoke(self, methodname, vargs, kwargs, flags=0, objectId=None):
230 """perform the remote method call communication"""
231 self.__check_owner()
232 current_context.response_annotations = {}
233 if self._pyroConnection is None:
234 self.__pyroCreateConnection()
235 serializer = serializers.serializers[self._pyroSerializer or config.SERIALIZER]
236 objectId = objectId or self._pyroConnection.objectId
237 annotations = current_context.annotations
238 if vargs and isinstance(vargs[0], SerializedBlob):
239 # special serialization of a 'blob' that stays serialized
240 data, flags = self.__serializeBlobArgs(vargs, kwargs, annotations, flags, objectId, methodname, serializer)
241 else:
242 # normal serialization of the remote call
243 data = serializer.dumpsCall(objectId, methodname, vargs, kwargs)
244 if methodname in self._pyroOneway:
245 flags |= protocol.FLAGS_ONEWAY
246 self._pyroSeq = (self._pyroSeq + 1) & 0xffff
247 msg = protocol.SendingMessage(protocol.MSG_INVOKE, flags, self._pyroSeq, serializer.serializer_id, data, annotations=annotations)
248 if config.LOGWIRE:
249 protocol.log_wiredata(log, "proxy wiredata sending", msg)
250 try:
251 self._pyroConnection.send(msg.data)
252 del msg # invite GC to collect the object, don't wait for out-of-scope
253 if flags & protocol.FLAGS_ONEWAY:
254 return None # oneway call, no response data
255 else:
256 msg = protocol.recv_stub(self._pyroConnection, [protocol.MSG_RESULT])
257 if config.LOGWIRE:
258 protocol.log_wiredata(log, "proxy wiredata received", msg)
259 self.__pyroCheckSequence(msg.seq)
260 if msg.serializer_id != serializer.serializer_id:
261 error = "invalid serializer in response: %d" % msg.serializer_id
262 log.error(error)
263 raise errors.SerializeError(error)
264 if msg.annotations:
265 current_context.response_annotations = msg.annotations
266 if self._pyroRawWireResponse:
267 return msg
268 data = serializer.loads(msg.data)
269 if msg.flags & protocol.FLAGS_ITEMSTREAMRESULT:
270 streamId = bytes(msg.annotations.get("STRM", b"")).decode()
271 if not streamId:
272 raise errors.ProtocolError("result of call is an iterator, but the server is not configured to allow streaming")
273 return _StreamResultIterator(streamId, self)
274 if msg.flags & protocol.FLAGS_EXCEPTION:
275 raise data # if you see this in your traceback, you should probably inspect the remote traceback as well
276 else:
277 return data
278 except (errors.CommunicationError, KeyboardInterrupt):
279 # Communication error during read. To avoid corrupt transfers, we close the connection.
280 # Otherwise we might receive the previous reply as a result of a new method call!
281 # Special case for keyboardinterrupt: people pressing ^C to abort the client
282 # may be catching the keyboardinterrupt in their code. We should probably be on the
283 # safe side and release the proxy connection in this case too, because they might
284 # be reusing the proxy object after catching the exception...
285 self._pyroRelease()
286 raise
287
288 def __pyroCheckSequence(self, seq):
289 if seq != self._pyroSeq:
290 err = "invoke: reply sequence out of sync, got %d expected %d" % (seq, self._pyroSeq)
291 log.error(err)
292 raise errors.ProtocolError(err)
293
294 def __pyroCreateConnection(self, replaceUri=False, connected_socket=None):
295 """
296 Connects this proxy to the remote Pyro daemon. Does connection handshake.
297 Returns true if a new connection was made, false if an existing one was already present.
298 """
299 def connect_and_handshake(conn):
300 try:
301 if self._pyroConnection is not None:
302 return False # already connected
303 if config.SSL:
304 sslContext = socketutil.get_ssl_context(clientcert=config.SSL_CLIENTCERT,
305 clientkey=config.SSL_CLIENTKEY,
306 keypassword=config.SSL_CLIENTKEYPASSWD,
307 cacerts=config.SSL_CACERTS)
308 else:
309 sslContext = None
310 sock = socketutil.create_socket(connect=connect_location,
311 reuseaddr=config.SOCK_REUSE,
312 timeout=self.__pyroTimeout,
313 nodelay=config.SOCK_NODELAY,
314 sslContext=sslContext)
315 conn = socketutil.SocketConnection(sock, uri.object)
316 # Do handshake.
317 serializer = serializers.serializers[self._pyroSerializer or config.SERIALIZER]
318 data = {"handshake": self._pyroHandshake, "object": uri.object}
319 data = serializer.dumps(data)
320 msg = protocol.SendingMessage(protocol.MSG_CONNECT, 0, self._pyroSeq, serializer.serializer_id,
321 data, annotations=current_context.annotations)
322 if config.LOGWIRE:
323 protocol.log_wiredata(log, "proxy connect sending", msg)
324 conn.send(msg.data)
325 msg = protocol.recv_stub(conn, [protocol.MSG_CONNECTOK, protocol.MSG_CONNECTFAIL])
326 if config.LOGWIRE:
327 protocol.log_wiredata(log, "proxy connect response received", msg)
328 except Exception as x:
329 if conn:
330 conn.close()
331 err = "cannot connect to %s: %s" % (connect_location, x)
332 log.error(err)
333 if isinstance(x, errors.CommunicationError):
334 raise
335 else:
336 raise errors.CommunicationError(err) from x
337 else:
338 handshake_response = "?"
339 if msg.data:
340 serializer = serializers.serializers_by_id[msg.serializer_id]
341 handshake_response = serializer.loads(msg.data)
342 if msg.type == protocol.MSG_CONNECTFAIL:
343 error = "connection to %s rejected: %s" % (connect_location, handshake_response)
344 conn.close()
345 log.error(error)
346 raise errors.CommunicationError(error)
347 elif msg.type == protocol.MSG_CONNECTOK:
348 self.__processMetadata(handshake_response["meta"])
349 handshake_response = handshake_response["handshake"]
350 self._pyroConnection = conn
351 self._pyroLocalSocket = conn.sock.getsockname()
352 if replaceUri:
353 self._pyroUri = uri
354 self._pyroValidateHandshake(handshake_response)
355 log.debug("connected to %s - %s - %s", self._pyroUri, conn.family(), "SSL" if sslContext else "unencrypted")
356 if msg.annotations:
357 current_context.response_annotations = msg.annotations
358 else:
359 conn.close()
360 err = "cannot connect to %s: invalid msg type %d received" % (connect_location, msg.type)
361 log.error(err)
362 raise errors.ProtocolError(err)
363
364 self.__check_owner()
365 if self._pyroConnection is not None:
366 return False # already connected
367 uri = core.resolve(self._pyroUri)
368 # socket connection (normal or Unix domain socket)
369 conn = None
370 log.debug("connecting to %s", uri)
371 connect_location = uri.sockname or (uri.host, uri.port)
372 if connected_socket:
373 self._pyroConnection = socketutil.SocketConnection(connected_socket, uri.object, True)
374 self._pyroLocalSocket = connected_socket.getsockname()
375 else:
376 connect_and_handshake(conn)
377 # obtain metadata if this feature is enabled, and the metadata is not known yet
378 if not self._pyroMethods and not self._pyroAttrs:
379 self._pyroGetMetadata(uri.object)
380 return True
381
382 def _pyroGetMetadata(self, objectId=None, known_metadata=None):
383 """
384 Get metadata from server (methods, attrs, oneway, ...) and remember them in some attributes of the proxy.
385 Usually this will already be known due to the default behavior of the connect handshake, where the
386 connect response also includes the metadata.
387 """
388 objectId = objectId or self._pyroUri.object
389 log.debug("getting metadata for object %s", objectId)
390 if self._pyroConnection is None and not known_metadata:
391 try:
392 self.__pyroCreateConnection()
393 except errors.PyroError:
394 log.error("problem getting metadata: cannot connect")
395 raise
396 if self._pyroMethods or self._pyroAttrs:
397 return # metadata has already been retrieved as part of creating the connection
398 try:
399 # invoke the get_metadata method on the daemon
400 result = known_metadata or self._pyroInvoke("get_metadata", [objectId], {}, objectId=core.DAEMON_NAME)
401 self.__processMetadata(result)
402 except errors.PyroError:
403 log.exception("problem getting metadata")
404 raise
405
406 def __processMetadata(self, metadata):
407 if not metadata:
408 return
409 self._pyroOneway = set(metadata["oneway"])
410 self._pyroMethods = set(metadata["methods"])
411 self._pyroAttrs = set(metadata["attrs"])
412 if log.isEnabledFor(logging.DEBUG):
413 log.debug("from meta: methods=%s, oneway methods=%s, attributes=%s",
414 sorted(self._pyroMethods), sorted(self._pyroOneway), sorted(self._pyroAttrs))
415 if not self._pyroMethods and not self._pyroAttrs:
416 raise errors.PyroError("remote object '%s' doesn't expose any methods or attributes. Did you forget setting @expose on them?" % self._pyroUri)
417
418 def _pyroReconnect(self, tries=100000000):
419 """
420 (Re)connect the proxy to the daemon containing the pyro object which the proxy is for.
421 In contrast to the _pyroBind method, this one first releases the connection (if the proxy is still connected)
422 and retries making a new connection until it succeeds or the given amount of tries ran out.
423 """
424 self._pyroRelease()
425 while tries:
426 try:
427 self.__pyroCreateConnection()
428 return
429 except errors.CommunicationError:
430 tries -= 1
431 if tries:
432 time.sleep(2)
433 msg = "failed to reconnect"
434 log.error(msg)
435 raise errors.ConnectionClosedError(msg)
436
437 def _pyroInvokeBatch(self, calls, oneway=False):
438 flags = protocol.FLAGS_BATCH
439 if oneway:
440 flags |= protocol.FLAGS_ONEWAY
441 return self._pyroInvoke("<batch>", calls, None, flags)
442
443 def _pyroValidateHandshake(self, response):
444 """
445 Process and validate the initial connection handshake response data received from the daemon.
446 Simply return without error if everything is ok.
447 Raise an exception if something is wrong and the connection should not be made.
448 """
449 return
450
451 def _pyroClaimOwnership(self):
452 """
453 The current thread claims the ownership of this proxy from another thread.
454 Any existing connection will remain active!
455 """
456 if get_ident() != self.__pyroOwnerThread:
457 # if self._pyroConnection is not None:
458 # self._pyroConnection.close()
459 # self._pyroConnection = None
460 self.__pyroOwnerThread = get_ident()
461
462 def __serializeBlobArgs(self, vargs, kwargs, annotations, flags, objectId, methodname, serializer):
463 """
464 Special handling of a "blob" argument that has to stay serialized until explicitly deserialized in client code.
465 This makes efficient, transparent gateways or dispatchers and such possible:
466 they don't have to de/reserialize the message and are independent from the serialized class definitions.
467 Annotations are passed in because some blob metadata is added. They're not part of the blob itself.
468 """
469 if len(vargs) > 1 or kwargs:
470 raise errors.SerializeError("if SerializedBlob is used, it must be the only argument")
471 blob = vargs[0]
472 flags |= protocol.FLAGS_KEEPSERIALIZED
473 # Pass the objectId and methodname separately in an annotation because currently,
474 # they are embedded inside the serialized message data. And we're not deserializing that,
475 # so we have to have another means of knowing the object and method it is meant for...
476 # A better solution is perhaps to split the actual remote method arguments from the
477 # control data (object + methodname) but that requires a major protocol change.
478 # The code below is not as nice but it works without any protocol change and doesn't
479 # require a hack either - so it's actually not bad like this.
480 import marshal
481 annotations["BLBI"] = marshal.dumps((blob.info, objectId, methodname))
482 if blob._contains_blob:
483 # directly pass through the already serialized msg data from within the blob
484 protocol_msg = blob._data
485 return protocol_msg.data, flags
486 else:
487 # replaces SerializedBlob argument with the data to be serialized
488 return serializer.dumpsCall(objectId, methodname, blob._data, kwargs), flags
489
490 def __check_owner(self):
491 if get_ident() != self.__pyroOwnerThread:
492 raise errors.PyroError("the calling thread is not the owner of this proxy, "
493 "create a new proxy in this thread or transfer ownership.")
494
495
496 class _RemoteMethod(object):
497 """method call abstraction"""
498
499 def __init__(self, send, name, max_retries):
500 self.__send = send
501 self.__name = name
502 self.__max_retries = max_retries
503
504 def __getattr__(self, name):
505 return _RemoteMethod(self.__send, "%s.%s" % (self.__name, name), self.__max_retries)
506
507 def __call__(self, *args, **kwargs):
508 for attempt in range(self.__max_retries + 1):
509 try:
510 return self.__send(self.__name, args, kwargs)
511 except (errors.ConnectionClosedError, errors.TimeoutError):
512 # only retry for recoverable network errors
513 if attempt >= self.__max_retries:
514 # last attempt, raise the exception
515 raise
516
517
518 class _StreamResultIterator(object):
519 """
520 Pyro returns this as a result of a remote call which returns an iterator or generator.
521 It is a normal iterable and produces elements on demand from the remote iterator.
522 You can simply use it in for loops, list comprehensions etc.
523 """
524 def __init__(self, streamId, proxy):
525 self.streamId = streamId
526 self.proxy = proxy
527 self.pyroseq = proxy._pyroSeq
528
529 def __iter__(self):
530 return self
531
532 def __next__(self):
533 if self.proxy is None:
534 raise StopIteration
535 if self.proxy._pyroConnection is None:
536 raise errors.ConnectionClosedError("the proxy for this stream result has been closed")
537 self.pyroseq += 1
538 try:
539 return self.proxy._pyroInvoke("get_next_stream_item", [self.streamId], {}, objectId=core.DAEMON_NAME)
540 except (StopIteration, GeneratorExit):
541 # when the iterator is exhausted, the proxy is removed to avoid unneeded close_stream calls later
542 # (the server has closed its part of the stream by itself already)
543 self.proxy = None
544 raise
545
546 def __del__(self):
547 try:
548 self.close()
549 except Exception:
550 pass
551
552 def close(self):
553 if self.proxy and self.proxy._pyroConnection is not None:
554 if self.pyroseq == self.proxy._pyroSeq:
555 # we're still in sync, it's okay to use the same proxy to close this stream
556 self.proxy._pyroInvoke("close_stream", [self.streamId], {},
557 flags=protocol.FLAGS_ONEWAY, objectId=core.DAEMON_NAME)
558 else:
559 # The proxy's sequence number has diverged.
560 # One of the reasons this can happen is because this call is being done from python's GC where
561 # it decides to gc old iterator objects *during a new call on the proxy*.
562 # If we use the same proxy and do a call in between, the other call on the proxy will get an out of sync seq and crash!
563 # We create a temporary second proxy to call close_stream on. This is inefficient, but avoids the problem.
564 with contextlib.suppress(errors.CommunicationError):
565 with self.proxy.__copy__() as closingProxy:
566 closingProxy._pyroInvoke("close_stream", [self.streamId], {},
567 flags=protocol.FLAGS_ONEWAY, objectId=core.DAEMON_NAME)
568 self.proxy = None
569
570
571 class _BatchedRemoteMethod(object):
572 """method call abstraction that is used with batched calls"""
573
574 def __init__(self, calls, name):
575 self.__calls = calls
576 self.__name = name
577
578 def __getattr__(self, name):
579 return _BatchedRemoteMethod(self.__calls, "%s.%s" % (self.__name, name))
580
581 def __call__(self, *args, **kwargs):
582 self.__calls.append((self.__name, args, kwargs))
583
584
585 class BatchProxy(object):
586 """Proxy that lets you batch multiple method calls into one.
587 It is constructed with a reference to the normal proxy that will
588 carry out the batched calls. Call methods on this object that you want to batch,
589 and finally call the batch proxy itself. That call will return a generator
590 for the results of every method call in the batch (in sequence)."""
591
592 def __init__(self, proxy):
593 self.__proxy = proxy
594 self.__calls = []
595
596 def __getattr__(self, name):
597 return _BatchedRemoteMethod(self.__calls, name)
598
599 def __enter__(self):
600 return self
601
602 def __exit__(self, *args):
603 pass
604
605 def __copy__(self):
606 copy = type(self)(self.__proxy)
607 copy.__calls = list(self.__calls)
608 return copy
609
610 def __resultsgenerator(self, results):
611 for result in results:
612 if isinstance(result, core._ExceptionWrapper):
613 result.raiseIt() # re-raise the remote exception locally.
614 else:
615 yield result # it is a regular result object, yield that and continue.
616
617 def __call__(self, oneway=False):
618 self.__proxy._pyroClaimOwnership()
619 results = self.__proxy._pyroInvokeBatch(self.__calls, oneway)
620 self.__calls = [] # clear for re-use
621 if not oneway:
622 return self.__resultsgenerator(results)
623
624 def _pyroInvoke(self, name, args, kwargs):
625 # ignore all parameters, we just need to execute the batch
626 results = self.__proxy._pyroInvokeBatch(self.__calls)
627 self.__calls = [] # clear for re-use
628 return self.__resultsgenerator(results)
629
630
631 class SerializedBlob(object):
632 """
633 Used to wrap some data to make Pyro pass this object transparently (it keeps the serialized payload as-is)
634 Only when you need to access the actual client data you can deserialize on demand.
635 This makes efficient, transparent gateways or dispatchers and such possible:
636 they don't have to de/reserialize the message and are independent from the serialized class definitions.
637 You have to pass this as the only parameter to a remote method call for Pyro to understand it.
638 Init arguments:
639 ``info`` = some (small) descriptive data about the blob. Can be a simple id or name or guid. Must be marshallable.
640 ``data`` = the actual client data payload that you want to transfer in the blob. Can be anything that you would
641 otherwise have used as regular remote call arguments.
642 """
643 def __init__(self, info, data, is_blob=False):
644 self.info = info
645 self._data = data
646 self._contains_blob = is_blob
647 if is_blob and not isinstance(data, (protocol.SendingMessage, protocol.ReceivingMessage)):
648 raise TypeError("data should be a protocol message object if is_blob is true")
649
650 def deserialized(self):
651 """Retrieves the client data stored in this blob. Deserializes the data automatically if required."""
652 if self._contains_blob:
653 protocol_msg = self._data
654 serializer = serializers.serializers_by_id[protocol_msg.serializer_id]
655 if isinstance(protocol_msg, protocol.ReceivingMessage):
656 _, _, data, _ = serializer.loads(protocol_msg.data)
657 else:
658 # strip off header bytes from SendingMessage
659 payload_data = memoryview(protocol_msg.data)[protocol._header_size:]
660 _, _, data, _ = serializer.loads(payload_data)
661 return data
662 else:
663 return self._data
664
665
666 # register the special serializers for the pyro objects
667 serpent.register_class(Proxy, serializers.pyro_class_serpent_serializer)
668 serializers.SerializerBase.register_class_to_dict(Proxy, serializers.serialize_pyro_object_to_dict, serpent_too=False)