~launchpad-pqm/launchpad/devel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

# Explicit is better than implicit.
# pylint: disable-msg=W0602,W0603
"""Helpers to time out external operations."""

__metaclass__ = type
__all__ = [
    "get_default_timeout_function",
    "SafeTransportWithTimeout",
    "set_default_timeout_function",
    "TimeoutError",
    "TransportWithTimeout",
    "urlfetch",
    "with_timeout",
    ]

import httplib
import socket
import sys
from threading import Thread
import urllib2
from xmlrpclib import (
    SafeTransport,
    Transport,
    )


default_timeout_function = None


def get_default_timeout_function():
    """Return the function returning the default timeout value to use."""
    global default_timeout_function
    return default_timeout_function


def set_default_timeout_function(timeout_function):
    """Change the function returning the default timeout value to use."""
    global default_timeout_function
    default_timeout_function = timeout_function


class TimeoutError(Exception):
    """Exception raised when a function doesn't complete within time."""


class ThreadCapturingResult(Thread):
    """Thread subclass that saves the return value of its target.

    It also saves exceptions raised when invoking the target.
    """

    def __init__(self, target, args, kwargs, **opt):
        super(ThreadCapturingResult, self).__init__(**opt)
        self.target = target
        self.args = args
        self.kwargs = kwargs

    def run(self):
        """See `Thread`."""
        try:
            self.result = self.target(*self.args, **self.kwargs)
        except (SystemExit, KeyboardInterrupt):
            # Don't trap those.
            raise
        except Exception:
            self.exc_info = sys.exc_info()


class DefaultTimeout:
    """Descriptor returning the timeout computed by the default function."""

    def __get__(self, obj, type=None):
        global default_timeout_function
        if default_timeout_function is None:
            raise AssertionError(
                "no timeout set and there is no default timeout function.")
        return default_timeout_function()


class with_timeout:
    """Make sure the decorated function doesn't exceed a time out.

    This will execute the function in a separate thread. If the function
    doesn't complete in the timeout, a TimeoutError is raised. The clean-up
    function will be called to "stop" the thread. (If it's possible to do so.)
    """

    timeout = DefaultTimeout()

    def __init__(self, cleanup=None, timeout=None):
        """Creates the function decorator.

        :param cleanup: That may be a callable or a string. If it's a string,
            a method under that name will be looked up. That callable will
            be called if the timeout is exceeded.
        :param timeout: The number of seconds to wait for.
        """
        # If the cleanup function is specified by name, the function but be a
        # method, so defined in a class definition context.
        if isinstance(cleanup, basestring):
            frame = sys._getframe(1)
            f_locals = frame.f_locals

            # Try to make sure we were called from a class def.
            if f_locals is frame.f_globals or '__module__' not in f_locals:
                raise TypeError(
                    "when not wrapping a method, cleanup must be a callable.")
        self.cleanup = cleanup
        if timeout is not None:
            self.timeout = timeout

    def __call__(self, f):
        """Wraps the method."""
        def call_with_timeout(*args, **kwargs):
            t = ThreadCapturingResult(f, args, kwargs)
            t.start()
            t.join(self.timeout)
            if t.isAlive():
                if self.cleanup is not None:
                    if isinstance(self.cleanup, basestring):
                        # 'self' will be first positional argument.
                        getattr(args[0], self.cleanup)()
                    else:
                        self.cleanup()
                    # Collect cleaned-up worker thread.
                    t.join()
                raise TimeoutError("timeout exceeded.")
            if getattr(t, 'exc_info', None) is not None:
                exc_info = t.exc_info
                # Remove the cyclic reference for faster GC.
                del t.exc_info
                raise exc_info[0], exc_info[1], exc_info[2]
            return t.result

        return call_with_timeout


class CleanableHTTPHandler(urllib2.HTTPHandler):
    """Subclass of `urllib2.HTTPHandler` that can be cleaned-up."""

    def http_open(self, req):
        """See `urllib2.HTTPHandler`."""
        def connection_factory(*args, **kwargs):
            """Save the created connection so that we can clean it up."""
            self.__conn = httplib.HTTPConnection(*args, **kwargs)
            return self.__conn
        return self.do_open(connection_factory, req)

    def reset_connection(self):
        """Reset the underlying HTTP connection."""
        try:
            self.__conn.sock.shutdown(socket.SHUT_RDWR)
        except AttributeError:
            # It's possible that the other thread closed the socket
            # beforehand.
            pass
        self.__conn.close()


class URLFetcher:
    """Object fetching remote URLs with a time out."""

    @with_timeout(cleanup='cleanup')
    def fetch(self, url, data=None):
        """Fetch the URL using a custom HTTP handler supporting timeout."""
        assert url.startswith('http://'), "only http is supported."
        self.handler = CleanableHTTPHandler()
        opener = urllib2.build_opener(self.handler)
        return opener.open(url, data).read()

    def cleanup(self):
        """Reset the connection when the operation timed out."""
        self.handler.reset_connection()


def urlfetch(url, data=None):
    """Wrapper for `urllib2.urlopen()` that times out."""
    return URLFetcher().fetch(url, data)


class TransportWithTimeout(Transport):
    """Create a HTTP transport for XMLRPC with timeouts."""

    def make_connection(self, host):
        """Create the connection for the transport and save it."""
        self.conn = Transport.make_connection(self, host)
        return self.conn

    @with_timeout(cleanup='cleanup')
    def request(self, host, handler, request_body, verbose=0):
        """Make the request but using the with_timeout decorator."""
        return Transport.request(
            self, host, handler, request_body, verbose)

    def cleanup(self):
        """In the event of a timeout cleanup by closing the connection."""
        try:
            self.conn._conn.sock.shutdown(socket.SHUT_RDWR)
        except AttributeError:
            # It's possible that the other thread closed the socket
            # beforehand.
            pass
        self.conn._conn.close()


class SafeTransportWithTimeout(SafeTransport):
    """Create a HTTPS transport for XMLRPC with timeouts."""

    def make_connection(self, host):
        """Create the connection for the transport and save it."""
        self.conn = SafeTransport.make_connection(self, host)
        return self.conn

    @with_timeout(cleanup='cleanup')
    def request(self, host, handler, request_body, verbose=0):
        """Make the request but using the with_timeout decorator."""
        return SafeTransport.request(
            self, host, handler, request_body, verbose)

    def cleanup(self):
        """In the event of a timeout cleanup by closing the connection."""
        try:
            self.conn._conn.sock.shutdown(socket.SHUT_RDWR)
        except AttributeError:
            # It's possible that the other thread closed the socket
            # beforehand.
            pass
        self.conn._conn.close()