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