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