OLD | NEW |
1 # Copyright 2013 The Chromium Authors. All rights reserved. | 1 # Copyright 2013 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 """Thread and ThreadGroup that reraise exceptions on the main thread.""" | 5 """Thread and ThreadGroup that reraise exceptions on the main thread.""" |
6 # pylint: disable=W0212 | |
7 | 6 |
8 import logging | 7 import logging |
9 import sys | 8 import sys |
10 import threading | 9 import threading |
| 10 import time |
11 import traceback | 11 import traceback |
12 | 12 |
13 from pylib.utils import watchdog_timer | 13 import watchdog_timer |
14 | 14 |
15 | 15 |
16 class TimeoutError(Exception): | 16 class TimeoutError(Exception): |
17 """Module-specific timeout exception.""" | 17 """Module-specific timeout exception.""" |
18 pass | 18 pass |
19 | 19 |
20 | 20 |
21 def LogThreadStack(thread): | 21 def LogThreadStack(thread): |
22 """Log the stack for the given thread. | 22 """Log the stack for the given thread. |
23 | 23 |
24 Args: | 24 Args: |
25 thread: a threading.Thread instance. | 25 thread: a threading.Thread instance. |
26 """ | 26 """ |
27 stack = sys._current_frames()[thread.ident] | 27 stack = sys._current_frames()[thread.ident] |
28 logging.critical('*' * 80) | 28 logging.critical('*' * 80) |
29 logging.critical('Stack dump for thread \'%s\'', thread.name) | 29 logging.critical('Stack dump for thread \'%s\'', thread.name) |
30 logging.critical('*' * 80) | 30 logging.critical('*' * 80) |
31 for filename, lineno, name, line in traceback.extract_stack(stack): | 31 for filename, lineno, name, line in traceback.extract_stack(stack): |
32 logging.critical('File: "%s", line %d, in %s', filename, lineno, name) | 32 logging.critical('File: "%s", line %d, in %s', filename, lineno, name) |
33 if line: | 33 if line: |
34 logging.critical(' %s', line.strip()) | 34 logging.critical(' %s', line.strip()) |
35 logging.critical('*' * 80) | 35 logging.critical('*' * 80) |
36 | 36 |
37 | 37 |
38 class ReraiserThread(threading.Thread): | 38 class ReraiserThread(threading.Thread): |
39 """Thread class that can reraise exceptions.""" | 39 """Thread class that can reraise exceptions.""" |
40 | 40 |
41 def __init__(self, func, args=None, kwargs=None, name=None): | 41 def __init__(self, func, args=[], kwargs={}, name=None): |
42 """Initialize thread. | 42 """Initialize thread. |
43 | 43 |
44 Args: | 44 Args: |
45 func: callable to call on a new thread. | 45 func: callable to call on a new thread. |
46 args: list of positional arguments for callable, defaults to empty. | 46 args: list of positional arguments for callable, defaults to empty. |
47 kwargs: dictionary of keyword arguments for callable, defaults to empty. | 47 kwargs: dictionary of keyword arguments for callable, defaults to empty. |
48 name: thread name, defaults to Thread-N. | 48 name: thread name, defaults to Thread-N. |
49 """ | 49 """ |
50 super(ReraiserThread, self).__init__(name=name) | 50 super(ReraiserThread, self).__init__(name=name) |
51 if not args: | |
52 args = [] | |
53 if not kwargs: | |
54 kwargs = {} | |
55 self.daemon = True | 51 self.daemon = True |
56 self._func = func | 52 self._func = func |
57 self._args = args | 53 self._args = args |
58 self._kwargs = kwargs | 54 self._kwargs = kwargs |
59 self._exc_info = None | 55 self._exc_info = None |
60 | 56 |
61 def ReraiseIfException(self): | 57 def ReraiseIfException(self): |
62 """Reraise exception if an exception was raised in the thread.""" | 58 """Reraise exception if an exception was raised in the thread.""" |
63 if self._exc_info: | 59 if self._exc_info: |
64 raise self._exc_info[0], self._exc_info[1], self._exc_info[2] | 60 raise self._exc_info[0], self._exc_info[1], self._exc_info[2] |
65 | 61 |
66 #override | 62 #override |
67 def run(self): | 63 def run(self): |
68 """Overrides Thread.run() to add support for reraising exceptions.""" | 64 """Overrides Thread.run() to add support for reraising exceptions.""" |
69 try: | 65 try: |
70 self._func(*self._args, **self._kwargs) | 66 self._func(*self._args, **self._kwargs) |
71 except: | 67 except: |
72 self._exc_info = sys.exc_info() | 68 self._exc_info = sys.exc_info() |
73 raise | 69 raise |
74 | 70 |
75 | 71 |
76 class ReraiserThreadGroup(object): | 72 class ReraiserThreadGroup(object): |
77 """A group of ReraiserThread objects.""" | 73 """A group of ReraiserThread objects.""" |
78 | 74 |
79 def __init__(self, threads=None): | 75 def __init__(self, threads=[]): |
80 """Initialize thread group. | 76 """Initialize thread group. |
81 | 77 |
82 Args: | 78 Args: |
83 threads: a list of ReraiserThread objects; defaults to empty. | 79 threads: a list of ReraiserThread objects; defaults to empty. |
84 """ | 80 """ |
85 if not threads: | |
86 threads = [] | |
87 self._threads = threads | 81 self._threads = threads |
88 | 82 |
89 def Add(self, thread): | 83 def Add(self, thread): |
90 """Add a thread to the group. | 84 """Add a thread to the group. |
91 | 85 |
92 Args: | 86 Args: |
93 thread: a ReraiserThread object. | 87 thread: a ReraiserThread object. |
94 """ | 88 """ |
95 self._threads.append(thread) | 89 self._threads.append(thread) |
96 | 90 |
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
131 | 125 |
132 Args: | 126 Args: |
133 watcher: Watchdog object providing timeout, by default waits forever. | 127 watcher: Watchdog object providing timeout, by default waits forever. |
134 """ | 128 """ |
135 try: | 129 try: |
136 self._JoinAll(watcher) | 130 self._JoinAll(watcher) |
137 except TimeoutError: | 131 except TimeoutError: |
138 for thread in (t for t in self._threads if t.isAlive()): | 132 for thread in (t for t in self._threads if t.isAlive()): |
139 LogThreadStack(thread) | 133 LogThreadStack(thread) |
140 raise | 134 raise |
OLD | NEW |