~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/http_server.py

  • Committer: Vincent Ladeuil
  • Date: 2011-08-20 09:28:27 UTC
  • mfrom: (5050.78.2 2.2)
  • mto: (5609.48.8 2.3)
  • mto: This revision was merged to the branch mainline in revision 6090.
  • Revision ID: v.ladeuil+lp@free.fr-20110820092827-9dyakfslp0r3hb1k
Merge 2.2 into 2.3 (including fix for #614713, #609187 and #812928)

Show diffs side-by-side

added added

removed removed

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