~bzr-pqm/bzr/bzr.dev

5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
1
# Copyright (C) 2011 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
import sys
18
import threading
19
20
5652.1.2 by Vincent Ladeuil
Use clearer names.
21
class CatchingExceptionThread(threading.Thread):
22
    """A thread that keeps track of exceptions.
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
23
24
    If an exception occurs during the thread execution, it's caught and
25
    re-raised when the thread is joined().
26
    """
27
28
    def __init__(self, *args, **kwargs):
29
        # There are cases where the calling thread must wait, yet, if an
30
        # exception occurs, the event should be set so the caller is not
31
        # blocked. The main example is a calling thread that want to wait for
32
        # the called thread to be in a given state before continuing.
33
        try:
5652.1.2 by Vincent Ladeuil
Use clearer names.
34
            sync_event = kwargs.pop('sync_event')
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
35
        except KeyError:
36
            # If the caller didn't pass a specific event, create our own
5652.1.2 by Vincent Ladeuil
Use clearer names.
37
            sync_event = threading.Event()
38
        super(CatchingExceptionThread, self).__init__(*args, **kwargs)
39
        self.set_sync_event(sync_event)
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
40
        self.exception = None
41
        self.ignored_exceptions = None # see set_ignored_exceptions
5652.1.4 by Vincent Ladeuil
Add CatchingExceptionThread.set_and_switch() to avoid race conditions.
42
        self.lock = threading.Lock()
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
43
44
    # compatibility thunk for python-2.4 and python-2.5...
45
    if sys.version_info < (2, 6):
46
        name = property(threading.Thread.getName, threading.Thread.setName)
47
5652.1.2 by Vincent Ladeuil
Use clearer names.
48
    def set_sync_event(self, event):
49
        """Set the ``sync_event`` event used to synchronize exception catching.
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
50
51
        When the thread uses an event to synchronize itself with another thread
52
        (setting it when the other thread can wake up from a ``wait`` call),
53
        the event must be set after catching an exception or the other thread
54
        will hang.
55
56
        Some threads require multiple events and should set the relevant one
57
        when appropriate.
5652.1.2 by Vincent Ladeuil
Use clearer names.
58
5652.1.4 by Vincent Ladeuil
Add CatchingExceptionThread.set_and_switch() to avoid race conditions.
59
        Note that the event should be initially cleared so the caller can
60
        wait() on him and be released when the thread set the event.
61
62
        Also note that the thread can use multiple events, setting them as it
63
        progress, while the caller can chose to wait on any of them. What
64
        matters is that there is always one event set so that the caller is
65
        always released when an exception is caught. Re-using the same event is
66
        therefore risky as the thread itself has no idea about which event the
67
        caller is waiting on. If the caller has already been released then a
68
        cleared event won't guarantee that the caller is still waiting on it.
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
69
        """
5652.1.2 by Vincent Ladeuil
Use clearer names.
70
        self.sync_event = event
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
71
5652.1.5 by Vincent Ladeuil
Align method name and implementation.
72
    def switch_and_set(self, new):
73
        """Switch to a new ``sync_event`` and set the current one.
5652.1.4 by Vincent Ladeuil
Add CatchingExceptionThread.set_and_switch() to avoid race conditions.
74
75
        Using this method protects against race conditions while setting a new
76
        ``sync_event``.
77
78
        Note that this allows a caller to wait either on the old or the new
79
        event depending on whether it wants a fine control on what is happening
80
        inside a thread.
81
82
        :param new: The event that will become ``sync_event``
83
        """
84
        cur = self.sync_event
85
        self.lock.acquire()
86
        try: # Always release the lock
87
            try:
88
                self.set_sync_event(new)
89
                # From now on, any exception will be synced with the new event
90
            except:
91
                # Unlucky, we couldn't set the new sync event, try restoring a
92
                # safe state
93
                self.set_sync_event(cur)
94
                raise
95
            # Setting the current ``sync_event`` will release callers waiting
96
            # on it, note that it will also be set in run() if an exception is
97
            # raised
98
            cur.set()
99
        finally:
100
            self.lock.release()
101
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
102
    def set_ignored_exceptions(self, ignored):
103
        """Declare which exceptions will be ignored.
104
105
        :param ignored: Can be either:
106
           - None: all exceptions will be raised,
107
           - an exception class: the instances of this class will be ignored,
108
           - a tuple of exception classes: the instances of any class of the
109
             list will be ignored,
110
           - a callable: that will be passed the exception object
111
             and should return True if the exception should be ignored
112
        """
113
        if ignored is None:
114
            self.ignored_exceptions = None
115
        elif isinstance(ignored, (Exception, tuple)):
116
            self.ignored_exceptions = lambda e: isinstance(e, ignored)
117
        else:
118
            self.ignored_exceptions = ignored
119
120
    def run(self):
121
        """Overrides Thread.run to capture any exception."""
5652.1.2 by Vincent Ladeuil
Use clearer names.
122
        self.sync_event.clear()
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
123
        try:
124
            try:
5652.1.2 by Vincent Ladeuil
Use clearer names.
125
                super(CatchingExceptionThread, self).run()
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
126
            except:
127
                self.exception = sys.exc_info()
128
        finally:
129
            # Make sure the calling thread is released
5652.1.2 by Vincent Ladeuil
Use clearer names.
130
            self.sync_event.set()
131
132
133
    def join(self, timeout=None):
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
134
        """Overrides Thread.join to raise any exception caught.
135
136
        Calling join(timeout=0) will raise the caught exception or return None
137
        if the thread is still alive.
138
        """
5652.1.2 by Vincent Ladeuil
Use clearer names.
139
        super(CatchingExceptionThread, self).join(timeout)
5652.1.1 by Vincent Ladeuil
Split ThreadWithException out of the tests hierarchy.
140
        if self.exception is not None:
141
            exc_class, exc_value, exc_tb = self.exception
142
            self.exception = None # The exception should be raised only once
143
            if (self.ignored_exceptions is None
144
                or not self.ignored_exceptions(exc_value)):
145
                # Raise non ignored exceptions
146
                raise exc_class, exc_value, exc_tb
147
148
    def pending_exception(self):
149
        """Raise the caught exception.
150
151
        This does nothing if no exception occurred.
152
        """
153
        self.join(timeout=0)