Debian Codegraph @

lib-python/3/multiprocessing/util.py

raw symbols SCIP
1 #
2 # Module providing various facilities to other parts of the package
3 #
4 # multiprocessing/util.py
5 #
6 # Copyright (c) 2006-2008, R Oudkerk
7 # Licensed to PSF under a Contributor Agreement.
8 #
9
10 import os
11 import itertools
12 import sys
13 import weakref
14 import atexit
15 import threading # we want threading to install it's
16 # cleanup function before multiprocessing does
17 from subprocess import _args_from_interpreter_flags
18
19 from . import process
20
21 __all__ = [
22 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger',
23 'log_to_stderr', 'get_temp_dir', 'register_after_fork',
24 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal',
25 'close_all_fds_except', 'SUBDEBUG', 'SUBWARNING',
26 ]
27
28 #
29 # Logging
30 #
31
32 NOTSET = 0
33 SUBDEBUG = 5
34 DEBUG = 10
35 INFO = 20
36 SUBWARNING = 25
37
38 LOGGER_NAME = 'multiprocessing'
39 DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s'
40
41 _logger = None
42 _log_to_stderr = False
43
44 def sub_debug(msg, *args):
45 if _logger:
46 _logger.log(SUBDEBUG, msg, *args, stacklevel=2)
47
48 def debug(msg, *args):
49 if _logger:
50 _logger.log(DEBUG, msg, *args, stacklevel=2)
51
52 def info(msg, *args):
53 if _logger:
54 _logger.log(INFO, msg, *args, stacklevel=2)
55
56 def sub_warning(msg, *args):
57 if _logger:
58 _logger.log(SUBWARNING, msg, *args, stacklevel=2)
59
60 def get_logger():
61 '''
62 Returns logger used by multiprocessing
63 '''
64 global _logger
65 import logging
66
67 logging._acquireLock()
68 try:
69 if not _logger:
70
71 _logger = logging.getLogger(LOGGER_NAME)
72 _logger.propagate = 0
73
74 # XXX multiprocessing should cleanup before logging
75 if hasattr(atexit, 'unregister'):
76 atexit.unregister(_exit_function)
77 atexit.register(_exit_function)
78 else:
79 atexit._exithandlers.remove((_exit_function, (), {}))
80 atexit._exithandlers.append((_exit_function, (), {}))
81
82 finally:
83 logging._releaseLock()
84
85 return _logger
86
87 def log_to_stderr(level=None):
88 '''
89 Turn on logging and add a handler which prints to stderr
90 '''
91 global _log_to_stderr
92 import logging
93
94 logger = get_logger()
95 formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
96 handler = logging.StreamHandler()
97 handler.setFormatter(formatter)
98 logger.addHandler(handler)
99
100 if level:
101 logger.setLevel(level)
102 _log_to_stderr = True
103 return _logger
104
105
106 # Abstract socket support
107
108 def _platform_supports_abstract_sockets():
109 if sys.platform == "linux":
110 return True
111 if hasattr(sys, 'getandroidapilevel'):
112 return True
113 return False
114
115
116 def is_abstract_socket_namespace(address):
117 if not address:
118 return False
119 if isinstance(address, bytes):
120 return address[0] == 0
121 elif isinstance(address, str):
122 return address[0] == "\0"
123 raise TypeError(f'address type of {address!r} unrecognized')
124
125
126 abstract_sockets_supported = _platform_supports_abstract_sockets()
127
128 #
129 # Function returning a temp directory which will be removed on exit
130 #
131
132 def _remove_temp_dir(rmtree, tempdir):
133 def onerror(func, path, err_info):
134 if not issubclass(err_info[0], FileNotFoundError):
135 raise
136 rmtree(tempdir, onerror=onerror)
137
138 current_process = process.current_process()
139 # current_process() can be None if the finalizer is called
140 # late during Python finalization
141 if current_process is not None:
142 current_process._config['tempdir'] = None
143
144 def get_temp_dir():
145 # get name of a temp directory which will be automatically cleaned up
146 tempdir = process.current_process()._config.get('tempdir')
147 if tempdir is None:
148 import shutil, tempfile
149 tempdir = tempfile.mkdtemp(prefix='pymp-')
150 info('created temp directory %s', tempdir)
151 # keep a strong reference to shutil.rmtree(), since the finalizer
152 # can be called late during Python shutdown
153 Finalize(None, _remove_temp_dir, args=(shutil.rmtree, tempdir),
154 exitpriority=-100)
155 process.current_process()._config['tempdir'] = tempdir
156 return tempdir
157
158 #
159 # Support for reinitialization of objects when bootstrapping a child process
160 #
161
162 _afterfork_registry = weakref.WeakValueDictionary()
163 _afterfork_counter = itertools.count()
164
165 def _run_after_forkers():
166 items = list(_afterfork_registry.items())
167 items.sort()
168 for (index, ident, func), obj in items:
169 try:
170 func(obj)
171 except Exception as e:
172 info('after forker raised exception %s', e)
173
174 def register_after_fork(obj, func):
175 _afterfork_registry[(next(_afterfork_counter), id(obj), func)] = obj
176
177 #
178 # Finalization using weakrefs
179 #
180
181 _finalizer_registry = {}
182 _finalizer_counter = itertools.count()
183
184
185 class Finalize(object):
186 '''
187 Class which supports object finalization using weakrefs
188 '''
189 def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None):
190 if (exitpriority is not None) and not isinstance(exitpriority,int):
191 raise TypeError(
192 "Exitpriority ({0!r}) must be None or int, not {1!s}".format(
193 exitpriority, type(exitpriority)))
194
195 if obj is not None:
196 self._weakref = weakref.ref(obj, self)
197 elif exitpriority is None:
198 raise ValueError("Without object, exitpriority cannot be None")
199
200 self._callback = callback
201 self._args = args
202 self._kwargs = kwargs or {}
203 self._key = (exitpriority, next(_finalizer_counter))
204 self._pid = os.getpid()
205
206 _finalizer_registry[self._key] = self
207
208 def __call__(self, wr=None,
209 # Need to bind these locally because the globals can have
210 # been cleared at shutdown
211 _finalizer_registry=_finalizer_registry,
212 sub_debug=sub_debug, getpid=os.getpid):
213 '''
214 Run the callback unless it has already been called or cancelled
215 '''
216 try:
217 del _finalizer_registry[self._key]
218 except KeyError:
219 sub_debug('finalizer no longer registered')
220 else:
221 if self._pid != getpid():
222 sub_debug('finalizer ignored because different process')
223 res = None
224 else:
225 sub_debug('finalizer calling %s with args %s and kwargs %s',
226 self._callback, self._args, self._kwargs)
227 res = self._callback(*self._args, **self._kwargs)
228 self._weakref = self._callback = self._args = \
229 self._kwargs = self._key = None
230 return res
231
232 def cancel(self):
233 '''
234 Cancel finalization of the object
235 '''
236 try:
237 del _finalizer_registry[self._key]
238 except KeyError:
239 pass
240 else:
241 self._weakref = self._callback = self._args = \
242 self._kwargs = self._key = None
243
244 def still_active(self):
245 '''
246 Return whether this finalizer is still waiting to invoke callback
247 '''
248 return self._key in _finalizer_registry
249
250 def __repr__(self):
251 try:
252 obj = self._weakref()
253 except (AttributeError, TypeError):
254 obj = None
255
256 if obj is None:
257 return '<%s object, dead>' % self.__class__.__name__
258
259 x = '<%s object, callback=%s' % (
260 self.__class__.__name__,
261 getattr(self._callback, '__name__', self._callback))
262 if self._args:
263 x += ', args=' + str(self._args)
264 if self._kwargs:
265 x += ', kwargs=' + str(self._kwargs)
266 if self._key[0] is not None:
267 x += ', exitpriority=' + str(self._key[0])
268 return x + '>'
269
270
271 def _run_finalizers(minpriority=None):
272 '''
273 Run all finalizers whose exit priority is not None and at least minpriority
274
275 Finalizers with highest priority are called first; finalizers with
276 the same priority will be called in reverse order of creation.
277 '''
278 if _finalizer_registry is None:
279 # This function may be called after this module's globals are
280 # destroyed. See the _exit_function function in this module for more
281 # notes.
282 return
283
284 if minpriority is None:
285 f = lambda p : p[0] is not None
286 else:
287 f = lambda p : p[0] is not None and p[0] >= minpriority
288
289 # Careful: _finalizer_registry may be mutated while this function
290 # is running (either by a GC run or by another thread).
291
292 # list(_finalizer_registry) should be atomic, while
293 # list(_finalizer_registry.items()) is not.
294 keys = [key for key in list(_finalizer_registry) if f(key)]
295 keys.sort(reverse=True)
296
297 for key in keys:
298 finalizer = _finalizer_registry.get(key)
299 # key may have been removed from the registry
300 if finalizer is not None:
301 sub_debug('calling %s', finalizer)
302 try:
303 finalizer()
304 except Exception:
305 import traceback
306 traceback.print_exc()
307
308 if minpriority is None:
309 _finalizer_registry.clear()
310
311 #
312 # Clean up on exit
313 #
314
315 def is_exiting():
316 '''
317 Returns true if the process is shutting down
318 '''
319 return _exiting or _exiting is None
320
321 _exiting = False
322
323 def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers,
324 active_children=process.active_children,
325 current_process=process.current_process):
326 # We hold on to references to functions in the arglist due to the
327 # situation described below, where this function is called after this
328 # module's globals are destroyed.
329
330 global _exiting
331
332 if not _exiting:
333 _exiting = True
334
335 info('process shutting down')
336 debug('running all "atexit" finalizers with priority >= 0')
337 _run_finalizers(0)
338
339 if current_process() is not None:
340 # We check if the current process is None here because if
341 # it's None, any call to ``active_children()`` will raise
342 # an AttributeError (active_children winds up trying to
343 # get attributes from util._current_process). One
344 # situation where this can happen is if someone has
345 # manipulated sys.modules, causing this module to be
346 # garbage collected. The destructor for the module type
347 # then replaces all values in the module dict with None.
348 # For instance, after setuptools runs a test it replaces
349 # sys.modules with a copy created earlier. See issues
350 # #9775 and #15881. Also related: #4106, #9205, and
351 # #9207.
352
353 for p in active_children():
354 if p.daemon:
355 info('calling terminate() for daemon %s', p.name)
356 p._popen.terminate()
357
358 for p in active_children():
359 info('calling join() for process %s', p.name)
360 p.join()
361
362 debug('running the remaining "atexit" finalizers')
363 _run_finalizers()
364
365 atexit.register(_exit_function)
366
367 #
368 # Some fork aware types
369 #
370
371 class ForkAwareThreadLock(object):
372 def __init__(self):
373 self._lock = threading.Lock()
374 self.acquire = self._lock.acquire
375 self.release = self._lock.release
376 register_after_fork(self, ForkAwareThreadLock._at_fork_reinit)
377
378 def _at_fork_reinit(self):
379 self._lock._at_fork_reinit()
380
381 def __enter__(self):
382 return self._lock.__enter__()
383
384 def __exit__(self, *args):
385 return self._lock.__exit__(*args)
386
387
388 class ForkAwareLocal(threading.local):
389 def __init__(self):
390 register_after_fork(self, lambda obj : obj.__dict__.clear())
391 def __reduce__(self):
392 return type(self), ()
393
394 #
395 # Close fds except those specified
396 #
397
398 try:
399 MAXFD = os.sysconf("SC_OPEN_MAX")
400 except Exception:
401 MAXFD = 256
402
403 def close_all_fds_except(fds):
404 fds = list(fds) + [-1, MAXFD]
405 fds.sort()
406 assert fds[-1] == MAXFD, 'fd too large'
407 for i in range(len(fds) - 1):
408 os.closerange(fds[i]+1, fds[i+1])
409 #
410 # Close sys.stdin and replace stdin with os.devnull
411 #
412
413 def _close_stdin():
414 if sys.stdin is None:
415 return
416
417 try:
418 sys.stdin.close()
419 except (OSError, ValueError):
420 pass
421
422 try:
423 fd = os.open(os.devnull, os.O_RDONLY)
424 try:
425 sys.stdin = open(fd, encoding="utf-8", closefd=False)
426 except:
427 os.close(fd)
428 raise
429 except (OSError, ValueError):
430 pass
431
432 #
433 # Flush standard streams, if any
434 #
435
436 def _flush_std_streams():
437 try:
438 sys.stdout.flush()
439 except (AttributeError, ValueError):
440 pass
441 try:
442 sys.stderr.flush()
443 except (AttributeError, ValueError):
444 pass
445
446 #
447 # Start a program with only specified fds kept open
448 #
449
450 def spawnv_passfds(path, args, passfds):
451 import _posixsubprocess
452 import subprocess
453 passfds = tuple(sorted(map(int, passfds)))
454 errpipe_read, errpipe_write = os.pipe()
455 try:
456 return _posixsubprocess.fork_exec(
457 args, [path], True, passfds, None, None,
458 -1, -1, -1, -1, -1, -1, errpipe_read, errpipe_write,
459 False, False, -1, None, None, None, -1, None,
460 subprocess._USE_VFORK)
461 finally:
462 os.close(errpipe_read)
463 os.close(errpipe_write)
464
465
466 def close_fds(*fds):
467 """Close each file descriptor given as an argument"""
468 for fd in fds:
469 os.close(fd)
470
471
472 def _cleanup_tests():
473 """Cleanup multiprocessing resources when multiprocessing tests
474 completed."""
475
476 from test import support
477
478 # cleanup multiprocessing
479 process._cleanup()
480
481 # Stop the ForkServer process if it's running
482 from multiprocessing import forkserver
483 forkserver._forkserver._stop()
484
485 # Stop the ResourceTracker process if it's running
486 from multiprocessing import resource_tracker
487 resource_tracker._resource_tracker._stop()
488
489 # bpo-37421: Explicitly call _run_finalizers() to remove immediately
490 # temporary directories created by multiprocessing.util.get_temp_dir().
491 _run_finalizers()
492 support.gc_collect()
493
494 support.reap_children()