managers.py 47 KB

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