blob: f47402a3ca99d48829b5f8e1a7ed289c1029706c [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module providing the `SyncManager` class for dealing
3# with shared objects
4#
5# multiprocessing/managers.py
6#
R. David Murray3fc969a2010-12-14 01:38:16 +00007# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01008# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00009#
10
11__all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ]
12
13#
14# Imports
15#
16
Benjamin Petersone711caf2008-06-11 16:44:04 +000017import sys
Benjamin Petersone711caf2008-06-11 16:44:04 +000018import threading
19import array
Benjamin Petersone711caf2008-06-11 16:44:04 +000020import queue
21
22from traceback import format_exc
23from multiprocessing import Process, current_process, active_children, Pool, util, connection
24from multiprocessing.process import AuthenticationString
Florent Xicluna04842a82011-11-11 20:05:50 +010025from multiprocessing.forking import exit, Popen, ForkingPickler
Charles-François Natalic8ce7152012-04-17 18:45:57 +020026from time import time as _time
Benjamin Petersone711caf2008-06-11 16:44:04 +000027
Benjamin Petersone711caf2008-06-11 16:44:04 +000028#
Benjamin Petersone711caf2008-06-11 16:44:04 +000029# Register some things for pickling
30#
31
32def reduce_array(a):
Antoine Pitrou1ce3eb52010-09-01 20:29:34 +000033 return array.array, (a.typecode, a.tobytes())
Amaury Forgeot d'Arc949d47d2008-08-19 21:30:55 +000034ForkingPickler.register(array.array, reduce_array)
Benjamin Petersone711caf2008-06-11 16:44:04 +000035
36view_types = [type(getattr({}, name)()) for name in ('items','keys','values')]
Benjamin Petersond61438a2008-06-25 13:04:48 +000037if view_types[0] is not list: # only needed in Py3.0
Benjamin Petersone711caf2008-06-11 16:44:04 +000038 def rebuild_as_list(obj):
39 return list, (list(obj),)
40 for view_type in view_types:
Amaury Forgeot d'Arc949d47d2008-08-19 21:30:55 +000041 ForkingPickler.register(view_type, rebuild_as_list)
Amaury Forgeot d'Arcd757e732008-08-20 08:58:40 +000042 import copyreg
43 copyreg.pickle(view_type, rebuild_as_list)
Benjamin Petersone711caf2008-06-11 16:44:04 +000044
45#
46# Type for identifying shared objects
47#
48
49class Token(object):
50 '''
51 Type to uniquely indentify a shared object
52 '''
53 __slots__ = ('typeid', 'address', 'id')
54
55 def __init__(self, typeid, address, id):
56 (self.typeid, self.address, self.id) = (typeid, address, id)
57
58 def __getstate__(self):
59 return (self.typeid, self.address, self.id)
60
61 def __setstate__(self, state):
62 (self.typeid, self.address, self.id) = state
63
64 def __repr__(self):
65 return 'Token(typeid=%r, address=%r, id=%r)' % \
66 (self.typeid, self.address, self.id)
67
68#
69# Function for communication with a manager's server process
70#
71
72def dispatch(c, id, methodname, args=(), kwds={}):
73 '''
74 Send a message to manager using connection `c` and return response
75 '''
76 c.send((id, methodname, args, kwds))
77 kind, result = c.recv()
78 if kind == '#RETURN':
79 return result
80 raise convert_to_error(kind, result)
81
82def convert_to_error(kind, result):
83 if kind == '#ERROR':
84 return result
85 elif kind == '#TRACEBACK':
86 assert type(result) is str
87 return RemoteError(result)
88 elif kind == '#UNSERIALIZABLE':
89 assert type(result) is str
90 return RemoteError('Unserializable message: %s\n' % result)
91 else:
92 return ValueError('Unrecognized message type')
93
94class RemoteError(Exception):
95 def __str__(self):
96 return ('\n' + '-'*75 + '\n' + str(self.args[0]) + '-'*75)
97
98#
99# Functions for finding the method names of an object
100#
101
102def all_methods(obj):
103 '''
104 Return a list of names of methods of `obj`
105 '''
106 temp = []
107 for name in dir(obj):
108 func = getattr(obj, name)
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200109 if callable(func):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000110 temp.append(name)
111 return temp
112
113def public_methods(obj):
114 '''
115 Return a list of names of methods of `obj` which do not start with '_'
116 '''
117 return [name for name in all_methods(obj) if name[0] != '_']
118
119#
120# Server which is run in a process controlled by a manager
121#
122
123class Server(object):
124 '''
125 Server class which runs in a process controlled by a manager object
126 '''
127 public = ['shutdown', 'create', 'accept_connection', 'get_methods',
128 'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref']
129
130 def __init__(self, registry, address, authkey, serializer):
131 assert isinstance(authkey, bytes)
132 self.registry = registry
133 self.authkey = AuthenticationString(authkey)
134 Listener, Client = listener_client[serializer]
135
136 # do authentication later
Charles-François Natalife8039b2011-12-23 19:06:48 +0100137 self.listener = Listener(address=address, backlog=16)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000138 self.address = self.listener.address
139
Jesse Noller63b3a972009-01-21 02:15:48 +0000140 self.id_to_obj = {'0': (None, ())}
Benjamin Petersone711caf2008-06-11 16:44:04 +0000141 self.id_to_refcount = {}
142 self.mutex = threading.RLock()
143 self.stop = 0
144
145 def serve_forever(self):
146 '''
147 Run the server forever
148 '''
149 current_process()._manager_server = self
150 try:
151 try:
152 while 1:
153 try:
154 c = self.listener.accept()
155 except (OSError, IOError):
156 continue
157 t = threading.Thread(target=self.handle_request, args=(c,))
Benjamin Petersonfae4c622008-08-18 18:40:08 +0000158 t.daemon = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000159 t.start()
160 except (KeyboardInterrupt, SystemExit):
161 pass
162 finally:
163 self.stop = 999
164 self.listener.close()
165
166 def handle_request(self, c):
167 '''
168 Handle a new connection
169 '''
170 funcname = result = request = None
171 try:
172 connection.deliver_challenge(c, self.authkey)
173 connection.answer_challenge(c, self.authkey)
174 request = c.recv()
175 ignore, funcname, args, kwds = request
176 assert funcname in self.public, '%r unrecognized' % funcname
177 func = getattr(self, funcname)
178 except Exception:
179 msg = ('#TRACEBACK', format_exc())
180 else:
181 try:
182 result = func(c, *args, **kwds)
183 except Exception:
184 msg = ('#TRACEBACK', format_exc())
185 else:
186 msg = ('#RETURN', result)
187 try:
188 c.send(msg)
189 except Exception as e:
190 try:
191 c.send(('#TRACEBACK', format_exc()))
192 except Exception:
193 pass
194 util.info('Failure to send message: %r', msg)
195 util.info(' ... request was %r', request)
196 util.info(' ... exception was %r', e)
197
198 c.close()
199
200 def serve_client(self, conn):
201 '''
202 Handle requests from the proxies in a particular process/thread
203 '''
204 util.debug('starting server thread to service %r',
Benjamin Peterson72753702008-08-18 18:09:21 +0000205 threading.current_thread().name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000206
207 recv = conn.recv
208 send = conn.send
209 id_to_obj = self.id_to_obj
210
211 while not self.stop:
212
213 try:
214 methodname = obj = None
215 request = recv()
216 ident, methodname, args, kwds = request
217 obj, exposed, gettypeid = id_to_obj[ident]
218
219 if methodname not in exposed:
220 raise AttributeError(
221 'method %r of %r object is not in exposed=%r' %
222 (methodname, type(obj), exposed)
223 )
224
225 function = getattr(obj, methodname)
226
227 try:
228 res = function(*args, **kwds)
229 except Exception as e:
230 msg = ('#ERROR', e)
231 else:
232 typeid = gettypeid and gettypeid.get(methodname, None)
233 if typeid:
234 rident, rexposed = self.create(conn, typeid, res)
235 token = Token(typeid, self.address, rident)
236 msg = ('#PROXY', (rexposed, token))
237 else:
238 msg = ('#RETURN', res)
239
240 except AttributeError:
241 if methodname is None:
242 msg = ('#TRACEBACK', format_exc())
243 else:
244 try:
245 fallback_func = self.fallback_mapping[methodname]
246 result = fallback_func(
247 self, conn, ident, obj, *args, **kwds
248 )
249 msg = ('#RETURN', result)
250 except Exception:
251 msg = ('#TRACEBACK', format_exc())
252
253 except EOFError:
254 util.debug('got EOF -- exiting thread serving %r',
Benjamin Peterson72753702008-08-18 18:09:21 +0000255 threading.current_thread().name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000256 sys.exit(0)
257
258 except Exception:
259 msg = ('#TRACEBACK', format_exc())
260
261 try:
262 try:
263 send(msg)
264 except Exception as e:
265 send(('#UNSERIALIZABLE', repr(msg)))
266 except Exception as e:
267 util.info('exception in thread serving %r',
Benjamin Peterson72753702008-08-18 18:09:21 +0000268 threading.current_thread().name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000269 util.info(' ... message was %r', msg)
270 util.info(' ... exception was %r', e)
271 conn.close()
272 sys.exit(1)
273
274 def fallback_getvalue(self, conn, ident, obj):
275 return obj
276
277 def fallback_str(self, conn, ident, obj):
278 return str(obj)
279
280 def fallback_repr(self, conn, ident, obj):
281 return repr(obj)
282
283 fallback_mapping = {
284 '__str__':fallback_str,
285 '__repr__':fallback_repr,
286 '#GETVALUE':fallback_getvalue
287 }
288
289 def dummy(self, c):
290 pass
291
292 def debug_info(self, c):
293 '''
294 Return some info --- useful to spot problems with refcounting
295 '''
296 self.mutex.acquire()
297 try:
298 result = []
299 keys = list(self.id_to_obj.keys())
300 keys.sort()
301 for ident in keys:
Jesse Noller63b3a972009-01-21 02:15:48 +0000302 if ident != '0':
Benjamin Petersone711caf2008-06-11 16:44:04 +0000303 result.append(' %s: refcount=%s\n %s' %
304 (ident, self.id_to_refcount[ident],
305 str(self.id_to_obj[ident][0])[:75]))
306 return '\n'.join(result)
307 finally:
308 self.mutex.release()
309
310 def number_of_objects(self, c):
311 '''
312 Number of shared objects
313 '''
Jesse Noller63b3a972009-01-21 02:15:48 +0000314 return len(self.id_to_obj) - 1 # don't count ident='0'
Benjamin Petersone711caf2008-06-11 16:44:04 +0000315
316 def shutdown(self, c):
317 '''
318 Shutdown this process
319 '''
320 try:
321 try:
322 util.debug('manager received shutdown message')
323 c.send(('#RETURN', None))
324
325 if sys.stdout != sys.__stdout__:
326 util.debug('resetting stdout, stderr')
327 sys.stdout = sys.__stdout__
328 sys.stderr = sys.__stderr__
329
330 util._run_finalizers(0)
331
332 for p in active_children():
333 util.debug('terminating a child process of manager')
334 p.terminate()
335
336 for p in active_children():
337 util.debug('terminating a child process of manager')
338 p.join()
339
340 util._run_finalizers()
341 util.info('manager exiting with exitcode 0')
342 except:
343 import traceback
344 traceback.print_exc()
345 finally:
346 exit(0)
347
348 def create(self, c, typeid, *args, **kwds):
349 '''
350 Create a new shared object and return its id
351 '''
352 self.mutex.acquire()
353 try:
354 callable, exposed, method_to_typeid, proxytype = \
355 self.registry[typeid]
356
357 if callable is None:
358 assert len(args) == 1 and not kwds
359 obj = args[0]
360 else:
361 obj = callable(*args, **kwds)
362
363 if exposed is None:
364 exposed = public_methods(obj)
365 if method_to_typeid is not None:
366 assert type(method_to_typeid) is dict
367 exposed = list(exposed) + list(method_to_typeid)
368
369 ident = '%x' % id(obj) # convert to string because xmlrpclib
370 # only has 32 bit signed integers
371 util.debug('%r callable returned object with id %r', typeid, ident)
372
373 self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid)
374 if ident not in self.id_to_refcount:
Jesse Noller824f4f32008-09-02 19:12:20 +0000375 self.id_to_refcount[ident] = 0
376 # increment the reference count immediately, to avoid
377 # this object being garbage collected before a Proxy
378 # object for it can be created. The caller of create()
379 # is responsible for doing a decref once the Proxy object
380 # has been created.
381 self.incref(c, ident)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000382 return ident, tuple(exposed)
383 finally:
384 self.mutex.release()
385
386 def get_methods(self, c, token):
387 '''
388 Return the methods of the shared object indicated by token
389 '''
390 return tuple(self.id_to_obj[token.id][1])
391
392 def accept_connection(self, c, name):
393 '''
394 Spawn a new thread to serve this connection
395 '''
Benjamin Peterson72753702008-08-18 18:09:21 +0000396 threading.current_thread().name = name
Benjamin Petersone711caf2008-06-11 16:44:04 +0000397 c.send(('#RETURN', None))
398 self.serve_client(c)
399
400 def incref(self, c, ident):
401 self.mutex.acquire()
402 try:
Jesse Noller824f4f32008-09-02 19:12:20 +0000403 self.id_to_refcount[ident] += 1
Benjamin Petersone711caf2008-06-11 16:44:04 +0000404 finally:
405 self.mutex.release()
406
407 def decref(self, c, ident):
408 self.mutex.acquire()
409 try:
410 assert self.id_to_refcount[ident] >= 1
411 self.id_to_refcount[ident] -= 1
412 if self.id_to_refcount[ident] == 0:
413 del self.id_to_obj[ident], self.id_to_refcount[ident]
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000414 util.debug('disposing of obj with id %r', ident)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000415 finally:
416 self.mutex.release()
417
418#
419# Class to represent state of a manager
420#
421
422class State(object):
423 __slots__ = ['value']
424 INITIAL = 0
425 STARTED = 1
426 SHUTDOWN = 2
427
428#
429# Mapping from serializer name to Listener and Client types
430#
431
432listener_client = {
433 'pickle' : (connection.Listener, connection.Client),
434 'xmlrpclib' : (connection.XmlListener, connection.XmlClient)
435 }
436
437#
438# Definition of BaseManager
439#
440
441class BaseManager(object):
442 '''
443 Base class for managers
444 '''
445 _registry = {}
446 _Server = Server
447
448 def __init__(self, address=None, authkey=None, serializer='pickle'):
449 if authkey is None:
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000450 authkey = current_process().authkey
Benjamin Petersone711caf2008-06-11 16:44:04 +0000451 self._address = address # XXX not final address if eg ('', 0)
452 self._authkey = AuthenticationString(authkey)
453 self._state = State()
454 self._state.value = State.INITIAL
455 self._serializer = serializer
456 self._Listener, self._Client = listener_client[serializer]
457
458 def __reduce__(self):
459 return type(self).from_address, \
460 (self._address, self._authkey, self._serializer)
461
462 def get_server(self):
463 '''
464 Return server object with serve_forever() method and address attribute
465 '''
466 assert self._state.value == State.INITIAL
467 return Server(self._registry, self._address,
468 self._authkey, self._serializer)
469
470 def connect(self):
471 '''
472 Connect manager object to the server process
473 '''
474 Listener, Client = listener_client[self._serializer]
475 conn = Client(self._address, authkey=self._authkey)
476 dispatch(conn, None, 'dummy')
477 self._state.value = State.STARTED
478
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000479 def start(self, initializer=None, initargs=()):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000480 '''
481 Spawn a server process for this manager object
482 '''
483 assert self._state.value == State.INITIAL
484
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200485 if initializer is not None and not callable(initializer):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000486 raise TypeError('initializer must be a callable')
487
Benjamin Petersone711caf2008-06-11 16:44:04 +0000488 # pipe over which we will retrieve address of server
489 reader, writer = connection.Pipe(duplex=False)
490
491 # spawn process which runs a server
492 self._process = Process(
493 target=type(self)._run_server,
494 args=(self._registry, self._address, self._authkey,
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000495 self._serializer, writer, initializer, initargs),
Benjamin Petersone711caf2008-06-11 16:44:04 +0000496 )
497 ident = ':'.join(str(i) for i in self._process._identity)
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000498 self._process.name = type(self).__name__ + '-' + ident
Benjamin Petersone711caf2008-06-11 16:44:04 +0000499 self._process.start()
500
501 # get address of server
502 writer.close()
503 self._address = reader.recv()
504 reader.close()
505
506 # register a finalizer
507 self._state.value = State.STARTED
508 self.shutdown = util.Finalize(
509 self, type(self)._finalize_manager,
510 args=(self._process, self._address, self._authkey,
511 self._state, self._Client),
512 exitpriority=0
513 )
514
515 @classmethod
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000516 def _run_server(cls, registry, address, authkey, serializer, writer,
517 initializer=None, initargs=()):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000518 '''
519 Create a server, report its address and run it
520 '''
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000521 if initializer is not None:
522 initializer(*initargs)
523
Benjamin Petersone711caf2008-06-11 16:44:04 +0000524 # create server
525 server = cls._Server(registry, address, authkey, serializer)
526
527 # inform parent process of the server's address
528 writer.send(server.address)
529 writer.close()
530
531 # run the manager
532 util.info('manager serving at %r', server.address)
533 server.serve_forever()
534
535 def _create(self, typeid, *args, **kwds):
536 '''
537 Create a new shared object; return the token and exposed tuple
538 '''
539 assert self._state.value == State.STARTED, 'server not yet started'
540 conn = self._Client(self._address, authkey=self._authkey)
541 try:
542 id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds)
543 finally:
544 conn.close()
545 return Token(typeid, self._address, id), exposed
546
547 def join(self, timeout=None):
548 '''
549 Join the manager process (if it has been spawned)
550 '''
551 self._process.join(timeout)
552
553 def _debug_info(self):
554 '''
555 Return some info about the servers shared objects and connections
556 '''
557 conn = self._Client(self._address, authkey=self._authkey)
558 try:
559 return dispatch(conn, None, 'debug_info')
560 finally:
561 conn.close()
562
563 def _number_of_objects(self):
564 '''
565 Return the number of shared objects
566 '''
567 conn = self._Client(self._address, authkey=self._authkey)
568 try:
569 return dispatch(conn, None, 'number_of_objects')
570 finally:
571 conn.close()
572
573 def __enter__(self):
574 return self
575
576 def __exit__(self, exc_type, exc_val, exc_tb):
577 self.shutdown()
578
579 @staticmethod
580 def _finalize_manager(process, address, authkey, state, _Client):
581 '''
582 Shutdown the manager process; will be registered as a finalizer
583 '''
584 if process.is_alive():
585 util.info('sending shutdown message to manager')
586 try:
587 conn = _Client(address, authkey=authkey)
588 try:
589 dispatch(conn, None, 'shutdown')
590 finally:
591 conn.close()
592 except Exception:
593 pass
594
595 process.join(timeout=0.2)
596 if process.is_alive():
597 util.info('manager still alive')
598 if hasattr(process, 'terminate'):
599 util.info('trying to `terminate()` manager process')
600 process.terminate()
601 process.join(timeout=0.1)
602 if process.is_alive():
603 util.info('manager still alive after terminate')
604
605 state.value = State.SHUTDOWN
606 try:
607 del BaseProxy._address_to_local[address]
608 except KeyError:
609 pass
610
611 address = property(lambda self: self._address)
612
613 @classmethod
614 def register(cls, typeid, callable=None, proxytype=None, exposed=None,
615 method_to_typeid=None, create_method=True):
616 '''
617 Register a typeid with the manager type
618 '''
619 if '_registry' not in cls.__dict__:
620 cls._registry = cls._registry.copy()
621
622 if proxytype is None:
623 proxytype = AutoProxy
624
625 exposed = exposed or getattr(proxytype, '_exposed_', None)
626
627 method_to_typeid = method_to_typeid or \
628 getattr(proxytype, '_method_to_typeid_', None)
629
630 if method_to_typeid:
631 for key, value in list(method_to_typeid.items()):
632 assert type(key) is str, '%r is not a string' % key
633 assert type(value) is str, '%r is not a string' % value
634
635 cls._registry[typeid] = (
636 callable, exposed, method_to_typeid, proxytype
637 )
638
639 if create_method:
640 def temp(self, *args, **kwds):
641 util.debug('requesting creation of a shared %r object', typeid)
642 token, exp = self._create(typeid, *args, **kwds)
643 proxy = proxytype(
644 token, self._serializer, manager=self,
645 authkey=self._authkey, exposed=exp
646 )
Jesse Noller824f4f32008-09-02 19:12:20 +0000647 conn = self._Client(token.address, authkey=self._authkey)
648 dispatch(conn, None, 'decref', (token.id,))
Benjamin Petersone711caf2008-06-11 16:44:04 +0000649 return proxy
650 temp.__name__ = typeid
651 setattr(cls, typeid, temp)
652
653#
654# Subclass of set which get cleared after a fork
655#
656
657class ProcessLocalSet(set):
658 def __init__(self):
659 util.register_after_fork(self, lambda obj: obj.clear())
660 def __reduce__(self):
661 return type(self), ()
662
663#
664# Definition of BaseProxy
665#
666
667class BaseProxy(object):
668 '''
669 A base for proxies of shared objects
670 '''
671 _address_to_local = {}
672 _mutex = util.ForkAwareThreadLock()
673
674 def __init__(self, token, serializer, manager=None,
675 authkey=None, exposed=None, incref=True):
676 BaseProxy._mutex.acquire()
677 try:
678 tls_idset = BaseProxy._address_to_local.get(token.address, None)
679 if tls_idset is None:
680 tls_idset = util.ForkAwareLocal(), ProcessLocalSet()
681 BaseProxy._address_to_local[token.address] = tls_idset
682 finally:
683 BaseProxy._mutex.release()
684
685 # self._tls is used to record the connection used by this
686 # thread to communicate with the manager at token.address
687 self._tls = tls_idset[0]
688
689 # self._idset is used to record the identities of all shared
690 # objects for which the current process owns references and
691 # which are in the manager at token.address
692 self._idset = tls_idset[1]
693
694 self._token = token
695 self._id = self._token.id
696 self._manager = manager
697 self._serializer = serializer
698 self._Client = listener_client[serializer][1]
699
700 if authkey is not None:
701 self._authkey = AuthenticationString(authkey)
702 elif self._manager is not None:
703 self._authkey = self._manager._authkey
704 else:
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000705 self._authkey = current_process().authkey
Benjamin Petersone711caf2008-06-11 16:44:04 +0000706
707 if incref:
708 self._incref()
709
710 util.register_after_fork(self, BaseProxy._after_fork)
711
712 def _connect(self):
713 util.debug('making connection to manager')
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000714 name = current_process().name
Benjamin Peterson72753702008-08-18 18:09:21 +0000715 if threading.current_thread().name != 'MainThread':
716 name += '|' + threading.current_thread().name
Benjamin Petersone711caf2008-06-11 16:44:04 +0000717 conn = self._Client(self._token.address, authkey=self._authkey)
718 dispatch(conn, None, 'accept_connection', (name,))
719 self._tls.connection = conn
720
721 def _callmethod(self, methodname, args=(), kwds={}):
722 '''
723 Try to call a method of the referrent and return a copy of the result
724 '''
725 try:
726 conn = self._tls.connection
727 except AttributeError:
728 util.debug('thread %r does not own a connection',
Benjamin Peterson72753702008-08-18 18:09:21 +0000729 threading.current_thread().name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000730 self._connect()
731 conn = self._tls.connection
732
733 conn.send((self._id, methodname, args, kwds))
734 kind, result = conn.recv()
735
736 if kind == '#RETURN':
737 return result
738 elif kind == '#PROXY':
739 exposed, token = result
740 proxytype = self._manager._registry[token.typeid][-1]
Jesse Noller824f4f32008-09-02 19:12:20 +0000741 proxy = proxytype(
Benjamin Petersone711caf2008-06-11 16:44:04 +0000742 token, self._serializer, manager=self._manager,
743 authkey=self._authkey, exposed=exposed
744 )
Jesse Noller824f4f32008-09-02 19:12:20 +0000745 conn = self._Client(token.address, authkey=self._authkey)
746 dispatch(conn, None, 'decref', (token.id,))
747 return proxy
Benjamin Petersone711caf2008-06-11 16:44:04 +0000748 raise convert_to_error(kind, result)
749
750 def _getvalue(self):
751 '''
752 Get a copy of the value of the referent
753 '''
754 return self._callmethod('#GETVALUE')
755
756 def _incref(self):
757 conn = self._Client(self._token.address, authkey=self._authkey)
758 dispatch(conn, None, 'incref', (self._id,))
759 util.debug('INCREF %r', self._token.id)
760
761 self._idset.add(self._id)
762
763 state = self._manager and self._manager._state
764
765 self._close = util.Finalize(
766 self, BaseProxy._decref,
767 args=(self._token, self._authkey, state,
768 self._tls, self._idset, self._Client),
769 exitpriority=10
770 )
771
772 @staticmethod
773 def _decref(token, authkey, state, tls, idset, _Client):
774 idset.discard(token.id)
775
776 # check whether manager is still alive
777 if state is None or state.value == State.STARTED:
778 # tell manager this process no longer cares about referent
779 try:
780 util.debug('DECREF %r', token.id)
781 conn = _Client(token.address, authkey=authkey)
782 dispatch(conn, None, 'decref', (token.id,))
783 except Exception as e:
784 util.debug('... decref failed %s', e)
785
786 else:
787 util.debug('DECREF %r -- manager already shutdown', token.id)
788
789 # check whether we can close this thread's connection because
790 # the process owns no more references to objects for this manager
791 if not idset and hasattr(tls, 'connection'):
792 util.debug('thread %r has no more proxies so closing conn',
Benjamin Peterson72753702008-08-18 18:09:21 +0000793 threading.current_thread().name)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000794 tls.connection.close()
795 del tls.connection
796
797 def _after_fork(self):
798 self._manager = None
799 try:
800 self._incref()
801 except Exception as e:
802 # the proxy may just be for a manager which has shutdown
803 util.info('incref failed: %s' % e)
804
805 def __reduce__(self):
806 kwds = {}
807 if Popen.thread_is_spawning():
808 kwds['authkey'] = self._authkey
809
810 if getattr(self, '_isauto', False):
811 kwds['exposed'] = self._exposed_
812 return (RebuildProxy,
813 (AutoProxy, self._token, self._serializer, kwds))
814 else:
815 return (RebuildProxy,
816 (type(self), self._token, self._serializer, kwds))
817
818 def __deepcopy__(self, memo):
819 return self._getvalue()
820
821 def __repr__(self):
822 return '<%s object, typeid %r at %s>' % \
823 (type(self).__name__, self._token.typeid, '0x%x' % id(self))
824
825 def __str__(self):
826 '''
827 Return representation of the referent (or a fall-back if that fails)
828 '''
829 try:
830 return self._callmethod('__repr__')
831 except Exception:
832 return repr(self)[:-1] + "; '__str__()' failed>"
833
834#
835# Function used for unpickling
836#
837
838def RebuildProxy(func, token, serializer, kwds):
839 '''
840 Function used for unpickling proxy objects.
841
842 If possible the shared object is returned, or otherwise a proxy for it.
843 '''
844 server = getattr(current_process(), '_manager_server', None)
845
846 if server and server.address == token.address:
847 return server.id_to_obj[token.id][0]
848 else:
849 incref = (
850 kwds.pop('incref', True) and
851 not getattr(current_process(), '_inheriting', False)
852 )
853 return func(token, serializer, incref=incref, **kwds)
854
855#
856# Functions to create proxies and proxy types
857#
858
859def MakeProxyType(name, exposed, _cache={}):
860 '''
861 Return an proxy type whose methods are given by `exposed`
862 '''
863 exposed = tuple(exposed)
864 try:
865 return _cache[(name, exposed)]
866 except KeyError:
867 pass
868
869 dic = {}
870
871 for meth in exposed:
872 exec('''def %s(self, *args, **kwds):
873 return self._callmethod(%r, args, kwds)''' % (meth, meth), dic)
874
875 ProxyType = type(name, (BaseProxy,), dic)
876 ProxyType._exposed_ = exposed
877 _cache[(name, exposed)] = ProxyType
878 return ProxyType
879
880
881def AutoProxy(token, serializer, manager=None, authkey=None,
882 exposed=None, incref=True):
883 '''
884 Return an auto-proxy for `token`
885 '''
886 _Client = listener_client[serializer][1]
887
888 if exposed is None:
889 conn = _Client(token.address, authkey=authkey)
890 try:
891 exposed = dispatch(conn, None, 'get_methods', (token,))
892 finally:
893 conn.close()
894
895 if authkey is None and manager is not None:
896 authkey = manager._authkey
897 if authkey is None:
Benjamin Peterson58ea9fe2008-08-19 19:17:39 +0000898 authkey = current_process().authkey
Benjamin Petersone711caf2008-06-11 16:44:04 +0000899
900 ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed)
901 proxy = ProxyType(token, serializer, manager=manager, authkey=authkey,
902 incref=incref)
903 proxy._isauto = True
904 return proxy
905
906#
907# Types/callables which we will register with SyncManager
908#
909
910class Namespace(object):
911 def __init__(self, **kwds):
912 self.__dict__.update(kwds)
913 def __repr__(self):
914 items = list(self.__dict__.items())
915 temp = []
916 for name, value in items:
917 if not name.startswith('_'):
918 temp.append('%s=%r' % (name, value))
919 temp.sort()
920 return 'Namespace(%s)' % str.join(', ', temp)
921
922class Value(object):
923 def __init__(self, typecode, value, lock=True):
924 self._typecode = typecode
925 self._value = value
926 def get(self):
927 return self._value
928 def set(self, value):
929 self._value = value
930 def __repr__(self):
931 return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value)
932 value = property(get, set)
933
934def Array(typecode, sequence, lock=True):
935 return array.array(typecode, sequence)
936
937#
938# Proxy types used by SyncManager
939#
940
941class IteratorProxy(BaseProxy):
Benjamin Petersond61438a2008-06-25 13:04:48 +0000942 _exposed_ = ('__next__', 'send', 'throw', 'close')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000943 def __iter__(self):
944 return self
945 def __next__(self, *args):
946 return self._callmethod('__next__', args)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000947 def send(self, *args):
948 return self._callmethod('send', args)
949 def throw(self, *args):
950 return self._callmethod('throw', args)
951 def close(self, *args):
952 return self._callmethod('close', args)
953
954
955class AcquirerProxy(BaseProxy):
956 _exposed_ = ('acquire', 'release')
957 def acquire(self, blocking=True):
958 return self._callmethod('acquire', (blocking,))
959 def release(self):
960 return self._callmethod('release')
961 def __enter__(self):
962 return self._callmethod('acquire')
963 def __exit__(self, exc_type, exc_val, exc_tb):
964 return self._callmethod('release')
965
966
967class ConditionProxy(AcquirerProxy):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000968 _exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000969 def wait(self, timeout=None):
970 return self._callmethod('wait', (timeout,))
971 def notify(self):
972 return self._callmethod('notify')
973 def notify_all(self):
Benjamin Peterson672b8032008-06-11 19:14:14 +0000974 return self._callmethod('notify_all')
Charles-François Natalic8ce7152012-04-17 18:45:57 +0200975 def wait_for(self, predicate, timeout=None):
976 result = predicate()
977 if result:
978 return result
979 if timeout is not None:
980 endtime = _time() + timeout
981 else:
982 endtime = None
983 waittime = None
984 while not result:
985 if endtime is not None:
986 waittime = endtime - _time()
987 if waittime <= 0:
988 break
989 self.wait(waittime)
990 result = predicate()
991 return result
992
Benjamin Petersone711caf2008-06-11 16:44:04 +0000993
994class EventProxy(BaseProxy):
Benjamin Peterson04f7d532008-06-12 17:02:47 +0000995 _exposed_ = ('is_set', 'set', 'clear', 'wait')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000996 def is_set(self):
Benjamin Peterson04f7d532008-06-12 17:02:47 +0000997 return self._callmethod('is_set')
Benjamin Petersone711caf2008-06-11 16:44:04 +0000998 def set(self):
999 return self._callmethod('set')
1000 def clear(self):
1001 return self._callmethod('clear')
1002 def wait(self, timeout=None):
1003 return self._callmethod('wait', (timeout,))
1004
1005class NamespaceProxy(BaseProxy):
1006 _exposed_ = ('__getattribute__', '__setattr__', '__delattr__')
1007 def __getattr__(self, key):
1008 if key[0] == '_':
1009 return object.__getattribute__(self, key)
1010 callmethod = object.__getattribute__(self, '_callmethod')
1011 return callmethod('__getattribute__', (key,))
1012 def __setattr__(self, key, value):
1013 if key[0] == '_':
1014 return object.__setattr__(self, key, value)
1015 callmethod = object.__getattribute__(self, '_callmethod')
1016 return callmethod('__setattr__', (key, value))
1017 def __delattr__(self, key):
1018 if key[0] == '_':
1019 return object.__delattr__(self, key)
1020 callmethod = object.__getattribute__(self, '_callmethod')
1021 return callmethod('__delattr__', (key,))
1022
1023
1024class ValueProxy(BaseProxy):
1025 _exposed_ = ('get', 'set')
1026 def get(self):
1027 return self._callmethod('get')
1028 def set(self, value):
1029 return self._callmethod('set', (value,))
1030 value = property(get, set)
1031
1032
1033BaseListProxy = MakeProxyType('BaseListProxy', (
1034 '__add__', '__contains__', '__delitem__', '__delslice__',
1035 '__getitem__', '__getslice__', '__len__', '__mul__',
1036 '__reversed__', '__rmul__', '__setitem__', '__setslice__',
1037 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
1038 'reverse', 'sort', '__imul__'
1039 )) # XXX __getslice__ and __setslice__ unneeded in Py3.0
1040class ListProxy(BaseListProxy):
1041 def __iadd__(self, value):
1042 self._callmethod('extend', (value,))
1043 return self
1044 def __imul__(self, value):
1045 self._callmethod('__imul__', (value,))
1046 return self
1047
1048
1049DictProxy = MakeProxyType('DictProxy', (
1050 '__contains__', '__delitem__', '__getitem__', '__len__',
1051 '__setitem__', 'clear', 'copy', 'get', 'has_key', 'items',
1052 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'
1053 ))
1054
1055
1056ArrayProxy = MakeProxyType('ArrayProxy', (
1057 '__len__', '__getitem__', '__setitem__', '__getslice__', '__setslice__'
1058 )) # XXX __getslice__ and __setslice__ unneeded in Py3.0
1059
1060
1061PoolProxy = MakeProxyType('PoolProxy', (
1062 'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join',
Antoine Pitroude911b22011-12-21 11:03:24 +01001063 'map', 'map_async', 'starmap', 'starmap_async', 'terminate'
Benjamin Petersone711caf2008-06-11 16:44:04 +00001064 ))
1065PoolProxy._method_to_typeid_ = {
1066 'apply_async': 'AsyncResult',
1067 'map_async': 'AsyncResult',
Antoine Pitroude911b22011-12-21 11:03:24 +01001068 'starmap_async': 'AsyncResult',
Benjamin Petersone711caf2008-06-11 16:44:04 +00001069 'imap': 'Iterator',
1070 'imap_unordered': 'Iterator'
1071 }
1072
1073#
1074# Definition of SyncManager
1075#
1076
1077class SyncManager(BaseManager):
1078 '''
1079 Subclass of `BaseManager` which supports a number of shared object types.
1080
1081 The types registered are those intended for the synchronization
1082 of threads, plus `dict`, `list` and `Namespace`.
1083
1084 The `multiprocessing.Manager()` function creates started instances of
1085 this class.
1086 '''
1087
1088SyncManager.register('Queue', queue.Queue)
1089SyncManager.register('JoinableQueue', queue.Queue)
1090SyncManager.register('Event', threading.Event, EventProxy)
1091SyncManager.register('Lock', threading.Lock, AcquirerProxy)
1092SyncManager.register('RLock', threading.RLock, AcquirerProxy)
1093SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy)
1094SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore,
1095 AcquirerProxy)
1096SyncManager.register('Condition', threading.Condition, ConditionProxy)
1097SyncManager.register('Pool', Pool, PoolProxy)
1098SyncManager.register('list', list, ListProxy)
1099SyncManager.register('dict', dict, DictProxy)
1100SyncManager.register('Value', Value, ValueProxy)
1101SyncManager.register('Array', Array, ArrayProxy)
1102SyncManager.register('Namespace', Namespace, NamespaceProxy)
1103
1104# types returned by methods of PoolProxy
1105SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False)
1106SyncManager.register('AsyncResult', create_method=False)