/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
1
# Copyright (C) 2010 Canonical Ltd
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
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
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
17
import errno
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
18
import socket
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
19
import SocketServer
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
20
import select
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
21
import sys
22
import threading
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
23
24
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
25
from bzrlib import (
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
26
    osutils,
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
27
    transport,
5017.3.15 by Vincent Ladeuil
Fix missing import.
28
    urlutils,
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
29
    )
5017.3.19 by Vincent Ladeuil
Move TestingPathFilteringServer to bzrlib.tests.test_server
30
from bzrlib.transport import (
5017.3.20 by Vincent Ladeuil
Move TestingChrootServer to bzrlib.tests.test_server
31
    chroot,
5017.3.19 by Vincent Ladeuil
Move TestingPathFilteringServer to bzrlib.tests.test_server
32
    pathfilter,
33
    )
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
34
from bzrlib.smart import server
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
35
36
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
37
def debug_threads():
38
    # FIXME: There is a dependency loop between bzrlib.tests and
39
    # bzrlib.tests.test_server that needs to be fixed. In the mean time
40
    # defining this function is enough for our needs. -- vila 20100611
41
    from bzrlib import tests
42
    return 'threads' in tests.selftest_debug_flags
43
44
5017.3.1 by Vincent Ladeuil
Create a tests.test_server.TestServer class out of transport.Server (while retaining the later for some special non-tests usages).
45
class TestServer(transport.Server):
46
    """A Transport Server dedicated to tests.
47
48
    The TestServer interface provides a server for a given transport. We use
49
    these servers as loopback testing tools. For any given transport the
50
    Servers it provides must either allow writing, or serve the contents
51
    of os.getcwdu() at the time start_server is called.
52
53
    Note that these are real servers - they must implement all the things
54
    that we want bzr transports to take advantage of.
55
    """
56
57
    def get_url(self):
58
        """Return a url for this server.
59
60
        If the transport does not represent a disk directory (i.e. it is
61
        a database like svn, or a memory only transport, it should return
62
        a connection to a newly established resource for this Server.
63
        Otherwise it should return a url that will provide access to the path
64
        that was os.getcwdu() when start_server() was called.
65
66
        Subsequent calls will return the same resource.
67
        """
68
        raise NotImplementedError
69
70
    def get_bogus_url(self):
71
        """Return a url for this protocol, that will fail to connect.
72
73
        This may raise NotImplementedError to indicate that this server cannot
74
        provide bogus urls.
75
        """
76
        raise NotImplementedError
77
78
5017.3.6 by Vincent Ladeuil
Fix some fallouts of moving test servers around.
79
class LocalURLServer(TestServer):
5017.3.3 by Vincent Ladeuil
Move LocalURLServer to bzrlib.tests.test_server
80
    """A pretend server for local transports, using file:// urls.
81
82
    Of course no actual server is required to access the local filesystem, so
83
    this just exists to tell the test code how to get to it.
84
    """
85
86
    def start_server(self):
87
        pass
88
89
    def get_url(self):
90
        """See Transport.Server.get_url."""
91
        return urlutils.local_path_to_url('')
92
93
5017.3.6 by Vincent Ladeuil
Fix some fallouts of moving test servers around.
94
class DecoratorServer(TestServer):
5017.3.2 by Vincent Ladeuil
Move DecoratorServer to test_server.py
95
    """Server for the TransportDecorator for testing with.
96
97
    To use this when subclassing TransportDecorator, override override the
98
    get_decorator_class method.
99
    """
100
101
    def start_server(self, server=None):
102
        """See bzrlib.transport.Server.start_server.
103
104
        :server: decorate the urls given by server. If not provided a
105
        LocalServer is created.
106
        """
107
        if server is not None:
108
            self._made_server = False
109
            self._server = server
110
        else:
111
            self._made_server = True
112
            self._server = LocalURLServer()
113
            self._server.start_server()
114
115
    def stop_server(self):
116
        if self._made_server:
117
            self._server.stop_server()
118
119
    def get_decorator_class(self):
120
        """Return the class of the decorators we should be constructing."""
121
        raise NotImplementedError(self.get_decorator_class)
122
123
    def get_url_prefix(self):
124
        """What URL prefix does this decorator produce?"""
125
        return self.get_decorator_class()._get_url_prefix()
126
127
    def get_bogus_url(self):
128
        """See bzrlib.transport.Server.get_bogus_url."""
129
        return self.get_url_prefix() + self._server.get_bogus_url()
130
131
    def get_url(self):
132
        """See bzrlib.transport.Server.get_url."""
133
        return self.get_url_prefix() + self._server.get_url()
134
135
5017.3.8 by Vincent Ladeuil
Move BrokenRenameServer to bzrlib.tests.test_server
136
class BrokenRenameServer(DecoratorServer):
137
    """Server for the BrokenRenameTransportDecorator for testing with."""
138
139
    def get_decorator_class(self):
140
        from bzrlib.transport import brokenrename
141
        return brokenrename.BrokenRenameTransportDecorator
142
143
5017.3.7 by Vincent Ladeuil
Move FakeNFSServer to bzrlib.tests.test_server
144
class FakeNFSServer(DecoratorServer):
145
    """Server for the FakeNFSTransportDecorator for testing with."""
146
147
    def get_decorator_class(self):
148
        from bzrlib.transport import fakenfs
149
        return fakenfs.FakeNFSTransportDecorator
150
151
5017.3.9 by Vincent Ladeuil
Move FakeVFATServer to bzrlib.tests.test_server
152
class FakeVFATServer(DecoratorServer):
153
    """A server that suggests connections through FakeVFATTransportDecorator
154
155
    For use in testing.
156
    """
157
158
    def get_decorator_class(self):
159
        from bzrlib.transport import fakevfat
5017.3.14 by Vincent Ladeuil
Fix some missing prefixes.
160
        return fakevfat.FakeVFATTransportDecorator
5017.3.9 by Vincent Ladeuil
Move FakeVFATServer to bzrlib.tests.test_server
161
162
5017.3.11 by Vincent Ladeuil
Move LogDecoratorServer to bzrlib.tests.test_server
163
class LogDecoratorServer(DecoratorServer):
164
    """Server for testing."""
165
166
    def get_decorator_class(self):
167
        from bzrlib.transport import log
168
        return log.TransportLogDecorator
169
170
5017.3.12 by Vincent Ladeuil
Move NoSmartTransportServer to bzrlib.tests.test_server
171
class NoSmartTransportServer(DecoratorServer):
172
    """Server for the NoSmartTransportDecorator for testing with."""
173
174
    def get_decorator_class(self):
175
        from bzrlib.transport import nosmart
5017.3.14 by Vincent Ladeuil
Fix some missing prefixes.
176
        return nosmart.NoSmartTransportDecorator
5017.3.12 by Vincent Ladeuil
Move NoSmartTransportServer to bzrlib.tests.test_server
177
178
5017.3.5 by Vincent Ladeuil
Move ReadonlyServer to bzrlib.tests.readonly
179
class ReadonlyServer(DecoratorServer):
180
    """Server for the ReadonlyTransportDecorator for testing with."""
181
182
    def get_decorator_class(self):
183
        from bzrlib.transport import readonly
184
        return readonly.ReadonlyTransportDecorator
185
186
5017.3.10 by Vincent Ladeuil
Move TraceServer to bzrlib.tests.test_server
187
class TraceServer(DecoratorServer):
188
    """Server for the TransportTraceDecorator for testing with."""
189
190
    def get_decorator_class(self):
191
        from bzrlib.transport import trace
5017.3.14 by Vincent Ladeuil
Fix some missing prefixes.
192
        return trace.TransportTraceDecorator
5017.3.10 by Vincent Ladeuil
Move TraceServer to bzrlib.tests.test_server
193
194
5017.3.13 by Vincent Ladeuil
Move UnlistableServer to bzrlib.tests.test_server
195
class UnlistableServer(DecoratorServer):
196
    """Server for the UnlistableTransportDecorator for testing with."""
197
198
    def get_decorator_class(self):
199
        from bzrlib.transport import unlistable
200
        return unlistable.UnlistableTransportDecorator
201
202
5017.3.19 by Vincent Ladeuil
Move TestingPathFilteringServer to bzrlib.tests.test_server
203
class TestingPathFilteringServer(pathfilter.PathFilteringServer):
204
205
    def __init__(self):
5017.3.20 by Vincent Ladeuil
Move TestingChrootServer to bzrlib.tests.test_server
206
        """TestingPathFilteringServer is not usable until start_server
207
        is called."""
5017.3.19 by Vincent Ladeuil
Move TestingPathFilteringServer to bzrlib.tests.test_server
208
209
    def start_server(self, backing_server=None):
210
        """Setup the Chroot on backing_server."""
211
        if backing_server is not None:
212
            self.backing_transport = transport.get_transport(
213
                backing_server.get_url())
214
        else:
215
            self.backing_transport = transport.get_transport('.')
216
        self.backing_transport.clone('added-by-filter').ensure_base()
217
        self.filter_func = lambda x: 'added-by-filter/' + x
218
        super(TestingPathFilteringServer, self).start_server()
219
5017.3.20 by Vincent Ladeuil
Move TestingChrootServer to bzrlib.tests.test_server
220
    def get_bogus_url(self):
221
        raise NotImplementedError
222
223
224
class TestingChrootServer(chroot.ChrootServer):
225
226
    def __init__(self):
227
        """TestingChrootServer is not usable until start_server is called."""
228
        super(TestingChrootServer, self).__init__(None)
229
230
    def start_server(self, backing_server=None):
231
        """Setup the Chroot on backing_server."""
232
        if backing_server is not None:
233
            self.backing_transport = transport.get_transport(
234
                backing_server.get_url())
235
        else:
236
            self.backing_transport = transport.get_transport('.')
237
        super(TestingChrootServer, self).start_server()
238
239
    def get_bogus_url(self):
240
        raise NotImplementedError
241
5017.3.19 by Vincent Ladeuil
Move TestingPathFilteringServer to bzrlib.tests.test_server
242
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
243
class ThreadWithException(threading.Thread):
244
    """A catching exception thread.
245
246
    If an exception occurs during the thread execution, it's caught and
247
    re-raised when the thread is joined().
248
    """
249
250
    def __init__(self, *args, **kwargs):
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
251
        # There are cases where the calling thread must wait, yet, if an
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
252
        # exception occurs, the event should be set so the caller is not
5247.2.5 by Vincent Ladeuil
Some cleanups.
253
        # blocked. The main example is a calling thread that want to wait for
254
        # the called thread to be in a given state before continuing.
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
255
        try:
256
            event = kwargs.pop('event')
257
        except KeyError:
258
            # If the caller didn't pass a specific event, create our own
259
            event = threading.Event()
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
260
        super(ThreadWithException, self).__init__(*args, **kwargs)
5247.3.10 by Vincent Ladeuil
Test errors during server life.
261
        self.set_event(event)
262
        self.exception = None
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
263
        self.ignored_exceptions = None # see set_ignored_exceptions
5247.3.10 by Vincent Ladeuil
Test errors during server life.
264
5247.5.18 by Vincent Ladeuil
Compatibility with python 2.5 and 2.4 for ThreadWithException.name.
265
    # compatibility thunk for python-2.4 and python-2.5...
266
    name = property(threading.Thread.getName, threading.Thread.setName)
267
5247.3.10 by Vincent Ladeuil
Test errors during server life.
268
    def set_event(self, event):
5247.2.5 by Vincent Ladeuil
Some cleanups.
269
        self.ready = event
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
270
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
271
    def set_ignored_exceptions(self, ignored):
272
        """Declare which exceptions will be ignored.
273
274
        :param ignored: Can be either:
275
           - None: all exceptions will be raised,
276
           - an exception class: the instances of this class will be ignored,
277
           - a tuple of exception classes: the instances of any class of the
278
             list will be ignored,
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
279
           - a callable: that will be passed the exception object
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
280
             and should return True if the exception should be ignored
281
        """
282
        if ignored is None:
283
            self.ignored_exceptions = None
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
284
        elif isinstance(ignored, (Exception, tuple)):
285
            self.ignored_exceptions = lambda e: isinstance(e, ignored)
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
286
        else:
287
            self.ignored_exceptions = ignored
288
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
289
    def run(self):
290
        """Overrides Thread.run to capture any exception."""
5247.2.5 by Vincent Ladeuil
Some cleanups.
291
        self.ready.clear()
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
292
        try:
5247.3.19 by Vincent Ladeuil
Fix python-2.4 incompatibility.
293
            try:
294
                super(ThreadWithException, self).run()
295
            except:
296
                self.exception = sys.exc_info()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
297
        finally:
298
            # Make sure the calling thread is released
5247.2.5 by Vincent Ladeuil
Some cleanups.
299
            self.ready.set()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
300
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
301
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
302
    def join(self, timeout=5):
5247.2.3 by Vincent Ladeuil
join(timeout=0) is useful to check for an exception without stopping the thread.
303
        """Overrides Thread.join to raise any exception caught.
304
305
306
        Calling join(timeout=0) will raise the caught exception or return None
5247.3.10 by Vincent Ladeuil
Test errors during server life.
307
        if the thread is still alive.
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
308
309
        The default timeout is set to 5 and should expire only when a thread
310
        serving a client connection is hung.
5247.2.3 by Vincent Ladeuil
join(timeout=0) is useful to check for an exception without stopping the thread.
311
        """
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
312
        super(ThreadWithException, self).join(timeout)
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
313
        if self.exception is not None:
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
314
            exc_class, exc_value, exc_tb = self.exception
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
315
            self.exception = None # The exception should be raised only once
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
316
            if (self.ignored_exceptions is None
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
317
                or not self.ignored_exceptions(exc_value)):
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
318
                # Raise non ignored exceptions
319
                raise exc_class, exc_value, exc_tb
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
320
        if timeout and self.isAlive():
321
            # The timeout expired without joining the thread, the thread is
322
            # therefore stucked and that's a failure as far as the test is
323
            # concerned. We used to hang here.
324
            raise AssertionError('thread %s hung' % (self.name,))
325
326
    def pending_exception(self):
327
        """Raise the caught exception.
328
329
        This does nothing if no exception occurred.
330
        """
331
        self.join(timeout=0)
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
332
333
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
334
class TestingTCPServerMixin:
335
    """Mixin to support running SocketServer.TCPServer in a thread.
336
337
    Tests are connecting from the main thread, the server has to be run in a
338
    separate thread.
339
    """
340
5247.3.16 by Vincent Ladeuil
All http tests passing (including https).
341
    # FIXME: sibling_class is a hack -- vila 20100604
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
342
    def __init__(self, sibling_class):
343
        self.sibling_class = sibling_class
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
344
        self.started = threading.Event()
345
        self.serving = threading.Event()
346
        self.stopped = threading.Event()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
347
        # We collect the resources used by the clients so we can release them
348
        # when shutting down
349
        self.clients = []
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
350
        self.ignored_exceptions = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
351
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
352
    def server_bind(self):
353
        # We need to override the SocketServer bind, yet, we still want to use
354
        # it so we need to use the sibling class to call it explicitly
355
        self.sibling_class.server_bind(self)
356
        # The following has been fixed in 2.5 so we need to provide it for
357
        # older python versions.
358
        if sys.version < (2, 5):
359
            self.server_address = self.socket.getsockname()
360
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
361
    def serve(self):
362
        self.serving.set()
363
        self.stopped.clear()
364
        # We are listening and ready to accept connections
365
        self.started.set()
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
366
        try:
367
            while self.serving.isSet():
368
                # Really a connection but the python framework is generic and
369
                # call them requests
370
                self.handle_request()
371
            # Let's close the listening socket
372
            self.server_close()
373
        finally:
374
            self.stopped.set()
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
375
5247.5.10 by Vincent Ladeuil
Fix broken test.
376
    def handle_request(self):
377
        """Handle one request.
378
379
        The python version swallows some socket exceptions and we don't use
380
        timeout, so we override it to better control the server behavior.
381
        """
382
        request, client_address = self.get_request()
383
        if self.verify_request(request, client_address):
384
            try:
385
                self.process_request(request, client_address)
386
            except:
387
                self.handle_error(request, client_address)
388
                self.close_request(request)
389
5247.3.9 by Vincent Ladeuil
Ensure a simple dialog can occur between a client and a server.
390
    def verify_request(self, request, client_address):
391
        """Verify the request.
392
393
        Return True if we should proceed with this request, False if we should
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
394
        not even touch a single byte in the socket ! This is useful when we
395
        stop the server with a dummy last connection.
5247.3.9 by Vincent Ladeuil
Ensure a simple dialog can occur between a client and a server.
396
        """
397
        return self.serving.isSet()
398
5247.3.10 by Vincent Ladeuil
Test errors during server life.
399
    def handle_error(self, request, client_address):
400
        # Stop serving and re-raise the last exception seen
401
        self.serving.clear()
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
402
#        self.sibling_class.handle_error(self, request, client_address)
5247.3.10 by Vincent Ladeuil
Test errors during server life.
403
        raise
404
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
405
    def ignored_exceptions_during_shutdown(self, e):
406
        if sys.platform == 'win32':
5247.5.8 by Vincent Ladeuil
Thanks for being inconsistently inconsistent.
407
            accepted_errnos = [errno.EBADF, errno.WSAEBADF, errno.WSAENOTCONN,
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
408
                               errno.WSAECONNRESET, errno.WSAESHUTDOWN]
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
409
        else:
410
            accepted_errnos = [errno.EBADF, errno.ENOTCONN, errno.ECONNRESET]
411
        if isinstance(e, socket.error) and e[0] in accepted_errnos:
412
            return True
413
        return False
414
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
415
    # The following methods are called by the main thread
416
417
    def stop_client_connections(self):
418
        while self.clients:
419
            c = self.clients.pop()
420
            self.shutdown_client(c)
421
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
422
    def shutdown_socket(self, sock):
423
        """Properly shutdown a socket.
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
424
425
        This should be called only when no other thread is trying to use the
426
        socket.
427
        """
428
        try:
429
            sock.shutdown(socket.SHUT_RDWR)
430
            sock.close()
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
431
        except Exception, e:
432
            if self.ignored_exceptions(e):
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
433
                pass
434
            else:
435
                raise
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
436
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
437
    # The following methods are called by the main thread
438
439
    def set_ignored_exceptions(self, thread, ignored_exceptions):
440
        self.ignored_exceptions = ignored_exceptions
441
        thread.set_ignored_exceptions(self.ignored_exceptions)
442
443
    def _pending_exception(self, thread):
444
        """Raise server uncaught exception.
445
446
        Daughter classes can override this if they use daughter threads.
447
        """
448
        thread.pending_exception()
449
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
450
451
class TestingTCPServer(TestingTCPServerMixin, SocketServer.TCPServer):
452
453
    def __init__(self, server_address, request_handler_class):
454
        TestingTCPServerMixin.__init__(self, SocketServer.TCPServer)
455
        SocketServer.TCPServer.__init__(self, server_address,
456
                                        request_handler_class)
457
458
    def get_request(self):
459
        """Get the request and client address from the socket."""
460
        sock, addr = self.sibling_class.get_request(self)
461
        self.clients.append((sock, addr))
462
        return sock, addr
463
464
    # The following methods are called by the main thread
465
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
466
    def shutdown_client(self, client):
467
        sock, addr = client
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
468
        self.shutdown_socket(sock)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
469
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
470
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
471
class TestingThreadingTCPServer(TestingTCPServerMixin,
472
                                SocketServer.ThreadingTCPServer):
473
474
    def __init__(self, server_address, request_handler_class):
475
        TestingTCPServerMixin.__init__(self, SocketServer.ThreadingTCPServer)
476
        SocketServer.TCPServer.__init__(self, server_address,
477
                                        request_handler_class)
478
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
479
    def get_request (self):
480
        """Get the request and client address from the socket."""
481
        sock, addr = self.sibling_class.get_request(self)
482
        # The thread is not create yet, it will be updated in process_request
483
        self.clients.append((sock, addr, None))
484
        return sock, addr
485
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
486
    def process_request_thread(self, started, stopped, request, client_address):
487
        started.set()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
488
        SocketServer.ThreadingTCPServer.process_request_thread(
489
            self, request, client_address)
490
        self.close_request(request)
491
        stopped.set()
492
493
    def process_request(self, request, client_address):
494
        """Start a new thread to process the request."""
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
495
        started = threading.Event()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
496
        stopped = threading.Event()
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
497
        t = ThreadWithException(
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
498
            event=stopped,
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
499
            name='%s -> %s' % (client_address, self.server_address),
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
500
            target = self.process_request_thread,
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
501
            args = (started, stopped, request, client_address))
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
502
        # Update the client description
503
        self.clients.pop()
504
        self.clients.append((request, client_address, t))
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
505
        # Propagate the exception handler since we must the same one for
506
        # connections running in their own threads than TestingTCPServer.
507
        t.set_ignored_exceptions(self.ignored_exceptions)
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
508
        t.start()
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
509
        started.wait()
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
510
        if debug_threads():
511
            print 'Client thread %s started' % (t.name,)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
512
        # If an exception occured during the thread start, it will get raised.
513
        t.pending_exception()
514
515
    # The following methods are called by the main thread
516
517
    def shutdown_client(self, client):
5247.5.2 by Vincent Ladeuil
Cosmetic change.
518
        sock, addr, connection_thread = client
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
519
        self.shutdown_socket(sock)
5247.5.2 by Vincent Ladeuil
Cosmetic change.
520
        if connection_thread is not None:
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
521
            # The thread has been created only if the request is processed but
522
            # after the connection is inited. This could happen during server
523
            # shutdown. If an exception occurred in the thread it will be
524
            # re-raised
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
525
            if debug_threads():
526
                print 'Client thread %s will be joined' % (
527
                    connection_thread.name,)
5247.5.2 by Vincent Ladeuil
Cosmetic change.
528
            connection_thread.join()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
529
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
530
    def set_ignored_exceptions(self, thread, ignored_exceptions):
531
        TestingTCPServerMixin.set_ignored_exceptions(self, thread,
532
                                                     ignored_exceptions)
533
        for sock, addr, connection_thread in self.clients:
534
            if connection_thread is not None:
535
                connection_thread.set_ignored_exceptions(
536
                    self.ignored_exceptions)
537
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
538
    def _pending_exception(self, thread):
539
        for sock, addr, connection_thread in self.clients:
540
            if connection_thread is not None:
541
                connection_thread.pending_exception()
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
542
        TestingTCPServerMixin._pending_exception(self, thread)
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
543
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
544
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
545
class TestingTCPServerInAThread(transport.Server):
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
546
    """A server in a thread that re-raise thread exceptions."""
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
547
548
    def __init__(self, server_address, server_class, request_handler_class):
549
        self.server_class = server_class
550
        self.request_handler_class = request_handler_class
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
551
        self.host, self.port = server_address
5247.3.10 by Vincent Ladeuil
Test errors during server life.
552
        self.server = None
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
553
        self._server_thread = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
554
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
555
    def __repr__(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
556
        return "%s(%s:%s)" % (self.__class__.__name__, self.host, self.port)
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
557
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
558
    def create_server(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
559
        return self.server_class((self.host, self.port),
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
560
                                 self.request_handler_class)
561
562
    def start_server(self):
563
        self.server = self.create_server()
564
        self._server_thread = ThreadWithException(
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
565
            event=self.server.started,
566
            target=self.run_server)
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
567
        self._server_thread.start()
568
        # Wait for the server thread to start (i.e release the lock)
569
        self.server.started.wait()
570
        # Get the real address, especially the port
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
571
        self.host, self.port = self.server.server_address
5247.5.18 by Vincent Ladeuil
Compatibility with python 2.5 and 2.4 for ThreadWithException.name.
572
        self._server_thread.name = self.server.server_address
573
        if debug_threads():
574
            print 'Server thread %s started' % (self._server_thread.name,)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
575
        # If an exception occured during the server start, it will get raised,
576
        # otherwise, the server is blocked on its accept() call.
577
        self._server_thread.pending_exception()
5247.3.10 by Vincent Ladeuil
Test errors during server life.
578
        # From now on, we'll use a different event to ensure the server can set
579
        # its exception
580
        self._server_thread.set_event(self.server.stopped)
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
581
582
    def run_server(self):
583
        self.server.serve()
584
585
    def stop_server(self):
586
        if self.server is None:
587
            return
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
588
        try:
589
            # The server has been started successfully, shut it down now.  As
5247.5.10 by Vincent Ladeuil
Fix broken test.
590
            # soon as we stop serving, no more connection are accepted except
591
            # one to get out of the blocking listen.
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
592
            self.set_ignored_exceptions(
593
                self.server.ignored_exceptions_during_shutdown)
5247.5.10 by Vincent Ladeuil
Fix broken test.
594
            self.server.serving.clear()
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
595
            if debug_threads():
596
                print 'Server thread %s will be joined' % (
597
                    self._server_thread.name,)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
598
            # The server is listening for a last connection, let's give it:
599
            last_conn = None
600
            try:
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
601
                last_conn = osutils.connect_socket((self.host, self.port))
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
602
            except socket.error, e:
603
                # But ignore connection errors as the point is to unblock the
604
                # server thread, it may happen that it's not blocked or even
605
                # not started.
606
                pass
607
            # We start shutting down the client while the server itself is
608
            # shutting down.
609
            self.server.stop_client_connections()
610
            # Now we wait for the thread running self.server.serve() to finish
611
            self.server.stopped.wait()
612
            if last_conn is not None:
613
                # Close the last connection without trying to use it. The
614
                # server will not process a single byte on that socket to avoid
615
                # complications (SSL starts with a handshake for example).
616
                last_conn.close()
5247.3.10 by Vincent Ladeuil
Test errors during server life.
617
            # Check for any exception that could have occurred in the server
618
            # thread
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
619
            try:
620
                self._server_thread.join()
621
            except Exception, e:
622
                if self.server.ignored_exceptions(e):
623
                    pass
624
                else:
625
                    raise
5247.3.10 by Vincent Ladeuil
Test errors during server life.
626
        finally:
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
627
            # Make sure we can be called twice safely, note that this means
628
            # that we will raise a single exception even if several occurred in
629
            # the various threads involved.
5247.3.10 by Vincent Ladeuil
Test errors during server life.
630
            self.server = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
631
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
632
    def set_ignored_exceptions(self, ignored_exceptions):
633
        """Install an exception handler for the server."""
634
        self.server.set_ignored_exceptions(self._server_thread,
635
                                           ignored_exceptions)
636
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
637
    def pending_exception(self):
638
        """Raise uncaught exception in the server."""
639
        self.server._pending_exception(self._server_thread)
640
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
641
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
642
class SmartTCPServer_for_testing(server.SmartTCPServer):
643
    """Server suitable for use by transport tests.
644
645
    This server is backed by the process's cwd.
646
    """
647
648
    def __init__(self, thread_name_suffix=''):
649
        super(SmartTCPServer_for_testing, self).__init__(None)
650
        self.client_path_extra = None
651
        self.thread_name_suffix = thread_name_suffix
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
652
        # We collect the sockets/threads used by the clients so we can
653
        # close/join them when shutting down
654
        self.clients = []
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
655
656
    def get_backing_transport(self, backing_transport_server):
657
        """Get a backing transport from a server we are decorating."""
658
        return transport.get_transport(backing_transport_server.get_url())
659
660
    def start_server(self, backing_transport_server=None,
661
              client_path_extra='/extra/'):
662
        """Set up server for testing.
663
664
        :param backing_transport_server: backing server to use.  If not
665
            specified, a LocalURLServer at the current working directory will
666
            be used.
667
        :param client_path_extra: a path segment starting with '/' to append to
668
            the root URL for this server.  For instance, a value of '/foo/bar/'
669
            will mean the root of the backing transport will be published at a
670
            URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
671
            `bzr://127.0.0.1:nnnn/`.  Default value is `extra`, so that tests
672
            by default will fail unless they do the necessary path translation.
673
        """
674
        if not client_path_extra.startswith('/'):
675
            raise ValueError(client_path_extra)
676
        from bzrlib.transport.chroot import ChrootServer
677
        if backing_transport_server is None:
678
            backing_transport_server = LocalURLServer()
679
        self.chroot_server = ChrootServer(
680
            self.get_backing_transport(backing_transport_server))
681
        self.chroot_server.start_server()
682
        self.backing_transport = transport.get_transport(
683
            self.chroot_server.get_url())
684
        self.root_client_path = self.client_path_extra = client_path_extra
685
        self.start_background_thread(self.thread_name_suffix)
686
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
687
    def serve_conn(self, conn, thread_name_suffix):
688
        conn_thread = super(SmartTCPServer_for_testing, self).serve_conn(
689
            conn, thread_name_suffix)
690
        self.clients.append((conn, conn_thread))
691
        return conn_thread
692
693
    def shutdown_client(self, client_socket):
694
        """Properly shutdown a client socket.
695
696
        Under some circumstances (as in bug #383920), we need to force the
697
        shutdown as python delays it until gc occur otherwise and the client
698
        may hang.
699
700
        This should be called only when no other thread is trying to use the
701
        socket.
702
        """
703
        try:
704
            # The request process has been completed, the thread is about to
705
            # die, let's shutdown the socket if we can.
706
            client_socket.shutdown(socket.SHUT_RDWR)
707
        except (socket.error, select.error), e:
708
            if e[0] in (errno.EBADF, errno.ENOTCONN):
709
                # Right, the socket is already down
710
                pass
711
            else:
712
                raise
713
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
714
    def stop_server(self):
715
        self.stop_background_thread()
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
716
        # Let's close all our pending clients too
717
        for sock, thread in self.clients:
718
            self.shutdown_client(sock)
719
            thread.join()
720
            del thread
721
        self.clients = []
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
722
        self.chroot_server.stop_server()
723
724
    def get_url(self):
725
        url = super(SmartTCPServer_for_testing, self).get_url()
726
        return url[:-1] + self.client_path_extra
727
728
    def get_bogus_url(self):
729
        """Return a URL which will fail to connect"""
730
        return 'bzr://127.0.0.1:1/'
731
732
733
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
734
    """Get a readonly server for testing."""
735
736
    def get_backing_transport(self, backing_transport_server):
737
        """Get a backing transport from a server we are decorating."""
738
        url = 'readonly+' + backing_transport_server.get_url()
739
        return transport.get_transport(url)
740
741
742
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
743
    """A variation of SmartTCPServer_for_testing that limits the client to
744
    using RPCs in protocol v2 (i.e. bzr <= 1.5).
745
    """
746
747
    def get_url(self):
748
        url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
749
        url = 'bzr-v2://' + url[len('bzr://'):]
750
        return url
751
752
753
class ReadonlySmartTCPServer_for_testing_v2_only(
754
    SmartTCPServer_for_testing_v2_only):
755
    """Get a readonly server for testing."""
756
757
    def get_backing_transport(self, backing_transport_server):
758
        """Get a backing transport from a server we are decorating."""
759
        url = 'readonly+' + backing_transport_server.get_url()
760
        return transport.get_transport(url)
761
762
763
764