/brz/remove-bazaar

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