managers.py 47 KB

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