view mercurial/chgserver.py @ 46568:0d840b9d200d

copies-rust: track "overwrites" directly within CopySource Overwrite are "rare enough" that explicitly keeping track of them is going to be "cheap", or at least much cheaper that issuing many `is_ancestor` calls. Even a simple implementation using no specific optimisation (eg: using the generic HashSet type) yield good result in most cases. They are interesting optimization to can do on top of that. We will implement them in later changesets. We tried different approach to speed up the overwrite detection and this one seems the most promising. Without further optimization, we already see sizable speedup on various cases. Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 363753 revs, 5.138169 s, 4.482399 s, -0.655770 s, × 0.8724, 12 µs/rev mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 362229 revs, 5.127809 s, 4.480366 s, -0.647443 s, × 0.8737, 12 µs/rev mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 359344 revs, 4.971136 s, 4.369070 s, -0.602066 s, × 0.8789, 12 µs/rev mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 192665 revs, 1.741678 s, 1.592506 s, -0.149172 s, × 0.9144, 8 µs/rev However, some of the case doing a lot of overwrite get significantly slower. The one with a really problematic slowdown are the special "head reducing" merge in mozilla-try so I am not too worried about them. In addition, further changeset are going to improve the performance of all this. Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 97052 revs, 1.343373 s, 2.119204 s, +0.775831 s, × 1.5775, 21 µs/rev mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 228985 revs, 40.314822 s, 87.824489 s, +47.509667 s, × 2.1785, 383 µs/rev mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 382065 revs, 20.048029 s, 43.304637 s, +23.256608 s, × 2.1600, 113 µs/rev Full benchmark below: Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mercurial x_revs_x_added_0_copies ad6b123de1c7 39cfcef4f463 : 1 revs, 0.000042 s, 0.000043 s, +0.000001 s, × 1.0238, 43 µs/rev mercurial x_revs_x_added_x_copies 2b1c78674230 0c1d10351869 : 6 revs, 0.000110 s, 0.000114 s, +0.000004 s, × 1.0364, 19 µs/rev mercurial x000_revs_x000_added_x_copies 81f8ff2a9bf2 dd3267698d84 : 1032 revs, 0.004945 s, 0.004937 s, -0.000008 s, × 0.9984, 4 µs/rev pypy x_revs_x_added_0_copies aed021ee8ae8 099ed31b181b : 9 revs, 0.000192 s, 0.000339 s, +0.000147 s, × 1.7656, 37 µs/rev pypy x_revs_x000_added_0_copies 4aa4e1f8e19a 359343b9ac0e : 1 revs, 0.000049 s, 0.000049 s, +0.000000 s, × 1.0000, 49 µs/rev pypy x_revs_x_added_x_copies ac52eb7bbbb0 72e022663155 : 7 revs, 0.000112 s, 0.000202 s, +0.000090 s, × 1.8036, 28 µs/rev pypy x_revs_x00_added_x_copies c3b14617fbd7 ace7255d9a26 : 1 revs, 0.000323 s, 0.000409 s, +0.000086 s, × 1.2663, 409 µs/rev pypy x_revs_x000_added_x000_copies df6f7a526b60 a83dc6a2d56f : 6 revs, 0.010042 s, 0.011984 s, +0.001942 s, × 1.1934, 1997 µs/rev pypy x000_revs_xx00_added_0_copies 89a76aede314 2f22446ff07e : 4785 revs, 0.049813 s, 0.050820 s, +0.001007 s, × 1.0202, 10 µs/rev pypy x000_revs_x000_added_x_copies 8a3b5bfd266e 2c68e87c3efe : 6780 revs, 0.079937 s, 0.087953 s, +0.008016 s, × 1.1003, 12 µs/rev pypy x000_revs_x000_added_x000_copies 89a76aede314 7b3dda341c84 : 5441 revs, 0.059412 s, 0.062902 s, +0.003490 s, × 1.0587, 11 µs/rev pypy x0000_revs_x_added_0_copies d1defd0dc478 c9cb1334cc78 : 43645 revs, 0.533769 s, 0.679234 s, +0.145465 s, × 1.2725, 15 µs/rev pypy x0000_revs_xx000_added_0_copies bf2c629d0071 4ffed77c095c : 2 revs, 0.013147 s, 0.013095 s, -0.000052 s, × 0.9960, 6547 µs/rev pypy x0000_revs_xx000_added_x000_copies 08ea3258278e d9fa043f30c0 : 11316 revs, 0.110680 s, 0.120910 s, +0.010230 s, × 1.0924, 10 µs/rev netbeans x_revs_x_added_0_copies fb0955ffcbcd a01e9239f9e7 : 2 revs, 0.000085 s, 0.000087 s, +0.000002 s, × 1.0235, 43 µs/rev netbeans x_revs_x000_added_0_copies 6f360122949f 20eb231cc7d0 : 2 revs, 0.000107 s, 0.000107 s, +0.000000 s, × 1.0000, 53 µs/rev netbeans x_revs_x_added_x_copies 1ada3faf6fb6 5a39d12eecf4 : 3 revs, 0.000175 s, 0.000186 s, +0.000011 s, × 1.0629, 62 µs/rev netbeans x_revs_x00_added_x_copies 35be93ba1e2c 9eec5e90c05f : 9 revs, 0.000720 s, 0.000754 s, +0.000034 s, × 1.0472, 83 µs/rev netbeans x000_revs_xx00_added_0_copies eac3045b4fdd 51d4ae7f1290 : 1421 revs, 0.010019 s, 0.010443 s, +0.000424 s, × 1.0423, 7 µs/rev netbeans x000_revs_x000_added_x_copies e2063d266acd 6081d72689dc : 1533 revs, 0.015602 s, 0.015697 s, +0.000095 s, × 1.0061, 10 µs/rev netbeans x000_revs_x000_added_x000_copies ff453e9fee32 411350406ec2 : 5750 revs, 0.058759 s, 0.063528 s, +0.004769 s, × 1.0812, 11 µs/rev netbeans x0000_revs_xx000_added_x000_copies 588c2d1ced70 1aad62e59ddd : 66949 revs, 0.491550 s, 0.545515 s, +0.053965 s, × 1.1098, 8 µs/rev mozilla-central x_revs_x_added_0_copies 3697f962bb7b 7015fcdd43a2 : 2 revs, 0.000087 s, 0.000089 s, +0.000002 s, × 1.0230, 44 µs/rev mozilla-central x_revs_x000_added_0_copies dd390860c6c9 40d0c5bed75d : 8 revs, 0.000268 s, 0.000265 s, -0.000003 s, × 0.9888, 33 µs/rev mozilla-central x_revs_x_added_x_copies 8d198483ae3b 14207ffc2b2f : 9 revs, 0.000181 s, 0.000381 s, +0.000200 s, × 2.1050, 42 µs/rev mozilla-central x_revs_x00_added_x_copies 98cbc58cc6bc 446a150332c3 : 7 revs, 0.000661 s, 0.000672 s, +0.000011 s, × 1.0166, 96 µs/rev mozilla-central x_revs_x000_added_x000_copies 3c684b4b8f68 0a5e72d1b479 : 3 revs, 0.003256 s, 0.003497 s, +0.000241 s, × 1.0740, 1165 µs/rev mozilla-central x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.066749 s, 0.073204 s, +0.006455 s, × 1.0967, 12200 µs/rev mozilla-central x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.006462 s, 0.006482 s, +0.000020 s, × 1.0031, 4 µs/rev mozilla-central x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.004919 s, 0.005066 s, +0.000147 s, × 1.0299, 123 µs/rev mozilla-central x000_revs_x000_added_x000_copies 7c97034feb78 4407bd0c6330 : 7839 revs, 0.062421 s, 0.065707 s, +0.003286 s, × 1.0526, 8 µs/rev mozilla-central x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.026633 s, 0.026800 s, +0.000167 s, × 1.0063, 43 µs/rev mozilla-central x0000_revs_xx000_added_x000_copies f78c615a656c 96a38b690156 : 30263 revs, 0.197792 s, 0.203856 s, +0.006064 s, × 1.0307, 6 µs/rev mozilla-central x00000_revs_x0000_added_x0000_copies 6832ae71433c 4c222a1d9a00 : 153721 revs, 1.259970 s, 1.293394 s, +0.033424 s, × 1.0265, 8 µs/rev mozilla-central x00000_revs_x00000_added_x000_copies 76caed42cf7c 1daa622bbe42 : 204976 revs, 1.689184 s, 1.698239 s, +0.009055 s, × 1.0054, 8 µs/rev mozilla-try x_revs_x_added_0_copies aaf6dde0deb8 9790f499805a : 2 revs, 0.000865 s, 0.000875 s, +0.000010 s, × 1.0116, 437 µs/rev mozilla-try x_revs_x000_added_0_copies d8d0222927b4 5bb8ce8c7450 : 2 revs, 0.000893 s, 0.000891 s, -0.000002 s, × 0.9978, 445 µs/rev mozilla-try x_revs_x_added_x_copies 092fcca11bdb 936255a0384a : 4 revs, 0.000172 s, 0.000292 s, +0.000120 s, × 1.6977, 73 µs/rev mozilla-try x_revs_x00_added_x_copies b53d2fadbdb5 017afae788ec : 2 revs, 0.001159 s, 0.003939 s, +0.002780 s, × 3.3986, 1969 µs/rev mozilla-try x_revs_x000_added_x000_copies 20408ad61ce5 6f0ee96e21ad : 1 revs, 0.031621 s, 0.033027 s, +0.001406 s, × 1.0445, 33027 µs/rev mozilla-try x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.068571 s, 0.073703 s, +0.005132 s, × 1.0748, 12283 µs/rev mozilla-try x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.006452 s, 0.006469 s, +0.000017 s, × 1.0026, 4 µs/rev mozilla-try x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.005443 s, 0.005278 s, -0.000165 s, × 0.9697, 128 µs/rev mozilla-try x000_revs_x000_added_x000_copies 1346fd0130e4 4c65cbdabc1f : 6657 revs, 0.063180 s, 0.064995 s, +0.001815 s, × 1.0287, 9 µs/rev mozilla-try x0000_revs_x_added_0_copies 63519bfd42ee a36a2a865d92 : 40314 revs, 0.293564 s, 0.301041 s, +0.007477 s, × 1.0255, 7 µs/rev mozilla-try x0000_revs_x_added_x_copies 9fe69ff0762d bcabf2a78927 : 38690 revs, 0.286595 s, 0.285575 s, -0.001020 s, × 0.9964, 7 µs/rev mozilla-try x0000_revs_xx000_added_x_copies 156f6e2674f2 4d0f2c178e66 : 8598 revs, 0.083256 s, 0.085597 s, +0.002341 s, × 1.0281, 9 µs/rev mozilla-try x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.027282 s, 0.027118 s, -0.000164 s, × 0.9940, 44 µs/rev mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 97052 revs, 1.343373 s, 2.119204 s, +0.775831 s, × 1.5775, 21 µs/rev mozilla-try x0000_revs_x0000_added_x0000_copies e928c65095ed e951f4ad123a : 52031 revs, 0.665737 s, 0.701479 s, +0.035742 s, × 1.0537, 13 µs/rev mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 363753 revs, 5.138169 s, 4.482399 s, -0.655770 s, × 0.8724, 12 µs/rev mozilla-try x00000_revs_x00000_added_0_copies dc8a3ca7010e d16fde900c9c : 34414 revs, 0.573276 s, 0.574082 s, +0.000806 s, × 1.0014, 16 µs/rev mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 362229 revs, 5.127809 s, 4.480366 s, -0.647443 s, × 0.8737, 12 µs/rev mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 359344 revs, 4.971136 s, 4.369070 s, -0.602066 s, × 0.8789, 12 µs/rev mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 192665 revs, 1.741678 s, 1.592506 s, -0.149172 s, × 0.9144, 8 µs/rev mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 228985 revs, 40.314822 s, 87.824489 s, +47.509667 s, × 2.1785, 383 µs/rev mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 382065 revs, 20.048029 s, 43.304637 s, +23.256608 s, × 2.1600, 113 µs/rev private : 459513 revs, 37.179470 s, 33.853687 s, -3.325783 s, × 0.9105, 73 µs/rev Differential Revision: https://phab.mercurial-scm.org/D9644
author Pierre-Yves David <pierre-yves.david@octobus.net>
date Tue, 15 Dec 2020 18:04:23 +0100
parents 6383bb86b700
children 33c0c25d0b0f
line wrap: on
line source

# chgserver.py - command server extension for cHg
#
# Copyright 2011 Yuya Nishihara <yuya@tcha.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

"""command server extension for cHg

'S' channel (read/write)
    propagate ui.system() request to client

'attachio' command
    attach client's stdio passed by sendmsg()

'chdir' command
    change current directory

'setenv' command
    replace os.environ completely

'setumask' command (DEPRECATED)
'setumask2' command
    set umask

'validate' command
    reload the config and check if the server is up to date

Config
------

::

  [chgserver]
  # how long (in seconds) should an idle chg server exit
  idletimeout = 3600

  # whether to skip config or env change checks
  skiphash = False
"""

from __future__ import absolute_import

import inspect
import os
import re
import socket
import stat
import struct
import time

from .i18n import _
from .pycompat import (
    getattr,
    setattr,
)
from .node import hex

from . import (
    commandserver,
    encoding,
    error,
    extensions,
    pycompat,
    util,
)

from .utils import (
    hashutil,
    procutil,
    stringutil,
)


def _hashlist(items):
    """return sha1 hexdigest for a list"""
    return hex(hashutil.sha1(stringutil.pprint(items)).digest())


# sensitive config sections affecting confighash
_configsections = [
    b'alias',  # affects global state commands.table
    b'diff-tools',  # affects whether gui or not in extdiff's uisetup
    b'eol',  # uses setconfig('eol', ...)
    b'extdiff',  # uisetup will register new commands
    b'extensions',
    b'fastannotate',  # affects annotate command and adds fastannonate cmd
    b'merge-tools',  # affects whether gui or not in extdiff's uisetup
    b'schemes',  # extsetup will update global hg.schemes
]

_configsectionitems = [
    (b'commands', b'show.aliasprefix'),  # show.py reads it in extsetup
]

# sensitive environment variables affecting confighash
_envre = re.compile(
    br'''\A(?:
                    CHGHG
                    |HG(?:DEMANDIMPORT|EMITWARNINGS|MODULEPOLICY|PROF|RCPATH)?
                    |HG(?:ENCODING|PLAIN).*
                    |LANG(?:UAGE)?
                    |LC_.*
                    |LD_.*
                    |PATH
                    |PYTHON.*
                    |TERM(?:INFO)?
                    |TZ
                    )\Z''',
    re.X,
)


def _confighash(ui):
    """return a quick hash for detecting config/env changes

    confighash is the hash of sensitive config items and environment variables.

    for chgserver, it is designed that once confighash changes, the server is
    not qualified to serve its client and should redirect the client to a new
    server. different from mtimehash, confighash change will not mark the
    server outdated and exit since the user can have different configs at the
    same time.
    """
    sectionitems = []
    for section in _configsections:
        sectionitems.append(ui.configitems(section))
    for section, item in _configsectionitems:
        sectionitems.append(ui.config(section, item))
    sectionhash = _hashlist(sectionitems)
    # If $CHGHG is set, the change to $HG should not trigger a new chg server
    if b'CHGHG' in encoding.environ:
        ignored = {b'HG'}
    else:
        ignored = set()
    envitems = [
        (k, v)
        for k, v in pycompat.iteritems(encoding.environ)
        if _envre.match(k) and k not in ignored
    ]
    envhash = _hashlist(sorted(envitems))
    return sectionhash[:6] + envhash[:6]


def _getmtimepaths(ui):
    """get a list of paths that should be checked to detect change

    The list will include:
    - extensions (will not cover all files for complex extensions)
    - mercurial/__version__.py
    - python binary
    """
    modules = [m for n, m in extensions.extensions(ui)]
    try:
        from . import __version__

        modules.append(__version__)
    except ImportError:
        pass
    files = []
    if pycompat.sysexecutable:
        files.append(pycompat.sysexecutable)
    for m in modules:
        try:
            files.append(pycompat.fsencode(inspect.getabsfile(m)))
        except TypeError:
            pass
    return sorted(set(files))


def _mtimehash(paths):
    """return a quick hash for detecting file changes

    mtimehash calls stat on given paths and calculate a hash based on size and
    mtime of each file. mtimehash does not read file content because reading is
    expensive. therefore it's not 100% reliable for detecting content changes.
    it's possible to return different hashes for same file contents.
    it's also possible to return a same hash for different file contents for
    some carefully crafted situation.

    for chgserver, it is designed that once mtimehash changes, the server is
    considered outdated immediately and should no longer provide service.

    mtimehash is not included in confighash because we only know the paths of
    extensions after importing them (there is imp.find_module but that faces
    race conditions). We need to calculate confighash without importing.
    """

    def trystat(path):
        try:
            st = os.stat(path)
            return (st[stat.ST_MTIME], st.st_size)
        except OSError:
            # could be ENOENT, EPERM etc. not fatal in any case
            pass

    return _hashlist(pycompat.maplist(trystat, paths))[:12]


class hashstate(object):
    """a structure storing confighash, mtimehash, paths used for mtimehash"""

    def __init__(self, confighash, mtimehash, mtimepaths):
        self.confighash = confighash
        self.mtimehash = mtimehash
        self.mtimepaths = mtimepaths

    @staticmethod
    def fromui(ui, mtimepaths=None):
        if mtimepaths is None:
            mtimepaths = _getmtimepaths(ui)
        confighash = _confighash(ui)
        mtimehash = _mtimehash(mtimepaths)
        ui.log(
            b'cmdserver',
            b'confighash = %s mtimehash = %s\n',
            confighash,
            mtimehash,
        )
        return hashstate(confighash, mtimehash, mtimepaths)


def _newchgui(srcui, csystem, attachio):
    class chgui(srcui.__class__):
        def __init__(self, src=None):
            super(chgui, self).__init__(src)
            if src:
                self._csystem = getattr(src, '_csystem', csystem)
            else:
                self._csystem = csystem

        def _runsystem(self, cmd, environ, cwd, out):
            # fallback to the original system method if
            #  a. the output stream is not stdout (e.g. stderr, cStringIO),
            #  b. or stdout is redirected by protectfinout(),
            # because the chg client is not aware of these situations and
            # will behave differently (i.e. write to stdout).
            if (
                out is not self.fout
                or not util.safehasattr(self.fout, b'fileno')
                or self.fout.fileno() != procutil.stdout.fileno()
                or self._finoutredirected
            ):
                return procutil.system(cmd, environ=environ, cwd=cwd, out=out)
            self.flush()
            return self._csystem(cmd, procutil.shellenviron(environ), cwd)

        def _runpager(self, cmd, env=None):
            self._csystem(
                cmd,
                procutil.shellenviron(env),
                type=b'pager',
                cmdtable={b'attachio': attachio},
            )
            return True

    return chgui(srcui)


def _loadnewui(srcui, args, cdebug):
    from . import dispatch  # avoid cycle

    newui = srcui.__class__.load()
    for a in [b'fin', b'fout', b'ferr', b'environ']:
        setattr(newui, a, getattr(srcui, a))
    if util.safehasattr(srcui, b'_csystem'):
        newui._csystem = srcui._csystem

    # command line args
    options = dispatch._earlyparseopts(newui, args)
    dispatch._parseconfig(newui, options[b'config'])

    # stolen from tortoisehg.util.copydynamicconfig()
    for section, name, value in srcui.walkconfig():
        source = srcui.configsource(section, name)
        if b':' in source or source == b'--config' or source.startswith(b'$'):
            # path:line or command line, or environ
            continue
        newui.setconfig(section, name, value, source)

    # load wd and repo config, copied from dispatch.py
    cwd = options[b'cwd']
    cwd = cwd and os.path.realpath(cwd) or None
    rpath = options[b'repository']
    path, newlui = dispatch._getlocal(newui, rpath, wd=cwd)

    extensions.populateui(newui)
    commandserver.setuplogging(newui, fp=cdebug)
    if newui is not newlui:
        extensions.populateui(newlui)
        commandserver.setuplogging(newlui, fp=cdebug)

    return (newui, newlui)


class channeledsystem(object):
    """Propagate ui.system() request in the following format:

    payload length (unsigned int),
    type, '\0',
    cmd, '\0',
    cwd, '\0',
    envkey, '=', val, '\0',
    ...
    envkey, '=', val

    if type == 'system', waits for:

    exitcode length (unsigned int),
    exitcode (int)

    if type == 'pager', repetitively waits for a command name ending with '\n'
    and executes it defined by cmdtable, or exits the loop if the command name
    is empty.
    """

    def __init__(self, in_, out, channel):
        self.in_ = in_
        self.out = out
        self.channel = channel

    def __call__(self, cmd, environ, cwd=None, type=b'system', cmdtable=None):
        args = [type, cmd, os.path.abspath(cwd or b'.')]
        args.extend(b'%s=%s' % (k, v) for k, v in pycompat.iteritems(environ))
        data = b'\0'.join(args)
        self.out.write(struct.pack(b'>cI', self.channel, len(data)))
        self.out.write(data)
        self.out.flush()

        if type == b'system':
            length = self.in_.read(4)
            (length,) = struct.unpack(b'>I', length)
            if length != 4:
                raise error.Abort(_(b'invalid response'))
            (rc,) = struct.unpack(b'>i', self.in_.read(4))
            return rc
        elif type == b'pager':
            while True:
                cmd = self.in_.readline()[:-1]
                if not cmd:
                    break
                if cmdtable and cmd in cmdtable:
                    cmdtable[cmd]()
                else:
                    raise error.Abort(_(b'unexpected command: %s') % cmd)
        else:
            raise error.ProgrammingError(b'invalid S channel type: %s' % type)


_iochannels = [
    # server.ch, ui.fp, mode
    (b'cin', b'fin', 'rb'),
    (b'cout', b'fout', 'wb'),
    (b'cerr', b'ferr', 'wb'),
]


class chgcmdserver(commandserver.server):
    def __init__(
        self, ui, repo, fin, fout, sock, prereposetups, hashstate, baseaddress
    ):
        super(chgcmdserver, self).__init__(
            _newchgui(ui, channeledsystem(fin, fout, b'S'), self.attachio),
            repo,
            fin,
            fout,
            prereposetups,
        )
        self.clientsock = sock
        self._ioattached = False
        self._oldios = []  # original (self.ch, ui.fp, fd) before "attachio"
        self.hashstate = hashstate
        self.baseaddress = baseaddress
        if hashstate is not None:
            self.capabilities = self.capabilities.copy()
            self.capabilities[b'validate'] = chgcmdserver.validate

    def cleanup(self):
        super(chgcmdserver, self).cleanup()
        # dispatch._runcatch() does not flush outputs if exception is not
        # handled by dispatch._dispatch()
        self.ui.flush()
        self._restoreio()
        self._ioattached = False

    def attachio(self):
        """Attach to client's stdio passed via unix domain socket; all
        channels except cresult will no longer be used
        """
        # tell client to sendmsg() with 1-byte payload, which makes it
        # distinctive from "attachio\n" command consumed by client.read()
        self.clientsock.sendall(struct.pack(b'>cI', b'I', 1))
        clientfds = util.recvfds(self.clientsock.fileno())
        self.ui.log(b'chgserver', b'received fds: %r\n', clientfds)

        ui = self.ui
        ui.flush()
        self._saveio()
        for fd, (cn, fn, mode) in zip(clientfds, _iochannels):
            assert fd > 0
            fp = getattr(ui, fn)
            os.dup2(fd, fp.fileno())
            os.close(fd)
            if self._ioattached:
                continue
            # reset buffering mode when client is first attached. as we want
            # to see output immediately on pager, the mode stays unchanged
            # when client re-attached. ferr is unchanged because it should
            # be unbuffered no matter if it is a tty or not.
            if fn == b'ferr':
                newfp = fp
            elif pycompat.ispy3:
                # On Python 3, the standard library doesn't offer line-buffered
                # binary streams, so wrap/unwrap it.
                if fp.isatty():
                    newfp = procutil.make_line_buffered(fp)
                else:
                    newfp = procutil.unwrap_line_buffered(fp)
            else:
                # Python 2 uses the I/O streams provided by the C library, so
                # make it line-buffered explicitly. Otherwise the default would
                # be decided on first write(), where fout could be a pager.
                if fp.isatty():
                    bufsize = 1  # line buffered
                else:
                    bufsize = -1  # system default
                newfp = os.fdopen(fp.fileno(), mode, bufsize)
            if newfp is not fp:
                setattr(ui, fn, newfp)
            setattr(self, cn, newfp)

        self._ioattached = True
        self.cresult.write(struct.pack(b'>i', len(clientfds)))

    def _saveio(self):
        if self._oldios:
            return
        ui = self.ui
        for cn, fn, _mode in _iochannels:
            ch = getattr(self, cn)
            fp = getattr(ui, fn)
            fd = os.dup(fp.fileno())
            self._oldios.append((ch, fp, fd))

    def _restoreio(self):
        if not self._oldios:
            return
        nullfd = os.open(os.devnull, os.O_WRONLY)
        ui = self.ui
        for (ch, fp, fd), (cn, fn, mode) in zip(self._oldios, _iochannels):
            newfp = getattr(ui, fn)
            # On Python 2, newfp and fp may be separate file objects associated
            # with the same fd, so we must close newfp while it's associated
            # with the client. Otherwise the new associated fd would be closed
            # when newfp gets deleted. On Python 3, newfp is just a wrapper
            # around fp even if newfp is not fp, so deleting newfp is safe.
            if not (pycompat.ispy3 or newfp is fp):
                newfp.close()
            # restore original fd: fp is open again
            try:
                if (pycompat.ispy3 or newfp is fp) and 'w' in mode:
                    # Discard buffered data which couldn't be flushed because
                    # of EPIPE. The data should belong to the current session
                    # and should never persist.
                    os.dup2(nullfd, fp.fileno())
                    fp.flush()
                os.dup2(fd, fp.fileno())
            except OSError as err:
                # According to issue6330, running chg on heavy loaded systems
                # can lead to EBUSY. [man dup2] indicates that, on Linux,
                # EBUSY comes from a race condition between open() and dup2().
                # However it's not clear why open() race occurred for
                # newfd=stdin/out/err.
                self.ui.log(
                    b'chgserver',
                    b'got %s while duplicating %s\n',
                    stringutil.forcebytestr(err),
                    fn,
                )
            os.close(fd)
            setattr(self, cn, ch)
            setattr(ui, fn, fp)
        os.close(nullfd)
        del self._oldios[:]

    def validate(self):
        """Reload the config and check if the server is up to date

        Read a list of '\0' separated arguments.
        Write a non-empty list of '\0' separated instruction strings or '\0'
        if the list is empty.
        An instruction string could be either:
            - "unlink $path", the client should unlink the path to stop the
              outdated server.
            - "redirect $path", the client should attempt to connect to $path
              first. If it does not work, start a new server. It implies
              "reconnect".
            - "exit $n", the client should exit directly with code n.
              This may happen if we cannot parse the config.
            - "reconnect", the client should close the connection and
              reconnect.
        If neither "reconnect" nor "redirect" is included in the instruction
        list, the client can continue with this server after completing all
        the instructions.
        """
        args = self._readlist()
        errorraised = False
        detailed_exit_code = 255
        try:
            self.ui, lui = _loadnewui(self.ui, args, self.cdebug)
        except error.RepoError as inst:
            # RepoError can be raised while trying to read shared source
            # configuration
            self.ui.error(_(b"abort: %s\n") % stringutil.forcebytestr(inst))
            if inst.hint:
                self.ui.error(_(b"(%s)\n") % inst.hint)
            errorraised = True
        except error.Abort as inst:
            if isinstance(inst, error.InputError):
                detailed_exit_code = 10
            elif isinstance(inst, error.ConfigError):
                detailed_exit_code = 30
            self.ui.error(inst.format())
            errorraised = True

        if errorraised:
            self.ui.flush()
            exit_code = 255
            if self.ui.configbool(b'ui', b'detailed-exit-code'):
                exit_code = detailed_exit_code
            self.cresult.write(b'exit %d' % exit_code)
            return
        newhash = hashstate.fromui(lui, self.hashstate.mtimepaths)
        insts = []
        if newhash.mtimehash != self.hashstate.mtimehash:
            addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
            insts.append(b'unlink %s' % addr)
            # mtimehash is empty if one or more extensions fail to load.
            # to be compatible with hg, still serve the client this time.
            if self.hashstate.mtimehash:
                insts.append(b'reconnect')
        if newhash.confighash != self.hashstate.confighash:
            addr = _hashaddress(self.baseaddress, newhash.confighash)
            insts.append(b'redirect %s' % addr)
        self.ui.log(b'chgserver', b'validate: %s\n', stringutil.pprint(insts))
        self.cresult.write(b'\0'.join(insts) or b'\0')

    def chdir(self):
        """Change current directory

        Note that the behavior of --cwd option is bit different from this.
        It does not affect --config parameter.
        """
        path = self._readstr()
        if not path:
            return
        self.ui.log(b'chgserver', b"chdir to '%s'\n", path)
        os.chdir(path)

    def setumask(self):
        """Change umask (DEPRECATED)"""
        # BUG: this does not follow the message frame structure, but kept for
        # backward compatibility with old chg clients for some time
        self._setumask(self._read(4))

    def setumask2(self):
        """Change umask"""
        data = self._readstr()
        if len(data) != 4:
            raise ValueError(b'invalid mask length in setumask2 request')
        self._setumask(data)

    def _setumask(self, data):
        mask = struct.unpack(b'>I', data)[0]
        self.ui.log(b'chgserver', b'setumask %r\n', mask)
        util.setumask(mask)

    def runcommand(self):
        # pager may be attached within the runcommand session, which should
        # be detached at the end of the session. otherwise the pager wouldn't
        # receive EOF.
        globaloldios = self._oldios
        self._oldios = []
        try:
            return super(chgcmdserver, self).runcommand()
        finally:
            self._restoreio()
            self._oldios = globaloldios

    def setenv(self):
        """Clear and update os.environ

        Note that not all variables can make an effect on the running process.
        """
        l = self._readlist()
        try:
            newenv = dict(s.split(b'=', 1) for s in l)
        except ValueError:
            raise ValueError(b'unexpected value in setenv request')
        self.ui.log(b'chgserver', b'setenv: %r\n', sorted(newenv.keys()))

        encoding.environ.clear()
        encoding.environ.update(newenv)

    capabilities = commandserver.server.capabilities.copy()
    capabilities.update(
        {
            b'attachio': attachio,
            b'chdir': chdir,
            b'runcommand': runcommand,
            b'setenv': setenv,
            b'setumask': setumask,
            b'setumask2': setumask2,
        }
    )

    if util.safehasattr(procutil, b'setprocname'):

        def setprocname(self):
            """Change process title"""
            name = self._readstr()
            self.ui.log(b'chgserver', b'setprocname: %r\n', name)
            procutil.setprocname(name)

        capabilities[b'setprocname'] = setprocname


def _tempaddress(address):
    return b'%s.%d.tmp' % (address, os.getpid())


def _hashaddress(address, hashstr):
    # if the basename of address contains '.', use only the left part. this
    # makes it possible for the client to pass 'server.tmp$PID' and follow by
    # an atomic rename to avoid locking when spawning new servers.
    dirname, basename = os.path.split(address)
    basename = basename.split(b'.', 1)[0]
    return b'%s-%s' % (os.path.join(dirname, basename), hashstr)


class chgunixservicehandler(object):
    """Set of operations for chg services"""

    pollinterval = 1  # [sec]

    def __init__(self, ui):
        self.ui = ui
        self._idletimeout = ui.configint(b'chgserver', b'idletimeout')
        self._lastactive = time.time()

    def bindsocket(self, sock, address):
        self._inithashstate(address)
        self._checkextensions()
        self._bind(sock)
        self._createsymlink()
        # no "listening at" message should be printed to simulate hg behavior

    def _inithashstate(self, address):
        self._baseaddress = address
        if self.ui.configbool(b'chgserver', b'skiphash'):
            self._hashstate = None
            self._realaddress = address
            return
        self._hashstate = hashstate.fromui(self.ui)
        self._realaddress = _hashaddress(address, self._hashstate.confighash)

    def _checkextensions(self):
        if not self._hashstate:
            return
        if extensions.notloaded():
            # one or more extensions failed to load. mtimehash becomes
            # meaningless because we do not know the paths of those extensions.
            # set mtimehash to an illegal hash value to invalidate the server.
            self._hashstate.mtimehash = b''

    def _bind(self, sock):
        # use a unique temp address so we can stat the file and do ownership
        # check later
        tempaddress = _tempaddress(self._realaddress)
        util.bindunixsocket(sock, tempaddress)
        self._socketstat = os.stat(tempaddress)
        sock.listen(socket.SOMAXCONN)
        # rename will replace the old socket file if exists atomically. the
        # old server will detect ownership change and exit.
        util.rename(tempaddress, self._realaddress)

    def _createsymlink(self):
        if self._baseaddress == self._realaddress:
            return
        tempaddress = _tempaddress(self._baseaddress)
        os.symlink(os.path.basename(self._realaddress), tempaddress)
        util.rename(tempaddress, self._baseaddress)

    def _issocketowner(self):
        try:
            st = os.stat(self._realaddress)
            return (
                st.st_ino == self._socketstat.st_ino
                and st[stat.ST_MTIME] == self._socketstat[stat.ST_MTIME]
            )
        except OSError:
            return False

    def unlinksocket(self, address):
        if not self._issocketowner():
            return
        # it is possible to have a race condition here that we may
        # remove another server's socket file. but that's okay
        # since that server will detect and exit automatically and
        # the client will start a new server on demand.
        util.tryunlink(self._realaddress)

    def shouldexit(self):
        if not self._issocketowner():
            self.ui.log(
                b'chgserver', b'%s is not owned, exiting.\n', self._realaddress
            )
            return True
        if time.time() - self._lastactive > self._idletimeout:
            self.ui.log(b'chgserver', b'being idle too long. exiting.\n')
            return True
        return False

    def newconnection(self):
        self._lastactive = time.time()

    def createcmdserver(self, repo, conn, fin, fout, prereposetups):
        return chgcmdserver(
            self.ui,
            repo,
            fin,
            fout,
            conn,
            prereposetups,
            self._hashstate,
            self._baseaddress,
        )


def chgunixservice(ui, repo, opts):
    # CHGINTERNALMARK is set by chg client. It is an indication of things are
    # started by chg so other code can do things accordingly, like disabling
    # demandimport or detecting chg client started by chg client. When executed
    # here, CHGINTERNALMARK is no longer useful and hence dropped to make
    # environ cleaner.
    if b'CHGINTERNALMARK' in encoding.environ:
        del encoding.environ[b'CHGINTERNALMARK']
    # Python3.7+ "coerces" the LC_CTYPE environment variable to a UTF-8 one if
    # it thinks the current value is "C". This breaks the hash computation and
    # causes chg to restart loop.
    if b'CHGORIG_LC_CTYPE' in encoding.environ:
        encoding.environ[b'LC_CTYPE'] = encoding.environ[b'CHGORIG_LC_CTYPE']
        del encoding.environ[b'CHGORIG_LC_CTYPE']
    elif b'CHG_CLEAR_LC_CTYPE' in encoding.environ:
        if b'LC_CTYPE' in encoding.environ:
            del encoding.environ[b'LC_CTYPE']
        del encoding.environ[b'CHG_CLEAR_LC_CTYPE']

    if repo:
        # one chgserver can serve multiple repos. drop repo information
        ui.setconfig(b'bundle', b'mainreporoot', b'', b'repo')
    h = chgunixservicehandler(ui)
    return commandserver.unixforkingservice(ui, repo=None, opts=opts, handler=h)