Debian Codegraph @

Pyro5/server.py

raw
1 """
2 Server related classes (Daemon etc)
3
4 Pyro - Python Remote Objects. Copyright by Irmen de Jong ([email protected]).
5 """
6
7 import os
8 import sys
9 import uuid
10 import time
11 import socket
12 import collections
13 import threading
14 import logging
15 import inspect
16 import warnings
17 import weakref
18 import serpent
19 import ipaddress
20 from typing import TypeVar, Tuple, Union, Optional, Dict, Any, Sequence, Set
21 from . import config, core, errors, serializers, socketutil, protocol, client
22 from .callcontext import current_context
23 from collections.abc import Callable
24
25 __all__ = ["Daemon", "DaemonObject", "callback", "expose", "behavior", "oneway", "serve"]
26
27 log = logging.getLogger("Pyro5.server")
28
29
30 _private_dunder_methods = frozenset([
31 "__init__", "__init_subclass__", "__class__", "__module__", "__weakref__",
32 "__call__", "__new__", "__del__", "__repr__",
33 "__str__", "__format__", "__nonzero__", "__bool__", "__coerce__",
34 "__cmp__", "__eq__", "__ne__", "__hash__", "__ge__", "__gt__", "__le__", "__lt__",
35 "__dir__", "__enter__", "__exit__", "__copy__", "__deepcopy__", "__sizeof__",
36 "__getattr__", "__setattr__", "__hasattr__", "__getattribute__", "__delattr__",
37 "__instancecheck__", "__subclasscheck__", "__getinitargs__", "__getnewargs__",
38 "__getstate__", "__setstate__", "__reduce__", "__reduce_ex__", "__subclasshook__"
39 ])
40
41
42 def is_private_attribute(attr_name: str) -> bool:
43 """returns if the attribute name is to be considered private or not."""
44 if attr_name in _private_dunder_methods:
45 return True
46 if not attr_name.startswith('_'):
47 return False
48 if len(attr_name) > 4 and attr_name.startswith("__") and attr_name.endswith("__"):
49 return False
50 return True
51
52
53 # decorators
54
55 def callback(method: Callable) -> Callable:
56 """
57 decorator to mark a method to be a 'callback'. This will make Pyro
58 raise any errors also on the callback side, and not only on the side
59 that does the callback call.
60 """
61 method._pyroCallback = True # type: ignore
62 return method
63
64
65 def oneway(method: Callable) -> Callable:
66 """
67 decorator to mark a method to be oneway (client won't wait for a response)
68 """
69 method._pyroOneway = True # type: ignore
70 return method
71
72
73 _T = TypeVar("_T", bound=Union[Callable, type])
74
75
76 def expose(method_or_class: _T) -> _T:
77 """
78 Decorator to mark a method or class to be exposed for remote calls.
79 You can apply it to a method or a class as a whole.
80 If you need to change the default instance mode or instance creator, also use a @behavior decorator.
81 """
82 if inspect.isdatadescriptor(method_or_class):
83 func = method_or_class.fget or method_or_class.fset or method_or_class.fdel # type: ignore
84 if is_private_attribute(func.__name__):
85 raise AttributeError("exposing private names (starting with _) is not allowed")
86 func._pyroExposed = True
87 return method_or_class
88 attrname = getattr(method_or_class, "__name__", None)
89 if not attrname or isinstance(method_or_class, (classmethod, staticmethod)):
90 # we could be dealing with a descriptor (classmethod/staticmethod), this means the order of the decorators is wrong
91 if inspect.ismethoddescriptor(method_or_class):
92 attrname = method_or_class.__get__(None, dict).__name__ # type: ignore
93 raise AttributeError("using @expose on a classmethod/staticmethod must be done "
94 "after @classmethod/@staticmethod. Method: " + attrname)
95 else:
96 raise AttributeError("@expose cannot determine what this is: "+repr(method_or_class))
97 if is_private_attribute(attrname):
98 raise AttributeError("exposing private names (starting with _) is not allowed")
99 if inspect.isclass(method_or_class):
100 clazz = method_or_class
101 log.debug("exposing all members of %r", clazz)
102 for name in clazz.__dict__:
103 if is_private_attribute(name):
104 continue
105 thing = getattr(clazz, name)
106 if inspect.isfunction(thing) or inspect.ismethoddescriptor(thing):
107 thing._pyroExposed = True
108 elif inspect.ismethod(thing):
109 thing.__func__._pyroExposed = True
110 elif inspect.isdatadescriptor(thing):
111 if getattr(thing, "fset", None):
112 thing.fset._pyroExposed = True
113 if getattr(thing, "fget", None):
114 thing.fget._pyroExposed = True
115 if getattr(thing, "fdel", None):
116 thing.fdel._pyroExposed = True
117 clazz._pyroExposed = True # type: ignore
118 return clazz
119 method_or_class._pyroExposed = True # type: ignore
120 return method_or_class
121
122
123 def behavior(instance_mode: str = "session", instance_creator: Optional[Callable] = None) -> Callable:
124 """
125 Decorator to specify the server behavior of your Pyro class.
126 """
127 def _behavior(clazz):
128 if not inspect.isclass(clazz):
129 raise TypeError("behavior decorator can only be used on a class")
130 if instance_mode not in ("single", "session", "percall"):
131 raise ValueError("invalid instance mode: " + instance_mode)
132 if instance_creator and not callable(instance_creator):
133 raise TypeError("instance_creator must be a callable")
134 clazz._pyroInstancing = (instance_mode, instance_creator)
135 return clazz
136 if not isinstance(instance_mode, str):
137 raise SyntaxError("behavior decorator is missing argument(s)")
138 return _behavior
139
140
141 @expose
142 class DaemonObject(object):
143 """The part of the daemon that is exposed as a Pyro object."""
144
145 def __init__(self, daemon):
146 self.daemon = daemon
147
148 def registered(self):
149 """returns a list of all object names registered in this daemon"""
150 return list(self.daemon.objectsById.keys())
151
152 def ping(self):
153 """a simple do-nothing method for testing purposes"""
154 pass
155
156 def info(self):
157 """return some descriptive information about the daemon"""
158 return "%s bound on %s, NAT %s, %d objects registered. Servertype: %s" % (
159 core.DAEMON_NAME, self.daemon.locationStr, self.daemon.natLocationStr,
160 len(self.daemon.objectsById), self.daemon.transportServer)
161
162 def get_metadata(self, objectId):
163 """
164 Get metadata for the given object (exposed methods, oneways, attributes).
165 """
166 obj = _unpack_weakref(self.daemon.objectsById.get(objectId))
167 if obj is not None:
168 metadata = _get_exposed_members(obj)
169 if not metadata["methods"] and not metadata["attrs"]:
170 # Something seems wrong: nothing is remotely exposed.
171 warnings.warn("Class %s doesn't expose any methods or attributes. Did you forget setting @expose on them?" % repr(obj))
172 return metadata
173 else:
174 log.debug("unknown object requested: %s", objectId)
175 raise errors.DaemonError("unknown object")
176
177 def get_next_stream_item(self, streamId):
178 if streamId not in self.daemon.streaming_responses:
179 raise errors.PyroError("item stream terminated")
180 client, timestamp, linger_timestamp, stream = self.daemon.streaming_responses[streamId]
181 if client is None:
182 # reset client connection association (can be None if proxy disconnected)
183 self.daemon.streaming_responses[streamId] = (current_context.client, timestamp, 0, stream)
184 try:
185 return next(stream)
186 except Exception:
187 # in case of error (or StopIteration!) the stream is removed
188 del self.daemon.streaming_responses[streamId]
189 raise
190
191 def close_stream(self, streamId):
192 if streamId in self.daemon.streaming_responses:
193 del self.daemon.streaming_responses[streamId]
194
195
196 class Daemon(object):
197 """
198 Pyro daemon. Contains server side logic and dispatches incoming remote method calls
199 to the appropriate objects.
200 """
201
202 def __init__(self, host=None, port=0, unixsocket=None, nathost=None, natport=None, interface=DaemonObject, connected_socket=None):
203 if connected_socket:
204 nathost = natport = None
205 else:
206 if host is None:
207 host = config.HOST
208 elif not isinstance(host, str):
209 host = str(host) # take care of the occasion where host is an ipaddress.IpAddress
210 if nathost is None:
211 nathost = config.NATHOST
212 elif not isinstance(nathost, str):
213 nathost = str(nathost) # take care of the occasion where host is an ipaddress.IpAddress
214 if natport is None and nathost is not None:
215 natport = config.NATPORT
216 if nathost and unixsocket:
217 raise ValueError("cannot use nathost together with unixsocket")
218 if (nathost is None) ^ (natport is None):
219 raise ValueError("must provide natport with nathost")
220 self.__mustshutdown = threading.Event()
221 self.__mustshutdown.set()
222 self.__loopstopped = threading.Event()
223 self.__loopstopped.set()
224 if connected_socket:
225 from .svr_existingconn import SocketServer_ExistingConnection
226 self.transportServer = SocketServer_ExistingConnection()
227 self.transportServer.init(self, connected_socket)
228 else:
229 if config.SERVERTYPE == "thread":
230 from .svr_threads import SocketServer_Threadpool
231 self.transportServer = SocketServer_Threadpool()
232 elif config.SERVERTYPE == "multiplex":
233 from .svr_multiplex import SocketServer_Multiplex
234 self.transportServer = SocketServer_Multiplex()
235 else:
236 raise errors.PyroError("invalid server type '%s'" % config.SERVERTYPE)
237 self.transportServer.init(self, host, port, unixsocket)
238 #: The location (str of the form ``host:portnumber``) on which the Daemon is listening
239 self.locationStr = self.transportServer.locationStr
240 log.debug("daemon created on %s - %s (pid %d)", self.locationStr, socketutil.family_str(self.transportServer.sock), os.getpid())
241 natport_for_loc = natport
242 if natport == 0:
243 # expose internal port number as NAT port as well. (don't use port because it could be 0 and will be chosen by the OS)
244 natport_for_loc = int(self.locationStr.split(":")[1])
245 # The NAT-location (str of the form ``nathost:natportnumber``) on which the Daemon is exposed for use with NAT-routing
246 self.natLocationStr = "%s:%d" % (nathost, natport_for_loc) if nathost else None
247 if self.natLocationStr:
248 log.debug("NAT address is %s", self.natLocationStr)
249 pyroObject = interface(self)
250 pyroObject._pyroId = core.DAEMON_NAME
251 # Dictionary from Pyro object id to the actual Pyro object registered by this id
252 self.objectsById = {pyroObject._pyroId: pyroObject}
253 log.debug("pyro protocol version: %d" % protocol.PROTOCOL_VERSION)
254 self._pyroInstances = {} # pyro objects for instance_mode=single (singletons, just one per daemon)
255 self.streaming_responses = {} # stream_id -> (client, creation_timestamp, linger_timestamp, stream)
256 self.housekeeper_lock = threading.Lock()
257 self.create_single_instance_lock = threading.Lock()
258 self.__mustshutdown.clear()
259 self.methodcall_error_handler = _default_methodcall_error_handler
260
261 @property
262 def sock(self):
263 """the server socket used by the daemon"""
264 return self.transportServer.sock
265
266 @property
267 def sockets(self):
268 """list of all sockets used by the daemon (server socket and all active client sockets)"""
269 return self.transportServer.sockets
270
271 @property
272 def selector(self):
273 """the multiplexing selector used, if using the multiplex server type"""
274 return self.transportServer.selector
275
276 @staticmethod
277 def serveSimple(objects, host=None, port=0, daemon=None, ns=True, verbose=True) -> None:
278 """
279 Backwards compatibility method to fire up a daemon and start serving requests.
280 New code should just use the global ``serve`` function instead.
281 """
282 serve(objects, host, port, daemon, ns, verbose)
283
284 def requestLoop(self, loopCondition=lambda: True) -> None:
285 """
286 Goes in a loop to service incoming requests, until someone breaks this
287 or calls shutdown from another thread.
288 """
289 self.__mustshutdown.clear()
290 log.info("daemon %s entering requestloop", self.locationStr)
291 try:
292 self.__loopstopped.clear()
293 self.transportServer.loop(loopCondition=lambda: not self.__mustshutdown.is_set() and loopCondition())
294 finally:
295 self.__loopstopped.set()
296 log.debug("daemon exits requestloop")
297
298 def events(self, eventsockets):
299 """for use in an external event loop: handle any requests that are pending for this daemon"""
300 return self.transportServer.events(eventsockets)
301
302 def shutdown(self):
303 """Cleanly terminate a daemon that is running in the requestloop."""
304 log.debug("daemon shutting down")
305 self.streaming_responses = {}
306 time.sleep(0.02)
307 self.__mustshutdown.set()
308 if self.transportServer:
309 self.transportServer.shutdown()
310 time.sleep(0.02)
311 self.close()
312 self.__loopstopped.wait(timeout=5) # use timeout to avoid deadlock situations
313
314 @property
315 def _shutting_down(self):
316 return self.__mustshutdown.is_set()
317
318 def _handshake(self, conn, denied_reason=None):
319 """
320 Perform connection handshake with new clients.
321 Client sends a MSG_CONNECT message with a serialized data payload.
322 If all is well, return with a CONNECT_OK message.
323 The reason we're not doing this with a MSG_INVOKE method call on the daemon
324 (like when retrieving the metadata) is because we need to force the clients
325 to get past an initial connect handshake before letting them invoke any method.
326 Return True for successful handshake, False if something was wrong.
327 If a denied_reason is given, the handshake will fail with the given reason.
328 """
329 serializer_id = serializers.MarshalSerializer.serializer_id
330 msg_seq = 0
331 try:
332 msg = protocol.recv_stub(conn, [protocol.MSG_CONNECT])
333 msg_seq = msg.seq
334 if denied_reason:
335 raise Exception(denied_reason)
336 if config.LOGWIRE:
337 protocol.log_wiredata(log, "daemon handshake received", msg)
338 if msg.flags & protocol.FLAGS_CORR_ID:
339 current_context.correlation_id = uuid.UUID(bytes=msg.corr_id)
340 else:
341 current_context.correlation_id = uuid.uuid4()
342 serializer_id = msg.serializer_id
343 serializer = serializers.serializers_by_id[serializer_id]
344 data = serializer.loads(msg.data)
345 handshake_response = self.validateHandshake(conn, data["handshake"])
346 handshake_response = {
347 "handshake": handshake_response,
348 "meta": self.objectsById[core.DAEMON_NAME].get_metadata(data["object"])
349 }
350 data = serializer.dumps(handshake_response)
351 msgtype = protocol.MSG_CONNECTOK
352 except errors.ConnectionClosedError:
353 log.debug("handshake failed, connection closed early")
354 return False
355 except Exception as x:
356 log.debug("handshake failed, reason:", exc_info=True)
357 serializer = serializers.serializers_by_id[serializer_id]
358 data = serializer.dumps(str(x))
359 msgtype = protocol.MSG_CONNECTFAIL
360 # We need a minimal amount of response data or the socket will remain blocked
361 # on some systems... (messages smaller than 40 bytes)
362 msg = protocol.SendingMessage(msgtype, 0, msg_seq, serializer_id, data, annotations=self.__annotations())
363 if config.LOGWIRE:
364 protocol.log_wiredata(log, "daemon handshake response", msg)
365 conn.send(msg.data)
366 return msg.type == protocol.MSG_CONNECTOK
367
368 def validateHandshake(self, conn, data):
369 """
370 Override this to create a connection validator for new client connections.
371 It should return a response data object normally if the connection is okay,
372 or should raise an exception if the connection should be denied.
373 """
374 return "hello"
375
376 def clientDisconnect(self, conn):
377 """
378 Override this to handle a client disconnect.
379 Conn is the SocketConnection object that was disconnected.
380 """
381 pass
382
383 def handleRequest(self, conn):
384 """
385 Handle incoming Pyro request. Catches any exception that may occur and
386 wraps it in a reply to the calling side, as to not make this server side loop
387 terminate due to exceptions caused by remote invocations.
388 """
389 request_flags = 0
390 request_seq = 0
391 request_serializer_id = serializers.MarshalSerializer.serializer_id
392 wasBatched = False
393 isCallback = False
394 try:
395 msg = protocol.recv_stub(conn, [protocol.MSG_INVOKE, protocol.MSG_PING])
396 except errors.CommunicationError as x:
397 # we couldn't even get data from the client, this is an immediate error
398 # log.info("error receiving data from client %s: %s", conn.sock.getpeername(), x)
399 raise x
400 try:
401 request_flags = msg.flags
402 request_seq = msg.seq
403 request_serializer_id = msg.serializer_id
404 if msg.flags & protocol.FLAGS_CORR_ID:
405 current_context.correlation_id = uuid.UUID(bytes=msg.corr_id)
406 else:
407 current_context.correlation_id = uuid.uuid4()
408 if config.LOGWIRE:
409 protocol.log_wiredata(log, "daemon wiredata received", msg)
410 if msg.type == protocol.MSG_PING:
411 # return same seq, but ignore any data (it's a ping, not an echo). Nothing is deserialized.
412 msg = protocol.SendingMessage(protocol.MSG_PING, 0, msg.seq, msg.serializer_id, b"pong", annotations=self.__annotations())
413 if config.LOGWIRE:
414 protocol.log_wiredata(log, "daemon wiredata sending", msg)
415 conn.send(msg.data)
416 return
417 serializer = serializers.serializers_by_id[msg.serializer_id]
418 if request_flags & protocol.FLAGS_KEEPSERIALIZED:
419 # pass on the wire protocol message blob unchanged
420 objId, method, vargs, kwargs = self.__deserializeBlobArgs(msg)
421 else:
422 # normal deserialization of remote call arguments
423 objId, method, vargs, kwargs = serializer.loadsCall(msg.data)
424 current_context.client = conn
425 try:
426 # store, because on oneway calls, socket will be disconnected:
427 current_context.client_sock_addr = conn.sock.getpeername()
428 except socket.error:
429 current_context.client_sock_addr = None # sometimes getpeername() doesn't work...
430 current_context.seq = msg.seq
431 current_context.annotations = msg.annotations
432 current_context.msg_flags = msg.flags
433 current_context.serializer_id = msg.serializer_id
434 del msg # invite GC to collect the object, don't wait for out-of-scope
435 obj = _unpack_weakref(self.objectsById.get(objId))
436 if obj is not None:
437 if inspect.isclass(obj):
438 obj = self._getInstance(obj, conn)
439 if request_flags & protocol.FLAGS_BATCH:
440 # batched method calls, loop over them all and collect all results
441 data = []
442 for method, vargs, kwargs in vargs:
443 method = _get_attribute(obj, method)
444 try:
445 result = method(*vargs, **kwargs) # this is the actual method call to the Pyro object
446 except Exception as xv:
447 self.methodcall_error_handler(self, current_context.client_sock_addr, method, vargs, kwargs, xv)
448 xv._pyroTraceback = errors.format_traceback(detailed=config.DETAILED_TRACEBACK)
449 data.append(core._ExceptionWrapper(xv))
450 break # stop processing the rest of the batch
451 else:
452 data.append(result) # note that we don't support streaming results in batch mode
453 wasBatched = True
454 else:
455 # normal single method call
456 if method == "__getattr__":
457 # special case for direct attribute access (only exposed @properties are accessible)
458 data = _get_exposed_property_value(obj, vargs[0])
459 if not request_flags & protocol.FLAGS_ONEWAY:
460 isStream, data = self._streamResponse(data, conn)
461 if isStream:
462 # throw an exception as well as setting message flags
463 # this way, it is backwards compatible with older pyro versions.
464 exc = errors.ProtocolError("result of call is an iterator")
465 ann = {"STRM": data.encode()} if data else {}
466 self._sendExceptionResponse(conn, request_seq, serializer.serializer_id, exc, None,
467 annotations=ann, flags=protocol.FLAGS_ITEMSTREAMRESULT)
468 return
469 elif method == "__setattr__":
470 # special case for direct attribute access (only exposed @properties are accessible)
471 data = _set_exposed_property_value(obj, vargs[0], vargs[1])
472 else:
473 method = _get_attribute(obj, method)
474 if request_flags & protocol.FLAGS_ONEWAY:
475 # oneway call to be run inside its own thread, otherwise client blocking can still occur
476 # on the next call on the same proxy
477 _OnewayCallThread(method, vargs, kwargs, self, current_context.client_sock_addr).start()
478 else:
479 isCallback = getattr(method, "_pyroCallback", False)
480 try:
481 data = method(*vargs, **kwargs) # this is the actual method call to the Pyro object
482 except Exception as xv:
483 self.methodcall_error_handler(self, current_context.client_sock_addr, method, vargs, kwargs, xv)
484 raise
485 if not request_flags & protocol.FLAGS_ONEWAY:
486 isStream, data = self._streamResponse(data, conn)
487 if isStream:
488 # throw an exception as well as setting message flags
489 # this way, it is backwards compatible with older pyro versions.
490 exc = errors.ProtocolError("result of call is an iterator")
491 ann = {"STRM": data.encode()} if data else {}
492 self._sendExceptionResponse(conn, request_seq, serializer.serializer_id, exc, None,
493 annotations=ann, flags=protocol.FLAGS_ITEMSTREAMRESULT)
494 return
495 else:
496 log.debug("unknown object requested: %s", objId)
497 raise errors.DaemonError("unknown object")
498 if request_flags & protocol.FLAGS_ONEWAY:
499 return # oneway call, don't send a response
500 else:
501 data = serializer.dumps(data)
502 response_flags = 0
503 if wasBatched:
504 response_flags |= protocol.FLAGS_BATCH
505 msg = protocol.SendingMessage(protocol.MSG_RESULT, response_flags, request_seq, serializer.serializer_id, data,
506 annotations=self.__annotations())
507 current_context.response_annotations = {}
508 if config.LOGWIRE:
509 protocol.log_wiredata(log, "daemon wiredata sending", msg)
510 conn.send(msg.data)
511 except Exception as xv:
512 msg = getattr(xv, "pyroMsg", None)
513 if msg:
514 request_seq = msg.seq
515 request_serializer_id = msg.serializer_id
516 if not isinstance(xv, errors.ConnectionClosedError):
517 if not request_flags & protocol.FLAGS_ONEWAY:
518 if isinstance(xv, errors.SerializeError) or not isinstance(xv, errors.CommunicationError):
519 # only return the error to the client if it wasn't a oneway call, and not a communication error
520 # (in these cases, it makes no sense to try to report the error back to the client...)
521 tblines = errors.format_traceback(detailed=config.DETAILED_TRACEBACK)
522 self._sendExceptionResponse(conn, request_seq, request_serializer_id, xv, tblines)
523 if isCallback or isinstance(xv, (errors.CommunicationError, errors.SecurityError)):
524 raise # re-raise if flagged as callback, communication or security error.
525
526 def _clientDisconnect(self, conn):
527 if config.ITER_STREAM_LINGER > 0:
528 # client goes away, keep streams around for a bit longer (allow reconnect)
529 for streamId in list(self.streaming_responses):
530 info = self.streaming_responses.get(streamId, None)
531 if info and info[0] is conn:
532 _, timestamp, _, stream = info
533 self.streaming_responses[streamId] = (None, timestamp, time.time(), stream)
534 else:
535 # client goes away, close any streams it had open as well
536 for streamId in list(self.streaming_responses):
537 info = self.streaming_responses.get(streamId, None)
538 if info and info[0] is conn:
539 del self.streaming_responses[streamId]
540 self.clientDisconnect(conn) # user overridable hook
541
542 def _housekeeping(self):
543 """
544 Perform periodical housekeeping actions (cleanups etc)
545 """
546 if self._shutting_down:
547 return
548 with self.housekeeper_lock:
549 if self.streaming_responses:
550 if config.ITER_STREAM_LIFETIME > 0:
551 # cleanup iter streams that are past their lifetime
552 for streamId in list(self.streaming_responses.keys()):
553 info = self.streaming_responses.get(streamId, None)
554 if info:
555 last_use_period = time.time() - info[1]
556 if 0 < config.ITER_STREAM_LIFETIME < last_use_period:
557 del self.streaming_responses[streamId]
558 if config.ITER_STREAM_LINGER > 0:
559 # cleanup iter streams that are past their linger time
560 for streamId in list(self.streaming_responses.keys()):
561 info = self.streaming_responses.get(streamId, None)
562 if info and info[2]:
563 linger_period = time.time() - info[2]
564 if linger_period > config.ITER_STREAM_LINGER:
565 del self.streaming_responses[streamId]
566 self.housekeeping()
567
568 def housekeeping(self):
569 """
570 Override this to add custom periodic housekeeping (cleanup) logic.
571 This will be called every few seconds by the running daemon's request loop.
572 """
573 pass
574
575 def _getInstance(self, clazz, conn):
576 """
577 Find or create a new instance of the class
578 """
579 def createInstance(clazz, creator):
580 try:
581 if creator:
582 obj = creator(clazz)
583 if isinstance(obj, clazz):
584 return obj
585 raise TypeError("instance creator returned object of different type")
586 return clazz()
587 except Exception:
588 log.exception("could not create pyro object instance")
589 raise
590 instance_mode, instance_creator = clazz._pyroInstancing
591 if instance_mode == "single":
592 # create and use one singleton instance of this class (not a global singleton, just exactly one per daemon)
593 with self.create_single_instance_lock:
594 instance = self._pyroInstances.get(clazz)
595 if not instance:
596 log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
597 instance = createInstance(clazz, instance_creator)
598 self._pyroInstances[clazz] = instance
599 return instance
600 elif instance_mode == "session":
601 # Create and use one instance for this proxy connection
602 # the instances are kept on the connection object.
603 # (this is the default instance mode when using new style @expose)
604 instance = conn.pyroInstances.get(clazz)
605 if not instance:
606 log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
607 instance = createInstance(clazz, instance_creator)
608 conn.pyroInstances[clazz] = instance
609 return instance
610 elif instance_mode == "percall":
611 # create and use a new instance just for this call
612 log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
613 return createInstance(clazz, instance_creator)
614 else:
615 raise errors.DaemonError("invalid instancemode in registered class")
616
617 def _sendExceptionResponse(self, connection, seq, serializer_id, exc_value, tbinfo, flags=0, annotations=None):
618 """send an exception back including the local traceback info"""
619 exc_value._pyroTraceback = tbinfo
620 serializer = serializers.serializers_by_id[serializer_id]
621 try:
622 data = serializer.dumps(exc_value)
623 except Exception:
624 # the exception object couldn't be serialized, use a generic PyroError instead
625 xt, xv, tb = sys.exc_info()
626 msg = "Error serializing exception: %s. Original exception: %s: %s" % (str(xv), type(exc_value), str(exc_value))
627 exc_value = errors.PyroError(msg)
628 exc_value._pyroTraceback = tbinfo
629 data = serializer.dumps(exc_value)
630 flags |= protocol.FLAGS_EXCEPTION
631 annotations = dict(annotations or {})
632 annotations.update(self.annotations())
633 msg = protocol.SendingMessage(protocol.MSG_RESULT, flags, seq, serializer.serializer_id, data, annotations=annotations)
634 if config.LOGWIRE:
635 protocol.log_wiredata(log, "daemon wiredata sending (error response)", msg)
636 connection.send(msg.data)
637
638 def register(self, obj_or_class, objectId=None, force=False, weak=False):
639 """
640 Register a Pyro object under the given id. Note that this object is now only
641 known inside this daemon, it is not automatically available in a name server.
642 This method returns a URI for the registered object.
643 Pyro checks if an object is already registered, unless you set force=True.
644 You can register a class or an object (instance) directly.
645 For a class, Pyro will create instances of it to handle the remote calls according
646 to the instance_mode (set via @expose on the class). The default there is one object
647 per session (=proxy connection). If you register an object directly, Pyro will use
648 that single object for *all* remote calls.
649 With *weak=True*, only weak reference to the object will be stored, and the object will
650 get unregistered from the daemon automatically when garbage-collected.
651 """
652 if objectId:
653 if not isinstance(objectId, str):
654 raise TypeError("objectId must be a string or None")
655 else:
656 objectId = "obj_" + uuid.uuid4().hex # generate a new objectId
657 if inspect.isclass(obj_or_class):
658 if weak: raise TypeError("Classes cannot be registered with weak=True.")
659 if not hasattr(obj_or_class, "_pyroInstancing"):
660 obj_or_class._pyroInstancing = ("session", None)
661 if not force:
662 if hasattr(obj_or_class, "_pyroId") and obj_or_class._pyroId != "": # check for empty string is needed for Cython
663 pyro_id = obj_or_class._pyroId
664 if pyro_id and self.objectsById.get(pyro_id) is obj_or_class:
665 raise errors.DaemonError("object or class already has a Pyro id")
666 if objectId in self.objectsById:
667 raise errors.DaemonError("an object or class is already registered with that id")
668 # set some pyro attributes
669 obj_or_class._pyroId = objectId
670 obj_or_class._pyroDaemon = self
671 # register a custom serializer for the type to automatically return proxies
672 # we need to do this for all known serializers
673 for ser in serializers.serializers.values():
674 if inspect.isclass(obj_or_class):
675 ser.register_type_replacement(obj_or_class, _pyro_obj_to_auto_proxy)
676 else:
677 ser.register_type_replacement(type(obj_or_class), _pyro_obj_to_auto_proxy)
678 # register the object/class in the mapping
679 self.objectsById[obj_or_class._pyroId] = obj_or_class if not weak else weakref.ref(obj_or_class)
680 if weak: weakref.finalize(obj_or_class,self.unregister,objectId)
681 return self.uriFor(objectId)
682
683 def unregister(self, objectOrId):
684 """
685 Remove a class or object from the known objects inside this daemon.
686 You can unregister the class/object directly, or with its id.
687 """
688 if objectOrId is None:
689 raise ValueError("object or objectid argument expected")
690 if not isinstance(objectOrId, str):
691 objectId = getattr(objectOrId, "_pyroId", None)
692 if objectId is None:
693 raise errors.DaemonError("object isn't registered")
694 else:
695 objectId = objectOrId
696 objectOrId = None
697 if objectId == core.DAEMON_NAME:
698 return
699 if objectId in self.objectsById:
700 del self.objectsById[objectId]
701 if objectOrId is not None:
702 del objectOrId._pyroId
703 del objectOrId._pyroDaemon
704 # Don't remove the custom type serializer because there may be
705 # other registered objects of the same type still depending on it.
706
707 def uriFor(self, objectOrId, nat=True):
708 """
709 Get a URI for the given object (or object id) from this daemon.
710 Only a daemon can hand out proper uris because the access location is
711 contained in them.
712 Note that unregistered objects cannot be given an uri, but unregistered
713 object names can (it's just a string we're creating in that case).
714 If nat is set to False, the configured NAT address (if any) is ignored and it will
715 return an URI for the internal address.
716 """
717 if not isinstance(objectOrId, str):
718 objectOrId = getattr(objectOrId, "_pyroId", None)
719 if objectOrId is None or objectOrId not in self.objectsById:
720 raise errors.DaemonError("object isn't registered in this daemon")
721 if nat:
722 loc = self.natLocationStr or self.locationStr
723 else:
724 loc = self.locationStr
725 return core.URI("PYRO:%s@%s" % (objectOrId, loc))
726
727 def resetMetadataCache(self, objectOrId, nat=True):
728 """Reset cache of metadata when a Daemon has available methods/attributes
729 dynamically updated. Clients will have to get a new proxy to see changes"""
730 uri = self.uriFor(objectOrId, nat)
731 # can only be cached if registered, else no-op
732 if uri.object in self.objectsById:
733 registered_object = _unpack_weakref(self.objectsById[uri.object])
734 # Clear cache regardless of how it is accessed
735 _reset_exposed_members(registered_object)
736
737 def proxyFor(self, objectOrId, nat=True):
738 """
739 Get a fully initialized Pyro Proxy for the given object (or object id) for this daemon.
740 If nat is False, the configured NAT address (if any) is ignored.
741 The object or id must be registered in this daemon, or you'll get an exception.
742 (you can't get a proxy for an unknown object)
743 """
744 uri = self.uriFor(objectOrId, nat)
745 proxy = client.Proxy(uri)
746 try:
747 registered_object = _unpack_weakref(self.objectsById[uri.object])
748 except KeyError:
749 raise errors.DaemonError("object isn't registered in this daemon")
750 meta = _get_exposed_members(registered_object)
751 proxy._pyroGetMetadata(known_metadata=meta)
752 return proxy
753
754 def close(self):
755 """Close down the server and release resources"""
756 self.__mustshutdown.set()
757 self.streaming_responses = {}
758 if self.transportServer:
759 log.debug("daemon closing")
760 self.transportServer.close()
761 self.transportServer = None
762
763 def annotations(self):
764 """Override to return a dict with custom user annotations to be sent with each response message."""
765 return {}
766
767 def combine(self, daemon):
768 """
769 Combines the event loop of the other daemon in the current daemon's loop.
770 You can then simply run the current daemon's requestLoop to serve both daemons.
771 This works fine on the multiplex server type, but doesn't work with the threaded server type.
772 """
773 log.debug("combining event loop with other daemon")
774 self.transportServer.combine_loop(daemon.transportServer)
775
776 def __annotations(self):
777 annotations = current_context.response_annotations
778 annotations.update(self.annotations())
779 return annotations
780
781 def __repr__(self):
782 if hasattr(self, "locationStr"):
783 family = socketutil.family_str(self.sock)
784 return "<%s.%s at 0x%x; %s - %s; %d objects>" % (self.__class__.__module__, self.__class__.__name__,
785 id(self), self.locationStr, family, len(self.objectsById))
786 else:
787 # daemon objects may come back from serialized form without being properly initialized (by design)
788 return "<%s.%s at 0x%x; unusable>" % (self.__class__.__module__, self.__class__.__name__, id(self))
789
790 def __enter__(self):
791 if not self.transportServer:
792 raise errors.PyroError("cannot reuse this object")
793 return self
794
795 def __exit__(self, exc_type, exc_value, traceback):
796 self.close()
797
798 def __getstate__(self):
799 # A little hack to make it possible to serialize Pyro objects, because they can reference a daemon,
800 # but it is not meant to be able to properly serialize/deserialize Daemon objects.
801 return tuple()
802
803 def __setstate__(self, state):
804 assert len(state) == 0
805
806 def _streamResponse(self, data, client):
807 if isinstance(data, collections.abc.Iterator) or inspect.isgenerator(data):
808 if config.ITER_STREAMING:
809 if type(data) in (type({}.keys()), type({}.values()), type({}.items())):
810 raise errors.PyroError("won't serialize or stream lazy dict iterators, convert to list yourself")
811 stream_id = str(uuid.uuid4())
812 self.streaming_responses[stream_id] = (client, time.time(), 0, data)
813 return True, stream_id
814 return True, None
815 return False, data
816
817 def __deserializeBlobArgs(self, protocolmsg):
818 import marshal
819 blobinfo = protocolmsg.annotations["BLBI"]
820 blobinfo, objId, method = marshal.loads(blobinfo)
821 blob = client.SerializedBlob(blobinfo, protocolmsg, is_blob=True)
822 return objId, method, (blob,), {} # object, method, vargs, kwargs
823
824
825 def serve(objects: Dict[Any, str], host: Optional[Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]] = None,
826 port: int = 0, daemon: Optional[Daemon] = None, use_ns: bool = True, verbose: bool = True) -> None:
827 """
828 Basic method to fire up a daemon (or supply one yourself).
829 objects is a dict containing objects to register as keys, and
830 their names (or None) as values. If ns is true they will be registered
831 in the naming server as well, otherwise they just stay local.
832 If you need to publish on a unix domain socket, or require finer control of the daemon's
833 behavior, you can't use this shortcut method. Create a Daemon yourself and use its
834 appropriate methods.
835 See the documentation on 'publishing objects' (in chapter: Servers) for more details.
836 """
837 if daemon is None:
838 daemon = Daemon(host, port)
839 with daemon:
840 ns = core.locate_ns() if use_ns else None
841 for obj, name in objects.items():
842 if ns:
843 localname = None # name is used for the name server
844 else:
845 localname = name # no name server, use name in daemon
846 uri = daemon.register(obj, localname)
847 if verbose:
848 print("Object {0}:\n uri = {1}".format(repr(obj), uri))
849 if name and ns:
850 ns.register(name, uri)
851 if verbose:
852 print(" name = {0}".format(name))
853 if verbose:
854 print("Pyro daemon running.")
855 daemon.requestLoop()
856
857
858 def _default_methodcall_error_handler(daemon: Daemon, client_sock: socketutil.SocketConnection,
859 method: Callable, vargs: Sequence[Any], kwargs: Dict[str, Any],
860 exception: Exception) -> None:
861 """The default routine called to process a exception raised in the user code of a method call"""
862 log.debug("exception occurred in method call user code: client={} method={} exception={}"
863 .format(client_sock, method.__qualname__, repr(exception)))
864
865
866 # register the special serializers for the pyro objects
867 serpent.register_class(Daemon, serializers.pyro_class_serpent_serializer)
868 serializers.SerializerBase.register_class_to_dict(Daemon, serializers.serialize_pyro_object_to_dict, serpent_too=False)
869
870
871 def _pyro_obj_to_auto_proxy(obj: Any) -> Any:
872 """reduce function that automatically replaces Pyro objects by a Proxy"""
873 daemon = getattr(obj, "_pyroDaemon", None)
874 if daemon:
875 # only return a proxy if the object is a registered pyro object
876 return daemon.proxyFor(obj)
877 return obj
878
879
880 def _get_attribute(obj: Any, attr: str) -> Any:
881 """
882 Resolves an attribute name to an object. Raises
883 an AttributeError if any attribute in the chain starts with a '``_``'.
884 Doesn't resolve a dotted name, because that is a security vulnerability.
885 It treats it as a single attribute name (and the lookup will likely fail).
886 """
887 if is_private_attribute(attr):
888 raise AttributeError("attempt to access private attribute '%s'" % attr)
889 else:
890 obj = getattr(obj, attr)
891 if getattr(obj, "_pyroExposed", False):
892 return obj
893 raise AttributeError("attempt to access unexposed attribute '%s'" % attr)
894
895
896 __exposed_member_cache = {} # type: Dict[Tuple[type, bool], Dict[str, Set[str]]]
897
898
899 def _reset_exposed_members(obj: Any, only_exposed: bool = True) -> None:
900 """Delete any cached exposed members forcing recalculation on next request"""
901 if not inspect.isclass(obj):
902 obj = obj.__class__
903 cache_key = (obj, only_exposed)
904 __exposed_member_cache.pop(cache_key, None)
905
906
907 def _get_exposed_members(obj: Any, only_exposed: bool = True) -> Dict[str, Set[str]]:
908 """
909 Return public and exposed members of the given object's class.
910 You can also provide a class directly.
911 Private members are ignored no matter what (names starting with underscore).
912 If only_exposed is True, only members tagged with the @expose decorator are
913 returned. If it is False, all public members are returned.
914 The return value consists of the exposed methods, exposed attributes, and methods
915 tagged as @oneway.
916 (All this is used as meta data that Pyro sends to the proxy if it asks for it)
917 """
918 if not inspect.isclass(obj):
919 obj = obj.__class__
920
921 cache_key = (obj, only_exposed)
922 if cache_key in __exposed_member_cache:
923 return __exposed_member_cache[cache_key]
924
925 methods = set() # all methods
926 oneway = set() # oneway methods
927 attrs = set() # attributes
928 for m in dir(obj): # also lists names inherited from super classes
929 if is_private_attribute(m):
930 continue
931 v = getattr(obj, m)
932 if inspect.ismethod(v) or inspect.isfunction(v) or inspect.ismethoddescriptor(v):
933 if getattr(v, "_pyroExposed", not only_exposed):
934 methods.add(m)
935 # check if the method is marked with the 'oneway' decorator:
936 if getattr(v, "_pyroOneway", False):
937 oneway.add(m)
938 elif inspect.isdatadescriptor(v):
939 func = getattr(v, "fget", None) or getattr(v, "fset", None) or getattr(v, "fdel", None)
940 if func is not None and getattr(func, "_pyroExposed", not only_exposed):
941 attrs.add(m)
942 # Note that we don't expose plain class attributes no matter what.
943 # it is a syntax error to add a decorator on them, and it is not possible
944 # to give them a _pyroExposed tag either.
945 # The way to expose attributes is by using properties for them.
946 # This automatically solves the protection/security issue: you have to
947 # explicitly decide to make an attribute into a @property (and to @expose it)
948 # before it becomes remotely accessible.
949 result = {
950 "methods": methods,
951 "oneway": oneway,
952 "attrs": attrs
953 }
954 __exposed_member_cache[cache_key] = result
955 return result
956
957
958 def _unpack_weakref(obj: Any):
959 """
960 Unpack weak reference, or return the object itself, if not a weak reference.
961 If the weak reference is dead (calling it returns None), raises an
962 exception. Even though register(...,weak=True) creates finalizer which
963 will delete the weakref from the mapping, it is possible that the object
964 is garbage-collected asynchronously between obtaining weakref from the
965 mapping and reference unpacking, making the weakref invalid; this is handled
966 by the exception here.
967 """
968 if not isinstance(obj,weakref.ref): return obj
969 ret=obj() # ret will hold strong reference to obj, until it gets deleted itself
970 if ret is None: raise errors.DaemonError("Weakly registered deleted meanwhile (or finalizer failed?).")
971 return ret
972
973 def _get_exposed_property_value(obj: Any, propname: str, only_exposed: bool = True) -> Any:
974 """
975 Return the value of an @exposed @property.
976 If the requested property is not a @property or not exposed,
977 an AttributeError is raised instead.
978 """
979 v = getattr(obj.__class__, propname)
980 if inspect.isdatadescriptor(v):
981 if v.fget and getattr(v.fget, "_pyroExposed", not only_exposed):
982 return v.fget(obj)
983 raise AttributeError("attempt to access unexposed or unknown remote attribute '%s'" % propname)
984
985
986 def _set_exposed_property_value(obj: Any, propname: str, value: Any, only_exposed: bool = True) -> Any:
987 """
988 Sets the value of an @exposed @property.
989 If the requested property is not a @property or not exposed,
990 an AttributeError is raised instead.
991 """
992 v = getattr(obj.__class__, propname)
993 if inspect.isdatadescriptor(v):
994 pfunc = v.fget or v.fset or v.fdel
995 if v.fset and getattr(pfunc, "_pyroExposed", not only_exposed):
996 return v.fset(obj, value)
997 raise AttributeError("attempt to access unexposed or unknown remote attribute '%s'" % propname)
998
999
1000 class _OnewayCallThread(threading.Thread):
1001 def __init__(self, pyro_method, vargs, kwargs, pyro_daemon, pyro_client_sock):
1002 super(_OnewayCallThread, self).__init__(target=self._methodcall, name="oneway-call")
1003 self.daemon = True
1004 self.parent_context = current_context.to_global()
1005 self.pyro_daemon = pyro_daemon
1006 self.pyro_client_sock = pyro_client_sock
1007 self.pyro_method = pyro_method
1008 self.pyro_vargs = vargs
1009 self.pyro_kwars = kwargs
1010
1011 def run(self):
1012 current_context.from_global(self.parent_context)
1013 super(_OnewayCallThread, self).run()
1014
1015 def _methodcall(self):
1016 try:
1017 self.pyro_method(*self.pyro_vargs, **self.pyro_kwars)
1018 except Exception as xv:
1019 self.pyro_daemon.methodcall_error_handler(self.pyro_daemon, self.pyro_client_sock,
1020 self.pyro_method, self.pyro_vargs, self.pyro_kwars,
1021 xv)