##// END OF EJS Templates
named branches: server branchmap wire protocol support (issue736)...
named branches: server branchmap wire protocol support (issue736) The repository command, 'branchmap', returns a dictionary, branchname -> [branchheads], and will be implemented for localrepo, httprepo and sshrepo. The following wire format is used for returning data: branchname1 branch1head2 branch1head2 ... branchname2 ... ... Branch names are URL encoded to escape white space, and branch heads are sent as hex encoded node ids. All branches and all their heads are sent. The background and motivation for this command is the desire for a richer named branch semantics when pushing changesets. The details are explained in the original proposal which is included below. 1. BACKGROUND The algorithm currently implemented in Mercurial only considers the graph theoretical heads when determining whether new heads are created, rather than using the branch heads as a count (the algorithm considers a branch head effectively closed when it is merged into another branch or a new named branch is started from that point onward). Our particular problem with the algorithm is that we'd like to see the following case working without forcing a push: Upsteam has: (0:dev) ---- (1:dev) \ `--- (2:stable) Someone merges stable into dev: (0:dev) ---- (1:dev) ------(3:dev) \ / `--- (2:stable) --------´ This can be pushed without --force (as it should). Now someone else does some coding on stable (a bug fix, say): (0:dev) ---- (1:dev) ------(3:dev) \ / `--- (2:stable) ---------´---------(4:stable) This time we need --force to push. We allow this to be pushed without using --force by getting all the remote branch heads (by extending the wire protocol with a new function). We would, furthermore, also prefer if it is impossible to push a new branch without --force (or a later --newbranch option so --force isn't shoe-horned into too many disparate functions, if need be), except of course in the case where the remote repository is empty. This is what our patches accomplish. 2. ALTERNATIVES We have, of course, considered some alternatives to reconstructing enough information to decide whether we are creating new remote branch heads, before we added the new wire protocol command. 2.1. LOOKUP ON REMOTE The main alternative is to use the information from remote.heads() and remote.lookup() to try to reconstruct enough graph information to decide whether we are creating new heads. This is not adequate as illustrated below. Remember that each lookup is typically a request-response pair over SSH or HTTP(S). If we have a simple repository at the remote end like this: (0:dev) ---- (1:dev) ---- (3:stable) \ `--- (2:dev) then remote.heads() will yield [2, 3]. Assume we have nodes [0, 1, 2] locally and want to create a new node, 4:dev, as a descendant from (1:dev), which should be OK as 1:dev is a branch head. If we do remote.lookup('dev') we will get [2]. Thus, we can get information about whether a branch exists on the remote server or not, but this does not solve our problem of figuring out whether we are creating new heads or not. Pushing 4:dev ought to be OK, since after the push, we still only have two heads on branch a. Using remote.lookup() and remote.heads() is thus not adequate to consistently decide whether we are creating new remote heads (e.g. in this situation the latter would never return 1:dev). 2.2. USING INCOMING TO RECONSTRUCT THE GRAPH An alternative would be to use information equivalent to hg incoming to get the full remote graph in addition to the local graph. To do this, we would have to get a changegroup(subset) bundle representing the remote end (which may be a substantial amount of data), getting the branch heads from an instantiated bundlerepository, deleting the bundle, and finally, we can compute the prepush logic. While this is backwards compatible, it will cause a possibly substantial slowdown of the push command as it first needs to pull in all changes. 3. FURTHER ARGUMENTS IN FAVOUR OF THE BRANCHMAP WIRE-PROTOCOL EXTENSION Currently, the commands incoming and pull, work based on the tip of a given branch if used with "-r branchname", making it hard to get all revisions of a certain branch only (if it has multiple heads). This can be solved by requesting the remote's branchheads and letting the revisions to be used with the command be these heads. This can be done by extending the commands with a new option, e.g.: hg pull -b branchname which will be turned into the equivalent of: hg pull -r branchhead1 -r branchhead2 -r branchhead3 We have a simple follow-up patch that can do this ready as well (although not submitted yet as it is pending the acceptance of the branch patch). 4. WRAP-UP We generally find that the branchmap wire protocol extension can provide better named branch support to Mercurial. Currently, some things, like the initial push scenario in this mail, are fairly counter-intuitive, and the more often you have to force push, the more it is likely you will get a lot of spurious and unnecessary merge nodes. Also, restricting incoming and pull to all changes on a branch rather than changes on the tip-most head would be a sensible extension to making named branches a first class citizen in Mercurial. Currently, named branches sometimes feel like a late-coming unwanted step-child. We have run it in a production environment for a while, with fewer multiple heads occurring in our repositories and fewer confused users as a result. Also, it fixes the long-standing issue 736. Co-contributor: Sune Foldager <cryo@cyanite.org>

File last commit:

r8312:b87a50b7 default
r8562:e3495c39 default
Show More
httprepo.py
245 lines | 8.7 KiB | text/x-python | PythonLexer
# httprepo.py - HTTP repository proxy classes for mercurial
#
# Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
# Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
from node import bin, hex, nullid
from i18n import _
import repo, changegroup, statichttprepo, error, url, util
import os, urllib, urllib2, urlparse, zlib, httplib
import errno, socket
def zgenerator(f):
zd = zlib.decompressobj()
try:
for chunk in util.filechunkiter(f):
yield zd.decompress(chunk)
except httplib.HTTPException:
raise IOError(None, _('connection ended unexpectedly'))
yield zd.flush()
class httprepository(repo.repository):
def __init__(self, ui, path):
self.path = path
self.caps = None
self.handler = None
scheme, netloc, urlpath, query, frag = urlparse.urlsplit(path)
if query or frag:
raise util.Abort(_('unsupported URL component: "%s"') %
(query or frag))
# urllib cannot handle URLs with embedded user or passwd
self._url, authinfo = url.getauthinfo(path)
self.ui = ui
self.ui.debug(_('using %s\n') % self._url)
self.urlopener = url.opener(ui, authinfo)
def __del__(self):
for h in self.urlopener.handlers:
h.close()
if hasattr(h, "close_all"):
h.close_all()
def url(self):
return self.path
# look up capabilities only when needed
def get_caps(self):
if self.caps is None:
try:
self.caps = set(self.do_read('capabilities').split())
except error.RepoError:
self.caps = set()
self.ui.debug(_('capabilities: %s\n') %
(' '.join(self.caps or ['none'])))
return self.caps
capabilities = property(get_caps)
def lock(self):
raise util.Abort(_('operation not supported over http'))
def do_cmd(self, cmd, **args):
data = args.pop('data', None)
headers = args.pop('headers', {})
self.ui.debug(_("sending %s command\n") % cmd)
q = {"cmd": cmd}
q.update(args)
qs = '?%s' % urllib.urlencode(q)
cu = "%s%s" % (self._url, qs)
try:
if data:
self.ui.debug(_("sending %s bytes\n") % len(data))
resp = self.urlopener.open(urllib2.Request(cu, data, headers))
except urllib2.HTTPError, inst:
if inst.code == 401:
raise util.Abort(_('authorization failed'))
raise
except httplib.HTTPException, inst:
self.ui.debug(_('http error while sending %s command\n') % cmd)
self.ui.traceback()
raise IOError(None, inst)
except IndexError:
# this only happens with Python 2.3, later versions raise URLError
raise util.Abort(_('http error, possibly caused by proxy setting'))
# record the url we got redirected to
resp_url = resp.geturl()
if resp_url.endswith(qs):
resp_url = resp_url[:-len(qs)]
if self._url != resp_url:
self.ui.status(_('real URL is %s\n') % resp_url)
self._url = resp_url
try:
proto = resp.getheader('content-type')
except AttributeError:
proto = resp.headers['content-type']
safeurl = url.hidepassword(self._url)
# accept old "text/plain" and "application/hg-changegroup" for now
if not (proto.startswith('application/mercurial-') or
proto.startswith('text/plain') or
proto.startswith('application/hg-changegroup')):
self.ui.debug(_("requested URL: '%s'\n") % url.hidepassword(cu))
raise error.RepoError(_("'%s' does not appear to be an hg repository")
% safeurl)
if proto.startswith('application/mercurial-'):
try:
version = proto.split('-', 1)[1]
version_info = tuple([int(n) for n in version.split('.')])
except ValueError:
raise error.RepoError(_("'%s' sent a broken Content-Type "
"header (%s)") % (safeurl, proto))
if version_info > (0, 1):
raise error.RepoError(_("'%s' uses newer protocol %s") %
(safeurl, version))
return resp
def do_read(self, cmd, **args):
fp = self.do_cmd(cmd, **args)
try:
return fp.read()
finally:
# if using keepalive, allow connection to be reused
fp.close()
def lookup(self, key):
self.requirecap('lookup', _('look up remote revision'))
d = self.do_cmd("lookup", key = key).read()
success, data = d[:-1].split(' ', 1)
if int(success):
return bin(data)
raise error.RepoError(data)
def heads(self):
d = self.do_read("heads")
try:
return map(bin, d[:-1].split(" "))
except:
raise error.ResponseError(_("unexpected response:"), d)
def branches(self, nodes):
n = " ".join(map(hex, nodes))
d = self.do_read("branches", nodes=n)
try:
br = [ tuple(map(bin, b.split(" "))) for b in d.splitlines() ]
return br
except:
raise error.ResponseError(_("unexpected response:"), d)
def between(self, pairs):
batch = 8 # avoid giant requests
r = []
for i in xrange(0, len(pairs), batch):
n = " ".join(["-".join(map(hex, p)) for p in pairs[i:i + batch]])
d = self.do_read("between", pairs=n)
try:
r += [ l and map(bin, l.split(" ")) or [] for l in d.splitlines() ]
except:
raise error.ResponseError(_("unexpected response:"), d)
return r
def changegroup(self, nodes, kind):
n = " ".join(map(hex, nodes))
f = self.do_cmd("changegroup", roots=n)
return util.chunkbuffer(zgenerator(f))
def changegroupsubset(self, bases, heads, source):
self.requirecap('changegroupsubset', _('look up remote changes'))
baselst = " ".join([hex(n) for n in bases])
headlst = " ".join([hex(n) for n in heads])
f = self.do_cmd("changegroupsubset", bases=baselst, heads=headlst)
return util.chunkbuffer(zgenerator(f))
def unbundle(self, cg, heads, source):
# have to stream bundle to a temp file because we do not have
# http 1.1 chunked transfer.
type = ""
types = self.capable('unbundle')
# servers older than d1b16a746db6 will send 'unbundle' as a
# boolean capability
try:
types = types.split(',')
except AttributeError:
types = [""]
if types:
for x in types:
if x in changegroup.bundletypes:
type = x
break
tempname = changegroup.writebundle(cg, None, type)
fp = url.httpsendfile(tempname, "rb")
try:
try:
resp = self.do_read(
'unbundle', data=fp,
headers={'Content-Type': 'application/octet-stream'},
heads=' '.join(map(hex, heads)))
resp_code, output = resp.split('\n', 1)
try:
ret = int(resp_code)
except ValueError, err:
raise error.ResponseError(
_('push failed (unexpected response):'), resp)
self.ui.write(output)
return ret
except socket.error, err:
if err[0] in (errno.ECONNRESET, errno.EPIPE):
raise util.Abort(_('push failed: %s') % err[1])
raise util.Abort(err[1])
finally:
fp.close()
os.unlink(tempname)
def stream_out(self):
return self.do_cmd('stream_out')
class httpsrepository(httprepository):
def __init__(self, ui, path):
if not url.has_https:
raise util.Abort(_('Python support for SSL and HTTPS '
'is not installed'))
httprepository.__init__(self, ui, path)
def instance(ui, path, create):
if create:
raise util.Abort(_('cannot create new http repository'))
try:
if path.startswith('https:'):
inst = httpsrepository(ui, path)
else:
inst = httprepository(ui, path)
inst.between([(nullid, nullid)])
return inst
except error.RepoError:
ui.note('(falling back to static-http)\n')
return statichttprepo.instance(ui, "static-" + path, create)