managers.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. #
  2. # Module providing manager classes 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. __all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ]
  11. #
  12. # Imports
  13. #
  14. import sys
  15. import threading
  16. import signal
  17. import array
  18. import queue
  19. import time
  20. import types
  21. import os
  22. from os import getpid
  23. from traceback import format_exc
  24. from . import connection
  25. from .context import reduction, get_spawning_popen, ProcessError
  26. from . import pool
  27. from . import process
  28. from . import util
  29. from . import get_context
  30. try:
  31. from . import shared_memory
  32. except ImportError:
  33. HAS_SHMEM = False
  34. else:
  35. HAS_SHMEM = True
  36. __all__.append('SharedMemoryManager')
  37. #
  38. # Register some things for pickling
  39. #
  40. def reduce_array(a):
  41. return array.array, (a.typecode, a.tobytes())
  42. reduction.register(array.array, reduce_array)
  43. view_types = [type(getattr({}, name)()) for name in ('items','keys','values')]
  44. if view_types[0] is not list: # only needed in Py3.0
  45. def rebuild_as_list(obj):
  46. return list, (list(obj),)
  47. for view_type in view_types:
  48. reduction.register(view_type, rebuild_as_list)
  49. #
  50. # Type for identifying shared objects
  51. #
  52. class Token(object):
  53. '''
  54. Type to uniquely identify a shared object
  55. '''
  56. __slots__ = ('typeid', 'address', 'id')
  57. def __init__(self, typeid, address, id):
  58. (self.typeid, self.address, self.id) = (typeid, address, id)
  59. def __getstate__(self):
  60. return (self.typeid, self.address, self.id)
  61. def __setstate__(self, state):
  62. (self.typeid, self.address, self.id) = state
  63. def __repr__(self):
  64. return '%s(typeid=%r, address=%r, id=%r)' % \
  65. (self.__class__.__name__, self.typeid, self.address, self.id)
  66. #
  67. # Function for communication with a manager's server process
  68. #
  69. def dispatch(c, id, methodname, args=(), kwds={}):
  70. '''
  71. Send a message to manager using connection `c` and return response
  72. '''
  73. c.send((id, methodname, args, kwds))
  74. kind, result = c.recv()
  75. if kind == '#RETURN':
  76. return result
  77. raise convert_to_error(kind, result)
  78. def convert_to_error(kind, result):
  79. if kind == '#ERROR':
  80. return result
  81. elif kind in ('#TRACEBACK', '#UNSERIALIZABLE'):
  82. if not isinstance(result, str):
  83. raise TypeError(
  84. "Result {0!r} (kind '{1}') type is {2}, not str".format(
  85. result, kind, type(result)))
  86. if kind == '#UNSERIALIZABLE':
  87. return RemoteError('Unserializable message: %s\n' % result)
  88. else:
  89. return RemoteError(result)
  90. else:
  91. return ValueError('Unrecognized message type {!r}'.format(kind))
  92. class RemoteError(Exception):
  93. def __str__(self):
  94. return ('\n' + '-'*75 + '\n' + str(self.args[0]) + '-'*75)
  95. #
  96. # Functions for finding the method names of an object
  97. #
  98. def all_methods(obj):
  99. '''
  100. Return a list of names of methods of `obj`
  101. '''
  102. temp = []
  103. for name in dir(obj):
  104. func = getattr(obj, name)
  105. if callable(func):
  106. temp.append(name)
  107. return temp
  108. def public_methods(obj):
  109. '''
  110. Return a list of names of methods of `obj` which do not start with '_'
  111. '''
  112. return [name for name in all_methods(obj) if name[0] != '_']
  113. #
  114. # Server which is run in a process controlled by a manager
  115. #
  116. class Server(object):
  117. '''
  118. Server class which runs in a process controlled by a manager object
  119. '''
  120. public = ['shutdown', 'create', 'accept_connection', 'get_methods',
  121. 'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref']
  122. def __init__(self, registry, address, authkey, serializer):
  123. if not isinstance(authkey, bytes):
  124. raise TypeError(
  125. "Authkey {0!r} is type {1!s}, not bytes".format(
  126. authkey, type(authkey)))
  127. self.registry = registry
  128. self.authkey = process.AuthenticationString(authkey)
  129. Listener, Client = listener_client[serializer]
  130. # do authentication later
  131. self.listener = Listener(address=address, backlog=16)
  132. self.address = self.listener.address
  133. self.id_to_obj = {'0': (None, ())}
  134. self.id_to_refcount = {}
  135. self.id_to_local_proxy_obj = {}
  136. self.mutex = threading.Lock()
  137. def serve_forever(self):
  138. '''
  139. Run the server forever
  140. '''
  141. self.stop_event = threading.Event()
  142. process.current_process()._manager_server = self
  143. try:
  144. accepter = threading.Thread(target=self.accepter)
  145. accepter.daemon = True
  146. accepter.start()
  147. try:
  148. while not self.stop_event.is_set():
  149. self.stop_event.wait(1)
  150. except (KeyboardInterrupt, SystemExit):
  151. pass
  152. finally:
  153. if sys.stdout != sys.__stdout__: # what about stderr?
  154. util.debug('resetting stdout, stderr')
  155. sys.stdout = sys.__stdout__
  156. sys.stderr = sys.__stderr__
  157. sys.exit(0)
  158. def accepter(self):
  159. while True:
  160. try:
  161. c = self.listener.accept()
  162. except OSError:
  163. continue
  164. t = threading.Thread(target=self.handle_request, args=(c,))
  165. t.daemon = True
  166. t.start()
  167. def handle_request(self, c):
  168. '''
  169. Handle a new connection
  170. '''
  171. funcname = result = request = None
  172. try:
  173. connection.deliver_challenge(c, self.authkey)
  174. connection.answer_challenge(c, self.authkey)
  175. request = c.recv()
  176. ignore, funcname, args, kwds = request
  177. assert funcname in self.public, '%r unrecognized' % funcname
  178. func = getattr(self, funcname)
  179. except Exception:
  180. msg = ('#TRACEBACK', format_exc())
  181. else:
  182. try:
  183. result = func(c, *args, **kwds)
  184. except Exception:
  185. msg = ('#TRACEBACK', format_exc())
  186. else:
  187. msg = ('#RETURN', result)
  188. try:
  189. c.send(msg)
  190. except Exception as e:
  191. try:
  192. c.send(('#TRACEBACK', format_exc()))
  193. except Exception:
  194. pass
  195. util.info('Failure to send message: %r', msg)
  196. util.info(' ... request was %r', request)
  197. util.info(' ... exception was %r', e)
  198. c.close()
  199. def serve_client(self, conn):
  200. '''
  201. Handle requests from the proxies in a particular process/thread
  202. '''
  203. util.debug('starting server thread to service %r',
  204. threading.current_thread().name)
  205. recv = conn.recv
  206. send = conn.send
  207. id_to_obj = self.id_to_obj
  208. while not self.stop_event.is_set():
  209. try:
  210. methodname = obj = None
  211. request = recv()
  212. ident, methodname, args, kwds = request
  213. try:
  214. obj, exposed, gettypeid = id_to_obj[ident]
  215. except KeyError as ke:
  216. try:
  217. obj, exposed, gettypeid = \
  218. self.id_to_local_proxy_obj[ident]
  219. except KeyError:
  220. raise ke
  221. if methodname not in exposed:
  222. raise AttributeError(
  223. 'method %r of %r object is not in exposed=%r' %
  224. (methodname, type(obj), exposed)
  225. )
  226. function = getattr(obj, methodname)
  227. try:
  228. res = function(*args, **kwds)
  229. except Exception as e:
  230. msg = ('#ERROR', e)
  231. else:
  232. typeid = gettypeid and gettypeid.get(methodname, None)
  233. if typeid:
  234. rident, rexposed = self.create(conn, typeid, res)
  235. token = Token(typeid, self.address, rident)
  236. msg = ('#PROXY', (rexposed, token))
  237. else:
  238. msg = ('#RETURN', res)
  239. except AttributeError:
  240. if methodname is None:
  241. msg = ('#TRACEBACK', format_exc())
  242. else:
  243. try:
  244. fallback_func = self.fallback_mapping[methodname]
  245. result = fallback_func(
  246. self, conn, ident, obj, *args, **kwds
  247. )
  248. msg = ('#RETURN', result)
  249. except Exception:
  250. msg = ('#TRACEBACK', format_exc())
  251. except EOFError:
  252. util.debug('got EOF -- exiting thread serving %r',
  253. threading.current_thread().name)
  254. sys.exit(0)
  255. except Exception:
  256. msg = ('#TRACEBACK', format_exc())
  257. try:
  258. try:
  259. send(msg)
  260. except Exception:
  261. send(('#UNSERIALIZABLE', format_exc()))
  262. except Exception as e:
  263. util.info('exception in thread serving %r',
  264. threading.current_thread().name)
  265. util.info(' ... message was %r', msg)
  266. util.info(' ... exception was %r', e)
  267. conn.close()
  268. sys.exit(1)
  269. def fallback_getvalue(self, conn, ident, obj):
  270. return obj
  271. def fallback_str(self, conn, ident, obj):
  272. return str(obj)
  273. def fallback_repr(self, conn, ident, obj):
  274. return repr(obj)
  275. fallback_mapping = {
  276. '__str__':fallback_str,
  277. '__repr__':fallback_repr,
  278. '#GETVALUE':fallback_getvalue
  279. }
  280. def dummy(self, c):
  281. pass
  282. def debug_info(self, c):
  283. '''
  284. Return some info --- useful to spot problems with refcounting
  285. '''
  286. # Perhaps include debug info about 'c'?
  287. with self.mutex:
  288. result = []
  289. keys = list(self.id_to_refcount.keys())
  290. keys.sort()
  291. for ident in keys:
  292. if ident != '0':
  293. result.append(' %s: refcount=%s\n %s' %
  294. (ident, self.id_to_refcount[ident],
  295. str(self.id_to_obj[ident][0])[:75]))
  296. return '\n'.join(result)
  297. def number_of_objects(self, c):
  298. '''
  299. Number of shared objects
  300. '''
  301. # Doesn't use (len(self.id_to_obj) - 1) as we shouldn't count ident='0'
  302. return len(self.id_to_refcount)
  303. def shutdown(self, c):
  304. '''
  305. Shutdown this process
  306. '''
  307. try:
  308. util.debug('manager received shutdown message')
  309. c.send(('#RETURN', None))
  310. except:
  311. import traceback
  312. traceback.print_exc()
  313. finally:
  314. self.stop_event.set()
  315. def create(self, c, typeid, /, *args, **kwds):
  316. '''
  317. Create a new shared object and return its id
  318. '''
  319. with self.mutex:
  320. callable, exposed, method_to_typeid, proxytype = \
  321. self.registry[typeid]
  322. if callable is None:
  323. if kwds or (len(args) != 1):
  324. raise ValueError(
  325. "Without callable, must have one non-keyword argument")
  326. obj = args[0]
  327. else:
  328. obj = callable(*args, **kwds)
  329. if exposed is None:
  330. exposed = public_methods(obj)
  331. if method_to_typeid is not None:
  332. if not isinstance(method_to_typeid, dict):
  333. raise TypeError(
  334. "Method_to_typeid {0!r}: type {1!s}, not dict".format(
  335. method_to_typeid, type(method_to_typeid)))
  336. exposed = list(exposed) + list(method_to_typeid)
  337. ident = '%x' % id(obj) # convert to string because xmlrpclib
  338. # only has 32 bit signed integers
  339. util.debug('%r callable returned object with id %r', typeid, ident)
  340. self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid)
  341. if ident not in self.id_to_refcount:
  342. self.id_to_refcount[ident] = 0
  343. self.incref(c, ident)
  344. return ident, tuple(exposed)
  345. def get_methods(self, c, token):
  346. '''
  347. Return the methods of the shared object indicated by token
  348. '''
  349. return tuple(self.id_to_obj[token.id][1])
  350. def accept_connection(self, c, name):
  351. '''
  352. Spawn a new thread to serve this connection
  353. '''
  354. threading.current_thread().name = name
  355. c.send(('#RETURN', None))
  356. self.serve_client(c)
  357. def incref(self, c, ident):
  358. with self.mutex:
  359. try:
  360. self.id_to_refcount[ident] += 1
  361. except KeyError as ke:
  362. # If no external references exist but an internal (to the
  363. # manager) still does and a new external reference is created
  364. # from it, restore the manager's tracking of it from the
  365. # previously stashed internal ref.
  366. if ident in self.id_to_local_proxy_obj:
  367. self.id_to_refcount[ident] = 1
  368. self.id_to_obj[ident] = \
  369. self.id_to_local_proxy_obj[ident]
  370. obj, exposed, gettypeid = self.id_to_obj[ident]
  371. util.debug('Server re-enabled tracking & INCREF %r', ident)
  372. else:
  373. raise ke
  374. def decref(self, c, ident):
  375. if ident not in self.id_to_refcount and \
  376. ident in self.id_to_local_proxy_obj:
  377. util.debug('Server DECREF skipping %r', ident)
  378. return
  379. with self.mutex:
  380. if self.id_to_refcount[ident] <= 0:
  381. raise AssertionError(
  382. "Id {0!s} ({1!r}) has refcount {2:n}, not 1+".format(
  383. ident, self.id_to_obj[ident],
  384. self.id_to_refcount[ident]))
  385. self.id_to_refcount[ident] -= 1
  386. if self.id_to_refcount[ident] == 0:
  387. del self.id_to_refcount[ident]
  388. if ident not in self.id_to_refcount:
  389. # Two-step process in case the object turns out to contain other
  390. # proxy objects (e.g. a managed list of managed lists).
  391. # Otherwise, deleting self.id_to_obj[ident] would trigger the
  392. # deleting of the stored value (another managed object) which would
  393. # in turn attempt to acquire the mutex that is already held here.
  394. self.id_to_obj[ident] = (None, (), None) # thread-safe
  395. util.debug('disposing of obj with id %r', ident)
  396. with self.mutex:
  397. del self.id_to_obj[ident]
  398. #
  399. # Class to represent state of a manager
  400. #
  401. class State(object):
  402. __slots__ = ['value']
  403. INITIAL = 0
  404. STARTED = 1
  405. SHUTDOWN = 2
  406. #
  407. # Mapping from serializer name to Listener and Client types
  408. #
  409. listener_client = {
  410. 'pickle' : (connection.Listener, connection.Client),
  411. 'xmlrpclib' : (connection.XmlListener, connection.XmlClient)
  412. }
  413. #
  414. # Definition of BaseManager
  415. #
  416. class BaseManager(object):
  417. '''
  418. Base class for managers
  419. '''
  420. _registry = {}
  421. _Server = Server
  422. def __init__(self, address=None, authkey=None, serializer='pickle',
  423. ctx=None):
  424. if authkey is None:
  425. authkey = process.current_process().authkey
  426. self._address = address # XXX not final address if eg ('', 0)
  427. self._authkey = process.AuthenticationString(authkey)
  428. self._state = State()
  429. self._state.value = State.INITIAL
  430. self._serializer = serializer
  431. self._Listener, self._Client = listener_client[serializer]
  432. self._ctx = ctx or get_context()
  433. def get_server(self):
  434. '''
  435. Return server object with serve_forever() method and address attribute
  436. '''
  437. if self._state.value != State.INITIAL:
  438. if self._state.value == State.STARTED:
  439. raise ProcessError("Already started server")
  440. elif self._state.value == State.SHUTDOWN:
  441. raise ProcessError("Manager has shut down")
  442. else:
  443. raise ProcessError(
  444. "Unknown state {!r}".format(self._state.value))
  445. return Server(self._registry, self._address,
  446. self._authkey, self._serializer)
  447. def connect(self):
  448. '''
  449. Connect manager object to the server process
  450. '''
  451. Listener, Client = listener_client[self._serializer]
  452. conn = Client(self._address, authkey=self._authkey)
  453. dispatch(conn, None, 'dummy')
  454. self._state.value = State.STARTED
  455. def start(self, initializer=None, initargs=()):
  456. '''
  457. Spawn a server process for this manager object
  458. '''
  459. if self._state.value != State.INITIAL:
  460. if self._state.value == State.STARTED:
  461. raise ProcessError("Already started server")
  462. elif self._state.value == State.SHUTDOWN:
  463. raise ProcessError("Manager has shut down")
  464. else:
  465. raise ProcessError(
  466. "Unknown state {!r}".format(self._state.value))
  467. if initializer is not None and not callable(initializer):
  468. raise TypeError('initializer must be a callable')
  469. # pipe over which we will retrieve address of server
  470. reader, writer = connection.Pipe(duplex=False)
  471. # spawn process which runs a server
  472. self._process = self._ctx.Process(
  473. target=type(self)._run_server,
  474. args=(self._registry, self._address, self._authkey,
  475. self._serializer, writer, initializer, initargs),
  476. )
  477. ident = ':'.join(str(i) for i in self._process._identity)
  478. self._process.name = type(self).__name__ + '-' + ident
  479. self._process.start()
  480. # get address of server
  481. writer.close()
  482. self._address = reader.recv()
  483. reader.close()
  484. # register a finalizer
  485. self._state.value = State.STARTED
  486. self.shutdown = util.Finalize(
  487. self, type(self)._finalize_manager,
  488. args=(self._process, self._address, self._authkey,
  489. self._state, self._Client),
  490. exitpriority=0
  491. )
  492. @classmethod
  493. def _run_server(cls, registry, address, authkey, serializer, writer,
  494. initializer=None, initargs=()):
  495. '''
  496. Create a server, report its address and run it
  497. '''
  498. # bpo-36368: protect server process from KeyboardInterrupt signals
  499. signal.signal(signal.SIGINT, signal.SIG_IGN)
  500. if initializer is not None:
  501. initializer(*initargs)
  502. # create server
  503. server = cls._Server(registry, address, authkey, serializer)
  504. # inform parent process of the server's address
  505. writer.send(server.address)
  506. writer.close()
  507. # run the manager
  508. util.info('manager serving at %r', server.address)
  509. server.serve_forever()
  510. def _create(self, typeid, /, *args, **kwds):
  511. '''
  512. Create a new shared object; return the token and exposed tuple
  513. '''
  514. assert self._state.value == State.STARTED, 'server not yet started'
  515. conn = self._Client(self._address, authkey=self._authkey)
  516. try:
  517. id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds)
  518. finally:
  519. conn.close()
  520. return Token(typeid, self._address, id), exposed
  521. def join(self, timeout=None):
  522. '''
  523. Join the manager process (if it has been spawned)
  524. '''
  525. if self._process is not None:
  526. self._process.join(timeout)
  527. if not self._process.is_alive():
  528. self._process = None
  529. def _debug_info(self):
  530. '''
  531. Return some info about the servers shared objects and connections
  532. '''
  533. conn = self._Client(self._address, authkey=self._authkey)
  534. try:
  535. return dispatch(conn, None, 'debug_info')
  536. finally:
  537. conn.close()
  538. def _number_of_objects(self):
  539. '''
  540. Return the number of shared objects
  541. '''
  542. conn = self._Client(self._address, authkey=self._authkey)
  543. try:
  544. return dispatch(conn, None, 'number_of_objects')
  545. finally:
  546. conn.close()
  547. def __enter__(self):
  548. if self._state.value == State.INITIAL:
  549. self.start()
  550. if self._state.value != State.STARTED:
  551. if self._state.value == State.INITIAL:
  552. raise ProcessError("Unable to start server")
  553. elif self._state.value == State.SHUTDOWN:
  554. raise ProcessError("Manager has shut down")
  555. else:
  556. raise ProcessError(
  557. "Unknown state {!r}".format(self._state.value))
  558. return self
  559. def __exit__(self, exc_type, exc_val, exc_tb):
  560. self.shutdown()
  561. @staticmethod
  562. def _finalize_manager(process, address, authkey, state, _Client):
  563. '''
  564. Shutdown the manager process; will be registered as a finalizer
  565. '''
  566. if process.is_alive():
  567. util.info('sending shutdown message to manager')
  568. try:
  569. conn = _Client(address, authkey=authkey)
  570. try:
  571. dispatch(conn, None, 'shutdown')
  572. finally:
  573. conn.close()
  574. except Exception:
  575. pass
  576. process.join(timeout=1.0)
  577. if process.is_alive():
  578. util.info('manager still alive')
  579. if hasattr(process, 'terminate'):
  580. util.info('trying to `terminate()` manager process')
  581. process.terminate()
  582. process.join(timeout=1.0)
  583. if process.is_alive():
  584. util.info('manager still alive after terminate')
  585. state.value = State.SHUTDOWN
  586. try:
  587. del BaseProxy._address_to_local[address]
  588. except KeyError:
  589. pass
  590. @property
  591. def address(self):
  592. return self._address
  593. @classmethod
  594. def register(cls, typeid, callable=None, proxytype=None, exposed=None,
  595. method_to_typeid=None, create_method=True):
  596. '''
  597. Register a typeid with the manager type
  598. '''
  599. if '_registry' not in cls.__dict__:
  600. cls._registry = cls._registry.copy()
  601. if proxytype is None:
  602. proxytype = AutoProxy
  603. exposed = exposed or getattr(proxytype, '_exposed_', None)
  604. method_to_typeid = method_to_typeid or \
  605. getattr(proxytype, '_method_to_typeid_', None)
  606. if method_to_typeid:
  607. for key, value in list(method_to_typeid.items()): # isinstance?
  608. assert type(key) is str, '%r is not a string' % key
  609. assert type(value) is str, '%r is not a string' % value
  610. cls._registry[typeid] = (
  611. callable, exposed, method_to_typeid, proxytype
  612. )
  613. if create_method:
  614. def temp(self, /, *args, **kwds):
  615. util.debug('requesting creation of a shared %r object', typeid)
  616. token, exp = self._create(typeid, *args, **kwds)
  617. proxy = proxytype(
  618. token, self._serializer, manager=self,
  619. authkey=self._authkey, exposed=exp
  620. )
  621. conn = self._Client(token.address, authkey=self._authkey)
  622. dispatch(conn, None, 'decref', (token.id,))
  623. return proxy
  624. temp.__name__ = typeid
  625. setattr(cls, typeid, temp)
  626. #
  627. # Subclass of set which get cleared after a fork
  628. #
  629. class ProcessLocalSet(set):
  630. def __init__(self):
  631. util.register_after_fork(self, lambda obj: obj.clear())
  632. def __reduce__(self):
  633. return type(self), ()
  634. #
  635. # Definition of BaseProxy
  636. #
  637. class BaseProxy(object):
  638. '''
  639. A base for proxies of shared objects
  640. '''
  641. _address_to_local = {}
  642. _mutex = util.ForkAwareThreadLock()
  643. def __init__(self, token, serializer, manager=None,
  644. authkey=None, exposed=None, incref=True, manager_owned=False):
  645. with BaseProxy._mutex:
  646. tls_idset = BaseProxy._address_to_local.get(token.address, None)
  647. if tls_idset is None:
  648. tls_idset = util.ForkAwareLocal(), ProcessLocalSet()
  649. BaseProxy._address_to_local[token.address] = tls_idset
  650. # self._tls is used to record the connection used by this
  651. # thread to communicate with the manager at token.address
  652. self._tls = tls_idset[0]
  653. # self._idset is used to record the identities of all shared
  654. # objects for which the current process owns references and
  655. # which are in the manager at token.address
  656. self._idset = tls_idset[1]
  657. self._token = token
  658. self._id = self._token.id
  659. self._manager = manager
  660. self._serializer = serializer
  661. self._Client = listener_client[serializer][1]
  662. # Should be set to True only when a proxy object is being created
  663. # on the manager server; primary use case: nested proxy objects.
  664. # RebuildProxy detects when a proxy is being created on the manager
  665. # and sets this value appropriately.
  666. self._owned_by_manager = manager_owned
  667. if authkey is not None:
  668. self._authkey = process.AuthenticationString(authkey)
  669. elif self._manager is not None:
  670. self._authkey = self._manager._authkey
  671. else:
  672. self._authkey = process.current_process().authkey
  673. if incref:
  674. self._incref()
  675. util.register_after_fork(self, BaseProxy._after_fork)
  676. def _connect(self):
  677. util.debug('making connection to manager')
  678. name = process.current_process().name
  679. if threading.current_thread().name != 'MainThread':
  680. name += '|' + threading.current_thread().name
  681. conn = self._Client(self._token.address, authkey=self._authkey)
  682. dispatch(conn, None, 'accept_connection', (name,))
  683. self._tls.connection = conn
  684. def _callmethod(self, methodname, args=(), kwds={}):
  685. '''
  686. Try to call a method of the referent and return a copy of the result
  687. '''
  688. try:
  689. conn = self._tls.connection
  690. except AttributeError:
  691. util.debug('thread %r does not own a connection',
  692. threading.current_thread().name)
  693. self._connect()
  694. conn = self._tls.connection
  695. conn.send((self._id, methodname, args, kwds))
  696. kind, result = conn.recv()
  697. if kind == '#RETURN':
  698. return result
  699. elif kind == '#PROXY':
  700. exposed, token = result
  701. proxytype = self._manager._registry[token.typeid][-1]
  702. token.address = self._token.address
  703. proxy = proxytype(
  704. token, self._serializer, manager=self._manager,
  705. authkey=self._authkey, exposed=exposed
  706. )
  707. conn = self._Client(token.address, authkey=self._authkey)
  708. dispatch(conn, None, 'decref', (token.id,))
  709. return proxy
  710. raise convert_to_error(kind, result)
  711. def _getvalue(self):
  712. '''
  713. Get a copy of the value of the referent
  714. '''
  715. return self._callmethod('#GETVALUE')
  716. def _incref(self):
  717. if self._owned_by_manager:
  718. util.debug('owned_by_manager skipped INCREF of %r', self._token.id)
  719. return
  720. conn = self._Client(self._token.address, authkey=self._authkey)
  721. dispatch(conn, None, 'incref', (self._id,))
  722. util.debug('INCREF %r', self._token.id)
  723. self._idset.add(self._id)
  724. state = self._manager and self._manager._state
  725. self._close = util.Finalize(
  726. self, BaseProxy._decref,
  727. args=(self._token, self._authkey, state,
  728. self._tls, self._idset, self._Client),
  729. exitpriority=10
  730. )
  731. @staticmethod
  732. def _decref(token, authkey, state, tls, idset, _Client):
  733. idset.discard(token.id)
  734. # check whether manager is still alive
  735. if state is None or state.value == State.STARTED:
  736. # tell manager this process no longer cares about referent
  737. try:
  738. util.debug('DECREF %r', token.id)
  739. conn = _Client(token.address, authkey=authkey)
  740. dispatch(conn, None, 'decref', (token.id,))
  741. except Exception as e:
  742. util.debug('... decref failed %s', e)
  743. else:
  744. util.debug('DECREF %r -- manager already shutdown', token.id)
  745. # check whether we can close this thread's connection because
  746. # the process owns no more references to objects for this manager
  747. if not idset and hasattr(tls, 'connection'):
  748. util.debug('thread %r has no more proxies so closing conn',
  749. threading.current_thread().name)
  750. tls.connection.close()
  751. del tls.connection
  752. def _after_fork(self):
  753. self._manager = None
  754. try:
  755. self._incref()
  756. except Exception as e:
  757. # the proxy may just be for a manager which has shutdown
  758. util.info('incref failed: %s' % e)
  759. def __reduce__(self):
  760. kwds = {}
  761. if get_spawning_popen() is not None:
  762. kwds['authkey'] = self._authkey
  763. if getattr(self, '_isauto', False):
  764. kwds['exposed'] = self._exposed_
  765. return (RebuildProxy,
  766. (AutoProxy, self._token, self._serializer, kwds))
  767. else:
  768. return (RebuildProxy,
  769. (type(self), self._token, self._serializer, kwds))
  770. def __deepcopy__(self, memo):
  771. return self._getvalue()
  772. def __repr__(self):
  773. return '<%s object, typeid %r at %#x>' % \
  774. (type(self).__name__, self._token.typeid, id(self))
  775. def __str__(self):
  776. '''
  777. Return representation of the referent (or a fall-back if that fails)
  778. '''
  779. try:
  780. return self._callmethod('__repr__')
  781. except Exception:
  782. return repr(self)[:-1] + "; '__str__()' failed>"
  783. #
  784. # Function used for unpickling
  785. #
  786. def RebuildProxy(func, token, serializer, kwds):
  787. '''
  788. Function used for unpickling proxy objects.
  789. '''
  790. server = getattr(process.current_process(), '_manager_server', None)
  791. if server and server.address == token.address:
  792. util.debug('Rebuild a proxy owned by manager, token=%r', token)
  793. kwds['manager_owned'] = True
  794. if token.id not in server.id_to_local_proxy_obj:
  795. server.id_to_local_proxy_obj[token.id] = \
  796. server.id_to_obj[token.id]
  797. incref = (
  798. kwds.pop('incref', True) and
  799. not getattr(process.current_process(), '_inheriting', False)
  800. )
  801. return func(token, serializer, incref=incref, **kwds)
  802. #
  803. # Functions to create proxies and proxy types
  804. #
  805. def MakeProxyType(name, exposed, _cache={}):
  806. '''
  807. Return a proxy type whose methods are given by `exposed`
  808. '''
  809. exposed = tuple(exposed)
  810. try:
  811. return _cache[(name, exposed)]
  812. except KeyError:
  813. pass
  814. dic = {}
  815. for meth in exposed:
  816. exec('''def %s(self, /, *args, **kwds):
  817. return self._callmethod(%r, args, kwds)''' % (meth, meth), dic)
  818. ProxyType = type(name, (BaseProxy,), dic)
  819. ProxyType._exposed_ = exposed
  820. _cache[(name, exposed)] = ProxyType
  821. return ProxyType
  822. def AutoProxy(token, serializer, manager=None, authkey=None,
  823. exposed=None, incref=True, manager_owned=False):
  824. '''
  825. Return an auto-proxy for `token`
  826. '''
  827. _Client = listener_client[serializer][1]
  828. if exposed is None:
  829. conn = _Client(token.address, authkey=authkey)
  830. try:
  831. exposed = dispatch(conn, None, 'get_methods', (token,))
  832. finally:
  833. conn.close()
  834. if authkey is None and manager is not None:
  835. authkey = manager._authkey
  836. if authkey is None:
  837. authkey = process.current_process().authkey
  838. ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed)
  839. proxy = ProxyType(token, serializer, manager=manager, authkey=authkey,
  840. incref=incref, manager_owned=manager_owned)
  841. proxy._isauto = True
  842. return proxy
  843. #
  844. # Types/callables which we will register with SyncManager
  845. #
  846. class Namespace(object):
  847. def __init__(self, /, **kwds):
  848. self.__dict__.update(kwds)
  849. def __repr__(self):
  850. items = list(self.__dict__.items())
  851. temp = []
  852. for name, value in items:
  853. if not name.startswith('_'):
  854. temp.append('%s=%r' % (name, value))
  855. temp.sort()
  856. return '%s(%s)' % (self.__class__.__name__, ', '.join(temp))
  857. class Value(object):
  858. def __init__(self, typecode, value, lock=True):
  859. self._typecode = typecode
  860. self._value = value
  861. def get(self):
  862. return self._value
  863. def set(self, value):
  864. self._value = value
  865. def __repr__(self):
  866. return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value)
  867. value = property(get, set)
  868. def Array(typecode, sequence, lock=True):
  869. return array.array(typecode, sequence)
  870. #
  871. # Proxy types used by SyncManager
  872. #
  873. class IteratorProxy(BaseProxy):
  874. _exposed_ = ('__next__', 'send', 'throw', 'close')
  875. def __iter__(self):
  876. return self
  877. def __next__(self, *args):
  878. return self._callmethod('__next__', args)
  879. def send(self, *args):
  880. return self._callmethod('send', args)
  881. def throw(self, *args):
  882. return self._callmethod('throw', args)
  883. def close(self, *args):
  884. return self._callmethod('close', args)
  885. class AcquirerProxy(BaseProxy):
  886. _exposed_ = ('acquire', 'release')
  887. def acquire(self, blocking=True, timeout=None):
  888. args = (blocking,) if timeout is None else (blocking, timeout)
  889. return self._callmethod('acquire', args)
  890. def release(self):
  891. return self._callmethod('release')
  892. def __enter__(self):
  893. return self._callmethod('acquire')
  894. def __exit__(self, exc_type, exc_val, exc_tb):
  895. return self._callmethod('release')
  896. class ConditionProxy(AcquirerProxy):
  897. _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all')
  898. def wait(self, timeout=None):
  899. return self._callmethod('wait', (timeout,))
  900. def notify(self, n=1):
  901. return self._callmethod('notify', (n,))
  902. def notify_all(self):
  903. return self._callmethod('notify_all')
  904. def wait_for(self, predicate, timeout=None):
  905. result = predicate()
  906. if result:
  907. return result
  908. if timeout is not None:
  909. endtime = time.monotonic() + timeout
  910. else:
  911. endtime = None
  912. waittime = None
  913. while not result:
  914. if endtime is not None:
  915. waittime = endtime - time.monotonic()
  916. if waittime <= 0:
  917. break
  918. self.wait(waittime)
  919. result = predicate()
  920. return result
  921. class EventProxy(BaseProxy):
  922. _exposed_ = ('is_set', 'set', 'clear', 'wait')
  923. def is_set(self):
  924. return self._callmethod('is_set')
  925. def set(self):
  926. return self._callmethod('set')
  927. def clear(self):
  928. return self._callmethod('clear')
  929. def wait(self, timeout=None):
  930. return self._callmethod('wait', (timeout,))
  931. class BarrierProxy(BaseProxy):
  932. _exposed_ = ('__getattribute__', 'wait', 'abort', 'reset')
  933. def wait(self, timeout=None):
  934. return self._callmethod('wait', (timeout,))
  935. def abort(self):
  936. return self._callmethod('abort')
  937. def reset(self):
  938. return self._callmethod('reset')
  939. @property
  940. def parties(self):
  941. return self._callmethod('__getattribute__', ('parties',))
  942. @property
  943. def n_waiting(self):
  944. return self._callmethod('__getattribute__', ('n_waiting',))
  945. @property
  946. def broken(self):
  947. return self._callmethod('__getattribute__', ('broken',))
  948. class NamespaceProxy(BaseProxy):
  949. _exposed_ = ('__getattribute__', '__setattr__', '__delattr__')
  950. def __getattr__(self, key):
  951. if key[0] == '_':
  952. return object.__getattribute__(self, key)
  953. callmethod = object.__getattribute__(self, '_callmethod')
  954. return callmethod('__getattribute__', (key,))
  955. def __setattr__(self, key, value):
  956. if key[0] == '_':
  957. return object.__setattr__(self, key, value)
  958. callmethod = object.__getattribute__(self, '_callmethod')
  959. return callmethod('__setattr__', (key, value))
  960. def __delattr__(self, key):
  961. if key[0] == '_':
  962. return object.__delattr__(self, key)
  963. callmethod = object.__getattribute__(self, '_callmethod')
  964. return callmethod('__delattr__', (key,))
  965. class ValueProxy(BaseProxy):
  966. _exposed_ = ('get', 'set')
  967. def get(self):
  968. return self._callmethod('get')
  969. def set(self, value):
  970. return self._callmethod('set', (value,))
  971. value = property(get, set)
  972. __class_getitem__ = classmethod(types.GenericAlias)
  973. BaseListProxy = MakeProxyType('BaseListProxy', (
  974. '__add__', '__contains__', '__delitem__', '__getitem__', '__len__',
  975. '__mul__', '__reversed__', '__rmul__', '__setitem__',
  976. 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
  977. 'reverse', 'sort', '__imul__'
  978. ))
  979. class ListProxy(BaseListProxy):
  980. def __iadd__(self, value):
  981. self._callmethod('extend', (value,))
  982. return self
  983. def __imul__(self, value):
  984. self._callmethod('__imul__', (value,))
  985. return self
  986. DictProxy = MakeProxyType('DictProxy', (
  987. '__contains__', '__delitem__', '__getitem__', '__iter__', '__len__',
  988. '__setitem__', 'clear', 'copy', 'get', 'items',
  989. 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'
  990. ))
  991. DictProxy._method_to_typeid_ = {
  992. '__iter__': 'Iterator',
  993. }
  994. ArrayProxy = MakeProxyType('ArrayProxy', (
  995. '__len__', '__getitem__', '__setitem__'
  996. ))
  997. BasePoolProxy = MakeProxyType('PoolProxy', (
  998. 'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join',
  999. 'map', 'map_async', 'starmap', 'starmap_async', 'terminate',
  1000. ))
  1001. BasePoolProxy._method_to_typeid_ = {
  1002. 'apply_async': 'AsyncResult',
  1003. 'map_async': 'AsyncResult',
  1004. 'starmap_async': 'AsyncResult',
  1005. 'imap': 'Iterator',
  1006. 'imap_unordered': 'Iterator'
  1007. }
  1008. class PoolProxy(BasePoolProxy):
  1009. def __enter__(self):
  1010. return self
  1011. def __exit__(self, exc_type, exc_val, exc_tb):
  1012. self.terminate()
  1013. #
  1014. # Definition of SyncManager
  1015. #
  1016. class SyncManager(BaseManager):
  1017. '''
  1018. Subclass of `BaseManager` which supports a number of shared object types.
  1019. The types registered are those intended for the synchronization
  1020. of threads, plus `dict`, `list` and `Namespace`.
  1021. The `multiprocessing.Manager()` function creates started instances of
  1022. this class.
  1023. '''
  1024. SyncManager.register('Queue', queue.Queue)
  1025. SyncManager.register('JoinableQueue', queue.Queue)
  1026. SyncManager.register('Event', threading.Event, EventProxy)
  1027. SyncManager.register('Lock', threading.Lock, AcquirerProxy)
  1028. SyncManager.register('RLock', threading.RLock, AcquirerProxy)
  1029. SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy)
  1030. SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore,
  1031. AcquirerProxy)
  1032. SyncManager.register('Condition', threading.Condition, ConditionProxy)
  1033. SyncManager.register('Barrier', threading.Barrier, BarrierProxy)
  1034. SyncManager.register('Pool', pool.Pool, PoolProxy)
  1035. SyncManager.register('list', list, ListProxy)
  1036. SyncManager.register('dict', dict, DictProxy)
  1037. SyncManager.register('Value', Value, ValueProxy)
  1038. SyncManager.register('Array', Array, ArrayProxy)
  1039. SyncManager.register('Namespace', Namespace, NamespaceProxy)
  1040. # types returned by methods of PoolProxy
  1041. SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False)
  1042. SyncManager.register('AsyncResult', create_method=False)
  1043. #
  1044. # Definition of SharedMemoryManager and SharedMemoryServer
  1045. #
  1046. if HAS_SHMEM:
  1047. class _SharedMemoryTracker:
  1048. "Manages one or more shared memory segments."
  1049. def __init__(self, name, segment_names=[]):
  1050. self.shared_memory_context_name = name
  1051. self.segment_names = segment_names
  1052. def register_segment(self, segment_name):
  1053. "Adds the supplied shared memory block name to tracker."
  1054. util.debug(f"Register segment {segment_name!r} in pid {getpid()}")
  1055. self.segment_names.append(segment_name)
  1056. def destroy_segment(self, segment_name):
  1057. """Calls unlink() on the shared memory block with the supplied name
  1058. and removes it from the list of blocks being tracked."""
  1059. util.debug(f"Destroy segment {segment_name!r} in pid {getpid()}")
  1060. self.segment_names.remove(segment_name)
  1061. segment = shared_memory.SharedMemory(segment_name)
  1062. segment.close()
  1063. segment.unlink()
  1064. def unlink(self):
  1065. "Calls destroy_segment() on all tracked shared memory blocks."
  1066. for segment_name in self.segment_names[:]:
  1067. self.destroy_segment(segment_name)
  1068. def __del__(self):
  1069. util.debug(f"Call {self.__class__.__name__}.__del__ in {getpid()}")
  1070. self.unlink()
  1071. def __getstate__(self):
  1072. return (self.shared_memory_context_name, self.segment_names)
  1073. def __setstate__(self, state):
  1074. self.__init__(*state)
  1075. class SharedMemoryServer(Server):
  1076. public = Server.public + \
  1077. ['track_segment', 'release_segment', 'list_segments']
  1078. def __init__(self, *args, **kwargs):
  1079. Server.__init__(self, *args, **kwargs)
  1080. address = self.address
  1081. # The address of Linux abstract namespaces can be bytes
  1082. if isinstance(address, bytes):
  1083. address = os.fsdecode(address)
  1084. self.shared_memory_context = \
  1085. _SharedMemoryTracker(f"shm_{address}_{getpid()}")
  1086. util.debug(f"SharedMemoryServer started by pid {getpid()}")
  1087. def create(self, c, typeid, /, *args, **kwargs):
  1088. """Create a new distributed-shared object (not backed by a shared
  1089. memory block) and return its id to be used in a Proxy Object."""
  1090. # Unless set up as a shared proxy, don't make shared_memory_context
  1091. # a standard part of kwargs. This makes things easier for supplying
  1092. # simple functions.
  1093. if hasattr(self.registry[typeid][-1], "_shared_memory_proxy"):
  1094. kwargs['shared_memory_context'] = self.shared_memory_context
  1095. return Server.create(self, c, typeid, *args, **kwargs)
  1096. def shutdown(self, c):
  1097. "Call unlink() on all tracked shared memory, terminate the Server."
  1098. self.shared_memory_context.unlink()
  1099. return Server.shutdown(self, c)
  1100. def track_segment(self, c, segment_name):
  1101. "Adds the supplied shared memory block name to Server's tracker."
  1102. self.shared_memory_context.register_segment(segment_name)
  1103. def release_segment(self, c, segment_name):
  1104. """Calls unlink() on the shared memory block with the supplied name
  1105. and removes it from the tracker instance inside the Server."""
  1106. self.shared_memory_context.destroy_segment(segment_name)
  1107. def list_segments(self, c):
  1108. """Returns a list of names of shared memory blocks that the Server
  1109. is currently tracking."""
  1110. return self.shared_memory_context.segment_names
  1111. class SharedMemoryManager(BaseManager):
  1112. """Like SyncManager but uses SharedMemoryServer instead of Server.
  1113. It provides methods for creating and returning SharedMemory instances
  1114. and for creating a list-like object (ShareableList) backed by shared
  1115. memory. It also provides methods that create and return Proxy Objects
  1116. that support synchronization across processes (i.e. multi-process-safe
  1117. locks and semaphores).
  1118. """
  1119. _Server = SharedMemoryServer
  1120. def __init__(self, *args, **kwargs):
  1121. if os.name == "posix":
  1122. # bpo-36867: Ensure the resource_tracker is running before
  1123. # launching the manager process, so that concurrent
  1124. # shared_memory manipulation both in the manager and in the
  1125. # current process does not create two resource_tracker
  1126. # processes.
  1127. from . import resource_tracker
  1128. resource_tracker.ensure_running()
  1129. BaseManager.__init__(self, *args, **kwargs)
  1130. util.debug(f"{self.__class__.__name__} created by pid {getpid()}")
  1131. def __del__(self):
  1132. util.debug(f"{self.__class__.__name__}.__del__ by pid {getpid()}")
  1133. pass
  1134. def get_server(self):
  1135. 'Better than monkeypatching for now; merge into Server ultimately'
  1136. if self._state.value != State.INITIAL:
  1137. if self._state.value == State.STARTED:
  1138. raise ProcessError("Already started SharedMemoryServer")
  1139. elif self._state.value == State.SHUTDOWN:
  1140. raise ProcessError("SharedMemoryManager has shut down")
  1141. else:
  1142. raise ProcessError(
  1143. "Unknown state {!r}".format(self._state.value))
  1144. return self._Server(self._registry, self._address,
  1145. self._authkey, self._serializer)
  1146. def SharedMemory(self, size):
  1147. """Returns a new SharedMemory instance with the specified size in
  1148. bytes, to be tracked by the manager."""
  1149. with self._Client(self._address, authkey=self._authkey) as conn:
  1150. sms = shared_memory.SharedMemory(None, create=True, size=size)
  1151. try:
  1152. dispatch(conn, None, 'track_segment', (sms.name,))
  1153. except BaseException as e:
  1154. sms.unlink()
  1155. raise e
  1156. return sms
  1157. def ShareableList(self, sequence):
  1158. """Returns a new ShareableList instance populated with the values
  1159. from the input sequence, to be tracked by the manager."""
  1160. with self._Client(self._address, authkey=self._authkey) as conn:
  1161. sl = shared_memory.ShareableList(sequence)
  1162. try:
  1163. dispatch(conn, None, 'track_segment', (sl.shm.name,))
  1164. except BaseException as e:
  1165. sl.shm.unlink()
  1166. raise e
  1167. return sl