~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/http_server.py

Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.

This is used to replace various ad hoc implementations of the same logic,
notably the version used in registry's _LazyObjectGetter which had a bug when
getting a module without also getting a member.  And of course, this new
function has unit tests, unlike the replaced code.

This also adds a KnownHooksRegistry subclass to provide a more natural home for
some other logic.

I'm not thrilled about the name of the new module or the new functions, but it's
hard to think of good names for such generic functionality.

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
import urllib
31
31
import urlparse
32
32
 
33
 
from bzrlib import transport
 
33
from bzrlib import (
 
34
    osutils,
 
35
    tests,
 
36
    transport,
 
37
    )
34
38
from bzrlib.tests import test_server
35
39
from bzrlib.transport import local
36
40
 
71
75
                self.headers.get('referer', '-'),
72
76
                self.headers.get('user-agent', '-'))
73
77
 
 
78
    def handle(self):
 
79
        SimpleHTTPServer.SimpleHTTPRequestHandler.handle(self)
 
80
        # Some client (pycurl, I'm looking at you) are more picky than others
 
81
        # and require that the socket itself is closed
 
82
        # (SocketServer.StreamRequestHandler only close the two associated
 
83
        # 'makefile' objects)
 
84
        self.connection.close()
 
85
 
74
86
    def handle_one_request(self):
75
87
        """Handle a single HTTP request.
76
88
 
78
90
        connection early to avoid polluting the test results.
79
91
        """
80
92
        try:
81
 
            SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
 
93
            self._handle_one_request()
82
94
        except socket.error, e:
83
95
            # Any socket error should close the connection, but some errors are
84
96
            # due to the client closing early and we don't want to pollute test
89
101
                                     errno.ECONNABORTED, errno.EBADF)):
90
102
                raise
91
103
 
 
104
    error_content_type = 'text/plain'
 
105
    error_message_format = '''\
 
106
Error code: %(code)s.
 
107
Message: %(message)s.
 
108
'''
 
109
 
 
110
    def send_error(self, code, message=None):
 
111
        """Send and log an error reply.
 
112
 
 
113
        We redefine the python-provided version to be able to set a 
 
114
        ``Content-Length`` header as some http/1.1 clients complain otherwise
 
115
        (see bug #568421).
 
116
 
 
117
        :param code: The HTTP error code.
 
118
 
 
119
        :param message: The explanation of the error code, Defaults to a short
 
120
             entry.
 
121
        """
 
122
 
 
123
        if message is None:
 
124
            try:
 
125
                message = self.responses[code][0]
 
126
            except KeyError:
 
127
                message = '???'
 
128
        self.log_error("code %d, message %s", code, message)
 
129
        content = (self.error_message_format %
 
130
                   {'code': code, 'message': message})
 
131
        self.send_response(code, message)
 
132
        self.send_header("Content-Type", self.error_content_type)
 
133
        self.send_header("Content-Length", "%d" % len(content))
 
134
        self.send_header('Connection', 'close')
 
135
        self.end_headers()
 
136
        if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
 
137
            self.wfile.write(content)
 
138
 
 
139
    def _handle_one_request(self):
 
140
        SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)
 
141
 
92
142
    _range_regexp = re.compile(r'^(?P<start>\d+)-(?P<end>\d+)$')
93
143
    _tail_regexp = re.compile(r'^-(?P<tail>\d+)$')
94
144
 
213
263
            # mode may cause newline translations, making the
214
264
            # actual size of the content transmitted *less* than
215
265
            # the content-length!
216
 
            file = open(path, 'rb')
 
266
            f = open(path, 'rb')
217
267
        except IOError:
218
268
            self.send_error(404, "File not found")
219
269
            return
220
270
 
221
 
        file_size = os.fstat(file.fileno())[6]
 
271
        file_size = os.fstat(f.fileno())[6]
222
272
        tail, ranges = self.parse_ranges(ranges_header_value)
223
273
        # Normalize tail into ranges
224
274
        if tail != 0:
245
295
            # RFC2616 14.16 and 14.35 says that when a server
246
296
            # encounters unsatisfiable range specifiers, it
247
297
            # SHOULD return a 416.
248
 
            file.close()
 
298
            f.close()
249
299
            # FIXME: We SHOULD send a Content-Range header too,
250
300
            # but the implementation of send_error does not
251
301
            # allows that. So far.
254
304
 
255
305
        if len(ranges) == 1:
256
306
            (start, end) = ranges[0]
257
 
            self.get_single_range(file, file_size, start, end)
 
307
            self.get_single_range(f, file_size, start, end)
258
308
        else:
259
 
            self.get_multiple_ranges(file, file_size, ranges)
260
 
        file.close()
 
309
            self.get_multiple_ranges(f, file_size, ranges)
 
310
        f.close()
261
311
 
262
312
    def translate_path(self, path):
263
313
        """Translate a /-separated PATH to the local filename syntax.
319
369
        self.test_case_server = test_case_server
320
370
        self._home_dir = test_case_server._home_dir
321
371
 
322
 
    def stop_server(self):
323
 
         """Called to clean-up the server.
324
 
 
325
 
         Since the server may be (surely is, even) in a blocking listen, we
326
 
         shutdown its socket before closing it.
327
 
         """
328
 
         # Note that is this executed as part of the implicit tear down in the
329
 
         # main thread while the server runs in its own thread. The clean way
330
 
         # to tear down the server is to instruct him to stop accepting
331
 
         # connections and wait for the current connection(s) to end
332
 
         # naturally. To end the connection naturally, the http transports
333
 
         # should close their socket when they do not need to talk to the
334
 
         # server anymore. This happens naturally during the garbage collection
335
 
         # phase of the test transport objetcs (the server clients), so we
336
 
         # don't have to worry about them.  So, for the server, we must tear
337
 
         # down here, from the main thread, when the test have ended.  Note
338
 
         # that since the server is in a blocking operation and since python
339
 
         # use select internally, shutting down the socket is reliable and
340
 
         # relatively clean.
341
 
         try:
342
 
             self.socket.shutdown(socket.SHUT_RDWR)
343
 
         except socket.error, e:
344
 
             # WSAENOTCONN (10057) 'Socket is not connected' is harmless on
345
 
             # windows (occurs before the first connection attempt
346
 
             # vila--20071230)
347
 
 
348
 
             # 'Socket is not connected' can also occur on OSX, with a
349
 
             # "regular" ENOTCONN (when something went wrong during test case
350
 
             # setup leading to self.setUp() *not* being called but
351
 
             # self.stop_server() still being called -- vila20081106
352
 
             if not len(e.args) or e.args[0] not in (errno.ENOTCONN, 10057):
353
 
                 raise
354
 
         # Let the server properly close the socket
355
 
         self.server_close()
356
 
 
357
 
 
358
 
class TestingHTTPServer(SocketServer.TCPServer, TestingHTTPServerMixin):
 
372
 
 
373
class TestingHTTPServer(test_server.TestingTCPServer, TestingHTTPServerMixin):
359
374
 
360
375
    def __init__(self, server_address, request_handler_class,
361
376
                 test_case_server):
 
377
        test_server.TestingTCPServer.__init__(self, server_address,
 
378
                                              request_handler_class)
362
379
        TestingHTTPServerMixin.__init__(self, test_case_server)
363
 
        SocketServer.TCPServer.__init__(self, server_address,
364
 
                                        request_handler_class)
365
 
 
366
 
 
367
 
class TestingThreadingHTTPServer(SocketServer.ThreadingTCPServer,
 
380
 
 
381
 
 
382
class TestingThreadingHTTPServer(test_server.TestingThreadingTCPServer,
368
383
                                 TestingHTTPServerMixin):
369
384
    """A threading HTTP test server for HTTP 1.1.
370
385
 
372
387
    server, we need an independent connection for each of them. We achieve that
373
388
    by spawning a new thread for each connection.
374
389
    """
375
 
 
376
390
    def __init__(self, server_address, request_handler_class,
377
391
                 test_case_server):
 
392
        test_server.TestingThreadingTCPServer.__init__(self, server_address,
 
393
                                                       request_handler_class)
378
394
        TestingHTTPServerMixin.__init__(self, test_case_server)
379
 
        SocketServer.ThreadingTCPServer.__init__(self, server_address,
380
 
                                                 request_handler_class)
381
 
        # Decides how threads will act upon termination of the main
382
 
        # process. This is prophylactic as we should not leave the threads
383
 
        # lying around.
384
 
        self.daemon_threads = True
385
 
 
386
 
    def process_request_thread(self, request, client_address):
387
 
        SocketServer.ThreadingTCPServer.process_request_thread(
388
 
            self, request, client_address)
389
 
        # Under some circumstances (as in bug #383920), we need to force the
390
 
        # shutdown as python delays it until gc occur otherwise and the client
391
 
        # may hang.
392
 
        try:
393
 
            # The request process has been completed, the thread is about to
394
 
            # die, let's shutdown the socket if we can.
395
 
            request.shutdown(socket.SHUT_RDWR)
396
 
        except (socket.error, select.error), e:
397
 
            if e[0] in (errno.EBADF, errno.ENOTCONN):
398
 
                # Right, the socket is already down
399
 
                pass
400
 
            else:
401
 
                raise
402
 
 
403
 
 
404
 
class HttpServer(transport.Server):
 
395
 
 
396
 
 
397
class HttpServer(test_server.TestingTCPServerInAThread):
405
398
    """A test server for http transports.
406
399
 
407
400
    Subclasses can provide a specific request handler.
429
422
        :param protocol_version: if specified, will override the protocol
430
423
            version of the request handler.
431
424
        """
432
 
        transport.Server.__init__(self)
433
 
        self.request_handler = request_handler
 
425
        # Depending on the protocol version, we will create the approriate
 
426
        # server
 
427
        if protocol_version is None:
 
428
            # Use the request handler one
 
429
            proto_vers = request_handler.protocol_version
 
430
        else:
 
431
            # Use our own, it will be used to override the request handler
 
432
            # one too.
 
433
            proto_vers = protocol_version
 
434
        # Get the appropriate server class for the required protocol
 
435
        serv_cls = self.http_server_class.get(proto_vers, None)
 
436
        if serv_cls is None:
 
437
            raise httplib.UnknownProtocol(proto_vers)
434
438
        self.host = 'localhost'
435
439
        self.port = 0
436
 
        self._httpd = None
437
 
        self.protocol_version = protocol_version
 
440
        super(HttpServer, self).__init__((self.host, self.port),
 
441
                                         serv_cls,
 
442
                                         request_handler)
 
443
        self.protocol_version = proto_vers
438
444
        # Allows tests to verify number of GET requests issued
439
445
        self.GET_request_nb = 0
440
 
 
441
 
    def create_httpd(self, serv_cls, rhandler_cls):
442
 
        return serv_cls((self.host, self.port), self.request_handler, self)
443
 
 
444
 
    def __repr__(self):
445
 
        return "%s(%s:%s)" % \
446
 
            (self.__class__.__name__, self.host, self.port)
447
 
 
448
 
    def _get_httpd(self):
449
 
        if self._httpd is None:
450
 
            rhandler = self.request_handler
451
 
            # Depending on the protocol version, we will create the approriate
452
 
            # server
453
 
            if self.protocol_version is None:
454
 
                # Use the request handler one
455
 
                proto_vers = rhandler.protocol_version
456
 
            else:
457
 
                # Use our own, it will be used to override the request handler
458
 
                # one too.
459
 
                proto_vers = self.protocol_version
460
 
            # Create the appropriate server for the required protocol
461
 
            serv_cls = self.http_server_class.get(proto_vers, None)
462
 
            if serv_cls is None:
463
 
                raise httplib.UnknownProtocol(proto_vers)
464
 
            else:
465
 
                self._httpd = self.create_httpd(serv_cls, rhandler)
466
 
            self.host, self.port = self._httpd.socket.getsockname()
467
 
        return self._httpd
468
 
 
469
 
    def _http_start(self):
470
 
        """Server thread main entry point. """
471
 
        self._http_running = False
472
 
        try:
473
 
            try:
474
 
                httpd = self._get_httpd()
475
 
                self._http_base_url = '%s://%s:%s/' % (self._url_protocol,
476
 
                                                       self.host, self.port)
477
 
                self._http_running = True
478
 
            except:
479
 
                # Whatever goes wrong, we save the exception for the main
480
 
                # thread. Note that since we are running in a thread, no signal
481
 
                # can be received, so we don't care about KeyboardInterrupt.
482
 
                self._http_exception = sys.exc_info()
483
 
        finally:
484
 
            # Release the lock or the main thread will block and the whole
485
 
            # process will hang.
486
 
            self._http_starting.release()
487
 
 
488
 
        # From now on, exceptions are taken care of by the
489
 
        # SocketServer.BaseServer or the request handler.
490
 
        while self._http_running:
491
 
            try:
492
 
                # Really an HTTP connection but the python framework is generic
493
 
                # and call them requests
494
 
                httpd.handle_request()
495
 
            except socket.timeout:
496
 
                pass
497
 
            except (socket.error, select.error), e:
498
 
                if (e[0] == errno.EBADF
499
 
                    or (sys.platform == 'win32' and e[0] == 10038)):
500
 
                    # Starting with python-2.6, handle_request may raise socket
501
 
                    # or select exceptions when the server is shut down (as we
502
 
                    # do).
503
 
                    # 10038 = WSAENOTSOCK
504
 
                    # http://msdn.microsoft.com/en-us/library/ms740668%28VS.85%29.aspx
505
 
                    pass
506
 
                else:
507
 
                    raise
 
446
        self._http_base_url = None
 
447
        self.logs = []
 
448
 
 
449
    def create_server(self):
 
450
        return self.server_class(
 
451
            (self.host, self.port), self.request_handler_class, self)
508
452
 
509
453
    def _get_remote_url(self, path):
510
454
        path_parts = path.split(os.path.sep)
535
479
                or isinstance(backing_transport_server,
536
480
                              test_server.LocalURLServer)):
537
481
            raise AssertionError(
538
 
                "HTTPServer currently assumes local transport, got %s" % \
 
482
                "HTTPServer currently assumes local transport, got %s" %
539
483
                backing_transport_server)
540
484
        self._home_dir = os.getcwdu()
541
485
        self._local_path_parts = self._home_dir.split(os.path.sep)
542
 
        self._http_base_url = None
543
 
 
544
 
        # Create the server thread
545
 
        self._http_starting = threading.Lock()
546
 
        self._http_starting.acquire()
547
 
        self._http_thread = threading.Thread(target=self._http_start)
548
 
        self._http_thread.setDaemon(True)
549
 
        self._http_exception = None
550
 
        self._http_thread.start()
551
 
 
552
 
        # Wait for the server thread to start (i.e release the lock)
553
 
        self._http_starting.acquire()
554
 
 
555
 
        if self._http_exception is not None:
556
 
            # Something went wrong during server start
557
 
            exc_class, exc_value, exc_tb = self._http_exception
558
 
            raise exc_class, exc_value, exc_tb
559
 
        self._http_starting.release()
560
486
        self.logs = []
561
487
 
562
 
    def stop_server(self):
563
 
        self._httpd.stop_server()
564
 
        self._http_running = False
565
 
        # We don't need to 'self._http_thread.join()' here since the thread is
566
 
        # a daemonic one and will be garbage collected anyway. Joining just
567
 
        # slows us down for no added benefit.
 
488
        super(HttpServer, self).start_server()
 
489
        self._http_base_url = '%s://%s:%s/' % (
 
490
            self._url_protocol, self.host, self.port)
568
491
 
569
492
    def get_url(self):
570
493
        """See bzrlib.transport.Server.get_url."""