core.py 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. """
  2. Core logic (uri, daemon, proxy stuff).
  3. Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
  4. """
  5. import inspect
  6. import collections
  7. import re
  8. import logging
  9. import sys
  10. import os
  11. import time
  12. import threading
  13. import uuid
  14. import base64
  15. import warnings
  16. import Pyro4.futures
  17. from Pyro4 import errors, threadutil, socketutil, util, constants, message
  18. from Pyro4.socketserver.threadpoolserver import SocketServer_Threadpool
  19. from Pyro4.socketserver.multiplexserver import SocketServer_Multiplex
  20. __all__ = ["URI", "Proxy", "Daemon", "current_context", "callback", "batch", "async", "expose", "behavior", "oneway"]
  21. if sys.version_info >= (3, 0):
  22. basestring = str
  23. log = logging.getLogger("Pyro4.core")
  24. class URI(object):
  25. """
  26. Pyro object URI (universal resource identifier).
  27. The uri format is like this: ``PYRO:objectid@location`` where location is one of:
  28. - ``hostname:port`` (tcp/ip socket on given port)
  29. - ``./u:sockname`` (Unix domain socket on localhost)
  30. There is also a 'Magic format' for simple name resolution using Name server:
  31. ``PYRONAME:objectname[@location]`` (optional name server location, can also omit location port)
  32. And one that looks up things in the name server by metadata:
  33. ``PYROMETA:meta1,meta2,...[@location]`` (optional name server location, can also omit location port)
  34. You can write the protocol in lowercase if you like (``pyro:...``) but it will
  35. automatically be converted to uppercase internally.
  36. """
  37. uriRegEx = re.compile(r"(?P<protocol>[Pp][Yy][Rr][Oo][a-zA-Z]*):(?P<object>\S+?)(@(?P<location>\S+))?$")
  38. def __init__(self, uri):
  39. if isinstance(uri, URI):
  40. state = uri.__getstate__()
  41. self.__setstate__(state)
  42. return
  43. if not isinstance(uri, basestring):
  44. raise TypeError("uri parameter object is of wrong type")
  45. self.sockname = self.host = self.port = None
  46. match = self.uriRegEx.match(uri)
  47. if not match:
  48. raise errors.PyroError("invalid uri")
  49. self.protocol = match.group("protocol").upper()
  50. self.object = match.group("object")
  51. location = match.group("location")
  52. if self.protocol == "PYRONAME":
  53. self._parseLocation(location, Pyro4.config.NS_PORT)
  54. elif self.protocol == "PYRO":
  55. if not location:
  56. raise errors.PyroError("invalid uri")
  57. self._parseLocation(location, None)
  58. elif self.protocol == "PYROMETA":
  59. self.object = set(m.strip() for m in self.object.split(","))
  60. self._parseLocation(location, Pyro4.config.NS_PORT)
  61. else:
  62. raise errors.PyroError("invalid uri (protocol)")
  63. def _parseLocation(self, location, defaultPort):
  64. if not location:
  65. return
  66. if location.startswith("./u:"):
  67. self.sockname = location[4:]
  68. if (not self.sockname) or ':' in self.sockname:
  69. raise errors.PyroError("invalid uri (location)")
  70. else:
  71. if location.startswith("["): # ipv6
  72. if location.startswith("[["): # possible mistake: double-bracketing
  73. raise errors.PyroError("invalid ipv6 address: enclosed in too many brackets")
  74. self.host, _, self.port = re.match(r"\[([0-9a-fA-F:%]+)](:(\d+))?", location).groups()
  75. else:
  76. self.host, _, self.port = location.partition(":")
  77. if not self.port:
  78. self.port = defaultPort
  79. try:
  80. self.port = int(self.port)
  81. except (ValueError, TypeError):
  82. raise errors.PyroError("invalid port in uri, port=" + str(self.port))
  83. @staticmethod
  84. def isUnixsockLocation(location):
  85. """determine if a location string is for a Unix domain socket"""
  86. return location.startswith("./u:")
  87. @property
  88. def location(self):
  89. """property containing the location string, for instance ``"servername.you.com:5555"``"""
  90. if self.host:
  91. if ":" in self.host: # ipv6
  92. return "[%s]:%d" % (self.host, self.port)
  93. else:
  94. return "%s:%d" % (self.host, self.port)
  95. elif self.sockname:
  96. return "./u:" + self.sockname
  97. else:
  98. return None
  99. def asString(self):
  100. """the string representation of this object"""
  101. if self.protocol == "PYROMETA":
  102. result = "PYROMETA:" + ",".join(self.object)
  103. else:
  104. result = self.protocol + ":" + self.object
  105. location = self.location
  106. if location:
  107. result += "@" + location
  108. return result
  109. def __str__(self):
  110. string = self.asString()
  111. if sys.version_info < (3, 0) and type(string) is unicode:
  112. return string.encode("ascii", "replace")
  113. return string
  114. def __unicode__(self):
  115. return self.asString()
  116. def __repr__(self):
  117. return "<%s.%s at 0x%x; %s>" % (self.__class__.__module__, self.__class__.__name__, id(self), str(self))
  118. def __eq__(self, other):
  119. if not isinstance(other, URI):
  120. return False
  121. return (self.protocol, self.object, self.sockname, self.host, self.port) == (other.protocol, other.object, other.sockname, other.host, other.port)
  122. def __ne__(self, other):
  123. return not self.__eq__(other)
  124. def __hash__(self):
  125. return hash((self.protocol, str(self.object), self.sockname, self.host, self.port))
  126. # note: getstate/setstate are not needed if we use pickle protocol 2,
  127. # but this way it helps pickle to make the representation smaller by omitting all attribute names.
  128. def __getstate__(self):
  129. return self.protocol, self.object, self.sockname, self.host, self.port
  130. def __setstate__(self, state):
  131. self.protocol, self.object, self.sockname, self.host, self.port = state
  132. def __getstate_for_dict__(self):
  133. return self.__getstate__()
  134. def __setstate_from_dict__(self, state):
  135. self.__setstate__(state)
  136. class _RemoteMethod(object):
  137. """method call abstraction"""
  138. def __init__(self, send, name, max_retries):
  139. self.__send = send
  140. self.__name = name
  141. self.__max_retries = max_retries
  142. def __getattr__(self, name):
  143. return _RemoteMethod(self.__send, "%s.%s" % (self.__name, name), self.__max_retries)
  144. def __call__(self, *args, **kwargs):
  145. for attempt in range(self.__max_retries + 1):
  146. try:
  147. return self.__send(self.__name, args, kwargs)
  148. except (errors.ConnectionClosedError, errors.TimeoutError):
  149. # only retry for recoverable network errors
  150. if attempt >= self.__max_retries:
  151. # last attempt, raise the exception
  152. raise
  153. class Proxy(object):
  154. """
  155. Pyro proxy for a remote object. Intercepts method calls and dispatches them to the remote object.
  156. .. automethod:: _pyroBind
  157. .. automethod:: _pyroRelease
  158. .. automethod:: _pyroReconnect
  159. .. automethod:: _pyroBatch
  160. .. automethod:: _pyroAsync
  161. .. automethod:: _pyroAnnotations
  162. .. automethod:: _pyroResponseAnnotations
  163. .. automethod:: _pyroValidateHandshake
  164. .. autoattribute:: _pyroTimeout
  165. .. autoattribute:: _pyroHmacKey
  166. .. attribute:: _pyroMaxRetries
  167. Number of retries to perform on communication calls by this proxy, allows you to override the default setting.
  168. .. attribute:: _pyroSerializer
  169. Name of the serializer to use by this proxy, allows you to override the default setting.
  170. .. attribute:: _pyroHandshake
  171. The data object that should be sent in the initial connection handshake message. Can be any serializable object.
  172. """
  173. __pyroAttributes = frozenset(
  174. ["__getnewargs__", "__getnewargs_ex__", "__getinitargs__", "_pyroConnection", "_pyroUri",
  175. "_pyroOneway", "_pyroMethods", "_pyroAttrs", "_pyroTimeout", "_pyroSeq", "_pyroHmacKey",
  176. "_pyroRawWireResponse", "_pyroHandshake", "_pyroMaxRetries", "_pyroSerializer", "_Proxy__async",
  177. "_Proxy__pyroHmacKey", "_Proxy__pyroTimeout", "_Proxy__pyroConnLock"])
  178. def __init__(self, uri):
  179. if isinstance(uri, basestring):
  180. uri = URI(uri)
  181. elif not isinstance(uri, URI):
  182. raise TypeError("expected Pyro URI")
  183. self._pyroUri = uri
  184. self._pyroConnection = None
  185. self._pyroSerializer = None # can be set to the name of a serializer to override the global one per-proxy
  186. self._pyroMethods = set() # all methods of the remote object, gotten from meta-data
  187. self._pyroAttrs = set() # attributes of the remote object, gotten from meta-data
  188. self._pyroOneway = set() # oneway-methods of the remote object, gotten from meta-data
  189. self._pyroSeq = 0 # message sequence number
  190. self._pyroRawWireResponse = False # internal switch to enable wire level responses
  191. self._pyroHandshake = "hello" # the data object that should be sent in the initial connection handshake message (can be any serializable object)
  192. self._pyroMaxRetries = Pyro4.config.MAX_RETRIES
  193. self.__pyroHmacKey = None
  194. self.__pyroTimeout = Pyro4.config.COMMTIMEOUT
  195. self.__pyroConnLock = threadutil.RLock()
  196. util.get_serializer(Pyro4.config.SERIALIZER) # assert that the configured serializer is available
  197. self.__async = False
  198. @property
  199. def _pyroHmacKey(self):
  200. """the HMAC key (bytes) that this proxy uses"""
  201. return self.__pyroHmacKey
  202. @_pyroHmacKey.setter
  203. def _pyroHmacKey(self, value):
  204. # if needed, convert the hmac value to bytes first
  205. if value and sys.version_info >= (3, 0) and type(value) is not bytes:
  206. value = value.encode("utf-8") # convert to bytes
  207. self.__pyroHmacKey = value
  208. def __del__(self):
  209. if hasattr(self, "_pyroConnection"):
  210. self._pyroRelease()
  211. def __getattr__(self, name):
  212. if name in Proxy.__pyroAttributes:
  213. # allows it to be safely pickled
  214. raise AttributeError(name)
  215. if Pyro4.config.METADATA:
  216. # get metadata if it's not there yet
  217. if not self._pyroMethods and not self._pyroAttrs:
  218. self._pyroGetMetadata()
  219. if name in self._pyroAttrs:
  220. return self._pyroInvoke("__getattr__", (name,), None)
  221. if Pyro4.config.METADATA and name not in self._pyroMethods:
  222. # client side check if the requested attr actually exists
  223. raise AttributeError("remote object '%s' has no exposed attribute or method '%s'" % (self._pyroUri, name))
  224. if self.__async:
  225. return _AsyncRemoteMethod(self, name, self._pyroMaxRetries)
  226. return _RemoteMethod(self._pyroInvoke, name, self._pyroMaxRetries)
  227. def __setattr__(self, name, value):
  228. if name in Proxy.__pyroAttributes:
  229. return super(Proxy, self).__setattr__(name, value) # one of the special pyro attributes
  230. if Pyro4.config.METADATA:
  231. # get metadata if it's not there yet
  232. if not self._pyroMethods and not self._pyroAttrs:
  233. self._pyroGetMetadata()
  234. if name in self._pyroAttrs:
  235. return self._pyroInvoke("__setattr__", (name, value), None) # remote attribute
  236. if Pyro4.config.METADATA:
  237. # client side validation if the requested attr actually exists
  238. raise AttributeError("remote object '%s' has no exposed attribute '%s'" % (self._pyroUri, name))
  239. # metadata disabled, just treat it as a local attribute on the proxy:
  240. return super(Proxy, self).__setattr__(name, value)
  241. def __repr__(self):
  242. connected = "connected" if self._pyroConnection else "not connected"
  243. return "<%s.%s at 0x%x; %s; for %s>" % (self.__class__.__module__, self.__class__.__name__,
  244. id(self), connected, self._pyroUri)
  245. def __unicode__(self):
  246. return str(self)
  247. def __getstate_for_dict__(self):
  248. encodedHmac = None
  249. if self._pyroHmacKey is not None:
  250. encodedHmac = "b64:"+(base64.b64encode(self._pyroHmacKey).decode("ascii"))
  251. # for backwards compatibility reasons we also put the timeout and maxretries into the state
  252. return self._pyroUri.asString(), tuple(self._pyroOneway), tuple(self._pyroMethods), tuple(self._pyroAttrs),\
  253. self.__pyroTimeout, encodedHmac, self._pyroHandshake, self._pyroMaxRetries, self._pyroSerializer
  254. def __setstate_from_dict__(self, state):
  255. uri = URI(state[0])
  256. oneway = set(state[1])
  257. methods = set(state[2])
  258. attrs = set(state[3])
  259. timeout = state[4]
  260. hmac_key = state[5]
  261. handshake = state[6]
  262. max_retries = state[7]
  263. serializer = None if len(state) < 9 else state[8]
  264. if hmac_key:
  265. if hmac_key.startswith("b64:"):
  266. hmac_key = base64.b64decode(hmac_key[4:].encode("ascii"))
  267. else:
  268. raise errors.ProtocolError("hmac encoding error")
  269. self.__setstate__((uri, oneway, methods, attrs, timeout, hmac_key, handshake, max_retries, serializer))
  270. def __getstate__(self):
  271. # for backwards compatibility reasons we also put the timeout and maxretries into the state
  272. return self._pyroUri, self._pyroOneway, self._pyroMethods, self._pyroAttrs, self.__pyroTimeout,\
  273. self._pyroHmacKey, self._pyroHandshake, self._pyroMaxRetries, self._pyroSerializer
  274. def __setstate__(self, state):
  275. # Note that the timeout and maxretries are also part of the state (for backwards compatibility reasons),
  276. # but we're not using them here. Instead we get the configured values from the 'local' config.
  277. self._pyroUri, self._pyroOneway, self._pyroMethods, self._pyroAttrs, _, self._pyroHmacKey, self._pyroHandshake = state[:7]
  278. self._pyroSerializer = None if len(state) < 9 else state[8]
  279. self.__pyroTimeout = Pyro4.config.COMMTIMEOUT
  280. self._pyroMaxRetries = Pyro4.config.MAX_RETRIES
  281. self._pyroConnection = None
  282. self._pyroSeq = 0
  283. self._pyroRawWireResponse = False
  284. self.__pyroConnLock = threadutil.RLock()
  285. self.__async = False
  286. def __copy__(self):
  287. uriCopy = URI(self._pyroUri)
  288. p = type(self)(uriCopy)
  289. p._pyroOneway = set(self._pyroOneway)
  290. p._pyroMethods = set(self._pyroMethods)
  291. p._pyroAttrs = set(self._pyroAttrs)
  292. p._pyroSerializer = self._pyroSerializer
  293. p._pyroTimeout = self._pyroTimeout
  294. p._pyroHandshake = self._pyroHandshake
  295. p._pyroHmacKey = self._pyroHmacKey
  296. p._pyroRawWireResponse = self._pyroRawWireResponse
  297. p._pyroMaxRetries = self._pyroMaxRetries
  298. p.__async = self.__async
  299. return p
  300. def __enter__(self):
  301. return self
  302. def __exit__(self, exc_type, exc_value, traceback):
  303. self._pyroRelease()
  304. def __eq__(self, other):
  305. if other is self:
  306. return True
  307. return isinstance(other, Proxy) and other._pyroUri == self._pyroUri
  308. def __ne__(self, other):
  309. if other and isinstance(other, Proxy):
  310. return other._pyroUri != self._pyroUri
  311. return True
  312. def __hash__(self):
  313. return hash(self._pyroUri)
  314. def __dir__(self):
  315. result = dir(self.__class__) + list(self.__dict__.keys())
  316. return sorted(set(result) | self._pyroMethods | self._pyroAttrs)
  317. def _pyroRelease(self):
  318. """release the connection to the pyro daemon"""
  319. with self.__pyroConnLock:
  320. if self._pyroConnection is not None:
  321. self._pyroConnection.close()
  322. self._pyroConnection = None
  323. log.debug("connection released")
  324. def _pyroBind(self):
  325. """
  326. Bind this proxy to the exact object from the uri. That means that the proxy's uri
  327. will be updated with a direct PYRO uri, if it isn't one yet.
  328. If the proxy is already bound, it will not bind again.
  329. """
  330. return self.__pyroCreateConnection(True)
  331. def __pyroGetTimeout(self):
  332. return self.__pyroTimeout
  333. def __pyroSetTimeout(self, timeout):
  334. self.__pyroTimeout = timeout
  335. if self._pyroConnection is not None:
  336. self._pyroConnection.timeout = timeout
  337. _pyroTimeout = property(__pyroGetTimeout, __pyroSetTimeout, doc="""
  338. The timeout in seconds for calls on this proxy. Defaults to ``None``.
  339. If the timeout expires before the remote method call returns,
  340. Pyro will raise a :exc:`Pyro4.errors.TimeoutError`""")
  341. def _pyroInvoke(self, methodname, vargs, kwargs, flags=0, objectId=None):
  342. """perform the remote method call communication"""
  343. with self.__pyroConnLock:
  344. if self._pyroConnection is None:
  345. # rebind here, don't do it from inside the invoke because deadlock will occur
  346. self.__pyroCreateConnection()
  347. serializer = util.get_serializer(self._pyroSerializer or Pyro4.config.SERIALIZER)
  348. data, compressed = serializer.serializeCall(
  349. objectId or self._pyroConnection.objectId, methodname, vargs, kwargs,
  350. compress=Pyro4.config.COMPRESSION)
  351. if compressed:
  352. flags |= Pyro4.message.FLAGS_COMPRESSED
  353. if methodname in self._pyroOneway:
  354. flags |= Pyro4.message.FLAGS_ONEWAY
  355. self._pyroSeq = (self._pyroSeq + 1) & 0xffff
  356. msg = message.Message(message.MSG_INVOKE, data, serializer.serializer_id, flags, self._pyroSeq, annotations=self._pyroAnnotations(), hmac_key=self._pyroHmacKey)
  357. if Pyro4.config.LOGWIRE:
  358. _log_wiredata(log, "proxy wiredata sending", msg)
  359. try:
  360. self._pyroConnection.send(msg.to_bytes())
  361. del msg # invite GC to collect the object, don't wait for out-of-scope
  362. if flags & message.FLAGS_ONEWAY:
  363. return None # oneway call, no response data
  364. else:
  365. msg = message.Message.recv(self._pyroConnection, [message.MSG_RESULT], hmac_key=self._pyroHmacKey)
  366. if Pyro4.config.LOGWIRE:
  367. _log_wiredata(log, "proxy wiredata received", msg)
  368. self.__pyroCheckSequence(msg.seq)
  369. if msg.serializer_id != serializer.serializer_id:
  370. error = "invalid serializer in response: %d" % msg.serializer_id
  371. log.error(error)
  372. raise errors.SerializeError(error)
  373. if msg.annotations:
  374. self._pyroResponseAnnotations(msg.annotations, msg.type)
  375. if self._pyroRawWireResponse:
  376. return util.SerializerBase.decompress_if_needed(msg)
  377. data = serializer.deserializeData(msg.data, compressed=msg.flags & message.FLAGS_COMPRESSED)
  378. if msg.flags & message.FLAGS_ITEMSTREAMRESULT:
  379. streamId = msg.annotations.get("STRM", b"").decode()
  380. if not streamId:
  381. raise errors.ProtocolError("result of call is an iterator, but the server is not configured to allow streaming")
  382. return _StreamResultIterator(streamId, self)
  383. if msg.flags & message.FLAGS_EXCEPTION:
  384. if sys.platform == "cli":
  385. util.fixIronPythonExceptionForPickle(data, False)
  386. raise data
  387. else:
  388. return data
  389. except (errors.CommunicationError, KeyboardInterrupt):
  390. # Communication error during read. To avoid corrupt transfers, we close the connection.
  391. # Otherwise we might receive the previous reply as a result of a new method call!
  392. # Special case for keyboardinterrupt: people pressing ^C to abort the client
  393. # may be catching the keyboardinterrupt in their code. We should probably be on the
  394. # safe side and release the proxy connection in this case too, because they might
  395. # be reusing the proxy object after catching the exception...
  396. self._pyroRelease()
  397. raise
  398. def __pyroCheckSequence(self, seq):
  399. if seq != self._pyroSeq:
  400. err = "invoke: reply sequence out of sync, got %d expected %d" % (seq, self._pyroSeq)
  401. log.error(err)
  402. raise errors.ProtocolError(err)
  403. def __pyroCreateConnection(self, replaceUri=False):
  404. """
  405. Connects this proxy to the remote Pyro daemon. Does connection handshake.
  406. Returns true if a new connection was made, false if an existing one was already present.
  407. """
  408. with self.__pyroConnLock:
  409. if self._pyroConnection is not None:
  410. return False # already connected
  411. from Pyro4.naming import resolve # don't import this globally because of cyclic dependency
  412. uri = resolve(self._pyroUri, self._pyroHmacKey)
  413. # socket connection (normal or Unix domain socket)
  414. conn = None
  415. log.debug("connecting to %s", uri)
  416. connect_location = uri.sockname or (uri.host, uri.port)
  417. try:
  418. if self._pyroConnection is not None:
  419. return False # already connected
  420. sock = socketutil.createSocket(connect=connect_location, reuseaddr=Pyro4.config.SOCK_REUSE, timeout=self.__pyroTimeout, nodelay=Pyro4.config.SOCK_NODELAY)
  421. conn = socketutil.SocketConnection(sock, uri.object)
  422. # Do handshake.
  423. serializer = util.get_serializer(self._pyroSerializer or Pyro4.config.SERIALIZER)
  424. data = {"handshake": self._pyroHandshake}
  425. if Pyro4.config.METADATA:
  426. # the object id is only used/needed when piggybacking the metadata on the connection response
  427. # make sure to pass the resolved object id instead of the logical id
  428. data["object"] = uri.object
  429. flags = Pyro4.message.FLAGS_META_ON_CONNECT
  430. else:
  431. flags = 0
  432. data, compressed = serializer.serializeData(data, Pyro4.config.COMPRESSION)
  433. if compressed:
  434. flags |= Pyro4.message.FLAGS_COMPRESSED
  435. msg = message.Message(message.MSG_CONNECT, data, serializer.serializer_id, flags, self._pyroSeq,
  436. annotations=self._pyroAnnotations(), hmac_key=self._pyroHmacKey)
  437. if Pyro4.config.LOGWIRE:
  438. _log_wiredata(log, "proxy connect sending", msg)
  439. conn.send(msg.to_bytes())
  440. msg = message.Message.recv(conn, [message.MSG_CONNECTOK, message.MSG_CONNECTFAIL], hmac_key=self._pyroHmacKey)
  441. if Pyro4.config.LOGWIRE:
  442. _log_wiredata(log, "proxy connect response received", msg)
  443. except Exception:
  444. x = sys.exc_info()[1]
  445. if conn:
  446. conn.close()
  447. err = "cannot connect: %s" % x
  448. log.error(err)
  449. if isinstance(x, errors.CommunicationError):
  450. raise
  451. else:
  452. ce = errors.CommunicationError(err)
  453. if sys.version_info >= (3, 0):
  454. ce.__cause__ = x
  455. raise ce
  456. else:
  457. handshake_response = "?"
  458. if msg.data:
  459. serializer = util.get_serializer_by_id(msg.serializer_id)
  460. handshake_response = serializer.deserializeData(msg.data, compressed=msg.flags & Pyro4.message.FLAGS_COMPRESSED)
  461. if msg.type == message.MSG_CONNECTFAIL:
  462. if sys.version_info < (3, 0):
  463. error = "connection rejected, reason: " + handshake_response.decode()
  464. else:
  465. error = "connection rejected, reason: " + handshake_response
  466. conn.close()
  467. log.error(error)
  468. raise errors.CommunicationError(error)
  469. elif msg.type == message.MSG_CONNECTOK:
  470. if msg.flags & message.FLAGS_META_ON_CONNECT:
  471. self.__processMetadata(handshake_response["meta"])
  472. handshake_response = handshake_response["handshake"]
  473. self._pyroConnection = conn
  474. if replaceUri:
  475. self._pyroUri = uri
  476. self._pyroValidateHandshake(handshake_response)
  477. log.debug("connected to %s", self._pyroUri)
  478. if msg.annotations:
  479. self._pyroResponseAnnotations(msg.annotations, msg.type)
  480. else:
  481. conn.close()
  482. err = "connect: invalid msg type %d received" % msg.type
  483. log.error(err)
  484. raise errors.ProtocolError(err)
  485. if Pyro4.config.METADATA:
  486. # obtain metadata if this feature is enabled, and the metadata is not known yet
  487. if self._pyroMethods or self._pyroAttrs:
  488. log.debug("reusing existing metadata")
  489. else:
  490. self._pyroGetMetadata(uri.object)
  491. return True
  492. def _pyroGetMetadata(self, objectId=None, known_metadata=None):
  493. """
  494. Get metadata from server (methods, attrs, oneway, ...) and remember them in some attributes of the proxy.
  495. Usually this will already be known due to the default behavior of the connect handshake, where the
  496. connect response also includes the metadata.
  497. """
  498. objectId = objectId or self._pyroUri.object
  499. log.debug("getting metadata for object %s", objectId)
  500. if self._pyroConnection is None and not known_metadata:
  501. try:
  502. self.__pyroCreateConnection()
  503. except errors.PyroError:
  504. log.error("problem getting metadata: cannot connect")
  505. raise
  506. if self._pyroMethods or self._pyroAttrs:
  507. return # metadata has already been retrieved as part of creating the connection
  508. try:
  509. # invoke the get_metadata method on the daemon
  510. result = known_metadata or self._pyroInvoke("get_metadata", [objectId], {}, objectId=constants.DAEMON_NAME)
  511. self.__processMetadata(result)
  512. except errors.PyroError:
  513. log.exception("problem getting metadata")
  514. raise
  515. def __processMetadata(self, metadata):
  516. if not metadata:
  517. return
  518. self._pyroOneway = set(metadata["oneway"])
  519. self._pyroMethods = set(metadata["methods"])
  520. self._pyroAttrs = set(metadata["attrs"])
  521. if log.isEnabledFor(logging.DEBUG):
  522. log.debug("from meta: oneway methods=%s", sorted(self._pyroOneway))
  523. log.debug("from meta: methods=%s", sorted(self._pyroMethods))
  524. log.debug("from meta: attributes=%s", sorted(self._pyroAttrs))
  525. if not self._pyroMethods and not self._pyroAttrs:
  526. raise errors.PyroError("remote object doesn't expose any methods or attributes. Did you forget setting @expose on them?")
  527. def _pyroReconnect(self, tries=100000000):
  528. """
  529. (Re)connect the proxy to the daemon containing the pyro object which the proxy is for.
  530. In contrast to the _pyroBind method, this one first releases the connection (if the proxy is still connected)
  531. and retries making a new connection until it succeeds or the given amount of tries ran out.
  532. """
  533. self._pyroRelease()
  534. while tries:
  535. try:
  536. self.__pyroCreateConnection()
  537. return
  538. except errors.CommunicationError:
  539. tries -= 1
  540. if tries:
  541. time.sleep(2)
  542. msg = "failed to reconnect"
  543. log.error(msg)
  544. raise errors.ConnectionClosedError(msg)
  545. def _pyroBatch(self):
  546. """returns a helper class that lets you create batched method calls on the proxy"""
  547. return _BatchProxyAdapter(self)
  548. def _pyroAsync(self):
  549. """returns an async version of the proxy so you can do asynchronous method calls"""
  550. asyncproxy = self.__copy__()
  551. asyncproxy.__async = True
  552. return asyncproxy
  553. def _pyroInvokeBatch(self, calls, oneway=False):
  554. flags = Pyro4.message.FLAGS_BATCH
  555. if oneway:
  556. flags |= Pyro4.message.FLAGS_ONEWAY
  557. return self._pyroInvoke("<batch>", calls, None, flags)
  558. def _pyroAnnotations(self):
  559. """
  560. Returns a dict with annotations to be sent with each message.
  561. Default behavior is to include the correlation id from the current context (if it is set).
  562. If you override this, don't forget to call the original method and add to the dictionary returned from it,
  563. rather than simply returning a new dictionary.
  564. (note that the Message may include an additional hmac annotation at the moment the message is sent)
  565. """
  566. if current_context.correlation_id:
  567. return {"CORR": current_context.correlation_id.bytes}
  568. return {}
  569. def _pyroResponseAnnotations(self, annotations, msgtype):
  570. """
  571. Process any response annotations (dictionary set by the daemon).
  572. Usually this contains the internal Pyro annotations such as hmac and correlation id,
  573. and if you override the annotations method in the daemon, can contain your own annotations as well.
  574. """
  575. pass
  576. def _pyroValidateHandshake(self, response):
  577. """
  578. Process and validate the initial connection handshake response data received from the daemon.
  579. Simply return without error if everything is ok.
  580. Raise an exception if something is wrong and the connection should not be made.
  581. """
  582. return
  583. class _StreamResultIterator(object):
  584. """
  585. Pyro returns this as a result of a remote call which returns an iterator or generator.
  586. It is a normal iterable and produces elements on demand from the remote iterator.
  587. You can simply use it in for loops, list comprehensions etc.
  588. """
  589. def __init__(self, streamId, proxy):
  590. self.streamId = streamId
  591. self.proxy = proxy
  592. def __iter__(self):
  593. return self
  594. def next(self):
  595. # python 2.x support
  596. return self.__next__()
  597. def __next__(self):
  598. if self.proxy._pyroConnection is None:
  599. raise errors.ConnectionClosedError("the proxy for this stream result has been closed")
  600. return self.proxy._pyroInvoke("get_next_stream_item", [self.streamId], {}, objectId=constants.DAEMON_NAME)
  601. def __del__(self):
  602. self.close()
  603. def close(self):
  604. if self.proxy and self.proxy._pyroConnection is not None:
  605. self.proxy._pyroInvoke("close_stream", [self.streamId], {}, flags=message.FLAGS_ONEWAY, objectId=constants.DAEMON_NAME)
  606. self.proxy = None
  607. class _BatchedRemoteMethod(object):
  608. """method call abstraction that is used with batched calls"""
  609. def __init__(self, calls, name):
  610. self.__calls = calls
  611. self.__name = name
  612. def __getattr__(self, name):
  613. return _BatchedRemoteMethod(self.__calls, "%s.%s" % (self.__name, name))
  614. def __call__(self, *args, **kwargs):
  615. self.__calls.append((self.__name, args, kwargs))
  616. class _BatchProxyAdapter(object):
  617. """Helper class that lets you batch multiple method calls into one.
  618. It is constructed with a reference to the normal proxy that will
  619. carry out the batched calls. Call methods on this object that you want to batch,
  620. and finally call the batch proxy itself. That call will return a generator
  621. for the results of every method call in the batch (in sequence)."""
  622. def __init__(self, proxy):
  623. self.__proxy = proxy
  624. self.__calls = []
  625. def __getattr__(self, name):
  626. return _BatchedRemoteMethod(self.__calls, name)
  627. def __enter__(self):
  628. return self
  629. def __exit__(self, *args):
  630. pass
  631. def __copy__(self):
  632. copy = type(self)(self.__proxy)
  633. copy.__calls = list(self.__calls)
  634. return copy
  635. def __resultsgenerator(self, results):
  636. for result in results:
  637. if isinstance(result, Pyro4.futures._ExceptionWrapper):
  638. result.raiseIt() # re-raise the remote exception locally.
  639. else:
  640. yield result # it is a regular result object, yield that and continue.
  641. def __call__(self, oneway=False, async=False):
  642. if oneway and async:
  643. raise errors.PyroError("async oneway calls make no sense")
  644. if async:
  645. return _AsyncRemoteMethod(self, "<asyncbatch>", self.__proxy._pyroMaxRetries)()
  646. else:
  647. results = self.__proxy._pyroInvokeBatch(self.__calls, oneway)
  648. self.__calls = [] # clear for re-use
  649. if not oneway:
  650. return self.__resultsgenerator(results)
  651. def _pyroInvoke(self, name, args, kwargs):
  652. # ignore all parameters, we just need to execute the batch
  653. results = self.__proxy._pyroInvokeBatch(self.__calls)
  654. self.__calls = [] # clear for re-use
  655. return self.__resultsgenerator(results)
  656. class _AsyncRemoteMethod(object):
  657. """async method call abstraction (call will run in a background thread)"""
  658. def __init__(self, proxy, name, max_retries):
  659. self.__proxy = proxy
  660. self.__name = name
  661. self.__max_retries = max_retries
  662. def __getattr__(self, name):
  663. return _AsyncRemoteMethod(self.__proxy, "%s.%s" % (self.__name, name), self.__max_retries)
  664. def __call__(self, *args, **kwargs):
  665. result = Pyro4.futures.FutureResult()
  666. thread = threadutil.Thread(target=self.__asynccall, args=(result, args, kwargs))
  667. thread.setDaemon(True)
  668. thread.start()
  669. return result
  670. def __asynccall(self, asyncresult, args, kwargs):
  671. for attempt in range(self.__max_retries + 1):
  672. try:
  673. # use a copy of the proxy otherwise calls would still be done in sequence,
  674. # and use contextmanager to close the proxy after we're done
  675. with self.__proxy.__copy__() as proxy:
  676. value = proxy._pyroInvoke(self.__name, args, kwargs)
  677. asyncresult.value = value
  678. return
  679. except (errors.ConnectionClosedError, errors.TimeoutError):
  680. # only retry for recoverable network errors
  681. if attempt >= self.__max_retries:
  682. # ignore any exceptions here, return them as part of the async result instead
  683. asyncresult.value = Pyro4.futures._ExceptionWrapper(sys.exc_info()[1])
  684. return
  685. except Exception:
  686. # ignore any exceptions here, return them as part of the async result instead
  687. asyncresult.value = Pyro4.futures._ExceptionWrapper(sys.exc_info()[1])
  688. return
  689. def batch(proxy):
  690. """convenience method to get a batch proxy adapter"""
  691. return proxy._pyroBatch()
  692. def async(proxy):
  693. """convenience method to get an async proxy"""
  694. return proxy._pyroAsync()
  695. def pyroObjectToAutoProxy(obj):
  696. """reduce function that automatically replaces Pyro objects by a Proxy"""
  697. if Pyro4.config.AUTOPROXY:
  698. daemon = getattr(obj, "_pyroDaemon", None)
  699. if daemon:
  700. # only return a proxy if the object is a registered pyro object
  701. return daemon.proxyFor(obj)
  702. return obj
  703. # decorators
  704. def callback(method):
  705. """
  706. decorator to mark a method to be a 'callback'. This will make Pyro
  707. raise any errors also on the callback side, and not only on the side
  708. that does the callback call.
  709. """
  710. method._pyroCallback = True
  711. return method
  712. def oneway(method):
  713. """
  714. decorator to mark a method to be oneway (client won't wait for a response)
  715. """
  716. method._pyroOneway = True
  717. return method
  718. def expose(method_or_class):
  719. """
  720. Decorator to mark a method or class to be exposed for remote calls (relevant when REQUIRE_EXPOSE=True)
  721. You can apply it to a method or a class as a whole.
  722. If you need to change the default instance mode or instance creator, also use a @behavior decorator.
  723. """
  724. if inspect.isdatadescriptor(method_or_class):
  725. func = method_or_class.fget or method_or_class.fset or method_or_class.fdel
  726. if util.is_private_attribute(func.__name__):
  727. raise AttributeError("exposing private names (starting with _) is not allowed")
  728. func._pyroExposed = True
  729. return method_or_class
  730. if util.is_private_attribute(method_or_class.__name__):
  731. raise AttributeError("exposing private names (starting with _) is not allowed")
  732. if inspect.isclass(method_or_class):
  733. clazz = method_or_class
  734. log.debug("exposing all members of %r", clazz)
  735. for name in clazz.__dict__:
  736. if util.is_private_attribute(name):
  737. continue
  738. thing = getattr(clazz, name)
  739. if inspect.isfunction(thing):
  740. thing._pyroExposed = True
  741. elif inspect.ismethod(thing):
  742. thing.__func__._pyroExposed = True
  743. elif inspect.isdatadescriptor(thing):
  744. if getattr(thing, "fset", None):
  745. thing.fset._pyroExposed = True
  746. if getattr(thing, "fget", None):
  747. thing.fget._pyroExposed = True
  748. if getattr(thing, "fdel", None):
  749. thing.fdel._pyroExposed = True
  750. clazz._pyroExposed = True
  751. return clazz
  752. method_or_class._pyroExposed = True
  753. return method_or_class
  754. def behavior(instance_mode="session", instance_creator=None):
  755. """
  756. Decorator to specify the server behavior of your Pyro class.
  757. """
  758. def _behavior(clazz):
  759. if not inspect.isclass(clazz):
  760. raise TypeError("behavior decorator can only be used on a class")
  761. if instance_mode not in ("single", "session", "percall"):
  762. raise ValueError("invalid instance mode: "+instance_mode)
  763. if instance_creator and not callable(instance_creator):
  764. raise TypeError("instance_creator must be a callable")
  765. clazz._pyroInstancing = (instance_mode, instance_creator)
  766. return clazz
  767. if not isinstance(instance_mode, basestring):
  768. raise SyntaxError("behavior decorator is missing argument(s)")
  769. return _behavior
  770. @expose
  771. class DaemonObject(object):
  772. """The part of the daemon that is exposed as a Pyro object."""
  773. def __init__(self, daemon):
  774. self.daemon = daemon
  775. def registered(self):
  776. """returns a list of all object names registered in this daemon"""
  777. return list(self.daemon.objectsById.keys())
  778. def ping(self):
  779. """a simple do-nothing method for testing purposes"""
  780. pass
  781. def info(self):
  782. """return some descriptive information about the daemon"""
  783. return "%s bound on %s, NAT %s, %d objects registered. Servertype: %s" % (
  784. constants.DAEMON_NAME, self.daemon.locationStr, self.daemon.natLocationStr,
  785. len(self.daemon.objectsById), self.daemon.transportServer)
  786. def get_metadata(self, objectId, as_lists=False):
  787. """
  788. Get metadata for the given object (exposed methods, oneways, attributes).
  789. If you get an error in your proxy saying that 'DaemonObject' has no attribute 'get_metdata',
  790. you're probably connecting to an older Pyro version (4.26 or earlier).
  791. Either upgrade the Pyro version or set METDATA config item to False in your client code.
  792. """
  793. obj = self.daemon.objectsById.get(objectId)
  794. if obj is not None:
  795. metadata = util.get_exposed_members(obj, only_exposed=Pyro4.config.REQUIRE_EXPOSE, as_lists=as_lists)
  796. if Pyro4.config.REQUIRE_EXPOSE and not metadata["methods"] and not metadata["attrs"]:
  797. # Something seems wrong: nothing is remotely exposed.
  798. # Possibly because older code not using @expose is now running with a more recent Pyro version
  799. # where @expose is mandatory in the default configuration. Give a hint to the user.
  800. warnings.warn("Class %r doesn't expose any methods or attributes. Did you forget setting @expose on them?" % type(obj))
  801. return metadata
  802. else:
  803. log.debug("unknown object requested: %s", objectId)
  804. raise errors.DaemonError("unknown object")
  805. def get_next_stream_item(self, streamId):
  806. if streamId not in self.daemon.streaming_responses:
  807. raise errors.PyroError("item stream terminated")
  808. client, timestamp, linger_timestamp, stream = self.daemon.streaming_responses[streamId]
  809. if client is None:
  810. # reset client connection association (can be None if proxy disconnected)
  811. self.daemon.streaming_responses[streamId] = (current_context.client, timestamp, 0, stream)
  812. try:
  813. return next(stream)
  814. except Exception:
  815. del self.daemon.streaming_responses[streamId]
  816. raise
  817. def close_stream(self, streamId):
  818. if streamId in self.daemon.streaming_responses:
  819. del self.daemon.streaming_responses[streamId]
  820. class Daemon(object):
  821. """
  822. Pyro daemon. Contains server side logic and dispatches incoming remote method calls
  823. to the appropriate objects.
  824. """
  825. def __init__(self, host=None, port=0, unixsocket=None, nathost=None, natport=None, interface=DaemonObject):
  826. if host is None:
  827. host = Pyro4.config.HOST
  828. if nathost is None:
  829. nathost = Pyro4.config.NATHOST
  830. if natport is None:
  831. natport = Pyro4.config.NATPORT or None
  832. if nathost and unixsocket:
  833. raise ValueError("cannot use nathost together with unixsocket")
  834. if (nathost is None) ^ (natport is None):
  835. raise ValueError("must provide natport with nathost")
  836. if Pyro4.config.SERVERTYPE == "thread":
  837. self.transportServer = SocketServer_Threadpool()
  838. elif Pyro4.config.SERVERTYPE == "multiplex":
  839. self.transportServer = SocketServer_Multiplex()
  840. else:
  841. raise errors.PyroError("invalid server type '%s'" % Pyro4.config.SERVERTYPE)
  842. self.transportServer.init(self, host, port, unixsocket)
  843. #: The location (str of the form ``host:portnumber``) on which the Daemon is listening
  844. self.locationStr = self.transportServer.locationStr
  845. log.debug("created daemon on %s (pid %d)", self.locationStr, os.getpid())
  846. natport_for_loc = natport
  847. if natport == 0:
  848. # 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)
  849. natport_for_loc = int(self.locationStr.split(":")[1])
  850. #: The NAT-location (str of the form ``nathost:natportnumber``) on which the Daemon is exposed for use with NAT-routing
  851. self.natLocationStr = "%s:%d" % (nathost, natport_for_loc) if nathost else None
  852. if self.natLocationStr:
  853. log.debug("NAT address is %s", self.natLocationStr)
  854. pyroObject = interface(self)
  855. pyroObject._pyroId = constants.DAEMON_NAME
  856. #: Dictionary from Pyro object id to the actual Pyro object registered by this id
  857. self.objectsById = {pyroObject._pyroId: pyroObject}
  858. self.__mustshutdown = threadutil.Event()
  859. self.__loopstopped = threadutil.Event()
  860. self.__loopstopped.set()
  861. # assert that the configured serializers are available, and remember their ids:
  862. self.__serializer_ids = {util.get_serializer(ser_name).serializer_id for ser_name in Pyro4.config.SERIALIZERS_ACCEPTED}
  863. log.debug("accepted serializers: %s" % Pyro4.config.SERIALIZERS_ACCEPTED)
  864. log.debug("pyro protocol version: %d pickle version: %d" % (constants.PROTOCOL_VERSION, Pyro4.config.PICKLE_PROTOCOL_VERSION))
  865. self.__pyroHmacKey = None
  866. self._pyroInstances = {} # pyro objects for instance_mode=single (singletons, just one per daemon)
  867. self.streaming_responses = {} # stream_id -> (client, creation_timestamp, linger_timestamp, stream)
  868. self.housekeeper_lock = threadutil.Lock()
  869. @property
  870. def _pyroHmacKey(self):
  871. return self.__pyroHmacKey
  872. @_pyroHmacKey.setter
  873. def _pyroHmacKey(self, value):
  874. # if needed, convert the hmac value to bytes first
  875. if value and sys.version_info >= (3, 0) and type(value) is not bytes:
  876. value = value.encode("utf-8") # convert to bytes
  877. self.__pyroHmacKey = value
  878. @property
  879. def sock(self):
  880. """the server socket used by the daemon"""
  881. return self.transportServer.sock
  882. @property
  883. def sockets(self):
  884. """list of all sockets used by the daemon (server socket and all active client sockets)"""
  885. return self.transportServer.sockets
  886. @property
  887. def selector(self):
  888. """the multiplexing selector used, if using the multiplex server type"""
  889. return self.transportServer.selector
  890. @staticmethod
  891. def serveSimple(objects, host=None, port=0, daemon=None, ns=True, verbose=True):
  892. """
  893. Basic method to fire up a daemon (or supply one yourself).
  894. objects is a dict containing objects to register as keys, and
  895. their names (or None) as values. If ns is true they will be registered
  896. in the naming server as well, otherwise they just stay local.
  897. If you need to publish on a unix domain socket you can't use this shortcut method.
  898. See the documentation on 'publishing objects' (in chapter: Servers) for more details.
  899. """
  900. if daemon is None:
  901. daemon = Daemon(host, port)
  902. with daemon:
  903. if ns:
  904. ns = Pyro4.naming.locateNS()
  905. for obj, name in objects.items():
  906. if ns:
  907. localname = None # name is used for the name server
  908. else:
  909. localname = name # no name server, use name in daemon
  910. uri = daemon.register(obj, localname)
  911. if verbose:
  912. print("Object {0}:\n uri = {1}".format(repr(obj), uri))
  913. if name and ns:
  914. ns.register(name, uri)
  915. if verbose:
  916. print(" name = {0}".format(name))
  917. if verbose:
  918. print("Pyro daemon running.")
  919. daemon.requestLoop()
  920. def requestLoop(self, loopCondition=lambda: True):
  921. """
  922. Goes in a loop to service incoming requests, until someone breaks this
  923. or calls shutdown from another thread.
  924. """
  925. self.__mustshutdown.clear()
  926. log.info("daemon %s entering requestloop", self.locationStr)
  927. try:
  928. self.__loopstopped.clear()
  929. condition = lambda: not self.__mustshutdown.isSet() and loopCondition()
  930. self.transportServer.loop(loopCondition=condition)
  931. finally:
  932. self.__loopstopped.set()
  933. log.debug("daemon exits requestloop")
  934. def events(self, eventsockets):
  935. """for use in an external event loop: handle any requests that are pending for this daemon"""
  936. return self.transportServer.events(eventsockets)
  937. def shutdown(self):
  938. """Cleanly terminate a daemon that is running in the requestloop."""
  939. log.debug("daemon shutting down")
  940. self.streaming_responses = {}
  941. time.sleep(0.02)
  942. self.__mustshutdown.set()
  943. if self.transportServer:
  944. self.transportServer.shutdown()
  945. time.sleep(0.02)
  946. self.close()
  947. self.__loopstopped.wait(timeout=5) # use timeout to avoid deadlock situations
  948. @property
  949. def _shutting_down(self):
  950. return self.__mustshutdown.is_set()
  951. def _handshake(self, conn, denied_reason=None):
  952. """
  953. Perform connection handshake with new clients.
  954. Client sends a MSG_CONNECT message with a serialized data payload.
  955. If all is well, return with a CONNECT_OK message.
  956. The reason we're not doing this with a MSG_INVOKE method call on the daemon
  957. (like when retrieving the metadata) is because we need to force the clients
  958. to get past an initial connect handshake before letting them invoke any method.
  959. Return True for successful handshake, False if something was wrong.
  960. If a denied_reason is given, the handshake will fail with the given reason.
  961. """
  962. serializer_id = message.SERIALIZER_MARSHAL
  963. msg_seq = 0
  964. try:
  965. msg = message.Message.recv(conn, [message.MSG_CONNECT], hmac_key=self._pyroHmacKey)
  966. msg_seq = msg.seq
  967. if denied_reason:
  968. raise Exception(denied_reason)
  969. if Pyro4.config.LOGWIRE:
  970. _log_wiredata(log, "daemon handshake received", msg)
  971. if msg.serializer_id not in self.__serializer_ids:
  972. raise errors.SerializeError("message used serializer that is not accepted: %d" % msg.serializer_id)
  973. if "CORR" in msg.annotations:
  974. current_context.correlation_id = uuid.UUID(bytes=msg.annotations["CORR"])
  975. else:
  976. current_context.correlation_id = uuid.uuid1()
  977. serializer_id = msg.serializer_id
  978. serializer = util.get_serializer_by_id(serializer_id)
  979. data = serializer.deserializeData(msg.data, msg.flags & Pyro4.message.FLAGS_COMPRESSED)
  980. handshake_response = self.validateHandshake(conn, data["handshake"])
  981. if msg.flags & message.FLAGS_META_ON_CONNECT:
  982. # Usually this flag will be enabled, which results in including the object metadata
  983. # in the handshake response. This avoids a separate remote call to get_metadata.
  984. flags = message.FLAGS_META_ON_CONNECT
  985. handshake_response = {
  986. "handshake": handshake_response,
  987. "meta": self.objectsById[constants.DAEMON_NAME].get_metadata(data["object"], as_lists=True)
  988. }
  989. else:
  990. flags = 0
  991. data, compressed = serializer.serializeData(handshake_response, Pyro4.config.COMPRESSION)
  992. msgtype = message.MSG_CONNECTOK
  993. if compressed:
  994. flags |= message.FLAGS_COMPRESSED
  995. except errors.ConnectionClosedError:
  996. log.debug("handshake failed, connection closed early")
  997. return False
  998. except Exception as x:
  999. log.debug("handshake failed, reason:", exc_info=True)
  1000. serializer = util.get_serializer_by_id(serializer_id)
  1001. data, compressed = serializer.serializeData(str(x), False)
  1002. msgtype = message.MSG_CONNECTFAIL
  1003. flags = message.FLAGS_COMPRESSED if compressed else 0
  1004. # We need a minimal amount of response data or the socket will remain blocked
  1005. # on some systems... (messages smaller than 40 bytes)
  1006. msg = message.Message(msgtype, data, serializer_id, flags, msg_seq, annotations=self.annotations(), hmac_key=self._pyroHmacKey)
  1007. if Pyro4.config.LOGWIRE:
  1008. _log_wiredata(log, "daemon handshake response", msg)
  1009. conn.send(msg.to_bytes())
  1010. return msg.type == message.MSG_CONNECTOK
  1011. def validateHandshake(self, conn, data):
  1012. """
  1013. Override this to create a connection validator for new client connections.
  1014. It should return a response data object normally if the connection is okay,
  1015. or should raise an exception if the connection should be denied.
  1016. """
  1017. return "hello"
  1018. def clientDisconnect(self, conn):
  1019. """
  1020. Override this to handle a client disconnect.
  1021. Conn is the SocketConnection object that was disconnected.
  1022. """
  1023. pass
  1024. def handleRequest(self, conn):
  1025. """
  1026. Handle incoming Pyro request. Catches any exception that may occur and
  1027. wraps it in a reply to the calling side, as to not make this server side loop
  1028. terminate due to exceptions caused by remote invocations.
  1029. """
  1030. request_flags = 0
  1031. request_seq = 0
  1032. request_serializer_id = util.MarshalSerializer.serializer_id
  1033. wasBatched = False
  1034. isCallback = False
  1035. try:
  1036. msg = message.Message.recv(conn, [message.MSG_INVOKE, message.MSG_PING], hmac_key=self._pyroHmacKey)
  1037. except errors.CommunicationError as x:
  1038. # we couldn't even get data from the client, this is an immediate error
  1039. # log.info("error receiving data from client %s: %s", conn.sock.getpeername(), x)
  1040. raise x
  1041. try:
  1042. request_flags = msg.flags
  1043. request_seq = msg.seq
  1044. request_serializer_id = msg.serializer_id
  1045. if "CORR" in msg.annotations:
  1046. current_context.correlation_id = uuid.UUID(bytes=msg.annotations["CORR"])
  1047. else:
  1048. current_context.correlation_id = uuid.uuid1()
  1049. if Pyro4.config.LOGWIRE:
  1050. _log_wiredata(log, "daemon wiredata received", msg)
  1051. if msg.type == message.MSG_PING:
  1052. # return same seq, but ignore any data (it's a ping, not an echo). Nothing is deserialized.
  1053. msg = message.Message(message.MSG_PING, b"pong", msg.serializer_id, 0, msg.seq, annotations=self.annotations(), hmac_key=self._pyroHmacKey)
  1054. if Pyro4.config.LOGWIRE:
  1055. _log_wiredata(log, "daemon wiredata sending", msg)
  1056. conn.send(msg.to_bytes())
  1057. return
  1058. if msg.serializer_id not in self.__serializer_ids:
  1059. raise errors.SerializeError("message used serializer that is not accepted: %d" % msg.serializer_id)
  1060. serializer = util.get_serializer_by_id(msg.serializer_id)
  1061. objId, method, vargs, kwargs = serializer.deserializeCall(msg.data, compressed=msg.flags & Pyro4.message.FLAGS_COMPRESSED)
  1062. current_context.client = conn
  1063. current_context.client_sock_addr = conn.sock.getpeername() # store this because on oneway calls the socket will be disconnected
  1064. current_context.seq = msg.seq
  1065. current_context.annotations = msg.annotations
  1066. current_context.msg_flags = msg.flags
  1067. current_context.serializer_id = msg.serializer_id
  1068. del msg # invite GC to collect the object, don't wait for out-of-scope
  1069. obj = self.objectsById.get(objId)
  1070. if obj is not None:
  1071. if inspect.isclass(obj):
  1072. obj = self._getInstance(obj, conn)
  1073. if request_flags & Pyro4.message.FLAGS_BATCH:
  1074. # batched method calls, loop over them all and collect all results
  1075. data = []
  1076. for method, vargs, kwargs in vargs:
  1077. method = util.getAttribute(obj, method)
  1078. try:
  1079. result = method(*vargs, **kwargs) # this is the actual method call to the Pyro object
  1080. except Exception:
  1081. xt, xv = sys.exc_info()[0:2]
  1082. log.debug("Exception occurred while handling batched request: %s", xv)
  1083. xv._pyroTraceback = util.formatTraceback(detailed=Pyro4.config.DETAILED_TRACEBACK)
  1084. if sys.platform == "cli":
  1085. util.fixIronPythonExceptionForPickle(xv, True) # piggyback attributes
  1086. data.append(Pyro4.futures._ExceptionWrapper(xv))
  1087. break # stop processing the rest of the batch
  1088. else:
  1089. data.append(result) # note that we don't support streaming results in batch mode
  1090. wasBatched = True
  1091. else:
  1092. # normal single method call
  1093. if method == "__getattr__":
  1094. # special case for direct attribute access (only exposed @properties are accessible)
  1095. data = util.get_exposed_property_value(obj, vargs[0], only_exposed=Pyro4.config.REQUIRE_EXPOSE)
  1096. elif method == "__setattr__":
  1097. # special case for direct attribute access (only exposed @properties are accessible)
  1098. data = util.set_exposed_property_value(obj, vargs[0], vargs[1], only_exposed=Pyro4.config.REQUIRE_EXPOSE)
  1099. else:
  1100. method = util.getAttribute(obj, method)
  1101. if request_flags & Pyro4.message.FLAGS_ONEWAY and Pyro4.config.ONEWAY_THREADED:
  1102. # oneway call to be run inside its own thread
  1103. _OnewayCallThread(target=method, args=vargs, kwargs=kwargs).start()
  1104. else:
  1105. isCallback = getattr(method, "_pyroCallback", False)
  1106. data = method(*vargs, **kwargs) # this is the actual method call to the Pyro object
  1107. if not request_flags & Pyro4.message.FLAGS_ONEWAY:
  1108. isStream, data = self._streamResponse(data, conn)
  1109. if isStream:
  1110. # throw an exception as well as setting message flags
  1111. # this way, it is backwards compatible with older pyro versions.
  1112. exc = Pyro4.errors.ProtocolError("result of call is an iterator")
  1113. ann = {"STRM": data.encode()} if data else {}
  1114. self._sendExceptionResponse(conn, request_seq, serializer.serializer_id, exc, None,
  1115. annotations=ann, flags=message.FLAGS_ITEMSTREAMRESULT)
  1116. return
  1117. else:
  1118. log.debug("unknown object requested: %s", objId)
  1119. raise errors.DaemonError("unknown object")
  1120. if request_flags & Pyro4.message.FLAGS_ONEWAY:
  1121. return # oneway call, don't send a response
  1122. else:
  1123. data, compressed = serializer.serializeData(data, compress=Pyro4.config.COMPRESSION)
  1124. response_flags = 0
  1125. if compressed:
  1126. response_flags |= Pyro4.message.FLAGS_COMPRESSED
  1127. if wasBatched:
  1128. response_flags |= Pyro4.message.FLAGS_BATCH
  1129. msg = message.Message(message.MSG_RESULT, data, serializer.serializer_id, response_flags, request_seq, annotations=self.annotations(), hmac_key=self._pyroHmacKey)
  1130. if Pyro4.config.LOGWIRE:
  1131. _log_wiredata(log, "daemon wiredata sending", msg)
  1132. conn.send(msg.to_bytes())
  1133. except Exception:
  1134. xt, xv = sys.exc_info()[0:2]
  1135. msg = getattr(xv, "pyroMsg", None)
  1136. if msg:
  1137. request_seq = msg.seq
  1138. request_serializer_id = msg.serializer_id
  1139. if xt is not errors.ConnectionClosedError:
  1140. log.debug("Exception occurred while handling request: %r", xv)
  1141. if not request_flags & Pyro4.message.FLAGS_ONEWAY:
  1142. if isinstance(xv, errors.SerializeError) or not isinstance(xv, errors.CommunicationError):
  1143. # only return the error to the client if it wasn't a oneway call, and not a communication error
  1144. # (in these cases, it makes no sense to try to report the error back to the client...)
  1145. tblines = util.formatTraceback(detailed=Pyro4.config.DETAILED_TRACEBACK)
  1146. self._sendExceptionResponse(conn, request_seq, request_serializer_id, xv, tblines)
  1147. if isCallback or isinstance(xv, (errors.CommunicationError, errors.SecurityError)):
  1148. raise # re-raise if flagged as callback, communication or security error.
  1149. def _clientDisconnect(self, conn):
  1150. if Pyro4.config.ITER_STREAM_LINGER > 0:
  1151. # client goes away, keep streams around for a bit longer (allow reconnect)
  1152. for streamId in list(self.streaming_responses):
  1153. info = self.streaming_responses.get(streamId, None)
  1154. if info and info[0] is conn:
  1155. _, timestamp, _, stream = info
  1156. self.streaming_responses[streamId] = (None, timestamp, time.time(), stream)
  1157. else:
  1158. # client goes away, close any streams it had open as well
  1159. for streamId in list(self.streaming_responses):
  1160. info = self.streaming_responses.get(streamId, None)
  1161. if info and info[0] is conn:
  1162. del self.streaming_responses[streamId]
  1163. self.clientDisconnect(conn) # user overridable hook
  1164. def _housekeeping(self):
  1165. """
  1166. Perform periodical housekeeping actions (cleanups etc)
  1167. """
  1168. if self._shutting_down:
  1169. return
  1170. if not self.streaming_responses:
  1171. return
  1172. with self.housekeeper_lock:
  1173. if Pyro4.config.ITER_STREAM_LIFETIME > 0:
  1174. # cleanup iter streams that are past their lifetime
  1175. for streamId in list(self.streaming_responses.keys()):
  1176. info = self.streaming_responses.get(streamId, None)
  1177. if info:
  1178. last_use_period = time.time() - info[1]
  1179. if 0 < Pyro4.config.ITER_STREAM_LIFETIME < last_use_period:
  1180. del self.streaming_responses[streamId]
  1181. if Pyro4.config.ITER_STREAM_LINGER > 0:
  1182. # cleanup iter streams that are past their linger time
  1183. for streamId in list(self.streaming_responses.keys()):
  1184. info = self.streaming_responses.get(streamId, None)
  1185. if info and info[2]:
  1186. linger_period = time.time() - info[2]
  1187. if linger_period > Pyro4.config.ITER_STREAM_LINGER:
  1188. del self.streaming_responses[streamId]
  1189. def _getInstance(self, clazz, conn):
  1190. """
  1191. Find or create a new instance of the class
  1192. """
  1193. def createInstance(clazz, creator):
  1194. try:
  1195. if creator:
  1196. obj = creator(clazz)
  1197. if isinstance(obj, clazz):
  1198. return obj
  1199. raise TypeError("instance creator returned object of different type")
  1200. return clazz()
  1201. except Exception:
  1202. log.exception("could not create pyro object instance")
  1203. raise
  1204. instance_mode, instance_creator = clazz._pyroInstancing
  1205. if instance_mode == "single":
  1206. # create and use one singleton instance of this class (not a global singleton, just exactly one per daemon)
  1207. instance = self._pyroInstances.get(clazz)
  1208. if not instance:
  1209. log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
  1210. instance = createInstance(clazz, instance_creator)
  1211. self._pyroInstances[clazz] = instance
  1212. return instance
  1213. elif instance_mode == "session":
  1214. # Create and use one instance for this proxy connection
  1215. # the instances are kept on the connection object.
  1216. # (this is the default instance mode when using new style @expose)
  1217. instance = conn.pyroInstances.get(clazz)
  1218. if not instance:
  1219. log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
  1220. instance = createInstance(clazz, instance_creator)
  1221. conn.pyroInstances[clazz] = instance
  1222. return instance
  1223. elif instance_mode == "percall":
  1224. # create and use a new instance just for this call
  1225. log.debug("instancemode %s: creating new pyro object for %s", instance_mode, clazz)
  1226. return createInstance(clazz, instance_creator)
  1227. else:
  1228. raise errors.DaemonError("invalid instancemode in registered class")
  1229. def _sendExceptionResponse(self, connection, seq, serializer_id, exc_value, tbinfo, flags=0, annotations={}):
  1230. """send an exception back including the local traceback info"""
  1231. exc_value._pyroTraceback = tbinfo
  1232. if sys.platform == "cli":
  1233. util.fixIronPythonExceptionForPickle(exc_value, True) # piggyback attributes
  1234. serializer = util.get_serializer_by_id(serializer_id)
  1235. try:
  1236. data, compressed = serializer.serializeData(exc_value)
  1237. except:
  1238. # the exception object couldn't be serialized, use a generic PyroError instead
  1239. xt, xv, tb = sys.exc_info()
  1240. msg = "Error serializing exception: %s. Original exception: %s: %s" % (str(xv), type(exc_value), str(exc_value))
  1241. exc_value = errors.PyroError(msg)
  1242. exc_value._pyroTraceback = tbinfo
  1243. if sys.platform == "cli":
  1244. util.fixIronPythonExceptionForPickle(exc_value, True) # piggyback attributes
  1245. data, compressed = serializer.serializeData(exc_value)
  1246. flags |= Pyro4.message.FLAGS_EXCEPTION
  1247. if compressed:
  1248. flags |= Pyro4.message.FLAGS_COMPRESSED
  1249. ann = self.annotations()
  1250. ann.update(annotations or {})
  1251. msg = message.Message(message.MSG_RESULT, data, serializer.serializer_id, flags, seq, annotations=ann, hmac_key=self._pyroHmacKey)
  1252. if Pyro4.config.LOGWIRE:
  1253. _log_wiredata(log, "daemon wiredata sending (error response)", msg)
  1254. connection.send(msg.to_bytes())
  1255. def register(self, obj_or_class, objectId=None, force=False):
  1256. """
  1257. Register a Pyro object under the given id. Note that this object is now only
  1258. known inside this daemon, it is not automatically available in a name server.
  1259. This method returns a URI for the registered object.
  1260. Pyro checks if an object is already registered, unless you set force=True.
  1261. You can register a class or an object (instance) directly.
  1262. For a class, Pyro will create instances of it to handle the remote calls according
  1263. to the instance_mode (set via @expose on the class). The default there is one object
  1264. per session (=proxy connection). If you register an object directly, Pyro will use
  1265. that single object for *all* remote calls.
  1266. """
  1267. if objectId:
  1268. if not isinstance(objectId, basestring):
  1269. raise TypeError("objectId must be a string or None")
  1270. else:
  1271. objectId = "obj_" + uuid.uuid4().hex # generate a new objectId
  1272. if inspect.isclass(obj_or_class):
  1273. if not hasattr(obj_or_class, "_pyroInstancing"):
  1274. obj_or_class._pyroInstancing = ("session", None)
  1275. if not force:
  1276. if hasattr(obj_or_class, "_pyroId") and obj_or_class._pyroId != "": # check for empty string is needed for Cython
  1277. raise errors.DaemonError("object or class already has a Pyro id")
  1278. if objectId in self.objectsById:
  1279. raise errors.DaemonError("an object or class is already registered with that id")
  1280. # set some pyro attributes
  1281. obj_or_class._pyroId = objectId
  1282. obj_or_class._pyroDaemon = self
  1283. if Pyro4.config.AUTOPROXY:
  1284. # register a custom serializer for the type to automatically return proxies
  1285. # we need to do this for all known serializers
  1286. for ser in util._serializers.values():
  1287. ser.register_type_replacement(type(obj_or_class), pyroObjectToAutoProxy)
  1288. # register the object/class in the mapping
  1289. self.objectsById[obj_or_class._pyroId] = obj_or_class
  1290. return self.uriFor(objectId)
  1291. def unregister(self, objectOrId):
  1292. """
  1293. Remove a class or object from the known objects inside this daemon.
  1294. You can unregister the class/object directly, or with its id.
  1295. """
  1296. if objectOrId is None:
  1297. raise ValueError("object or objectid argument expected")
  1298. if not isinstance(objectOrId, basestring):
  1299. objectId = getattr(objectOrId, "_pyroId", None)
  1300. if objectId is None:
  1301. raise errors.DaemonError("object isn't registered")
  1302. else:
  1303. objectId = objectOrId
  1304. objectOrId = None
  1305. if objectId == constants.DAEMON_NAME:
  1306. return
  1307. if objectId in self.objectsById:
  1308. del self.objectsById[objectId]
  1309. if objectOrId is not None:
  1310. del objectOrId._pyroId
  1311. del objectOrId._pyroDaemon
  1312. # Don't remove the custom type serializer because there may be
  1313. # other registered objects of the same type still depending on it.
  1314. def uriFor(self, objectOrId, nat=True):
  1315. """
  1316. Get a URI for the given object (or object id) from this daemon.
  1317. Only a daemon can hand out proper uris because the access location is
  1318. contained in them.
  1319. Note that unregistered objects cannot be given an uri, but unregistered
  1320. object names can (it's just a string we're creating in that case).
  1321. If nat is set to False, the configured NAT address (if any) is ignored and it will
  1322. return an URI for the internal address.
  1323. """
  1324. if not isinstance(objectOrId, basestring):
  1325. objectOrId = getattr(objectOrId, "_pyroId", None)
  1326. if objectOrId is None or objectOrId not in self.objectsById:
  1327. raise errors.DaemonError("object isn't registered in this daemon")
  1328. if nat:
  1329. loc = self.natLocationStr or self.locationStr
  1330. else:
  1331. loc = self.locationStr
  1332. return URI("PYRO:%s@%s" % (objectOrId, loc))
  1333. def resetMetadataCache(self, objectOrId, nat=True):
  1334. """Reset cache of metadata when a Daemon has available methods/attributes
  1335. dynamically updated. Clients will have to get a new proxy to see changes"""
  1336. uri = self.uriFor(objectOrId, nat)
  1337. # can only be cached if registered, else no-op
  1338. if uri.object in self.objectsById:
  1339. registered_object = self.objectsById[uri.object]
  1340. # Clear cache regardless of how it is accessed
  1341. util.reset_exposed_members(registered_object, Pyro4.config.REQUIRE_EXPOSE, as_lists=True)
  1342. util.reset_exposed_members(registered_object, Pyro4.config.REQUIRE_EXPOSE, as_lists=False)
  1343. def proxyFor(self, objectOrId, nat=True):
  1344. """
  1345. Get a fully initialized Pyro Proxy for the given object (or object id) for this daemon.
  1346. If nat is False, the configured NAT address (if any) is ignored.
  1347. The object or id must be registered in this daemon, or you'll get an exception.
  1348. (you can't get a proxy for an unknown object)
  1349. """
  1350. uri = self.uriFor(objectOrId, nat)
  1351. proxy = Proxy(uri)
  1352. try:
  1353. registered_object = self.objectsById[uri.object]
  1354. except KeyError:
  1355. raise errors.DaemonError("object isn't registered in this daemon")
  1356. meta = util.get_exposed_members(registered_object, only_exposed=Pyro4.config.REQUIRE_EXPOSE)
  1357. proxy._pyroGetMetadata(known_metadata=meta)
  1358. return proxy
  1359. def close(self):
  1360. """Close down the server and release resources"""
  1361. self.__mustshutdown.set()
  1362. self.streaming_responses = {}
  1363. if self.transportServer:
  1364. log.debug("daemon closing")
  1365. self.transportServer.close()
  1366. self.transportServer = None
  1367. def annotations(self):
  1368. """
  1369. Returns a dict with annotations to be sent with each message.
  1370. Default behavior is to include the correlation id from the current context (if it is set).
  1371. If you override this, don't forget to call the original method and add to the dictionary returned from it,
  1372. rather than simply returning a new dictionary.
  1373. """
  1374. if current_context.correlation_id:
  1375. return {"CORR": current_context.correlation_id.bytes}
  1376. return {}
  1377. def combine(self, daemon):
  1378. """
  1379. Combines the event loop of the other daemon in the current daemon's loop.
  1380. You can then simply run the current daemon's requestLoop to serve both daemons.
  1381. This works fine on the multiplex server type, but doesn't work with the threaded server type.
  1382. """
  1383. log.debug("combining event loop with other daemon")
  1384. self.transportServer.combine_loop(daemon.transportServer)
  1385. def __repr__(self):
  1386. return "<%s.%s at 0x%x; %s; %d objects>" % (self.__class__.__module__, self.__class__.__name__,
  1387. id(self), self.locationStr, len(self.objectsById))
  1388. def __enter__(self):
  1389. if not self.transportServer:
  1390. raise errors.PyroError("cannot reuse this object")
  1391. return self
  1392. def __exit__(self, exc_type, exc_value, traceback):
  1393. self.close()
  1394. def __getstate__(self):
  1395. return {} # a little hack to make it possible to serialize Pyro objects, because they can reference a daemon
  1396. def __getstate_for_dict__(self):
  1397. return tuple(self.__getstate__())
  1398. def __setstate_from_dict__(self, state):
  1399. pass
  1400. if sys.version_info < (3, 0):
  1401. __lazy_dict_iterator_types = (type({}.iterkeys()), type({}.itervalues()), type({}.iteritems()))
  1402. else:
  1403. __lazy_dict_iterator_types = (type({}.keys()), type({}.values()), type({}.items()))
  1404. def _streamResponse(self, data, client):
  1405. if isinstance(data, collections.Iterator) or inspect.isgenerator(data):
  1406. if Pyro4.config.ITER_STREAMING:
  1407. if type(data) in self.__lazy_dict_iterator_types:
  1408. raise errors.PyroError("won't serialize or stream lazy dict iterators, convert to list yourself")
  1409. stream_id = str(uuid.uuid4())
  1410. self.streaming_responses[stream_id] = (client, time.time(), 0, data)
  1411. return True, stream_id
  1412. return True, None
  1413. return False, data
  1414. # serpent serializer initialization
  1415. try:
  1416. import serpent
  1417. def pyro_class_serpent_serializer(obj, serializer, stream, level):
  1418. # Override the default way that a Pyro URI/proxy/daemon is serialized.
  1419. # Because it defines a __getstate__ it would otherwise just become a tuple,
  1420. # and not be deserialized as a class.
  1421. d = util.SerializerBase.class_to_dict(obj)
  1422. serializer.ser_builtins_dict(d, stream, level)
  1423. # register the special serializers for the pyro objects with Serpent
  1424. serpent.register_class(URI, pyro_class_serpent_serializer)
  1425. serpent.register_class(Proxy, pyro_class_serpent_serializer)
  1426. serpent.register_class(Daemon, pyro_class_serpent_serializer)
  1427. serpent.register_class(Pyro4.futures._ExceptionWrapper, pyro_class_serpent_serializer)
  1428. except ImportError:
  1429. pass
  1430. def serialize_core_object_to_dict(obj):
  1431. return {
  1432. "__class__": "Pyro4.core." + obj.__class__.__name__,
  1433. "state": obj.__getstate_for_dict__()
  1434. }
  1435. util.SerializerBase.register_class_to_dict(URI, serialize_core_object_to_dict, serpent_too=False)
  1436. util.SerializerBase.register_class_to_dict(Proxy, serialize_core_object_to_dict, serpent_too=False)
  1437. util.SerializerBase.register_class_to_dict(Daemon, serialize_core_object_to_dict, serpent_too=False)
  1438. util.SerializerBase.register_class_to_dict(Pyro4.futures._ExceptionWrapper, Pyro4.futures._ExceptionWrapper.__serialized_dict__, serpent_too=False)
  1439. def _log_wiredata(logger, text, msg):
  1440. """logs all the given properties of the wire message in the given logger"""
  1441. corr = str(uuid.UUID(bytes=msg.annotations["CORR"])) if "CORR" in msg.annotations else "?"
  1442. logger.debug("%s: msgtype=%d flags=0x%x ser=%d seq=%d corr=%s\nannotations=%r\ndata=%r" %
  1443. (text, msg.type, msg.flags, msg.serializer_id, msg.seq, corr, msg.annotations, msg.data))
  1444. class _CallContext(threading.local):
  1445. def __init__(self):
  1446. # per-thread initialization
  1447. self.client = None
  1448. self.client_sock_addr = None
  1449. self.seq = 0
  1450. self.msg_flags = 0
  1451. self.serializer_id = 0
  1452. self.annotations = {}
  1453. self.correlation_id = None
  1454. def to_global(self):
  1455. if sys.platform != "cli":
  1456. return dict(self.__dict__)
  1457. # ironpython somehow has problems getting at the values, so do it manually:
  1458. return {
  1459. "client": self.client,
  1460. "seq": self.seq,
  1461. "msg_flags": self.msg_flags,
  1462. "serializer_id": self.serializer_id,
  1463. "annotations": self.annotations,
  1464. "correlation_id": self.correlation_id,
  1465. "client_sock_addr": self.client_sock_addr
  1466. }
  1467. def from_global(self, values):
  1468. self.client = values["client"]
  1469. self.seq = values["seq"]
  1470. self.msg_flags = values["msg_flags"]
  1471. self.serializer_id = values["serializer_id"]
  1472. self.annotations = values["annotations"]
  1473. self.correlation_id = values["correlation_id"]
  1474. self.client_sock_addr = values["client_sock_addr"]
  1475. class _OnewayCallThread(threadutil.Thread):
  1476. def __init__(self, target, args, kwargs):
  1477. super(_OnewayCallThread, self).__init__(target=target, args=args, kwargs=kwargs, name="oneway-call")
  1478. self.daemon = True
  1479. self.parent_context = current_context.to_global()
  1480. def run(self):
  1481. current_context.from_global(self.parent_context)
  1482. super(_OnewayCallThread, self).run()
  1483. current_context = _CallContext()
  1484. """the context object for the current call. (thread-local)"""