Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

managers.py 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  1. #
  2. # Module providing the `SyncManager` class for dealing
  3. # with shared objects
  4. #
  5. # multiprocessing/managers.py
  6. #
  7. # Copyright (c) 2006-2008, R Oudkerk
  8. # Licensed to PSF under a Contributor Agreement.
  9. #
  10. from __future__ import absolute_import
  11. #
  12. # Imports
  13. #
  14. import sys
  15. import threading
  16. import array
  17. from traceback import format_exc
  18. from . import Process, current_process, active_children, Pool, util, connection
  19. from .five import Queue, items, monotonic
  20. from .process import AuthenticationString
  21. from .forking import exit, Popen
  22. from .reduction import ForkingPickler
  23. from .util import Finalize, error, info
  24. __all__ = ['BaseManager', 'SyncManager', 'BaseProxy', 'Token']
  25. #
  26. # Register some things for pickling
  27. #
  28. def reduce_array(a):
  29. return array.array, (a.typecode, a.tostring())
  30. ForkingPickler.register(array.array, reduce_array)
  31. view_types = [type(getattr({}, name)())
  32. for name in ('items', 'keys', 'values')]
  33. if view_types[0] is not list: # only needed in Py3.0
  34. def rebuild_as_list(obj):
  35. return list, (list(obj), )
  36. for view_type in view_types:
  37. ForkingPickler.register(view_type, rebuild_as_list)
  38. try:
  39. import copyreg
  40. except ImportError:
  41. pass
  42. else:
  43. copyreg.pickle(view_type, rebuild_as_list)
  44. #
  45. # Type for identifying shared objects
  46. #
  47. class Token(object):
  48. '''
  49. Type to uniquely indentify a shared object
  50. '''
  51. __slots__ = ('typeid', 'address', 'id')
  52. def __init__(self, typeid, address, id):
  53. (self.typeid, self.address, self.id) = (typeid, address, id)
  54. def __getstate__(self):
  55. return (self.typeid, self.address, self.id)
  56. def __setstate__(self, state):
  57. (self.typeid, self.address, self.id) = state
  58. def __repr__(self):
  59. return 'Token(typeid=%r, address=%r, id=%r)' % \
  60. (self.typeid, self.address, self.id)
  61. #
  62. # Function for communication with a manager's server process
  63. #
  64. def dispatch(c, id, methodname, args=(), kwds={}):
  65. '''
  66. Send a message to manager using connection `c` and return response
  67. '''
  68. c.send((id, methodname, args, kwds))
  69. kind, result = c.recv()
  70. if kind == '#RETURN':
  71. return result
  72. raise convert_to_error(kind, result)
  73. def convert_to_error(kind, result):
  74. if kind == '#ERROR':
  75. return result
  76. elif kind == '#TRACEBACK':
  77. assert type(result) is str
  78. return RemoteError(result)
  79. elif kind == '#UNSERIALIZABLE':
  80. assert type(result) is str
  81. return RemoteError('Unserializable message: %s\n' % result)
  82. else:
  83. return ValueError('Unrecognized message type')
  84. class RemoteError(Exception):
  85. def __str__(self):
  86. return ('\n' + '-' * 75 + '\n' + str(self.args[0]) + '-' * 75)
  87. #
  88. # Functions for finding the method names of an object
  89. #
  90. def all_methods(obj):
  91. '''
  92. Return a list of names of methods of `obj`
  93. '''
  94. temp = []
  95. for name in dir(obj):
  96. func = getattr(obj, name)
  97. if callable(func):
  98. temp.append(name)
  99. return temp
  100. def public_methods(obj):
  101. '''
  102. Return a list of names of methods of `obj` which do not start with '_'
  103. '''
  104. return [name for name in all_methods(obj) if name[0] != '_']
  105. #
  106. # Server which is run in a process controlled by a manager
  107. #
  108. class Server(object):
  109. '''
  110. Server class which runs in a process controlled by a manager object
  111. '''
  112. public = ['shutdown', 'create', 'accept_connection', 'get_methods',
  113. 'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref']
  114. def __init__(self, registry, address, authkey, serializer):
  115. assert isinstance(authkey, bytes)
  116. self.registry = registry
  117. self.authkey = AuthenticationString(authkey)
  118. Listener, Client = listener_client[serializer]
  119. # do authentication later
  120. self.listener = Listener(address=address, backlog=16)
  121. self.address = self.listener.address
  122. self.id_to_obj = {'0': (None, ())}
  123. self.id_to_refcount = {}
  124. self.mutex = threading.RLock()
  125. self.stop = 0
  126. def serve_forever(self):
  127. '''
  128. Run the server forever
  129. '''
  130. current_process()._manager_server = self
  131. try:
  132. try:
  133. while 1:
  134. try:
  135. c = self.listener.accept()
  136. except (OSError, IOError):
  137. continue
  138. t = threading.Thread(target=self.handle_request, args=(c,))
  139. t.daemon = True
  140. t.start()
  141. except (KeyboardInterrupt, SystemExit):
  142. pass
  143. finally:
  144. self.stop = 999
  145. self.listener.close()
  146. def handle_request(self, c):
  147. '''
  148. Handle a new connection
  149. '''
  150. funcname = result = request = None
  151. try:
  152. connection.deliver_challenge(c, self.authkey)
  153. connection.answer_challenge(c, self.authkey)
  154. request = c.recv()
  155. ignore, funcname, args, kwds = request
  156. assert funcname in self.public, '%r unrecognized' % funcname
  157. func = getattr(self, funcname)
  158. except Exception:
  159. msg = ('#TRACEBACK', format_exc())
  160. else:
  161. try:
  162. result = func(c, *args, **kwds)
  163. except Exception:
  164. msg = ('#TRACEBACK', format_exc())
  165. else:
  166. msg = ('#RETURN', result)
  167. try:
  168. c.send(msg)
  169. except Exception as exc:
  170. try:
  171. c.send(('#TRACEBACK', format_exc()))
  172. except Exception:
  173. pass
  174. info('Failure to send message: %r', msg)
  175. info(' ... request was %r', request)
  176. info(' ... exception was %r', exc)
  177. c.close()
  178. def serve_client(self, conn):
  179. '''
  180. Handle requests from the proxies in a particular process/thread
  181. '''
  182. util.debug('starting server thread to service %r',
  183. threading.currentThread().name)
  184. recv = conn.recv
  185. send = conn.send
  186. id_to_obj = self.id_to_obj
  187. while not self.stop:
  188. try:
  189. methodname = obj = None
  190. request = recv()
  191. ident, methodname, args, kwds = request
  192. obj, exposed, gettypeid = id_to_obj[ident]
  193. if methodname not in exposed:
  194. raise AttributeError(
  195. 'method %r of %r object is not in exposed=%r' % (
  196. methodname, type(obj), exposed)
  197. )
  198. function = getattr(obj, methodname)
  199. try:
  200. res = function(*args, **kwds)
  201. except Exception as exc:
  202. msg = ('#ERROR', exc)
  203. else:
  204. typeid = gettypeid and gettypeid.get(methodname, None)
  205. if typeid:
  206. rident, rexposed = self.create(conn, typeid, res)
  207. token = Token(typeid, self.address, rident)
  208. msg = ('#PROXY', (rexposed, token))
  209. else:
  210. msg = ('#RETURN', res)
  211. except AttributeError:
  212. if methodname is None:
  213. msg = ('#TRACEBACK', format_exc())
  214. else:
  215. try:
  216. fallback_func = self.fallback_mapping[methodname]
  217. result = fallback_func(
  218. self, conn, ident, obj, *args, **kwds
  219. )
  220. msg = ('#RETURN', result)
  221. except Exception:
  222. msg = ('#TRACEBACK', format_exc())
  223. except EOFError:
  224. util.debug('got EOF -- exiting thread serving %r',
  225. threading.currentThread().name)
  226. sys.exit(0)
  227. except Exception:
  228. msg = ('#TRACEBACK', format_exc())
  229. try:
  230. try:
  231. send(msg)
  232. except Exception:
  233. send(('#UNSERIALIZABLE', repr(msg)))
  234. except Exception as exc:
  235. info('exception in thread serving %r',
  236. threading.currentThread().name)
  237. info(' ... message was %r', msg)
  238. info(' ... exception was %r', exc)
  239. conn.close()
  240. sys.exit(1)
  241. def fallback_getvalue(self, conn, ident, obj):
  242. return obj
  243. def fallback_str(self, conn, ident, obj):
  244. return str(obj)
  245. def fallback_repr(self, conn, ident, obj):
  246. return repr(obj)
  247. fallback_mapping = {
  248. '__str__': fallback_str,
  249. '__repr__': fallback_repr,
  250. '#GETVALUE': fallback_getvalue,
  251. }
  252. def dummy(self, c):
  253. pass
  254. def debug_info(self, c):
  255. '''
  256. Return some info --- useful to spot problems with refcounting
  257. '''
  258. with self.mutex:
  259. result = []
  260. keys = list(self.id_to_obj.keys())
  261. keys.sort()
  262. for ident in keys:
  263. if ident != '0':
  264. result.append(' %s: refcount=%s\n %s' %
  265. (ident, self.id_to_refcount[ident],
  266. str(self.id_to_obj[ident][0])[:75]))
  267. return '\n'.join(result)
  268. def number_of_objects(self, c):
  269. '''
  270. Number of shared objects
  271. '''
  272. return len(self.id_to_obj) - 1 # don't count ident='0'
  273. def shutdown(self, c):
  274. '''
  275. Shutdown this process
  276. '''
  277. try:
  278. try:
  279. util.debug('manager received shutdown message')
  280. c.send(('#RETURN', None))
  281. if sys.stdout != sys.__stdout__:
  282. util.debug('resetting stdout, stderr')
  283. sys.stdout = sys.__stdout__
  284. sys.stderr = sys.__stderr__
  285. util._run_finalizers(0)
  286. for p in active_children():
  287. util.debug('terminating a child process of manager')
  288. p.terminate()
  289. for p in active_children():
  290. util.debug('terminating a child process of manager')
  291. p.join()
  292. util._run_finalizers()
  293. info('manager exiting with exitcode 0')
  294. except:
  295. if not error("Error while manager shutdown", exc_info=True):
  296. import traceback
  297. traceback.print_exc()
  298. finally:
  299. exit(0)
  300. def create(self, c, typeid, *args, **kwds):
  301. '''
  302. Create a new shared object and return its id
  303. '''
  304. with self.mutex:
  305. callable, exposed, method_to_typeid, proxytype = \
  306. self.registry[typeid]
  307. if callable is None:
  308. assert len(args) == 1 and not kwds
  309. obj = args[0]
  310. else:
  311. obj = callable(*args, **kwds)
  312. if exposed is None:
  313. exposed = public_methods(obj)
  314. if method_to_typeid is not None:
  315. assert type(method_to_typeid) is dict
  316. exposed = list(exposed) + list(method_to_typeid)
  317. # convert to string because xmlrpclib
  318. # only has 32 bit signed integers
  319. ident = '%x' % id(obj)
  320. util.debug('%r callable returned object with id %r', typeid, ident)
  321. self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid)
  322. if ident not in self.id_to_refcount:
  323. self.id_to_refcount[ident] = 0
  324. # increment the reference count immediately, to avoid
  325. # this object being garbage collected before a Proxy
  326. # object for it can be created. The caller of create()
  327. # is responsible for doing a decref once the Proxy object
  328. # has been created.
  329. self.incref(c, ident)
  330. return ident, tuple(exposed)
  331. def get_methods(self, c, token):
  332. '''
  333. Return the methods of the shared object indicated by token
  334. '''
  335. return tuple(self.id_to_obj[token.id][1])
  336. def accept_connection(self, c, name):
  337. '''
  338. Spawn a new thread to serve this connection
  339. '''
  340. threading.currentThread().name = name
  341. c.send(('#RETURN', None))
  342. self.serve_client(c)
  343. def incref(self, c, ident):
  344. with self.mutex:
  345. self.id_to_refcount[ident] += 1
  346. def decref(self, c, ident):
  347. with self.mutex:
  348. assert self.id_to_refcount[ident] >= 1
  349. self.id_to_refcount[ident] -= 1
  350. if self.id_to_refcount[ident] == 0:
  351. del self.id_to_obj[ident], self.id_to_refcount[ident]
  352. util.debug('disposing of obj with id %r', ident)
  353. #
  354. # Class to represent state of a manager
  355. #
  356. class State(object):
  357. __slots__ = ['value']
  358. INITIAL = 0
  359. STARTED = 1
  360. SHUTDOWN = 2
  361. #
  362. # Mapping from serializer name to Listener and Client types
  363. #
  364. listener_client = {
  365. 'pickle': (connection.Listener, connection.Client),
  366. 'xmlrpclib': (connection.XmlListener, connection.XmlClient),
  367. }
  368. #
  369. # Definition of BaseManager
  370. #
  371. class BaseManager(object):
  372. '''
  373. Base class for managers
  374. '''
  375. _registry = {}
  376. _Server = Server
  377. def __init__(self, address=None, authkey=None, serializer='pickle'):
  378. if authkey is None:
  379. authkey = current_process().authkey
  380. self._address = address # XXX not final address if eg ('', 0)
  381. self._authkey = AuthenticationString(authkey)
  382. self._state = State()
  383. self._state.value = State.INITIAL
  384. self._serializer = serializer
  385. self._Listener, self._Client = listener_client[serializer]
  386. def __reduce__(self):
  387. return (type(self).from_address,
  388. (self._address, self._authkey, self._serializer))
  389. def get_server(self):
  390. '''
  391. Return server object with serve_forever() method and address attribute
  392. '''
  393. assert self._state.value == State.INITIAL
  394. return Server(self._registry, self._address,
  395. self._authkey, self._serializer)
  396. def connect(self):
  397. '''
  398. Connect manager object to the server process
  399. '''
  400. Listener, Client = listener_client[self._serializer]
  401. conn = Client(self._address, authkey=self._authkey)
  402. dispatch(conn, None, 'dummy')
  403. self._state.value = State.STARTED
  404. def start(self, initializer=None, initargs=()):
  405. '''
  406. Spawn a server process for this manager object
  407. '''
  408. assert self._state.value == State.INITIAL
  409. if initializer is not None and not callable(initializer):
  410. raise TypeError('initializer must be a callable')
  411. # pipe over which we will retrieve address of server
  412. reader, writer = connection.Pipe(duplex=False)
  413. # spawn process which runs a server
  414. self._process = Process(
  415. target=type(self)._run_server,
  416. args=(self._registry, self._address, self._authkey,
  417. self._serializer, writer, initializer, initargs),
  418. )
  419. ident = ':'.join(str(i) for i in self._process._identity)
  420. self._process.name = type(self).__name__ + '-' + ident
  421. self._process.start()
  422. # get address of server
  423. writer.close()
  424. self._address = reader.recv()
  425. reader.close()
  426. # register a finalizer
  427. self._state.value = State.STARTED
  428. self.shutdown = Finalize(
  429. self, type(self)._finalize_manager,
  430. args=(self._process, self._address, self._authkey,
  431. self._state, self._Client),
  432. exitpriority=0
  433. )
  434. @classmethod
  435. def _run_server(cls, registry, address, authkey, serializer, writer,
  436. initializer=None, initargs=()):
  437. '''
  438. Create a server, report its address and run it
  439. '''
  440. if initializer is not None:
  441. initializer(*initargs)
  442. # create server
  443. server = cls._Server(registry, address, authkey, serializer)
  444. # inform parent process of the server's address
  445. writer.send(server.address)
  446. writer.close()
  447. # run the manager
  448. info('manager serving at %r', server.address)
  449. server.serve_forever()
  450. def _create(self, typeid, *args, **kwds):
  451. '''
  452. Create a new shared object; return the token and exposed tuple
  453. '''
  454. assert self._state.value == State.STARTED, 'server not yet started'
  455. conn = self._Client(self._address, authkey=self._authkey)
  456. try:
  457. id, exposed = dispatch(conn, None, 'create',
  458. (typeid,) + args, kwds)
  459. finally:
  460. conn.close()
  461. return Token(typeid, self._address, id), exposed
  462. def join(self, timeout=None):
  463. '''
  464. Join the manager process (if it has been spawned)
  465. '''
  466. self._process.join(timeout)
  467. def _debug_info(self):
  468. '''
  469. Return some info about the servers shared objects and connections
  470. '''
  471. conn = self._Client(self._address, authkey=self._authkey)
  472. try:
  473. return dispatch(conn, None, 'debug_info')
  474. finally:
  475. conn.close()
  476. def _number_of_objects(self):
  477. '''
  478. Return the number of shared objects
  479. '''
  480. conn = self._Client(self._address, authkey=self._authkey)
  481. try:
  482. return dispatch(conn, None, 'number_of_objects')
  483. finally:
  484. conn.close()
  485. def __enter__(self):
  486. return self
  487. def __exit__(self, exc_type, exc_val, exc_tb):
  488. self.shutdown()
  489. @staticmethod
  490. def _finalize_manager(process, address, authkey, state, _Client):
  491. '''
  492. Shutdown the manager process; will be registered as a finalizer
  493. '''
  494. if process.is_alive():
  495. info('sending shutdown message to manager')
  496. try:
  497. conn = _Client(address, authkey=authkey)
  498. try:
  499. dispatch(conn, None, 'shutdown')
  500. finally:
  501. conn.close()
  502. except Exception:
  503. pass
  504. process.join(timeout=0.2)
  505. if process.is_alive():
  506. info('manager still alive')
  507. if hasattr(process, 'terminate'):
  508. info('trying to `terminate()` manager process')
  509. process.terminate()
  510. process.join(timeout=0.1)
  511. if process.is_alive():
  512. info('manager still alive after terminate')
  513. state.value = State.SHUTDOWN
  514. try:
  515. del BaseProxy._address_to_local[address]
  516. except KeyError:
  517. pass
  518. address = property(lambda self: self._address)
  519. @classmethod
  520. def register(cls, typeid, callable=None, proxytype=None, exposed=None,
  521. method_to_typeid=None, create_method=True):
  522. '''
  523. Register a typeid with the manager type
  524. '''
  525. if '_registry' not in cls.__dict__:
  526. cls._registry = cls._registry.copy()
  527. if proxytype is None:
  528. proxytype = AutoProxy
  529. exposed = exposed or getattr(proxytype, '_exposed_', None)
  530. method_to_typeid = (
  531. method_to_typeid or
  532. getattr(proxytype, '_method_to_typeid_', None)
  533. )
  534. if method_to_typeid:
  535. for key, value in items(method_to_typeid):
  536. assert type(key) is str, '%r is not a string' % key
  537. assert type(value) is str, '%r is not a string' % value
  538. cls._registry[typeid] = (
  539. callable, exposed, method_to_typeid, proxytype
  540. )
  541. if create_method:
  542. def temp(self, *args, **kwds):
  543. util.debug('requesting creation of a shared %r object', typeid)
  544. token, exp = self._create(typeid, *args, **kwds)
  545. proxy = proxytype(
  546. token, self._serializer, manager=self,
  547. authkey=self._authkey, exposed=exp
  548. )
  549. conn = self._Client(token.address, authkey=self._authkey)
  550. dispatch(conn, None, 'decref', (token.id,))
  551. return proxy
  552. temp.__name__ = typeid
  553. setattr(cls, typeid, temp)
  554. #
  555. # Subclass of set which get cleared after a fork
  556. #
  557. class ProcessLocalSet(set):
  558. def __init__(self):
  559. util.register_after_fork(self, lambda obj: obj.clear())
  560. def __reduce__(self):
  561. return type(self), ()
  562. #
  563. # Definition of BaseProxy
  564. #
  565. class BaseProxy(object):
  566. '''
  567. A base for proxies of shared objects
  568. '''
  569. _address_to_local = {}
  570. _mutex = util.ForkAwareThreadLock()
  571. def __init__(self, token, serializer, manager=None,
  572. authkey=None, exposed=None, incref=True):
  573. BaseProxy._mutex.acquire()
  574. try:
  575. tls_idset = BaseProxy._address_to_local.get(token.address, None)
  576. if tls_idset is None:
  577. tls_idset = util.ForkAwareLocal(), ProcessLocalSet()
  578. BaseProxy._address_to_local[token.address] = tls_idset
  579. finally:
  580. BaseProxy._mutex.release()
  581. # self._tls is used to record the connection used by this
  582. # thread to communicate with the manager at token.address
  583. self._tls = tls_idset[0]
  584. # self._idset is used to record the identities of all shared
  585. # objects for which the current process owns references and
  586. # which are in the manager at token.address
  587. self._idset = tls_idset[1]
  588. self._token = token
  589. self._id = self._token.id
  590. self._manager = manager
  591. self._serializer = serializer
  592. self._Client = listener_client[serializer][1]
  593. if authkey is not None:
  594. self._authkey = AuthenticationString(authkey)
  595. elif self._manager is not None:
  596. self._authkey = self._manager._authkey
  597. else:
  598. self._authkey = current_process().authkey
  599. if incref:
  600. self._incref()
  601. util.register_after_fork(self, BaseProxy._after_fork)
  602. def _connect(self):
  603. util.debug('making connection to manager')
  604. name = current_process().name
  605. if threading.currentThread().name != 'MainThread':
  606. name += '|' + threading.currentThread().name
  607. conn = self._Client(self._token.address, authkey=self._authkey)
  608. dispatch(conn, None, 'accept_connection', (name,))
  609. self._tls.connection = conn
  610. def _callmethod(self, methodname, args=(), kwds={}):
  611. '''
  612. Try to call a method of the referrent and return a copy of the result
  613. '''
  614. try:
  615. conn = self._tls.connection
  616. except AttributeError:
  617. util.debug('thread %r does not own a connection',
  618. threading.currentThread().name)
  619. self._connect()
  620. conn = self._tls.connection
  621. conn.send((self._id, methodname, args, kwds))
  622. kind, result = conn.recv()
  623. if kind == '#RETURN':
  624. return result
  625. elif kind == '#PROXY':
  626. exposed, token = result
  627. proxytype = self._manager._registry[token.typeid][-1]
  628. proxy = proxytype(
  629. token, self._serializer, manager=self._manager,
  630. authkey=self._authkey, exposed=exposed
  631. )
  632. conn = self._Client(token.address, authkey=self._authkey)
  633. dispatch(conn, None, 'decref', (token.id,))
  634. return proxy
  635. raise convert_to_error(kind, result)
  636. def _getvalue(self):
  637. '''
  638. Get a copy of the value of the referent
  639. '''
  640. return self._callmethod('#GETVALUE')
  641. def _incref(self):
  642. conn = self._Client(self._token.address, authkey=self._authkey)
  643. dispatch(conn, None, 'incref', (self._id,))
  644. util.debug('INCREF %r', self._token.id)
  645. self._idset.add(self._id)
  646. state = self._manager and self._manager._state
  647. self._close = Finalize(
  648. self, BaseProxy._decref,
  649. args=(self._token, self._authkey, state,
  650. self._tls, self._idset, self._Client),
  651. exitpriority=10
  652. )
  653. @staticmethod
  654. def _decref(token, authkey, state, tls, idset, _Client):
  655. idset.discard(token.id)
  656. # check whether manager is still alive
  657. if state is None or state.value == State.STARTED:
  658. # tell manager this process no longer cares about referent
  659. try:
  660. util.debug('DECREF %r', token.id)
  661. conn = _Client(token.address, authkey=authkey)
  662. dispatch(conn, None, 'decref', (token.id,))
  663. except Exception as exc:
  664. util.debug('... decref failed %s', exc)
  665. else:
  666. util.debug('DECREF %r -- manager already shutdown', token.id)
  667. # check whether we can close this thread's connection because
  668. # the process owns no more references to objects for this manager
  669. if not idset and hasattr(tls, 'connection'):
  670. util.debug('thread %r has no more proxies so closing conn',
  671. threading.currentThread().name)
  672. tls.connection.close()
  673. del tls.connection
  674. def _after_fork(self):
  675. self._manager = None
  676. try:
  677. self._incref()
  678. except Exception as exc:
  679. # the proxy may just be for a manager which has shutdown
  680. info('incref failed: %s', exc)
  681. def __reduce__(self):
  682. kwds = {}
  683. if Popen.thread_is_spawning():
  684. kwds['authkey'] = self._authkey
  685. if getattr(self, '_isauto', False):
  686. kwds['exposed'] = self._exposed_
  687. return (RebuildProxy,
  688. (AutoProxy, self._token, self._serializer, kwds))
  689. else:
  690. return (RebuildProxy,
  691. (type(self), self._token, self._serializer, kwds))
  692. def __deepcopy__(self, memo):
  693. return self._getvalue()
  694. def __repr__(self):
  695. return '<%s object, typeid %r at %s>' % \
  696. (type(self).__name__, self._token.typeid, '0x%x' % id(self))
  697. def __str__(self):
  698. '''
  699. Return representation of the referent (or a fall-back if that fails)
  700. '''
  701. try:
  702. return self._callmethod('__repr__')
  703. except Exception:
  704. return repr(self)[:-1] + "; '__str__()' failed>"
  705. #
  706. # Function used for unpickling
  707. #
  708. def RebuildProxy(func, token, serializer, kwds):
  709. '''
  710. Function used for unpickling proxy objects.
  711. If possible the shared object is returned, or otherwise a proxy for it.
  712. '''
  713. server = getattr(current_process(), '_manager_server', None)
  714. if server and server.address == token.address:
  715. return server.id_to_obj[token.id][0]
  716. else:
  717. incref = (
  718. kwds.pop('incref', True) and
  719. not getattr(current_process(), '_inheriting', False)
  720. )
  721. return func(token, serializer, incref=incref, **kwds)
  722. #
  723. # Functions to create proxies and proxy types
  724. #
  725. def MakeProxyType(name, exposed, _cache={}):
  726. '''
  727. Return an proxy type whose methods are given by `exposed`
  728. '''
  729. exposed = tuple(exposed)
  730. try:
  731. return _cache[(name, exposed)]
  732. except KeyError:
  733. pass
  734. dic = {}
  735. for meth in exposed:
  736. exec('''def %s(self, *args, **kwds):
  737. return self._callmethod(%r, args, kwds)''' % (meth, meth), dic)
  738. ProxyType = type(name, (BaseProxy,), dic)
  739. ProxyType._exposed_ = exposed
  740. _cache[(name, exposed)] = ProxyType
  741. return ProxyType
  742. def AutoProxy(token, serializer, manager=None, authkey=None,
  743. exposed=None, incref=True):
  744. '''
  745. Return an auto-proxy for `token`
  746. '''
  747. _Client = listener_client[serializer][1]
  748. if exposed is None:
  749. conn = _Client(token.address, authkey=authkey)
  750. try:
  751. exposed = dispatch(conn, None, 'get_methods', (token,))
  752. finally:
  753. conn.close()
  754. if authkey is None and manager is not None:
  755. authkey = manager._authkey
  756. if authkey is None:
  757. authkey = current_process().authkey
  758. ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed)
  759. proxy = ProxyType(token, serializer, manager=manager, authkey=authkey,
  760. incref=incref)
  761. proxy._isauto = True
  762. return proxy
  763. #
  764. # Types/callables which we will register with SyncManager
  765. #
  766. class Namespace(object):
  767. def __init__(self, **kwds):
  768. self.__dict__.update(kwds)
  769. def __repr__(self):
  770. items = list(self.__dict__.items())
  771. temp = []
  772. for name, value in items:
  773. if not name.startswith('_'):
  774. temp.append('%s=%r' % (name, value))
  775. temp.sort()
  776. return 'Namespace(%s)' % str.join(', ', temp)
  777. class Value(object):
  778. def __init__(self, typecode, value, lock=True):
  779. self._typecode = typecode
  780. self._value = value
  781. def get(self):
  782. return self._value
  783. def set(self, value):
  784. self._value = value
  785. def __repr__(self):
  786. return '%s(%r, %r)' % (type(self).__name__,
  787. self._typecode, self._value)
  788. value = property(get, set)
  789. def Array(typecode, sequence, lock=True):
  790. return array.array(typecode, sequence)
  791. #
  792. # Proxy types used by SyncManager
  793. #
  794. class IteratorProxy(BaseProxy):
  795. if sys.version_info[0] == 3:
  796. _exposed = ('__next__', 'send', 'throw', 'close')
  797. else:
  798. _exposed_ = ('__next__', 'next', 'send', 'throw', 'close')
  799. def next(self, *args):
  800. return self._callmethod('next', args)
  801. def __iter__(self):
  802. return self
  803. def __next__(self, *args):
  804. return self._callmethod('__next__', args)
  805. def send(self, *args):
  806. return self._callmethod('send', args)
  807. def throw(self, *args):
  808. return self._callmethod('throw', args)
  809. def close(self, *args):
  810. return self._callmethod('close', args)
  811. class AcquirerProxy(BaseProxy):
  812. _exposed_ = ('acquire', 'release')
  813. def acquire(self, blocking=True):
  814. return self._callmethod('acquire', (blocking,))
  815. def release(self):
  816. return self._callmethod('release')
  817. def __enter__(self):
  818. return self._callmethod('acquire')
  819. def __exit__(self, exc_type, exc_val, exc_tb):
  820. return self._callmethod('release')
  821. class ConditionProxy(AcquirerProxy):
  822. _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all')
  823. def wait(self, timeout=None):
  824. return self._callmethod('wait', (timeout,))
  825. def notify(self):
  826. return self._callmethod('notify')
  827. def notify_all(self):
  828. return self._callmethod('notify_all')
  829. def wait_for(self, predicate, timeout=None):
  830. result = predicate()
  831. if result:
  832. return result
  833. if timeout is not None:
  834. endtime = monotonic() + timeout
  835. else:
  836. endtime = None
  837. waittime = None
  838. while not result:
  839. if endtime is not None:
  840. waittime = endtime - monotonic()
  841. if waittime <= 0:
  842. break
  843. self.wait(waittime)
  844. result = predicate()
  845. return result
  846. class EventProxy(BaseProxy):
  847. _exposed_ = ('is_set', 'set', 'clear', 'wait')
  848. def is_set(self):
  849. return self._callmethod('is_set')
  850. def set(self):
  851. return self._callmethod('set')
  852. def clear(self):
  853. return self._callmethod('clear')
  854. def wait(self, timeout=None):
  855. return self._callmethod('wait', (timeout,))
  856. class NamespaceProxy(BaseProxy):
  857. _exposed_ = ('__getattribute__', '__setattr__', '__delattr__')
  858. def __getattr__(self, key):
  859. if key[0] == '_':
  860. return object.__getattribute__(self, key)
  861. callmethod = object.__getattribute__(self, '_callmethod')
  862. return callmethod('__getattribute__', (key,))
  863. def __setattr__(self, key, value):
  864. if key[0] == '_':
  865. return object.__setattr__(self, key, value)
  866. callmethod = object.__getattribute__(self, '_callmethod')
  867. return callmethod('__setattr__', (key, value))
  868. def __delattr__(self, key):
  869. if key[0] == '_':
  870. return object.__delattr__(self, key)
  871. callmethod = object.__getattribute__(self, '_callmethod')
  872. return callmethod('__delattr__', (key,))
  873. class ValueProxy(BaseProxy):
  874. _exposed_ = ('get', 'set')
  875. def get(self):
  876. return self._callmethod('get')
  877. def set(self, value):
  878. return self._callmethod('set', (value,))
  879. value = property(get, set)
  880. BaseListProxy = MakeProxyType('BaseListProxy', (
  881. '__add__', '__contains__', '__delitem__', '__delslice__',
  882. '__getitem__', '__getslice__', '__len__', '__mul__',
  883. '__reversed__', '__rmul__', '__setitem__', '__setslice__',
  884. 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
  885. 'reverse', 'sort', '__imul__',
  886. )) # XXX __getslice__ and __setslice__ unneeded in Py3.0
  887. class ListProxy(BaseListProxy):
  888. def __iadd__(self, value):
  889. self._callmethod('extend', (value,))
  890. return self
  891. def __imul__(self, value):
  892. self._callmethod('__imul__', (value,))
  893. return self
  894. DictProxy = MakeProxyType('DictProxy', (
  895. '__contains__', '__delitem__', '__getitem__', '__len__',
  896. '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items',
  897. 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values',
  898. ))
  899. ArrayProxy = MakeProxyType('ArrayProxy', (
  900. '__len__', '__getitem__', '__setitem__', '__getslice__', '__setslice__',
  901. )) # XXX __getslice__ and __setslice__ unneeded in Py3.0
  902. PoolProxy = MakeProxyType('PoolProxy', (
  903. 'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join',
  904. 'map', 'map_async', 'starmap', 'starmap_async', 'terminate',
  905. ))
  906. PoolProxy._method_to_typeid_ = {
  907. 'apply_async': 'AsyncResult',
  908. 'map_async': 'AsyncResult',
  909. 'starmap_async': 'AsyncResult',
  910. 'imap': 'Iterator',
  911. 'imap_unordered': 'Iterator',
  912. }
  913. #
  914. # Definition of SyncManager
  915. #
  916. class SyncManager(BaseManager):
  917. '''
  918. Subclass of `BaseManager` which supports a number of shared object types.
  919. The types registered are those intended for the synchronization
  920. of threads, plus `dict`, `list` and `Namespace`.
  921. The `billiard.Manager()` function creates started instances of
  922. this class.
  923. '''
  924. SyncManager.register('Queue', Queue)
  925. SyncManager.register('JoinableQueue', Queue)
  926. SyncManager.register('Event', threading.Event, EventProxy)
  927. SyncManager.register('Lock', threading.Lock, AcquirerProxy)
  928. SyncManager.register('RLock', threading.RLock, AcquirerProxy)
  929. SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy)
  930. SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore,
  931. AcquirerProxy)
  932. SyncManager.register('Condition', threading.Condition, ConditionProxy)
  933. SyncManager.register('Pool', Pool, PoolProxy)
  934. SyncManager.register('list', list, ListProxy)
  935. SyncManager.register('dict', dict, DictProxy)
  936. SyncManager.register('Value', Value, ValueProxy)
  937. SyncManager.register('Array', Array, ArrayProxy)
  938. SyncManager.register('Namespace', Namespace, NamespaceProxy)
  939. # types returned by methods of PoolProxy
  940. SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False)
  941. SyncManager.register('AsyncResult', create_method=False)