Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 1 | # |
| 2 | # Module providing various facilities to other parts of the package |
| 3 | # |
| 4 | # multiprocessing/util.py |
| 5 | # |
R. David Murray | 3fc969a | 2010-12-14 01:38:16 +0000 | [diff] [blame] | 6 | # Copyright (c) 2006-2008, R Oudkerk |
| 7 | # All rights reserved. |
| 8 | # |
| 9 | # Redistribution and use in source and binary forms, with or without |
| 10 | # modification, are permitted provided that the following conditions |
| 11 | # are met: |
| 12 | # |
| 13 | # 1. Redistributions of source code must retain the above copyright |
| 14 | # notice, this list of conditions and the following disclaimer. |
| 15 | # 2. Redistributions in binary form must reproduce the above copyright |
| 16 | # notice, this list of conditions and the following disclaimer in the |
| 17 | # documentation and/or other materials provided with the distribution. |
| 18 | # 3. Neither the name of author nor the names of any contributors may be |
| 19 | # used to endorse or promote products derived from this software |
| 20 | # without specific prior written permission. |
| 21 | # |
| 22 | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND |
| 23 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 24 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 25 | # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE |
| 26 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 27 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS |
| 28 | # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |
| 29 | # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
| 30 | # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY |
| 31 | # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF |
| 32 | # SUCH DAMAGE. |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 33 | # |
| 34 | |
Antoine Pitrou | 176f07d | 2011-06-06 19:35:31 +0200 | [diff] [blame] | 35 | import functools |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 36 | import itertools |
| 37 | import weakref |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 38 | import atexit |
Antoine Pitrou | 176f07d | 2011-06-06 19:35:31 +0200 | [diff] [blame] | 39 | import select |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 40 | import threading # we want threading to install it's |
| 41 | # cleanup function before multiprocessing does |
| 42 | |
| 43 | from multiprocessing.process import current_process, active_children |
| 44 | |
| 45 | __all__ = [ |
| 46 | 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger', |
| 47 | 'log_to_stderr', 'get_temp_dir', 'register_after_fork', |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 48 | 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal', |
| 49 | 'SUBDEBUG', 'SUBWARNING', |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 50 | ] |
| 51 | |
| 52 | # |
| 53 | # Logging |
| 54 | # |
| 55 | |
| 56 | NOTSET = 0 |
| 57 | SUBDEBUG = 5 |
| 58 | DEBUG = 10 |
| 59 | INFO = 20 |
| 60 | SUBWARNING = 25 |
| 61 | |
| 62 | LOGGER_NAME = 'multiprocessing' |
| 63 | DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s' |
| 64 | |
| 65 | _logger = None |
| 66 | _log_to_stderr = False |
| 67 | |
| 68 | def sub_debug(msg, *args): |
| 69 | if _logger: |
| 70 | _logger.log(SUBDEBUG, msg, *args) |
| 71 | |
| 72 | def debug(msg, *args): |
| 73 | if _logger: |
| 74 | _logger.log(DEBUG, msg, *args) |
| 75 | |
| 76 | def info(msg, *args): |
| 77 | if _logger: |
| 78 | _logger.log(INFO, msg, *args) |
| 79 | |
| 80 | def sub_warning(msg, *args): |
| 81 | if _logger: |
| 82 | _logger.log(SUBWARNING, msg, *args) |
| 83 | |
| 84 | def get_logger(): |
| 85 | ''' |
| 86 | Returns logger used by multiprocessing |
| 87 | ''' |
| 88 | global _logger |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 89 | import logging, atexit |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 90 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 91 | logging._acquireLock() |
| 92 | try: |
| 93 | if not _logger: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 94 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 95 | _logger = logging.getLogger(LOGGER_NAME) |
| 96 | _logger.propagate = 0 |
| 97 | logging.addLevelName(SUBDEBUG, 'SUBDEBUG') |
| 98 | logging.addLevelName(SUBWARNING, 'SUBWARNING') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 99 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 100 | # XXX multiprocessing should cleanup before logging |
| 101 | if hasattr(atexit, 'unregister'): |
| 102 | atexit.unregister(_exit_function) |
| 103 | atexit.register(_exit_function) |
| 104 | else: |
| 105 | atexit._exithandlers.remove((_exit_function, (), {})) |
| 106 | atexit._exithandlers.append((_exit_function, (), {})) |
| 107 | |
| 108 | finally: |
| 109 | logging._releaseLock() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 110 | |
| 111 | return _logger |
| 112 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 113 | def log_to_stderr(level=None): |
| 114 | ''' |
| 115 | Turn on logging and add a handler which prints to stderr |
| 116 | ''' |
| 117 | global _log_to_stderr |
| 118 | import logging |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 119 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 120 | logger = get_logger() |
| 121 | formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT) |
| 122 | handler = logging.StreamHandler() |
| 123 | handler.setFormatter(formatter) |
| 124 | logger.addHandler(handler) |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 125 | |
| 126 | if level: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 127 | logger.setLevel(level) |
| 128 | _log_to_stderr = True |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 129 | return _logger |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 130 | |
| 131 | # |
| 132 | # Function returning a temp directory which will be removed on exit |
| 133 | # |
| 134 | |
| 135 | def get_temp_dir(): |
| 136 | # get name of a temp directory which will be automatically cleaned up |
| 137 | if current_process()._tempdir is None: |
| 138 | import shutil, tempfile |
| 139 | tempdir = tempfile.mkdtemp(prefix='pymp-') |
| 140 | info('created temp directory %s', tempdir) |
| 141 | Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100) |
| 142 | current_process()._tempdir = tempdir |
| 143 | return current_process()._tempdir |
| 144 | |
| 145 | # |
| 146 | # Support for reinitialization of objects when bootstrapping a child process |
| 147 | # |
| 148 | |
| 149 | _afterfork_registry = weakref.WeakValueDictionary() |
| 150 | _afterfork_counter = itertools.count() |
| 151 | |
| 152 | def _run_after_forkers(): |
| 153 | items = list(_afterfork_registry.items()) |
| 154 | items.sort() |
| 155 | for (index, ident, func), obj in items: |
| 156 | try: |
| 157 | func(obj) |
| 158 | except Exception as e: |
| 159 | info('after forker raised exception %s', e) |
| 160 | |
| 161 | def register_after_fork(obj, func): |
| 162 | _afterfork_registry[(next(_afterfork_counter), id(obj), func)] = obj |
| 163 | |
| 164 | # |
| 165 | # Finalization using weakrefs |
| 166 | # |
| 167 | |
| 168 | _finalizer_registry = {} |
| 169 | _finalizer_counter = itertools.count() |
| 170 | |
| 171 | |
| 172 | class Finalize(object): |
| 173 | ''' |
| 174 | Class which supports object finalization using weakrefs |
| 175 | ''' |
| 176 | def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None): |
| 177 | assert exitpriority is None or type(exitpriority) is int |
| 178 | |
| 179 | if obj is not None: |
| 180 | self._weakref = weakref.ref(obj, self) |
| 181 | else: |
| 182 | assert exitpriority is not None |
| 183 | |
| 184 | self._callback = callback |
| 185 | self._args = args |
| 186 | self._kwargs = kwargs or {} |
| 187 | self._key = (exitpriority, next(_finalizer_counter)) |
| 188 | |
| 189 | _finalizer_registry[self._key] = self |
| 190 | |
Antoine Pitrou | 71a28a9 | 2011-07-09 01:03:00 +0200 | [diff] [blame] | 191 | def __call__(self, wr=None, |
| 192 | # Need to bind these locally because the globals can have |
| 193 | # been cleared at shutdown |
| 194 | _finalizer_registry=_finalizer_registry, |
| 195 | sub_debug=sub_debug): |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 196 | ''' |
| 197 | Run the callback unless it has already been called or cancelled |
| 198 | ''' |
| 199 | try: |
| 200 | del _finalizer_registry[self._key] |
| 201 | except KeyError: |
| 202 | sub_debug('finalizer no longer registered') |
| 203 | else: |
| 204 | sub_debug('finalizer calling %s with args %s and kwargs %s', |
| 205 | self._callback, self._args, self._kwargs) |
| 206 | res = self._callback(*self._args, **self._kwargs) |
| 207 | self._weakref = self._callback = self._args = \ |
| 208 | self._kwargs = self._key = None |
| 209 | return res |
| 210 | |
| 211 | def cancel(self): |
| 212 | ''' |
| 213 | Cancel finalization of the object |
| 214 | ''' |
| 215 | try: |
| 216 | del _finalizer_registry[self._key] |
| 217 | except KeyError: |
| 218 | pass |
| 219 | else: |
| 220 | self._weakref = self._callback = self._args = \ |
| 221 | self._kwargs = self._key = None |
| 222 | |
| 223 | def still_active(self): |
| 224 | ''' |
| 225 | Return whether this finalizer is still waiting to invoke callback |
| 226 | ''' |
| 227 | return self._key in _finalizer_registry |
| 228 | |
| 229 | def __repr__(self): |
| 230 | try: |
| 231 | obj = self._weakref() |
| 232 | except (AttributeError, TypeError): |
| 233 | obj = None |
| 234 | |
| 235 | if obj is None: |
| 236 | return '<Finalize object, dead>' |
| 237 | |
| 238 | x = '<Finalize object, callback=%s' % \ |
| 239 | getattr(self._callback, '__name__', self._callback) |
| 240 | if self._args: |
| 241 | x += ', args=' + str(self._args) |
| 242 | if self._kwargs: |
| 243 | x += ', kwargs=' + str(self._kwargs) |
| 244 | if self._key[0] is not None: |
| 245 | x += ', exitprority=' + str(self._key[0]) |
| 246 | return x + '>' |
| 247 | |
| 248 | |
| 249 | def _run_finalizers(minpriority=None): |
| 250 | ''' |
| 251 | Run all finalizers whose exit priority is not None and at least minpriority |
| 252 | |
| 253 | Finalizers with highest priority are called first; finalizers with |
| 254 | the same priority will be called in reverse order of creation. |
| 255 | ''' |
| 256 | if minpriority is None: |
| 257 | f = lambda p : p[0][0] is not None |
| 258 | else: |
| 259 | f = lambda p : p[0][0] is not None and p[0][0] >= minpriority |
| 260 | |
| 261 | items = [x for x in list(_finalizer_registry.items()) if f(x)] |
| 262 | items.sort(reverse=True) |
| 263 | |
| 264 | for key, finalizer in items: |
| 265 | sub_debug('calling %s', finalizer) |
| 266 | try: |
| 267 | finalizer() |
| 268 | except Exception: |
| 269 | import traceback |
| 270 | traceback.print_exc() |
| 271 | |
| 272 | if minpriority is None: |
| 273 | _finalizer_registry.clear() |
| 274 | |
| 275 | # |
| 276 | # Clean up on exit |
| 277 | # |
| 278 | |
| 279 | def is_exiting(): |
| 280 | ''' |
| 281 | Returns true if the process is shutting down |
| 282 | ''' |
| 283 | return _exiting or _exiting is None |
| 284 | |
| 285 | _exiting = False |
| 286 | |
| 287 | def _exit_function(): |
| 288 | global _exiting |
| 289 | |
| 290 | info('process shutting down') |
| 291 | debug('running all "atexit" finalizers with priority >= 0') |
| 292 | _run_finalizers(0) |
| 293 | |
| 294 | for p in active_children(): |
| 295 | if p._daemonic: |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 296 | info('calling terminate() for daemon %s', p.name) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 297 | p._popen.terminate() |
| 298 | |
| 299 | for p in active_children(): |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 300 | info('calling join() for process %s', p.name) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 301 | p.join() |
| 302 | |
| 303 | debug('running the remaining "atexit" finalizers') |
| 304 | _run_finalizers() |
| 305 | |
| 306 | atexit.register(_exit_function) |
| 307 | |
| 308 | # |
| 309 | # Some fork aware types |
| 310 | # |
| 311 | |
| 312 | class ForkAwareThreadLock(object): |
| 313 | def __init__(self): |
| 314 | self._lock = threading.Lock() |
| 315 | self.acquire = self._lock.acquire |
| 316 | self.release = self._lock.release |
| 317 | register_after_fork(self, ForkAwareThreadLock.__init__) |
| 318 | |
| 319 | class ForkAwareLocal(threading.local): |
| 320 | def __init__(self): |
| 321 | register_after_fork(self, lambda obj : obj.__dict__.clear()) |
| 322 | def __reduce__(self): |
| 323 | return type(self), () |
Antoine Pitrou | 176f07d | 2011-06-06 19:35:31 +0200 | [diff] [blame] | 324 | |
| 325 | |
| 326 | # |
| 327 | # Automatic retry after EINTR |
| 328 | # |
| 329 | |
Antoine Pitrou | 24d659d | 2011-10-23 23:49:42 +0200 | [diff] [blame] | 330 | def _eintr_retry(func): |
Antoine Pitrou | 176f07d | 2011-06-06 19:35:31 +0200 | [diff] [blame] | 331 | @functools.wraps(func) |
| 332 | def wrapped(*args, **kwargs): |
| 333 | while True: |
| 334 | try: |
| 335 | return func(*args, **kwargs) |
Antoine Pitrou | 24d659d | 2011-10-23 23:49:42 +0200 | [diff] [blame] | 336 | except InterruptedError: |
| 337 | continue |
Antoine Pitrou | 176f07d | 2011-06-06 19:35:31 +0200 | [diff] [blame] | 338 | return wrapped |