view mercurial/dagutil.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 015ded095933
children 09397d0dd3b7
line wrap: on
line source

# dagutil.py - dag utilities for mercurial
#
# Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
# and Peter Arrenbrecht <peter@arrenbrecht.ch>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import absolute_import

from .i18n import _
from .node import nullrev

class basedag(object):
    '''generic interface for DAGs

    terms:
    "ix" (short for index) identifies a nodes internally,
    "id" identifies one externally.

    All params are ixs unless explicitly suffixed otherwise.
    Pluralized params are lists or sets.
    '''

    def __init__(self):
        self._inverse = None

    def nodeset(self):
        '''set of all node ixs'''
        raise NotImplementedError

    def heads(self):
        '''list of head ixs'''
        raise NotImplementedError

    def parents(self, ix):
        '''list of parents ixs of ix'''
        raise NotImplementedError

    def inverse(self):
        '''inverse DAG, where parents becomes children, etc.'''
        raise NotImplementedError

    def ancestorset(self, starts, stops=None):
        '''
        set of all ancestors of starts (incl), but stop walk at stops (excl)
        '''
        raise NotImplementedError

    def descendantset(self, starts, stops=None):
        '''
        set of all descendants of starts (incl), but stop walk at stops (excl)
        '''
        return self.inverse().ancestorset(starts, stops)

    def headsetofconnecteds(self, ixs):
        '''
        subset of connected list of ixs so that no node has a descendant in it

        By "connected list" we mean that if an ancestor and a descendant are in
        the list, then so is at least one path connecting them.
        '''
        raise NotImplementedError

    def externalize(self, ix):
        '''return a node id'''
        return self._externalize(ix)

    def externalizeall(self, ixs):
        '''return a list of (or set if given a set) of node ids'''
        ids = self._externalizeall(ixs)
        if isinstance(ixs, set):
            return set(ids)
        return list(ids)

    def internalize(self, id):
        '''return a node ix'''
        return self._internalize(id)

    def internalizeall(self, ids, filterunknown=False):
        '''return a list of (or set if given a set) of node ixs'''
        ixs = self._internalizeall(ids, filterunknown)
        if isinstance(ids, set):
            return set(ixs)
        return list(ixs)


class genericdag(basedag):
    '''generic implementations for DAGs'''

    def ancestorset(self, starts, stops=None):
        if stops:
            stops = set(stops)
        else:
            stops = set()
        seen = set()
        pending = list(starts)
        while pending:
            n = pending.pop()
            if n not in seen and n not in stops:
                seen.add(n)
                pending.extend(self.parents(n))
        return seen

    def headsetofconnecteds(self, ixs):
        hds = set(ixs)
        if not hds:
            return hds
        for n in ixs:
            for p in self.parents(n):
                hds.discard(p)
        assert hds
        return hds


class revlogbaseddag(basedag):
    '''generic dag interface to a revlog'''

    def __init__(self, revlog, nodeset):
        basedag.__init__(self)
        self._revlog = revlog
        self._heads = None
        self._nodeset = nodeset

    def nodeset(self):
        return self._nodeset

    def heads(self):
        if self._heads is None:
            self._heads = self._getheads()
        return self._heads

    def _externalize(self, ix):
        return self._revlog.index[ix][7]
    def _externalizeall(self, ixs):
        idx = self._revlog.index
        return [idx[i][7] for i in ixs]

    def _internalize(self, id):
        ix = self._revlog.rev(id)
        if ix == nullrev:
            raise LookupError(id, self._revlog.indexfile, _('nullid'))
        return ix
    def _internalizeall(self, ids, filterunknown):
        rl = self._revlog
        if filterunknown:
            return [r for r in map(rl.nodemap.get, ids)
                    if (r is not None
                        and r != nullrev
                        and r not in rl.filteredrevs)]
        return map(self._internalize, ids)


class revlogdag(revlogbaseddag):
    '''dag interface to a revlog'''

    def __init__(self, revlog):
        revlogbaseddag.__init__(self, revlog, set(revlog))

    def _getheads(self):
        return [r for r in self._revlog.headrevs() if r != nullrev]

    def parents(self, ix):
        rlog = self._revlog
        idx = rlog.index
        revdata = idx[ix]
        prev = revdata[5]
        if prev != nullrev:
            prev2 = revdata[6]
            if prev2 == nullrev:
                return [prev]
            return [prev, prev2]
        prev2 = revdata[6]
        if prev2 != nullrev:
            return [prev2]
        return []

    def inverse(self):
        if self._inverse is None:
            self._inverse = inverserevlogdag(self)
        return self._inverse

    def ancestorset(self, starts, stops=None):
        rlog = self._revlog
        idx = rlog.index
        if stops:
            stops = set(stops)
        else:
            stops = set()
        seen = set()
        pending = list(starts)
        while pending:
            rev = pending.pop()
            if rev not in seen and rev not in stops:
                seen.add(rev)
                revdata = idx[rev]
                for i in [5, 6]:
                    prev = revdata[i]
                    if prev != nullrev:
                        pending.append(prev)
        return seen

    def headsetofconnecteds(self, ixs):
        if not ixs:
            return set()
        rlog = self._revlog
        idx = rlog.index
        headrevs = set(ixs)
        for rev in ixs:
            revdata = idx[rev]
            for i in [5, 6]:
                prev = revdata[i]
                if prev != nullrev:
                    headrevs.discard(prev)
        assert headrevs
        return headrevs

    def linearize(self, ixs):
        '''linearize and topologically sort a list of revisions

        The linearization process tries to create long runs of revs where
        a child rev comes immediately after its first parent. This is done by
        visiting the heads of the given revs in inverse topological order,
        and for each visited rev, visiting its second parent, then its first
        parent, then adding the rev itself to the output list.
        '''
        sorted = []
        visit = list(self.headsetofconnecteds(ixs))
        visit.sort(reverse=True)
        finished = set()

        while visit:
            cur = visit.pop()
            if cur < 0:
                cur = -cur - 1
                if cur not in finished:
                    sorted.append(cur)
                    finished.add(cur)
            else:
                visit.append(-cur - 1)
                visit += [p for p in self.parents(cur)
                          if p in ixs and p not in finished]
        assert len(sorted) == len(ixs)
        return sorted


class inverserevlogdag(revlogbaseddag, genericdag):
    '''inverse of an existing revlog dag; see revlogdag.inverse()'''

    def __init__(self, orig):
        revlogbaseddag.__init__(self, orig._revlog, orig._nodeset)
        self._orig = orig
        self._children = {}
        self._roots = []
        self._walkfrom = len(self._revlog) - 1

    def _walkto(self, walkto):
        rev = self._walkfrom
        cs = self._children
        roots = self._roots
        idx = self._revlog.index
        while rev >= walkto:
            data = idx[rev]
            isroot = True
            for prev in [data[5], data[6]]: # parent revs
                if prev != nullrev:
                    cs.setdefault(prev, []).append(rev)
                    isroot = False
            if isroot:
                roots.append(rev)
            rev -= 1
        self._walkfrom = rev

    def _getheads(self):
        self._walkto(nullrev)
        return self._roots

    def parents(self, ix):
        if ix is None:
            return []
        if ix <= self._walkfrom:
            self._walkto(ix)
        return self._children.get(ix, [])

    def inverse(self):
        return self._orig