blob: 0b695e46e596d9fede1d7b27afb10921243eb6fe [file] [log] [blame]
Benjamin Petersone711caf2008-06-11 16:44:04 +00001#
2# Module providing various facilities to other parts of the package
3#
4# multiprocessing/util.py
5#
R. David Murray3fc969a2010-12-14 01:38:16 +00006# Copyright (c) 2006-2008, R Oudkerk
Richard Oudkerk3e268aa2012-04-30 12:13:55 +01007# Licensed to PSF under a Contributor Agreement.
Benjamin Petersone711caf2008-06-11 16:44:04 +00008#
9
Richard Oudkerk739ae562012-05-25 13:54:53 +010010import os
Benjamin Petersone711caf2008-06-11 16:44:04 +000011import itertools
12import weakref
Benjamin Petersone711caf2008-06-11 16:44:04 +000013import atexit
14import threading # we want threading to install it's
15 # cleanup function before multiprocessing does
Antoine Pitrouebdcd852012-05-18 18:33:07 +020016from subprocess import _args_from_interpreter_flags
Benjamin Petersone711caf2008-06-11 16:44:04 +000017
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010018from . import process
Benjamin Petersone711caf2008-06-11 16:44:04 +000019
20__all__ = [
21 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger',
22 'log_to_stderr', 'get_temp_dir', 'register_after_fork',
Jesse Noller41faa542009-01-25 03:45:53 +000023 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal',
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010024 'close_all_fds_except', 'SUBDEBUG', 'SUBWARNING',
Benjamin Petersone711caf2008-06-11 16:44:04 +000025 ]
26
27#
28# Logging
29#
30
31NOTSET = 0
32SUBDEBUG = 5
33DEBUG = 10
34INFO = 20
35SUBWARNING = 25
36
37LOGGER_NAME = 'multiprocessing'
38DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s'
39
40_logger = None
41_log_to_stderr = False
42
43def sub_debug(msg, *args):
44 if _logger:
45 _logger.log(SUBDEBUG, msg, *args)
46
47def debug(msg, *args):
48 if _logger:
49 _logger.log(DEBUG, msg, *args)
50
51def info(msg, *args):
52 if _logger:
53 _logger.log(INFO, msg, *args)
54
55def sub_warning(msg, *args):
56 if _logger:
57 _logger.log(SUBWARNING, msg, *args)
58
59def get_logger():
60 '''
61 Returns logger used by multiprocessing
62 '''
63 global _logger
Florent Xicluna04842a82011-11-11 20:05:50 +010064 import logging
Benjamin Petersone711caf2008-06-11 16:44:04 +000065
Jesse Noller41faa542009-01-25 03:45:53 +000066 logging._acquireLock()
67 try:
68 if not _logger:
Benjamin Petersone711caf2008-06-11 16:44:04 +000069
Jesse Noller41faa542009-01-25 03:45:53 +000070 _logger = logging.getLogger(LOGGER_NAME)
71 _logger.propagate = 0
Benjamin Petersone711caf2008-06-11 16:44:04 +000072
Jesse Noller41faa542009-01-25 03:45:53 +000073 # XXX multiprocessing should cleanup before logging
74 if hasattr(atexit, 'unregister'):
75 atexit.unregister(_exit_function)
76 atexit.register(_exit_function)
77 else:
78 atexit._exithandlers.remove((_exit_function, (), {}))
79 atexit._exithandlers.append((_exit_function, (), {}))
80
81 finally:
82 logging._releaseLock()
Benjamin Petersone711caf2008-06-11 16:44:04 +000083
84 return _logger
85
Benjamin Petersone711caf2008-06-11 16:44:04 +000086def log_to_stderr(level=None):
87 '''
88 Turn on logging and add a handler which prints to stderr
89 '''
90 global _log_to_stderr
91 import logging
Jesse Noller41faa542009-01-25 03:45:53 +000092
Benjamin Petersone711caf2008-06-11 16:44:04 +000093 logger = get_logger()
94 formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
95 handler = logging.StreamHandler()
96 handler.setFormatter(formatter)
97 logger.addHandler(handler)
Jesse Noller41faa542009-01-25 03:45:53 +000098
99 if level:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000100 logger.setLevel(level)
101 _log_to_stderr = True
Jesse Noller41faa542009-01-25 03:45:53 +0000102 return _logger
Benjamin Petersone711caf2008-06-11 16:44:04 +0000103
104#
105# Function returning a temp directory which will be removed on exit
106#
107
108def get_temp_dir():
109 # get name of a temp directory which will be automatically cleaned up
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100110 tempdir = process.current_process()._config.get('tempdir')
111 if tempdir is None:
Benjamin Petersone711caf2008-06-11 16:44:04 +0000112 import shutil, tempfile
113 tempdir = tempfile.mkdtemp(prefix='pymp-')
114 info('created temp directory %s', tempdir)
115 Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100)
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100116 process.current_process()._config['tempdir'] = tempdir
117 return tempdir
Benjamin Petersone711caf2008-06-11 16:44:04 +0000118
119#
120# Support for reinitialization of objects when bootstrapping a child process
121#
122
123_afterfork_registry = weakref.WeakValueDictionary()
124_afterfork_counter = itertools.count()
125
126def _run_after_forkers():
127 items = list(_afterfork_registry.items())
128 items.sort()
129 for (index, ident, func), obj in items:
130 try:
131 func(obj)
132 except Exception as e:
133 info('after forker raised exception %s', e)
134
135def register_after_fork(obj, func):
136 _afterfork_registry[(next(_afterfork_counter), id(obj), func)] = obj
137
138#
139# Finalization using weakrefs
140#
141
142_finalizer_registry = {}
143_finalizer_counter = itertools.count()
144
145
146class Finalize(object):
147 '''
148 Class which supports object finalization using weakrefs
149 '''
150 def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None):
151 assert exitpriority is None or type(exitpriority) is int
152
153 if obj is not None:
154 self._weakref = weakref.ref(obj, self)
155 else:
156 assert exitpriority is not None
157
158 self._callback = callback
159 self._args = args
160 self._kwargs = kwargs or {}
161 self._key = (exitpriority, next(_finalizer_counter))
Richard Oudkerk739ae562012-05-25 13:54:53 +0100162 self._pid = os.getpid()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000163
164 _finalizer_registry[self._key] = self
165
Antoine Pitrou71a28a92011-07-09 01:03:00 +0200166 def __call__(self, wr=None,
167 # Need to bind these locally because the globals can have
168 # been cleared at shutdown
169 _finalizer_registry=_finalizer_registry,
Richard Oudkerkad064442012-06-04 18:58:59 +0100170 sub_debug=sub_debug, getpid=os.getpid):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000171 '''
172 Run the callback unless it has already been called or cancelled
173 '''
174 try:
175 del _finalizer_registry[self._key]
176 except KeyError:
177 sub_debug('finalizer no longer registered')
178 else:
Richard Oudkerkad064442012-06-04 18:58:59 +0100179 if self._pid != getpid():
Richard Oudkerk739ae562012-05-25 13:54:53 +0100180 sub_debug('finalizer ignored because different process')
181 res = None
182 else:
183 sub_debug('finalizer calling %s with args %s and kwargs %s',
184 self._callback, self._args, self._kwargs)
185 res = self._callback(*self._args, **self._kwargs)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000186 self._weakref = self._callback = self._args = \
187 self._kwargs = self._key = None
188 return res
189
190 def cancel(self):
191 '''
192 Cancel finalization of the object
193 '''
194 try:
195 del _finalizer_registry[self._key]
196 except KeyError:
197 pass
198 else:
199 self._weakref = self._callback = self._args = \
200 self._kwargs = self._key = None
201
202 def still_active(self):
203 '''
204 Return whether this finalizer is still waiting to invoke callback
205 '''
206 return self._key in _finalizer_registry
207
208 def __repr__(self):
209 try:
210 obj = self._weakref()
211 except (AttributeError, TypeError):
212 obj = None
213
214 if obj is None:
215 return '<Finalize object, dead>'
216
217 x = '<Finalize object, callback=%s' % \
218 getattr(self._callback, '__name__', self._callback)
219 if self._args:
220 x += ', args=' + str(self._args)
221 if self._kwargs:
222 x += ', kwargs=' + str(self._kwargs)
223 if self._key[0] is not None:
224 x += ', exitprority=' + str(self._key[0])
225 return x + '>'
226
227
228def _run_finalizers(minpriority=None):
229 '''
230 Run all finalizers whose exit priority is not None and at least minpriority
231
232 Finalizers with highest priority are called first; finalizers with
233 the same priority will be called in reverse order of creation.
234 '''
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400235 if _finalizer_registry is None:
236 # This function may be called after this module's globals are
237 # destroyed. See the _exit_function function in this module for more
238 # notes.
239 return
Alexander Belopolsky7f704c12012-09-09 13:25:06 -0400240
Benjamin Petersone711caf2008-06-11 16:44:04 +0000241 if minpriority is None:
242 f = lambda p : p[0][0] is not None
243 else:
244 f = lambda p : p[0][0] is not None and p[0][0] >= minpriority
245
246 items = [x for x in list(_finalizer_registry.items()) if f(x)]
247 items.sort(reverse=True)
248
249 for key, finalizer in items:
250 sub_debug('calling %s', finalizer)
251 try:
252 finalizer()
253 except Exception:
254 import traceback
255 traceback.print_exc()
256
257 if minpriority is None:
258 _finalizer_registry.clear()
259
260#
261# Clean up on exit
262#
263
264def is_exiting():
265 '''
266 Returns true if the process is shutting down
267 '''
268 return _exiting or _exiting is None
269
270_exiting = False
271
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400272def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers,
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100273 active_children=process.active_children,
274 current_process=process.current_process):
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400275 # We hold on to references to functions in the arglist due to the
276 # situation described below, where this function is called after this
277 # module's globals are destroyed.
278
Benjamin Petersone711caf2008-06-11 16:44:04 +0000279 global _exiting
280
Richard Oudkerk73d9a292012-06-14 15:30:10 +0100281 if not _exiting:
282 _exiting = True
Benjamin Petersone711caf2008-06-11 16:44:04 +0000283
Richard Oudkerk73d9a292012-06-14 15:30:10 +0100284 info('process shutting down')
285 debug('running all "atexit" finalizers with priority >= 0')
286 _run_finalizers(0)
Benjamin Petersone711caf2008-06-11 16:44:04 +0000287
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400288 if current_process() is not None:
289 # We check if the current process is None here because if
Andrew Svetlov5b898402012-12-18 21:26:36 +0200290 # it's None, any call to ``active_children()`` will raise
Richard Oudkerke8cd6bb2012-09-13 17:27:15 +0100291 # an AttributeError (active_children winds up trying to
292 # get attributes from util._current_process). One
293 # situation where this can happen is if someone has
294 # manipulated sys.modules, causing this module to be
295 # garbage collected. The destructor for the module type
296 # then replaces all values in the module dict with None.
297 # For instance, after setuptools runs a test it replaces
298 # sys.modules with a copy created earlier. See issues
299 # #9775 and #15881. Also related: #4106, #9205, and
300 # #9207.
Benjamin Petersone711caf2008-06-11 16:44:04 +0000301
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400302 for p in active_children():
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100303 if p.daemon:
Alexander Belopolskyf36c49d2012-09-09 13:20:58 -0400304 info('calling terminate() for daemon %s', p.name)
305 p._popen.terminate()
306
307 for p in active_children():
308 info('calling join() for process %s', p.name)
309 p.join()
Richard Oudkerk73d9a292012-06-14 15:30:10 +0100310
311 debug('running the remaining "atexit" finalizers')
312 _run_finalizers()
Benjamin Petersone711caf2008-06-11 16:44:04 +0000313
314atexit.register(_exit_function)
315
316#
317# Some fork aware types
318#
319
320class ForkAwareThreadLock(object):
321 def __init__(self):
Richard Oudkerk409c3132013-04-17 20:58:00 +0100322 self._reset()
323 register_after_fork(self, ForkAwareThreadLock._reset)
324
325 def _reset(self):
Benjamin Petersone711caf2008-06-11 16:44:04 +0000326 self._lock = threading.Lock()
327 self.acquire = self._lock.acquire
328 self.release = self._lock.release
Benjamin Petersone711caf2008-06-11 16:44:04 +0000329
330class ForkAwareLocal(threading.local):
331 def __init__(self):
332 register_after_fork(self, lambda obj : obj.__dict__.clear())
333 def __reduce__(self):
334 return type(self), ()
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100335
336#
337# Close fds except those specified
338#
339
340try:
341 MAXFD = os.sysconf("SC_OPEN_MAX")
342except Exception:
343 MAXFD = 256
344
345def close_all_fds_except(fds):
346 fds = list(fds) + [-1, MAXFD]
347 fds.sort()
348 assert fds[-1] == MAXFD, 'fd too large'
349 for i in range(len(fds) - 1):
350 os.closerange(fds[i]+1, fds[i+1])
351
352#
353# Start a program with only specified fds kept open
354#
355
356def spawnv_passfds(path, args, passfds):
Victor Stinner67973c02013-08-28 12:21:47 +0200357 import _posixsubprocess
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100358 passfds = sorted(passfds)
Victor Stinnerdaf45552013-08-28 00:53:59 +0200359 errpipe_read, errpipe_write = os.pipe()
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100360 try:
361 return _posixsubprocess.fork_exec(
362 args, [os.fsencode(path)], True, passfds, None, None,
363 -1, -1, -1, -1, -1, -1, errpipe_read, errpipe_write,
364 False, False, None)
365 finally:
366 os.close(errpipe_read)
367 os.close(errpipe_write)