• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""A thread pool that logs exceptions raised by tasks executed within it."""
15
16import logging
17
18from concurrent import futures
19
20logging.basicConfig()
21_LOGGER = logging.getLogger(__name__)
22
23
24def _wrap(behavior):
25    """Wraps an arbitrary callable behavior in exception-logging."""
26
27    def _wrapping(*args, **kwargs):
28        try:
29            return behavior(*args, **kwargs)
30        except Exception:
31            _LOGGER.exception(
32                'Unexpected exception from %s executed in logging pool!',
33                behavior)
34            raise
35
36    return _wrapping
37
38
39class _LoggingPool(object):
40    """An exception-logging futures.ThreadPoolExecutor-compatible thread pool."""
41
42    def __init__(self, backing_pool):
43        self._backing_pool = backing_pool
44
45    def __enter__(self):
46        return self
47
48    def __exit__(self, exc_type, exc_val, exc_tb):
49        self._backing_pool.shutdown(wait=True)
50
51    def submit(self, fn, *args, **kwargs):
52        return self._backing_pool.submit(_wrap(fn), *args, **kwargs)
53
54    def map(self, func, *iterables, **kwargs):
55        return self._backing_pool.map(
56            _wrap(func), *iterables, timeout=kwargs.get('timeout', None))
57
58    def shutdown(self, wait=True):
59        self._backing_pool.shutdown(wait=wait)
60
61
62def pool(max_workers):
63    """Creates a thread pool that logs exceptions raised by the tasks within it.
64
65  Args:
66    max_workers: The maximum number of worker threads to allow the pool.
67
68  Returns:
69    A futures.ThreadPoolExecutor-compatible thread pool that logs exceptions
70      raised by the tasks executed within it.
71  """
72    return _LoggingPool(futures.ThreadPoolExecutor(max_workers))
73