/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
265
    def set_event(self, event):
5247.2.5 by Vincent Ladeuil
Some cleanups.
266
        self.ready = event
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
267
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
268
    def set_ignored_exceptions(self, ignored):
269
        """Declare which exceptions will be ignored.
270
271
        :param ignored: Can be either:
272
           - None: all exceptions will be raised,
273
           - an exception class: the instances of this class will be ignored,
274
           - a tuple of exception classes: the instances of any class of the
275
             list will be ignored,
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
276
           - 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.
277
             and should return True if the exception should be ignored
278
        """
279
        if ignored is None:
280
            self.ignored_exceptions = None
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
281
        elif isinstance(ignored, (Exception, tuple)):
282
            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.
283
        else:
284
            self.ignored_exceptions = ignored
285
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
286
    def run(self):
287
        """Overrides Thread.run to capture any exception."""
5247.2.5 by Vincent Ladeuil
Some cleanups.
288
        self.ready.clear()
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
289
        try:
5247.3.19 by Vincent Ladeuil
Fix python-2.4 incompatibility.
290
            try:
291
                super(ThreadWithException, self).run()
292
            except:
293
                self.exception = sys.exc_info()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
294
        finally:
295
            # Make sure the calling thread is released
5247.2.5 by Vincent Ladeuil
Some cleanups.
296
            self.ready.set()
5247.2.4 by Vincent Ladeuil
Add an event to ThreadWithException that can be shared with the calling thread.
297
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
298
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
299
    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.
300
        """Overrides Thread.join to raise any exception caught.
301
302
303
        Calling join(timeout=0) will raise the caught exception or return None
5247.3.10 by Vincent Ladeuil
Test errors during server life.
304
        if the thread is still alive.
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
305
306
        The default timeout is set to 5 and should expire only when a thread
307
        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.
308
        """
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
309
        super(ThreadWithException, self).join(timeout)
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
310
        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.
311
            exc_class, exc_value, exc_tb = self.exception
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
312
            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.
313
            if (self.ignored_exceptions is None
5247.5.6 by Vincent Ladeuil
Just pass the exception object to simplify.
314
                or not self.ignored_exceptions(exc_value)):
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
315
                # Raise non ignored exceptions
316
                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.
317
        if timeout and self.isAlive():
318
            # The timeout expired without joining the thread, the thread is
319
            # therefore stucked and that's a failure as far as the test is
320
            # concerned. We used to hang here.
321
            raise AssertionError('thread %s hung' % (self.name,))
322
323
    def pending_exception(self):
324
        """Raise the caught exception.
325
326
        This does nothing if no exception occurred.
327
        """
328
        self.join(timeout=0)
5247.2.2 by Vincent Ladeuil
Implement a thread that can re-raise exceptions.
329
330
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
331
class TestingTCPServerMixin:
332
    """Mixin to support running SocketServer.TCPServer in a thread.
333
334
    Tests are connecting from the main thread, the server has to be run in a
335
    separate thread.
336
    """
337
5247.3.16 by Vincent Ladeuil
All http tests passing (including https).
338
    # FIXME: sibling_class is a hack -- vila 20100604
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
339
    def __init__(self, sibling_class):
340
        self.sibling_class = sibling_class
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
341
        self.started = threading.Event()
342
        self.serving = threading.Event()
343
        self.stopped = threading.Event()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
344
        # We collect the resources used by the clients so we can release them
345
        # when shutting down
346
        self.clients = []
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
347
        self.ignored_exceptions = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
348
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
349
    def server_bind(self):
350
        # We need to override the SocketServer bind, yet, we still want to use
351
        # it so we need to use the sibling class to call it explicitly
352
        self.sibling_class.server_bind(self)
353
        # The following has been fixed in 2.5 so we need to provide it for
354
        # older python versions.
355
        if sys.version < (2, 5):
356
            self.server_address = self.socket.getsockname()
357
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
358
    def serve(self):
359
        self.serving.set()
360
        self.stopped.clear()
361
        # We are listening and ready to accept connections
362
        self.started.set()
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
363
        try:
364
            while self.serving.isSet():
365
                # Really a connection but the python framework is generic and
366
                # call them requests
367
                self.handle_request()
368
            # Let's close the listening socket
369
            self.server_close()
370
        finally:
371
            self.stopped.set()
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
372
5247.5.10 by Vincent Ladeuil
Fix broken test.
373
    def handle_request(self):
374
        """Handle one request.
375
376
        The python version swallows some socket exceptions and we don't use
377
        timeout, so we override it to better control the server behavior.
378
        """
379
        request, client_address = self.get_request()
380
        if self.verify_request(request, client_address):
381
            try:
382
                self.process_request(request, client_address)
383
            except:
384
                self.handle_error(request, client_address)
385
                self.close_request(request)
386
5247.3.9 by Vincent Ladeuil
Ensure a simple dialog can occur between a client and a server.
387
    def verify_request(self, request, client_address):
388
        """Verify the request.
389
390
        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.
391
        not even touch a single byte in the socket ! This is useful when we
392
        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.
393
        """
394
        return self.serving.isSet()
395
5247.3.10 by Vincent Ladeuil
Test errors during server life.
396
    def handle_error(self, request, client_address):
397
        # Stop serving and re-raise the last exception seen
398
        self.serving.clear()
5247.3.18 by Vincent Ladeuil
Fix some fallouts from previous fixes, all tests passing (no more http leaks).
399
#        self.sibling_class.handle_error(self, request, client_address)
5247.3.10 by Vincent Ladeuil
Test errors during server life.
400
        raise
401
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
402
    def ignored_exceptions_during_shutdown(self, e):
403
        if sys.platform == 'win32':
5247.5.8 by Vincent Ladeuil
Thanks for being inconsistently inconsistent.
404
            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.
405
                               errno.WSAECONNRESET, errno.WSAESHUTDOWN]
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
406
        else:
407
            accepted_errnos = [errno.EBADF, errno.ENOTCONN, errno.ECONNRESET]
408
        if isinstance(e, socket.error) and e[0] in accepted_errnos:
409
            return True
410
        return False
411
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
412
    # The following methods are called by the main thread
413
414
    def stop_client_connections(self):
415
        while self.clients:
416
            c = self.clients.pop()
417
            self.shutdown_client(c)
418
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
419
    def shutdown_socket(self, sock):
420
        """Properly shutdown a socket.
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
421
422
        This should be called only when no other thread is trying to use the
423
        socket.
424
        """
425
        try:
426
            sock.shutdown(socket.SHUT_RDWR)
427
            sock.close()
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
428
        except Exception, e:
429
            if self.ignored_exceptions(e):
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
430
                pass
431
            else:
432
                raise
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
433
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
434
    # The following methods are called by the main thread
435
436
    def set_ignored_exceptions(self, thread, ignored_exceptions):
437
        self.ignored_exceptions = ignored_exceptions
438
        thread.set_ignored_exceptions(self.ignored_exceptions)
439
440
    def _pending_exception(self, thread):
441
        """Raise server uncaught exception.
442
443
        Daughter classes can override this if they use daughter threads.
444
        """
445
        thread.pending_exception()
446
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
447
448
class TestingTCPServer(TestingTCPServerMixin, SocketServer.TCPServer):
449
450
    def __init__(self, server_address, request_handler_class):
451
        TestingTCPServerMixin.__init__(self, SocketServer.TCPServer)
452
        SocketServer.TCPServer.__init__(self, server_address,
453
                                        request_handler_class)
454
455
    def get_request(self):
456
        """Get the request and client address from the socket."""
457
        sock, addr = self.sibling_class.get_request(self)
458
        self.clients.append((sock, addr))
459
        return sock, addr
460
461
    # The following methods are called by the main thread
462
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
463
    def shutdown_client(self, client):
464
        sock, addr = client
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
465
        self.shutdown_socket(sock)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
466
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
467
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
468
class TestingThreadingTCPServer(TestingTCPServerMixin,
469
                                SocketServer.ThreadingTCPServer):
470
471
    def __init__(self, server_address, request_handler_class):
472
        TestingTCPServerMixin.__init__(self, SocketServer.ThreadingTCPServer)
473
        SocketServer.TCPServer.__init__(self, server_address,
474
                                        request_handler_class)
475
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
476
    def get_request (self):
477
        """Get the request and client address from the socket."""
478
        sock, addr = self.sibling_class.get_request(self)
479
        # The thread is not create yet, it will be updated in process_request
480
        self.clients.append((sock, addr, None))
481
        return sock, addr
482
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
483
    def process_request_thread(self, started, stopped, request, client_address):
484
        started.set()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
485
        SocketServer.ThreadingTCPServer.process_request_thread(
486
            self, request, client_address)
487
        self.close_request(request)
488
        stopped.set()
489
490
    def process_request(self, request, client_address):
491
        """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.
492
        started = threading.Event()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
493
        stopped = threading.Event()
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
494
        t = ThreadWithException(
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
495
            event=stopped,
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
496
            name='%s -> %s' % (client_address, self.server_address),
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
497
            target = self.process_request_thread,
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
498
            args = (started, stopped, request, client_address))
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
499
        # Update the client description
500
        self.clients.pop()
501
        self.clients.append((request, client_address, t))
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
502
        # Propagate the exception handler since we must the same one for
503
        # connections running in their own threads than TestingTCPServer.
504
        t.set_ignored_exceptions(self.ignored_exceptions)
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
505
        t.start()
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
506
        started.wait()
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
507
        if debug_threads():
508
            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.
509
        # If an exception occured during the thread start, it will get raised.
510
        t.pending_exception()
511
512
    # The following methods are called by the main thread
513
514
    def shutdown_client(self, client):
5247.5.2 by Vincent Ladeuil
Cosmetic change.
515
        sock, addr, connection_thread = client
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
516
        self.shutdown_socket(sock)
5247.5.2 by Vincent Ladeuil
Cosmetic change.
517
        if connection_thread is not None:
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
518
            # The thread has been created only if the request is processed but
519
            # after the connection is inited. This could happen during server
520
            # shutdown. If an exception occurred in the thread it will be
521
            # re-raised
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
522
            if debug_threads():
523
                print 'Client thread %s will be joined' % (
524
                    connection_thread.name,)
5247.5.2 by Vincent Ladeuil
Cosmetic change.
525
            connection_thread.join()
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
526
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
527
    def set_ignored_exceptions(self, thread, ignored_exceptions):
528
        TestingTCPServerMixin.set_ignored_exceptions(self, thread,
529
                                                     ignored_exceptions)
530
        for sock, addr, connection_thread in self.clients:
531
            if connection_thread is not None:
532
                connection_thread.set_ignored_exceptions(
533
                    self.ignored_exceptions)
534
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
535
    def _pending_exception(self, thread):
536
        for sock, addr, connection_thread in self.clients:
537
            if connection_thread is not None:
538
                connection_thread.pending_exception()
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
539
        TestingTCPServerMixin._pending_exception(self, thread)
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
540
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
541
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
542
class TestingTCPServerInAThread(transport.Server):
5247.3.11 by Vincent Ladeuil
Start implementing the threading variants.
543
    """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
544
545
    def __init__(self, server_address, server_class, request_handler_class):
546
        self.server_class = server_class
547
        self.request_handler_class = request_handler_class
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
548
        self.host, self.port = server_address
5247.3.10 by Vincent Ladeuil
Test errors during server life.
549
        self.server = None
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
550
        self._server_thread = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
551
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
552
    def __repr__(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
553
        return "%s(%s:%s)" % (self.__class__.__name__, self.host, self.port)
5247.3.14 by Vincent Ladeuil
Use a proper load_tests.
554
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
555
    def create_server(self):
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
556
        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
557
                                 self.request_handler_class)
558
559
    def start_server(self):
560
        self.server = self.create_server()
561
        self._server_thread = ThreadWithException(
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
562
            event=self.server.started,
5247.3.30 by Vincent Ladeuil
Merge propagate-exceptions into http-leaks
563
            name='(%s:%s)' % (self.host, self.port),
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
564
            target=self.run_server)
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
565
        self._server_thread.start()
566
        # Wait for the server thread to start (i.e release the lock)
567
        self.server.started.wait()
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
568
        if debug_threads():
569
            print 'Server thread %s started' % (self._server_thread.name,)
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
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.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
572
        # If an exception occured during the server start, it will get raised,
573
        # otherwise, the server is blocked on its accept() call.
574
        self._server_thread.pending_exception()
5247.3.10 by Vincent Ladeuil
Test errors during server life.
575
        # From now on, we'll use a different event to ensure the server can set
576
        # its exception
577
        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
578
579
    def run_server(self):
580
        self.server.serve()
581
582
    def stop_server(self):
583
        if self.server is None:
584
            return
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
585
        try:
586
            # The server has been started successfully, shut it down now.  As
5247.5.10 by Vincent Ladeuil
Fix broken test.
587
            # soon as we stop serving, no more connection are accepted except
588
            # one to get out of the blocking listen.
5247.5.7 by Vincent Ladeuil
Factor out socket exception handling during server shutdown.
589
            self.set_ignored_exceptions(
590
                self.server.ignored_exceptions_during_shutdown)
5247.5.10 by Vincent Ladeuil
Fix broken test.
591
            self.server.serving.clear()
5247.5.17 by Vincent Ladeuil
Add some basic debug tracing controlled by -Ethreads.
592
            if debug_threads():
593
                print 'Server thread %s will be joined' % (
594
                    self._server_thread.name,)
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
595
            # The server is listening for a last connection, let's give it:
596
            last_conn = None
597
            try:
5247.3.15 by Vincent Ladeuil
All http tests passing, https failing.
598
                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.
599
            except socket.error, e:
600
                # But ignore connection errors as the point is to unblock the
601
                # server thread, it may happen that it's not blocked or even
602
                # not started.
603
                pass
604
            # We start shutting down the client while the server itself is
605
            # shutting down.
606
            self.server.stop_client_connections()
607
            # Now we wait for the thread running self.server.serve() to finish
608
            self.server.stopped.wait()
609
            if last_conn is not None:
610
                # Close the last connection without trying to use it. The
611
                # server will not process a single byte on that socket to avoid
612
                # complications (SSL starts with a handshake for example).
613
                last_conn.close()
5247.3.10 by Vincent Ladeuil
Test errors during server life.
614
            # Check for any exception that could have occurred in the server
615
            # thread
5247.5.9 by Vincent Ladeuil
Use a better sync for test_exception_swallowed_while_serving test.
616
            try:
617
                self._server_thread.join()
618
            except Exception, e:
619
                if self.server.ignored_exceptions(e):
620
                    pass
621
                else:
622
                    raise
5247.3.10 by Vincent Ladeuil
Test errors during server life.
623
        finally:
5247.3.13 by Vincent Ladeuil
Really test against a threading server and properly shutdown socket and threads.
624
            # Make sure we can be called twice safely, note that this means
625
            # that we will raise a single exception even if several occurred in
626
            # the various threads involved.
5247.3.10 by Vincent Ladeuil
Test errors during server life.
627
            self.server = None
5247.3.8 by Vincent Ladeuil
Start implementing a TCP server running in its own thread (using
628
5247.5.4 by Vincent Ladeuil
Implement an execption handling mechanism that can be injected in ThreadWithException.
629
    def set_ignored_exceptions(self, ignored_exceptions):
630
        """Install an exception handler for the server."""
631
        self.server.set_ignored_exceptions(self._server_thread,
632
                                           ignored_exceptions)
633
5247.5.3 by Vincent Ladeuil
Fix exception raising only once for a given ThreadWithException.
634
    def pending_exception(self):
635
        """Raise uncaught exception in the server."""
636
        self.server._pending_exception(self._server_thread)
637
5247.3.12 by Vincent Ladeuil
Spawn a thread for each connection from a client.
638
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
639
class SmartTCPServer_for_testing(server.SmartTCPServer):
640
    """Server suitable for use by transport tests.
641
642
    This server is backed by the process's cwd.
643
    """
644
645
    def __init__(self, thread_name_suffix=''):
646
        super(SmartTCPServer_for_testing, self).__init__(None)
647
        self.client_path_extra = None
648
        self.thread_name_suffix = thread_name_suffix
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
649
        # We collect the sockets/threads used by the clients so we can
650
        # close/join them when shutting down
651
        self.clients = []
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
652
653
    def get_backing_transport(self, backing_transport_server):
654
        """Get a backing transport from a server we are decorating."""
655
        return transport.get_transport(backing_transport_server.get_url())
656
657
    def start_server(self, backing_transport_server=None,
658
              client_path_extra='/extra/'):
659
        """Set up server for testing.
660
661
        :param backing_transport_server: backing server to use.  If not
662
            specified, a LocalURLServer at the current working directory will
663
            be used.
664
        :param client_path_extra: a path segment starting with '/' to append to
665
            the root URL for this server.  For instance, a value of '/foo/bar/'
666
            will mean the root of the backing transport will be published at a
667
            URL like `bzr://127.0.0.1:nnnn/foo/bar/`, rather than
668
            `bzr://127.0.0.1:nnnn/`.  Default value is `extra`, so that tests
669
            by default will fail unless they do the necessary path translation.
670
        """
671
        if not client_path_extra.startswith('/'):
672
            raise ValueError(client_path_extra)
673
        from bzrlib.transport.chroot import ChrootServer
674
        if backing_transport_server is None:
675
            backing_transport_server = LocalURLServer()
676
        self.chroot_server = ChrootServer(
677
            self.get_backing_transport(backing_transport_server))
678
        self.chroot_server.start_server()
679
        self.backing_transport = transport.get_transport(
680
            self.chroot_server.get_url())
681
        self.root_client_path = self.client_path_extra = client_path_extra
682
        self.start_background_thread(self.thread_name_suffix)
683
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
684
    def serve_conn(self, conn, thread_name_suffix):
685
        conn_thread = super(SmartTCPServer_for_testing, self).serve_conn(
686
            conn, thread_name_suffix)
687
        self.clients.append((conn, conn_thread))
688
        return conn_thread
689
690
    def shutdown_client(self, client_socket):
691
        """Properly shutdown a client socket.
692
693
        Under some circumstances (as in bug #383920), we need to force the
694
        shutdown as python delays it until gc occur otherwise and the client
695
        may hang.
696
697
        This should be called only when no other thread is trying to use the
698
        socket.
699
        """
700
        try:
701
            # The request process has been completed, the thread is about to
702
            # die, let's shutdown the socket if we can.
703
            client_socket.shutdown(socket.SHUT_RDWR)
704
        except (socket.error, select.error), e:
705
            if e[0] in (errno.EBADF, errno.ENOTCONN):
706
                # Right, the socket is already down
707
                pass
708
            else:
709
                raise
710
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
711
    def stop_server(self):
712
        self.stop_background_thread()
5247.1.1 by Vincent Ladeuil
Merge previous attempt into current trunk
713
        # Let's close all our pending clients too
714
        for sock, thread in self.clients:
715
            self.shutdown_client(sock)
716
            thread.join()
717
            del thread
718
        self.clients = []
5017.3.18 by Vincent Ladeuil
Move SmartTCPServer_for_testing and friends to bzrlib.tests.test_server
719
        self.chroot_server.stop_server()
720
721
    def get_url(self):
722
        url = super(SmartTCPServer_for_testing, self).get_url()
723
        return url[:-1] + self.client_path_extra
724
725
    def get_bogus_url(self):
726
        """Return a URL which will fail to connect"""
727
        return 'bzr://127.0.0.1:1/'
728
729
730
class ReadonlySmartTCPServer_for_testing(SmartTCPServer_for_testing):
731
    """Get a readonly server for testing."""
732
733
    def get_backing_transport(self, backing_transport_server):
734
        """Get a backing transport from a server we are decorating."""
735
        url = 'readonly+' + backing_transport_server.get_url()
736
        return transport.get_transport(url)
737
738
739
class SmartTCPServer_for_testing_v2_only(SmartTCPServer_for_testing):
740
    """A variation of SmartTCPServer_for_testing that limits the client to
741
    using RPCs in protocol v2 (i.e. bzr <= 1.5).
742
    """
743
744
    def get_url(self):
745
        url = super(SmartTCPServer_for_testing_v2_only, self).get_url()
746
        url = 'bzr-v2://' + url[len('bzr://'):]
747
        return url
748
749
750
class ReadonlySmartTCPServer_for_testing_v2_only(
751
    SmartTCPServer_for_testing_v2_only):
752
    """Get a readonly server for testing."""
753
754
    def get_backing_transport(self, backing_transport_server):
755
        """Get a backing transport from a server we are decorating."""
756
        url = 'readonly+' + backing_transport_server.get_url()
757
        return transport.get_transport(url)
758
759
760
761