Mercurial > hg
view mercurial/url.py @ 42044:bb271ec2fbfb
compression: introduce a `storage.revlog.zstd.level` configuration
This option control the zstd compression level used when compressing revlog
chunk. The usage of zstd for revlog compression has not graduated from
experimental yet, but we intend to fix that soon.
The option name for the compression level is more straight forward to pick, so
this changesets comes first. Having a dedicated option for each compression
engine is useful because they don't support the same range of values.
I ran the same measurement as for the zlib compression level (in the parent
changesets). The variation in repository size is stay mostly in the same (small)
range. The "read/write" performance see smallish variation, but are overall much
better than zlib. Write performance show the same tend of having better write
performance for when reaching high-end compression.
Again, we don't intend to change the default zstd compression level (currently:
3) in this series. However this is worth investigating in the future.
The Performance comparison of zlib vs zstd is quite impressive. The repository
size stay in the same range, but the performance are much better in all
situations.
Comparison summary
==================
We are looking at:
- performance range for zlib
- performance range for zstd
- comparison of default zstd (level-3) to default zlib (level 6)
- comparison of the slowest zstd time to the fastest zlib time
Read performance:
-----------------
| zlib | zstd | cmp | f2s
mercurial | 0.170159 - 0.189219 | 0.144127 - 0.149624 | 80% | 88%
pypy | 2.679217 - 2.768691 | 1.532317 - 1.705044 | 60% | 63%
netbeans | 122.477027 - 141.620281 | 72.996346 - 89.731560 | 58% | 73%
mozilla | 147.867662 - 170.572118 | 91.700995 - 105.853099 | 56% | 71%
Write performance:
------------------
| zlib | zstd | cmp | f2s
mercurial | 53.250304 - 56.2936129 | 40.877025 - 45.677286 | 75% | 86%
pypy | 460.721984 - 476.589918 | 270.545409 - 301.002219 | 63% | 65%
netbeans | 520.560316 - 715.930400 | 370.356311 - 428.329652 | 55% | 82%
mozilla | 739.803002 - 987.056093 | 505.152906 - 591.930683 | 57% | 80%
Raw data
--------
repo alg lvl .hg/store size 00manifest.d read write
mercurial zlib 1 49,402,813 5,963,475 0.170159 53.250304
mercurial zlib 6 47,197,397 5,875,730 0.182820 56.264320
mercurial zlib 9 47,121,596 5,849,781 0.189219 56.293612
mercurial zstd 1 49,737,084 5,966,355 0.144127 40.877025
mercurial zstd 3 48,961,867 5,895,208 0.146376 42.268142
mercurial zstd 5 48,200,592 5,938,676 0.149624 43.162875
mercurial zstd 10 47,833,520 5,913,353 0.145185 44.012489
mercurial zstd 15 47,314,604 5,728,679 0.147686 45.677286
mercurial zstd 20 47,330,502 5,830,539 0.145789 45.025407
mercurial zstd 22 47,330,076 5,830,539 0.143996 44.690460
pypy zlib 1 370,830,572 28,462,425 2.679217 460.721984
pypy zlib 6 340,112,317 27,648,747 2.768691 467.537158
pypy zlib 9 338,360,736 27,639,003 2.763495 476.589918
pypy zstd 1 362,377,479 27,916,214 1.532317 270.545409
pypy zstd 3 354,137,693 27,905,988 1.686718 294.951509
pypy zstd 5 342,640,043 27,655,774 1.705044 301.002219
pypy zstd 10 334,224,327 27,164,493 1.567287 285.186239
pypy zstd 15 329,000,363 26,645,965 1.637729 299.561332
pypy zstd 20 324,534,039 26,199,547 1.526813 302.149827
pypy zstd 22 324,530,595 26,198,932 1.525718 307.821218
netbeans zlib 1 1,281,847,810 165,495,457 122.477027 520.560316
netbeans zlib 6 1,205,284,353 159,161,207 139.876147 715.930400
netbeans zlib 9 1,197,135,671 155,034,586 141.620281 678.297064
netbeans zstd 1 1,259,581,737 160,840,613 72.996346 370.356311
netbeans zstd 3 1,232,978,122 157,691,551 81.622317 396.733087
netbeans zstd 5 1,208,034,075 160,246,880 83.080549 364.342626
netbeans zstd 10 1,188,624,176 156,083,417 79.323935 403.594602
netbeans zstd 15 1,176,973,589 153,859,477 89.731560 428.329652
netbeans zstd 20 1,162,958,258 151,147,535 82.842667 392.335349
netbeans zstd 22 1,162,707,029 151,150,220 82.565695 402.840655
mozilla zlib 1 2,775,497,186 298,527,987 147.867662 751.263721
mozilla zlib 6 2,596,856,420 286,597,671 170.572118 987.056093
mozilla zlib 9 2,587,542,494 287,018,264 163.622338 739.803002
mozilla zstd 1 2,723,159,348 286,617,532 91.700995 570.042751
mozilla zstd 3 2,665,055,001 286,152,013 95.240155 561.412805
mozilla zstd 5 2,607,819,817 288,060,030 101.978048 505.152906
mozilla zstd 10 2,558,761,085 283,967,648 104.113481 497.771202
mozilla zstd 15 2,526,216,060 275,581,300 105.853099 591.930683
mozilla zstd 20 2,485,114,806 266,478,859 95.268795 576.515389
mozilla zstd 22 2,484,869,080 266,456,505 94.429282 572.785537
author | Pierre-Yves David <pierre-yves.david@octobus.net> |
---|---|
date | Wed, 27 Mar 2019 18:35:59 +0100 |
parents | 544035846830 |
children | 2a3c0106ded9 |
line wrap: on
line source
# url.py - HTTP handling for mercurial # # Copyright 2005, 2006, 2007, 2008 Matt Mackall <mpm@selenic.com> # Copyright 2006, 2007 Alexis S. L. Carvalho <alexis@cecm.usp.br> # 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 or any later version. from __future__ import absolute_import import base64 import os import socket import sys from .i18n import _ from . import ( encoding, error, httpconnection as httpconnectionmod, keepalive, pycompat, sslutil, urllibcompat, util, ) from .utils import ( stringutil, ) httplib = util.httplib stringio = util.stringio urlerr = util.urlerr urlreq = util.urlreq def escape(s, quote=None): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. This is the same as cgi.escape in Python, but always operates on bytes, whereas cgi.escape in Python 3 only works on unicodes. ''' s = s.replace(b"&", b"&") s = s.replace(b"<", b"<") s = s.replace(b">", b">") if quote: s = s.replace(b'"', b""") return s class passwordmgr(object): def __init__(self, ui, passwddb): self.ui = ui self.passwddb = passwddb def add_password(self, realm, uri, user, passwd): return self.passwddb.add_password(realm, uri, user, passwd) def find_user_password(self, realm, authuri): assert isinstance(realm, (type(None), str)) assert isinstance(authuri, str) authinfo = self.passwddb.find_user_password(realm, authuri) user, passwd = authinfo user, passwd = pycompat.bytesurl(user), pycompat.bytesurl(passwd) if user and passwd: self._writedebug(user, passwd) return (pycompat.strurl(user), pycompat.strurl(passwd)) if not user or not passwd: res = httpconnectionmod.readauthforuri(self.ui, authuri, user) if res: group, auth = res user, passwd = auth.get('username'), auth.get('password') self.ui.debug("using auth.%s.* for authentication\n" % group) if not user or not passwd: u = util.url(pycompat.bytesurl(authuri)) u.query = None if not self.ui.interactive(): raise error.Abort(_('http authorization required for %s') % util.hidepassword(bytes(u))) self.ui.write(_("http authorization required for %s\n") % util.hidepassword(bytes(u))) self.ui.write(_("realm: %s\n") % pycompat.bytesurl(realm)) if user: self.ui.write(_("user: %s\n") % user) else: user = self.ui.prompt(_("user:"), default=None) if not passwd: passwd = self.ui.getpass() self.passwddb.add_password(realm, authuri, user, passwd) self._writedebug(user, passwd) return (pycompat.strurl(user), pycompat.strurl(passwd)) def _writedebug(self, user, passwd): msg = _('http auth: user %s, password %s\n') self.ui.debug(msg % (user, passwd and '*' * len(passwd) or 'not set')) def find_stored_password(self, authuri): return self.passwddb.find_user_password(None, authuri) class proxyhandler(urlreq.proxyhandler): def __init__(self, ui): proxyurl = (ui.config("http_proxy", "host") or encoding.environ.get('http_proxy')) # XXX proxyauthinfo = None if proxyurl: # proxy can be proper url or host[:port] if not (proxyurl.startswith('http:') or proxyurl.startswith('https:')): proxyurl = 'http://' + proxyurl + '/' proxy = util.url(proxyurl) if not proxy.user: proxy.user = ui.config("http_proxy", "user") proxy.passwd = ui.config("http_proxy", "passwd") # see if we should use a proxy for this url no_list = ["localhost", "127.0.0.1"] no_list.extend([p.lower() for p in ui.configlist("http_proxy", "no")]) no_list.extend([p.strip().lower() for p in encoding.environ.get("no_proxy", '').split(',') if p.strip()]) # "http_proxy.always" config is for running tests on localhost if ui.configbool("http_proxy", "always"): self.no_list = [] else: self.no_list = no_list # Keys and values need to be str because the standard library # expects them to be. proxyurl = str(proxy) proxies = {r'http': proxyurl, r'https': proxyurl} ui.debug('proxying through %s\n' % util.hidepassword(bytes(proxy))) else: proxies = {} urlreq.proxyhandler.__init__(self, proxies) self.ui = ui def proxy_open(self, req, proxy, type_): host = pycompat.bytesurl(urllibcompat.gethost(req)).split(':')[0] for e in self.no_list: if host == e: return None if e.startswith('*.') and host.endswith(e[2:]): return None if e.startswith('.') and host.endswith(e[1:]): return None return urlreq.proxyhandler.proxy_open(self, req, proxy, type_) def _gen_sendfile(orgsend): def _sendfile(self, data): # send a file if isinstance(data, httpconnectionmod.httpsendfile): # if auth required, some data sent twice, so rewind here data.seek(0) for chunk in util.filechunkiter(data): orgsend(self, chunk) else: orgsend(self, data) return _sendfile has_https = util.safehasattr(urlreq, 'httpshandler') class httpconnection(keepalive.HTTPConnection): # must be able to send big bundle as stream. send = _gen_sendfile(keepalive.HTTPConnection.send) def getresponse(self): proxyres = getattr(self, 'proxyres', None) if proxyres: if proxyres.will_close: self.close() self.proxyres = None return proxyres return keepalive.HTTPConnection.getresponse(self) # Large parts of this function have their origin from before Python 2.6 # and could potentially be removed. def _generic_start_transaction(handler, h, req): tunnel_host = req._tunnel_host if tunnel_host: if tunnel_host[:7] not in [r'http://', r'https:/']: tunnel_host = r'https://' + tunnel_host new_tunnel = True else: tunnel_host = urllibcompat.getselector(req) new_tunnel = False if new_tunnel or tunnel_host == urllibcompat.getfullurl(req): # has proxy u = util.url(pycompat.bytesurl(tunnel_host)) if new_tunnel or u.scheme == 'https': # only use CONNECT for HTTPS h.realhostport = ':'.join([u.host, (u.port or '443')]) h.headers = req.headers.copy() h.headers.update(handler.parent.addheaders) return h.realhostport = None h.headers = None def _generic_proxytunnel(self): proxyheaders = dict( [(x, self.headers[x]) for x in self.headers if x.lower().startswith(r'proxy-')]) self.send('CONNECT %s HTTP/1.0\r\n' % self.realhostport) for header in proxyheaders.iteritems(): self.send('%s: %s\r\n' % header) self.send('\r\n') # majority of the following code is duplicated from # httplib.HTTPConnection as there are no adequate places to # override functions to provide the needed functionality # strict was removed in Python 3.4. kwargs = {} if not pycompat.ispy3: kwargs['strict'] = self.strict res = self.response_class(self.sock, method=self._method, **kwargs) while True: version, status, reason = res._read_status() if status != httplib.CONTINUE: break # skip lines that are all whitespace list(iter(lambda: res.fp.readline().strip(), '')) res.status = status res.reason = reason.strip() if res.status == 200: # skip lines until we find a blank line list(iter(res.fp.readline, '\r\n')) return True if version == 'HTTP/1.0': res.version = 10 elif version.startswith('HTTP/1.'): res.version = 11 elif version == 'HTTP/0.9': res.version = 9 else: raise httplib.UnknownProtocol(version) if res.version == 9: res.length = None res.chunked = 0 res.will_close = 1 res.msg = httplib.HTTPMessage(stringio()) return False res.msg = httplib.HTTPMessage(res.fp) res.msg.fp = None # are we using the chunked-style of transfer encoding? trenc = res.msg.getheader('transfer-encoding') if trenc and trenc.lower() == "chunked": res.chunked = 1 res.chunk_left = None else: res.chunked = 0 # will the connection close at the end of the response? res.will_close = res._check_close() # do we have a Content-Length? # NOTE: RFC 2616, section 4.4, #3 says we ignore this if # transfer-encoding is "chunked" length = res.msg.getheader('content-length') if length and not res.chunked: try: res.length = int(length) except ValueError: res.length = None else: if res.length < 0: # ignore nonsensical negative lengths res.length = None else: res.length = None # does the body have a fixed length? (of zero) if (status == httplib.NO_CONTENT or status == httplib.NOT_MODIFIED or 100 <= status < 200 or # 1xx codes res._method == 'HEAD'): res.length = 0 # if the connection remains open, and we aren't using chunked, and # a content-length was not provided, then assume that the connection # WILL close. if (not res.will_close and not res.chunked and res.length is None): res.will_close = 1 self.proxyres = res return False class httphandler(keepalive.HTTPHandler): def http_open(self, req): return self.do_open(httpconnection, req) def _start_transaction(self, h, req): _generic_start_transaction(self, h, req) return keepalive.HTTPHandler._start_transaction(self, h, req) class logginghttpconnection(keepalive.HTTPConnection): def __init__(self, createconn, *args, **kwargs): keepalive.HTTPConnection.__init__(self, *args, **kwargs) self._create_connection = createconn if sys.version_info < (2, 7, 7): # copied from 2.7.14, since old implementations directly call # socket.create_connection() def connect(self): self.sock = self._create_connection((self.host, self.port), self.timeout, self.source_address) if self._tunnel_host: self._tunnel() class logginghttphandler(httphandler): """HTTP handler that logs socket I/O.""" def __init__(self, logfh, name, observeropts, timeout=None): super(logginghttphandler, self).__init__(timeout=timeout) self._logfh = logfh self._logname = name self._observeropts = observeropts # do_open() calls the passed class to instantiate an HTTPConnection. We # pass in a callable method that creates a custom HTTPConnection instance # whose callback to create the socket knows how to proxy the socket. def http_open(self, req): return self.do_open(self._makeconnection, req) def _makeconnection(self, *args, **kwargs): def createconnection(*args, **kwargs): sock = socket.create_connection(*args, **kwargs) return util.makeloggingsocket(self._logfh, sock, self._logname, **self._observeropts) return logginghttpconnection(createconnection, *args, **kwargs) if has_https: class httpsconnection(keepalive.HTTPConnection): response_class = keepalive.HTTPResponse default_port = httplib.HTTPS_PORT # must be able to send big bundle as stream. send = _gen_sendfile(keepalive.safesend) getresponse = keepalive.wrapgetresponse(httplib.HTTPConnection) def __init__(self, host, port=None, key_file=None, cert_file=None, *args, **kwargs): keepalive.HTTPConnection.__init__(self, host, port, *args, **kwargs) self.key_file = key_file self.cert_file = cert_file def connect(self): self.sock = socket.create_connection((self.host, self.port)) host = self.host if self.realhostport: # use CONNECT proxy _generic_proxytunnel(self) host = self.realhostport.rsplit(':', 1)[0] self.sock = sslutil.wrapsocket( self.sock, self.key_file, self.cert_file, ui=self.ui, serverhostname=host) sslutil.validatesocket(self.sock) class httpshandler(keepalive.KeepAliveHandler, urlreq.httpshandler): def __init__(self, ui, timeout=None): keepalive.KeepAliveHandler.__init__(self, timeout=timeout) urlreq.httpshandler.__init__(self) self.ui = ui self.pwmgr = passwordmgr(self.ui, self.ui.httppasswordmgrdb) def _start_transaction(self, h, req): _generic_start_transaction(self, h, req) return keepalive.KeepAliveHandler._start_transaction(self, h, req) def https_open(self, req): # urllibcompat.getfullurl() does not contain credentials # and we may need them to match the certificates. url = urllibcompat.getfullurl(req) user, password = self.pwmgr.find_stored_password(url) res = httpconnectionmod.readauthforuri(self.ui, url, user) if res: group, auth = res self.auth = auth self.ui.debug("using auth.%s.* for authentication\n" % group) else: self.auth = None return self.do_open(self._makeconnection, req) def _makeconnection(self, host, port=None, *args, **kwargs): keyfile = None certfile = None if len(args) >= 1: # key_file keyfile = args[0] if len(args) >= 2: # cert_file certfile = args[1] args = args[2:] # if the user has specified different key/cert files in # hgrc, we prefer these if self.auth and 'key' in self.auth and 'cert' in self.auth: keyfile = self.auth['key'] certfile = self.auth['cert'] conn = httpsconnection(host, port, keyfile, certfile, *args, **kwargs) conn.ui = self.ui return conn class httpdigestauthhandler(urlreq.httpdigestauthhandler): def __init__(self, *args, **kwargs): urlreq.httpdigestauthhandler.__init__(self, *args, **kwargs) self.retried_req = None def reset_retry_count(self): # Python 2.6.5 will call this on 401 or 407 errors and thus loop # forever. We disable reset_retry_count completely and reset in # http_error_auth_reqed instead. pass def http_error_auth_reqed(self, auth_header, host, req, headers): # Reset the retry counter once for each request. if req is not self.retried_req: self.retried_req = req self.retried = 0 return urlreq.httpdigestauthhandler.http_error_auth_reqed( self, auth_header, host, req, headers) class httpbasicauthhandler(urlreq.httpbasicauthhandler): def __init__(self, *args, **kwargs): self.auth = None urlreq.httpbasicauthhandler.__init__(self, *args, **kwargs) self.retried_req = None def http_request(self, request): if self.auth: request.add_unredirected_header(self.auth_header, self.auth) return request def https_request(self, request): if self.auth: request.add_unredirected_header(self.auth_header, self.auth) return request def reset_retry_count(self): # Python 2.6.5 will call this on 401 or 407 errors and thus loop # forever. We disable reset_retry_count completely and reset in # http_error_auth_reqed instead. pass def http_error_auth_reqed(self, auth_header, host, req, headers): # Reset the retry counter once for each request. if req is not self.retried_req: self.retried_req = req self.retried = 0 return urlreq.httpbasicauthhandler.http_error_auth_reqed( self, auth_header, host, req, headers) def retry_http_basic_auth(self, host, req, realm): user, pw = self.passwd.find_user_password( realm, urllibcompat.getfullurl(req)) if pw is not None: raw = "%s:%s" % (pycompat.bytesurl(user), pycompat.bytesurl(pw)) auth = r'Basic %s' % pycompat.strurl(base64.b64encode(raw).strip()) if req.get_header(self.auth_header, None) == auth: return None self.auth = auth req.add_unredirected_header(self.auth_header, auth) return self.parent.open(req) else: return None class cookiehandler(urlreq.basehandler): def __init__(self, ui): self.cookiejar = None cookiefile = ui.config('auth', 'cookiefile') if not cookiefile: return cookiefile = util.expandpath(cookiefile) try: cookiejar = util.cookielib.MozillaCookieJar( pycompat.fsdecode(cookiefile)) cookiejar.load() self.cookiejar = cookiejar except util.cookielib.LoadError as e: ui.warn(_('(error loading cookie file %s: %s; continuing without ' 'cookies)\n') % (cookiefile, stringutil.forcebytestr(e))) def http_request(self, request): if self.cookiejar: self.cookiejar.add_cookie_header(request) return request def https_request(self, request): if self.cookiejar: self.cookiejar.add_cookie_header(request) return request handlerfuncs = [] def opener(ui, authinfo=None, useragent=None, loggingfh=None, loggingname=b's', loggingopts=None, sendaccept=True): ''' construct an opener suitable for urllib2 authinfo will be added to the password manager The opener can be configured to log socket events if the various ``logging*`` arguments are specified. ``loggingfh`` denotes a file object to log events to. ``loggingname`` denotes the name of the to print when logging. ``loggingopts`` is a dict of keyword arguments to pass to the constructed ``util.socketobserver`` instance. ``sendaccept`` allows controlling whether the ``Accept`` request header is sent. The header is sent by default. ''' timeout = ui.configwith(float, 'http', 'timeout') handlers = [] if loggingfh: handlers.append(logginghttphandler(loggingfh, loggingname, loggingopts or {}, timeout=timeout)) # We don't yet support HTTPS when logging I/O. If we attempt to open # an HTTPS URL, we'll likely fail due to unknown protocol. else: handlers.append(httphandler(timeout=timeout)) if has_https: handlers.append(httpshandler(ui, timeout=timeout)) handlers.append(proxyhandler(ui)) passmgr = passwordmgr(ui, ui.httppasswordmgrdb) if authinfo is not None: realm, uris, user, passwd = authinfo saveduser, savedpass = passmgr.find_stored_password(uris[0]) if user != saveduser or passwd: passmgr.add_password(realm, uris, user, passwd) ui.debug('http auth: user %s, password %s\n' % (user, passwd and '*' * len(passwd) or 'not set')) handlers.extend((httpbasicauthhandler(passmgr), httpdigestauthhandler(passmgr))) handlers.extend([h(ui, passmgr) for h in handlerfuncs]) handlers.append(cookiehandler(ui)) opener = urlreq.buildopener(*handlers) # keepalive.py's handlers will populate these attributes if they exist. opener.requestscount = 0 opener.sentbytescount = 0 opener.receivedbytescount = 0 # The user agent should should *NOT* be used by servers for e.g. # protocol detection or feature negotiation: there are other # facilities for that. # # "mercurial/proto-1.0" was the original user agent string and # exists for backwards compatibility reasons. # # The "(Mercurial %s)" string contains the distribution # name and version. Other client implementations should choose their # own distribution name. Since servers should not be using the user # agent string for anything, clients should be able to define whatever # user agent they deem appropriate. # # The custom user agent is for lfs, because unfortunately some servers # do look at this value. if not useragent: agent = 'mercurial/proto-1.0 (Mercurial %s)' % util.version() opener.addheaders = [(r'User-agent', pycompat.sysstr(agent))] else: opener.addheaders = [(r'User-agent', pycompat.sysstr(useragent))] # This header should only be needed by wire protocol requests. But it has # been sent on all requests since forever. We keep sending it for backwards # compatibility reasons. Modern versions of the wire protocol use # X-HgProto-<N> for advertising client support. if sendaccept: opener.addheaders.append((r'Accept', r'application/mercurial-0.1')) return opener def open(ui, url_, data=None): u = util.url(url_) if u.scheme: u.scheme = u.scheme.lower() url_, authinfo = u.authinfo() else: path = util.normpath(os.path.abspath(url_)) url_ = 'file://' + pycompat.bytesurl(urlreq.pathname2url(path)) authinfo = None return opener(ui, authinfo).open(pycompat.strurl(url_), data) def wrapresponse(resp): """Wrap a response object with common error handlers. This ensures that any I/O from any consumer raises the appropriate error and messaging. """ origread = resp.read class readerproxy(resp.__class__): def read(self, size=None): try: return origread(size) except httplib.IncompleteRead as e: # e.expected is an integer if length known or None otherwise. if e.expected: got = len(e.partial) total = e.expected + got msg = _('HTTP request error (incomplete response; ' 'expected %d bytes got %d)') % (total, got) else: msg = _('HTTP request error (incomplete response)') raise error.PeerTransportError( msg, hint=_('this may be an intermittent network failure; ' 'if the error persists, consider contacting the ' 'network or server operator')) except httplib.HTTPException as e: raise error.PeerTransportError( _('HTTP request error (%s)') % e, hint=_('this may be an intermittent network failure; ' 'if the error persists, consider contacting the ' 'network or server operator')) resp.__class__ = readerproxy