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 | |
| 35 | import itertools |
| 36 | import weakref |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 37 | import atexit |
| 38 | import threading # we want threading to install it's |
| 39 | # cleanup function before multiprocessing does |
| 40 | |
| 41 | from multiprocessing.process import current_process, active_children |
| 42 | |
| 43 | __all__ = [ |
| 44 | 'sub_debug', 'debug', 'info', 'sub_warning', 'get_logger', |
| 45 | 'log_to_stderr', 'get_temp_dir', 'register_after_fork', |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 46 | 'is_exiting', 'Finalize', 'ForkAwareThreadLock', 'ForkAwareLocal', |
| 47 | 'SUBDEBUG', 'SUBWARNING', |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 48 | ] |
| 49 | |
| 50 | # |
| 51 | # Logging |
| 52 | # |
| 53 | |
| 54 | NOTSET = 0 |
| 55 | SUBDEBUG = 5 |
| 56 | DEBUG = 10 |
| 57 | INFO = 20 |
| 58 | SUBWARNING = 25 |
| 59 | |
| 60 | LOGGER_NAME = 'multiprocessing' |
| 61 | DEFAULT_LOGGING_FORMAT = '[%(levelname)s/%(processName)s] %(message)s' |
| 62 | |
| 63 | _logger = None |
| 64 | _log_to_stderr = False |
| 65 | |
| 66 | def sub_debug(msg, *args): |
| 67 | if _logger: |
| 68 | _logger.log(SUBDEBUG, msg, *args) |
| 69 | |
| 70 | def debug(msg, *args): |
| 71 | if _logger: |
| 72 | _logger.log(DEBUG, msg, *args) |
| 73 | |
| 74 | def info(msg, *args): |
| 75 | if _logger: |
| 76 | _logger.log(INFO, msg, *args) |
| 77 | |
| 78 | def sub_warning(msg, *args): |
| 79 | if _logger: |
| 80 | _logger.log(SUBWARNING, msg, *args) |
| 81 | |
| 82 | def get_logger(): |
| 83 | ''' |
| 84 | Returns logger used by multiprocessing |
| 85 | ''' |
| 86 | global _logger |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 87 | import logging, atexit |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 88 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 89 | logging._acquireLock() |
| 90 | try: |
| 91 | if not _logger: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 92 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 93 | _logger = logging.getLogger(LOGGER_NAME) |
| 94 | _logger.propagate = 0 |
| 95 | logging.addLevelName(SUBDEBUG, 'SUBDEBUG') |
| 96 | logging.addLevelName(SUBWARNING, 'SUBWARNING') |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 97 | |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 98 | # XXX multiprocessing should cleanup before logging |
| 99 | if hasattr(atexit, 'unregister'): |
| 100 | atexit.unregister(_exit_function) |
| 101 | atexit.register(_exit_function) |
| 102 | else: |
| 103 | atexit._exithandlers.remove((_exit_function, (), {})) |
| 104 | atexit._exithandlers.append((_exit_function, (), {})) |
| 105 | |
| 106 | finally: |
| 107 | logging._releaseLock() |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 108 | |
| 109 | return _logger |
| 110 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 111 | def log_to_stderr(level=None): |
| 112 | ''' |
| 113 | Turn on logging and add a handler which prints to stderr |
| 114 | ''' |
| 115 | global _log_to_stderr |
| 116 | import logging |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 117 | |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 118 | logger = get_logger() |
| 119 | formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT) |
| 120 | handler = logging.StreamHandler() |
| 121 | handler.setFormatter(formatter) |
| 122 | logger.addHandler(handler) |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 123 | |
| 124 | if level: |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 125 | logger.setLevel(level) |
| 126 | _log_to_stderr = True |
Jesse Noller | 41faa54 | 2009-01-25 03:45:53 +0000 | [diff] [blame] | 127 | return _logger |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 128 | |
| 129 | # |
| 130 | # Function returning a temp directory which will be removed on exit |
| 131 | # |
| 132 | |
| 133 | def get_temp_dir(): |
| 134 | # get name of a temp directory which will be automatically cleaned up |
| 135 | if current_process()._tempdir is None: |
| 136 | import shutil, tempfile |
| 137 | tempdir = tempfile.mkdtemp(prefix='pymp-') |
| 138 | info('created temp directory %s', tempdir) |
| 139 | Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100) |
| 140 | current_process()._tempdir = tempdir |
| 141 | return current_process()._tempdir |
| 142 | |
| 143 | # |
| 144 | # Support for reinitialization of objects when bootstrapping a child process |
| 145 | # |
| 146 | |
| 147 | _afterfork_registry = weakref.WeakValueDictionary() |
| 148 | _afterfork_counter = itertools.count() |
| 149 | |
| 150 | def _run_after_forkers(): |
| 151 | items = list(_afterfork_registry.items()) |
| 152 | items.sort() |
| 153 | for (index, ident, func), obj in items: |
| 154 | try: |
| 155 | func(obj) |
| 156 | except Exception as e: |
| 157 | info('after forker raised exception %s', e) |
| 158 | |
| 159 | def register_after_fork(obj, func): |
| 160 | _afterfork_registry[(next(_afterfork_counter), id(obj), func)] = obj |
| 161 | |
| 162 | # |
| 163 | # Finalization using weakrefs |
| 164 | # |
| 165 | |
| 166 | _finalizer_registry = {} |
| 167 | _finalizer_counter = itertools.count() |
| 168 | |
| 169 | |
| 170 | class Finalize(object): |
| 171 | ''' |
| 172 | Class which supports object finalization using weakrefs |
| 173 | ''' |
| 174 | def __init__(self, obj, callback, args=(), kwargs=None, exitpriority=None): |
| 175 | assert exitpriority is None or type(exitpriority) is int |
| 176 | |
| 177 | if obj is not None: |
| 178 | self._weakref = weakref.ref(obj, self) |
| 179 | else: |
| 180 | assert exitpriority is not None |
| 181 | |
| 182 | self._callback = callback |
| 183 | self._args = args |
| 184 | self._kwargs = kwargs or {} |
| 185 | self._key = (exitpriority, next(_finalizer_counter)) |
| 186 | |
| 187 | _finalizer_registry[self._key] = self |
| 188 | |
| 189 | def __call__(self, wr=None): |
| 190 | ''' |
| 191 | Run the callback unless it has already been called or cancelled |
| 192 | ''' |
| 193 | try: |
| 194 | del _finalizer_registry[self._key] |
| 195 | except KeyError: |
| 196 | sub_debug('finalizer no longer registered') |
| 197 | else: |
| 198 | sub_debug('finalizer calling %s with args %s and kwargs %s', |
| 199 | self._callback, self._args, self._kwargs) |
| 200 | res = self._callback(*self._args, **self._kwargs) |
| 201 | self._weakref = self._callback = self._args = \ |
| 202 | self._kwargs = self._key = None |
| 203 | return res |
| 204 | |
| 205 | def cancel(self): |
| 206 | ''' |
| 207 | Cancel finalization of the object |
| 208 | ''' |
| 209 | try: |
| 210 | del _finalizer_registry[self._key] |
| 211 | except KeyError: |
| 212 | pass |
| 213 | else: |
| 214 | self._weakref = self._callback = self._args = \ |
| 215 | self._kwargs = self._key = None |
| 216 | |
| 217 | def still_active(self): |
| 218 | ''' |
| 219 | Return whether this finalizer is still waiting to invoke callback |
| 220 | ''' |
| 221 | return self._key in _finalizer_registry |
| 222 | |
| 223 | def __repr__(self): |
| 224 | try: |
| 225 | obj = self._weakref() |
| 226 | except (AttributeError, TypeError): |
| 227 | obj = None |
| 228 | |
| 229 | if obj is None: |
| 230 | return '<Finalize object, dead>' |
| 231 | |
| 232 | x = '<Finalize object, callback=%s' % \ |
| 233 | getattr(self._callback, '__name__', self._callback) |
| 234 | if self._args: |
| 235 | x += ', args=' + str(self._args) |
| 236 | if self._kwargs: |
| 237 | x += ', kwargs=' + str(self._kwargs) |
| 238 | if self._key[0] is not None: |
| 239 | x += ', exitprority=' + str(self._key[0]) |
| 240 | return x + '>' |
| 241 | |
| 242 | |
| 243 | def _run_finalizers(minpriority=None): |
| 244 | ''' |
| 245 | Run all finalizers whose exit priority is not None and at least minpriority |
| 246 | |
| 247 | Finalizers with highest priority are called first; finalizers with |
| 248 | the same priority will be called in reverse order of creation. |
| 249 | ''' |
| 250 | if minpriority is None: |
| 251 | f = lambda p : p[0][0] is not None |
| 252 | else: |
| 253 | f = lambda p : p[0][0] is not None and p[0][0] >= minpriority |
| 254 | |
| 255 | items = [x for x in list(_finalizer_registry.items()) if f(x)] |
| 256 | items.sort(reverse=True) |
| 257 | |
| 258 | for key, finalizer in items: |
| 259 | sub_debug('calling %s', finalizer) |
| 260 | try: |
| 261 | finalizer() |
| 262 | except Exception: |
| 263 | import traceback |
| 264 | traceback.print_exc() |
| 265 | |
| 266 | if minpriority is None: |
| 267 | _finalizer_registry.clear() |
| 268 | |
| 269 | # |
| 270 | # Clean up on exit |
| 271 | # |
| 272 | |
| 273 | def is_exiting(): |
| 274 | ''' |
| 275 | Returns true if the process is shutting down |
| 276 | ''' |
| 277 | return _exiting or _exiting is None |
| 278 | |
| 279 | _exiting = False |
| 280 | |
| 281 | def _exit_function(): |
| 282 | global _exiting |
| 283 | |
| 284 | info('process shutting down') |
| 285 | debug('running all "atexit" finalizers with priority >= 0') |
| 286 | _run_finalizers(0) |
| 287 | |
| 288 | for p in active_children(): |
| 289 | if p._daemonic: |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 290 | info('calling terminate() for daemon %s', p.name) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 291 | p._popen.terminate() |
| 292 | |
| 293 | for p in active_children(): |
Benjamin Peterson | 58ea9fe | 2008-08-19 19:17:39 +0000 | [diff] [blame] | 294 | info('calling join() for process %s', p.name) |
Benjamin Peterson | e711caf | 2008-06-11 16:44:04 +0000 | [diff] [blame] | 295 | p.join() |
| 296 | |
| 297 | debug('running the remaining "atexit" finalizers') |
| 298 | _run_finalizers() |
| 299 | |
| 300 | atexit.register(_exit_function) |
| 301 | |
| 302 | # |
| 303 | # Some fork aware types |
| 304 | # |
| 305 | |
| 306 | class ForkAwareThreadLock(object): |
| 307 | def __init__(self): |
| 308 | self._lock = threading.Lock() |
| 309 | self.acquire = self._lock.acquire |
| 310 | self.release = self._lock.release |
| 311 | register_after_fork(self, ForkAwareThreadLock.__init__) |
| 312 | |
| 313 | class ForkAwareLocal(threading.local): |
| 314 | def __init__(self): |
| 315 | register_after_fork(self, lambda obj : obj.__dict__.clear()) |
| 316 | def __reduce__(self): |
| 317 | return type(self), () |