view mercurial/httpclient/socketutil.py @ 26623:5a95fe44121d

clonebundles: support for seeding clones from pre-generated bundles Cloning can be an expensive operation for servers because the server generates a bundle from existing repository data at request time. For a large repository like mozilla-central, this consumes 4+ minutes of CPU time on the server. It also results in significant network utilization. Multiplied by hundreds or even thousands of clients and the ensuing load can result in difficulties scaling the Mercurial server. Despite generation of bundles being deterministic until the next changeset is added, the generation of bundles to service a clone request is not cached. Each clone thus performs redundant work. This is wasteful. This patch introduces the "clonebundles" extension and related client-side functionality to help alleviate this deficiency. The client-side feature is behind an experimental flag and is not enabled by default. It works as follows: 1) Server operator generates a bundle and makes it available on a server (likely HTTP). 2) Server operator defines the URL of a bundle file in a .hg/clonebundles.manifest file. 3) Client `hg clone`ing sees the server is advertising bundle URLs. 4) Client fetches and applies the advertised bundle. 5) Client performs equivalent of `hg pull` to fetch changes made since the bundle was created. Essentially, the server performs the expensive work of generating a bundle once and all subsequent clones fetch a static file from somewhere. Scaling static file serving is a much more manageable problem than scaling a Python application like Mercurial. Assuming your repository grows less than 1% per day, the end result is 99+% of CPU and network load from clones is eliminated, allowing Mercurial servers to scale more easily. Serving static files also means data can be transferred to clients as fast as they can consume it, rather than as fast as servers can generate it. This makes clones faster. Mozilla has implemented similar functionality of this patch on hg.mozilla.org using a custom extension. We are hosting bundle files in Amazon S3 and CloudFront (a CDN) and have successfully offloaded >1 TB/day in data transfer from hg.mozilla.org, freeing up significant bandwidth and CPU resources. The positive impact has been stellar and I believe it has proved its value to be included in Mercurial core. I feel it is important for the client-side support to be enabled in core by default because it means that clients will get faster, more reliable clones and will enable server operators to reduce load without requiring any client-side configuration changes (assuming clients are up to date, of course). The scope of this feature is narrowly and specifically tailored to cloning, despite "serve pulls from pre-generated bundles" being a valid and useful feature. I would eventually like for Mercurial servers to support transferring *all* repository data via statically hosted files. You could imagine a server that siphons all pushed data to bundle files and instructs clients to apply a stream of bundles to reconstruct all repository data. This feature, while useful and powerful, is significantly more work to implement because it requires the server component have awareness of discovery and a mapping of which changesets are in which files. Full, clone bundles, by contrast, are much simpler. The wire protocol command is named "clonebundles" instead of something more generic like "staticbundles" to leave the door open for a new, more powerful and more generic server-side component with minimal backwards compatibility implications. The name "bundleclone" is used by Mozilla's extension and would cause problems since there are subtle differences in Mozilla's extension. Mozilla's experience with this idea has taught us that some form of "content negotiation" is required. Not all clients will support all bundle formats or even URLs (advanced TLS requirements, etc). To ensure the highest uptake possible, a server needs to advertise multiple versions of bundles and clients need to be able to choose the most appropriate from that list one. The "attributes" in each server-advertised entry facilitate this filtering and sorting. Their use will become apparent in subsequent patches. Initial inspiration and credit for the idea of cloning from static files belongs to Augie Fackler and his "lookaside clone" extension proof of concept.
author Gregory Szorc <gregory.szorc@gmail.com>
date Fri, 09 Oct 2015 11:22:01 -0700
parents 328739ea70c3
children 1ad9da968a2e
line wrap: on
line source

# Copyright 2010, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Abstraction to simplify socket use for Python < 2.6

This will attempt to use the ssl module and the new
socket.create_connection method, but fall back to the old
methods if those are unavailable.
"""
import logging
import socket

logger = logging.getLogger(__name__)

try:
    import ssl
    # make demandimporters load the module
    ssl.wrap_socket # pylint: disable=W0104
    have_ssl = True
except ImportError:
    import httplib
    import urllib2
    have_ssl = getattr(urllib2, 'HTTPSHandler', False)
    ssl = False


try:
    create_connection = socket.create_connection
except AttributeError:
    def create_connection(address):
        """Backport of socket.create_connection from Python 2.6."""
        host, port = address
        msg = "getaddrinfo returns an empty list"
        sock = None
        for res in socket.getaddrinfo(host, port, 0,
                                      socket.SOCK_STREAM):
            af, socktype, proto, unused_canonname, sa = res
            try:
                sock = socket.socket(af, socktype, proto)
                logger.info("connect: (%s, %s)", host, port)
                sock.connect(sa)
            except socket.error as msg:
                logger.info('connect fail: %s %s', host, port)
                if sock:
                    sock.close()
                sock = None
                continue
            break
        if not sock:
            raise socket.error(msg)
        return sock

if ssl:
    wrap_socket = ssl.wrap_socket
    CERT_NONE = ssl.CERT_NONE
    CERT_OPTIONAL = ssl.CERT_OPTIONAL
    CERT_REQUIRED = ssl.CERT_REQUIRED
else:
    class FakeSocket(httplib.FakeSocket):
        """Socket wrapper that supports SSL."""

        # Silence lint about this goofy backport class
        # pylint: disable=W0232,E1101,R0903,R0913,C0111

        # backport the behavior from Python 2.6, which is to busy wait
        # on the socket instead of anything nice. Sigh.
        # See http://bugs.python.org/issue3890 for more info.
        def recv(self, buflen=1024, flags=0):
            """ssl-aware wrapper around socket.recv
            """
            if flags != 0:
                raise ValueError(
                    "non-zero flags not allowed in calls to recv() on %s" %
                    self.__class__)
            while True:
                try:
                    return self._ssl.read(buflen)
                except socket.sslerror as x:
                    if x.args[0] == socket.SSL_ERROR_WANT_READ:
                        continue
                    else:
                        raise x

    _PROTOCOL_SSLv23 = 2

    CERT_NONE = 0
    CERT_OPTIONAL = 1
    CERT_REQUIRED = 2

    # Disable unused-argument because we're making a dumb wrapper
    # that's like an upstream method.
    #
    # pylint: disable=W0613,R0913
    def wrap_socket(sock, keyfile=None, certfile=None,
                server_side=False, cert_reqs=CERT_NONE,
                ssl_version=_PROTOCOL_SSLv23, ca_certs=None,
                do_handshake_on_connect=True,
                suppress_ragged_eofs=True):
        """Backport of ssl.wrap_socket from Python 2.6."""
        if cert_reqs != CERT_NONE and ca_certs:
            raise CertificateValidationUnsupported(
                'SSL certificate validation requires the ssl module'
                '(included in Python 2.6 and later.)')
        sslob = socket.ssl(sock)
        # borrow httplib's workaround for no ssl.wrap_socket
        sock = FakeSocket(sock, sslob)
        return sock
    # pylint: enable=W0613,R0913


class CertificateValidationUnsupported(Exception):
    """Exception raised when cert validation is requested but unavailable."""
# no-check-code