core.py 96 KB

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