2015-12-23 16:23:56 +03:00
|
|
|
# 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.
|
|
|
|
|
2016-10-15 08:30:16 +03:00
|
|
|
"""command server extension for cHg
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
'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
|
|
|
|
|
2016-02-29 17:05:45 +03:00
|
|
|
'setumask' command
|
|
|
|
set umask
|
|
|
|
|
2016-03-05 16:56:59 +03:00
|
|
|
'validate' command
|
|
|
|
reload the config and check if the server is up to date
|
|
|
|
|
2016-02-29 17:05:45 +03:00
|
|
|
Config
|
|
|
|
------
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
[chgserver]
|
2017-02-17 10:10:47 +03:00
|
|
|
# how long (in seconds) should an idle chg server exit
|
|
|
|
idletimeout = 3600
|
|
|
|
|
|
|
|
# whether to skip config or env change checks
|
|
|
|
skiphash = False
|
2015-12-23 16:23:56 +03:00
|
|
|
"""
|
|
|
|
|
|
|
|
from __future__ import absolute_import
|
|
|
|
|
|
|
|
import errno
|
2016-06-10 07:12:33 +03:00
|
|
|
import hashlib
|
2016-02-26 17:59:39 +03:00
|
|
|
import inspect
|
2015-12-23 16:23:56 +03:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import struct
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
import time
|
2015-12-23 16:23:56 +03:00
|
|
|
|
2016-10-15 08:30:16 +03:00
|
|
|
from .i18n import _
|
2015-12-23 16:23:56 +03:00
|
|
|
|
2016-10-15 08:30:16 +03:00
|
|
|
from . import (
|
2015-12-23 16:23:56 +03:00
|
|
|
commandserver,
|
2016-12-17 23:16:39 +03:00
|
|
|
encoding,
|
2015-12-23 16:23:56 +03:00
|
|
|
error,
|
2016-02-26 17:59:39 +03:00
|
|
|
extensions,
|
2015-12-23 16:23:56 +03:00
|
|
|
osutil,
|
2016-12-19 21:50:07 +03:00
|
|
|
pycompat,
|
2015-12-23 16:23:56 +03:00
|
|
|
util,
|
|
|
|
)
|
|
|
|
|
|
|
|
_log = commandserver.log
|
|
|
|
|
2016-02-26 17:50:04 +03:00
|
|
|
def _hashlist(items):
|
|
|
|
"""return sha1 hexdigest for a list"""
|
2016-06-10 07:12:33 +03:00
|
|
|
return hashlib.sha1(str(items)).hexdigest()
|
2016-02-26 17:50:04 +03:00
|
|
|
|
|
|
|
# sensitive config sections affecting confighash
|
2016-03-11 16:00:20 +03:00
|
|
|
_configsections = [
|
2016-05-07 16:51:32 +03:00
|
|
|
'alias', # affects global state commands.table
|
2016-03-11 16:00:20 +03:00
|
|
|
'extdiff', # uisetup will register new commands
|
|
|
|
'extensions',
|
|
|
|
]
|
2016-02-26 17:50:04 +03:00
|
|
|
|
|
|
|
# sensitive environment variables affecting confighash
|
|
|
|
_envre = re.compile(r'''\A(?:
|
|
|
|
CHGHG
|
2016-12-14 05:17:59 +03:00
|
|
|
|HG(?:[A-Z].*)?
|
2016-02-26 17:50:04 +03:00
|
|
|
|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))
|
|
|
|
sectionhash = _hashlist(sectionitems)
|
2016-12-17 23:16:39 +03:00
|
|
|
envitems = [(k, v) for k, v in encoding.environ.iteritems()
|
|
|
|
if _envre.match(k)]
|
2016-02-26 17:50:04 +03:00
|
|
|
envhash = _hashlist(sorted(envitems))
|
|
|
|
return sectionhash[:6] + envhash[:6]
|
|
|
|
|
2016-02-26 17:59:39 +03:00
|
|
|
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:
|
2016-10-15 08:30:16 +03:00
|
|
|
from . import __version__
|
2016-02-26 17:59:39 +03:00
|
|
|
modules.append(__version__)
|
|
|
|
except ImportError:
|
|
|
|
pass
|
2016-12-19 21:50:07 +03:00
|
|
|
files = [pycompat.sysexecutable]
|
2016-02-26 17:59:39 +03:00
|
|
|
for m in modules:
|
|
|
|
try:
|
|
|
|
files.append(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.
|
2016-06-30 01:53:20 +03:00
|
|
|
|
|
|
|
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.
|
2016-02-26 17:59:39 +03:00
|
|
|
"""
|
|
|
|
def trystat(path):
|
|
|
|
try:
|
|
|
|
st = os.stat(path)
|
|
|
|
return (st.st_mtime, st.st_size)
|
|
|
|
except OSError:
|
|
|
|
# could be ENOENT, EPERM etc. not fatal in any case
|
|
|
|
pass
|
|
|
|
return _hashlist(map(trystat, paths))[:12]
|
|
|
|
|
2016-02-24 23:45:47 +03:00
|
|
|
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)
|
|
|
|
_log('confighash = %s mtimehash = %s\n' % (confighash, mtimehash))
|
|
|
|
return hashstate(confighash, mtimehash, mtimepaths)
|
|
|
|
|
2017-01-10 01:59:31 +03:00
|
|
|
def _newchgui(srcui, csystem, attachio):
|
2015-12-23 16:23:56 +03:00
|
|
|
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
|
|
|
|
|
2017-02-18 19:16:45 +03:00
|
|
|
def _runsystem(self, cmd, environ, cwd, out):
|
2016-03-17 21:27:48 +03:00
|
|
|
# fallback to the original system method if the output needs to be
|
|
|
|
# captured (to self._buffers), or the output stream is not stdout
|
|
|
|
# (e.g. stderr, cStringIO), because the chg client is not aware of
|
|
|
|
# these situations and will behave differently (write to stdout).
|
2017-02-18 19:00:10 +03:00
|
|
|
if (out is not self.fout
|
2016-03-17 21:27:48 +03:00
|
|
|
or not util.safehasattr(self.fout, 'fileno')
|
2016-10-20 17:53:36 +03:00
|
|
|
or self.fout.fileno() != util.stdout.fileno()):
|
2017-02-18 19:16:45 +03:00
|
|
|
return util.system(cmd, environ=environ, cwd=cwd, out=out)
|
2015-12-23 16:23:56 +03:00
|
|
|
self.flush()
|
2017-02-18 19:16:45 +03:00
|
|
|
return self._csystem(cmd, util.shellenviron(environ), cwd)
|
2015-12-23 16:23:56 +03:00
|
|
|
|
2017-01-10 01:59:31 +03:00
|
|
|
def _runpager(self, cmd):
|
|
|
|
self._csystem(cmd, util.shellenviron(), type='pager',
|
|
|
|
cmdtable={'attachio': attachio})
|
|
|
|
|
2015-12-23 16:23:56 +03:00
|
|
|
return chgui(srcui)
|
|
|
|
|
2016-03-20 20:44:15 +03:00
|
|
|
def _loadnewui(srcui, args):
|
2016-10-15 08:30:16 +03:00
|
|
|
from . import dispatch # avoid cycle
|
2016-10-15 08:37:18 +03:00
|
|
|
|
2016-12-06 00:36:35 +03:00
|
|
|
newui = srcui.__class__.load()
|
2015-12-23 16:23:56 +03:00
|
|
|
for a in ['fin', 'fout', 'ferr', 'environ']:
|
|
|
|
setattr(newui, a, getattr(srcui, a))
|
|
|
|
if util.safehasattr(srcui, '_csystem'):
|
|
|
|
newui._csystem = srcui._csystem
|
2016-02-26 18:22:46 +03:00
|
|
|
|
|
|
|
# command line args
|
2016-04-04 03:10:51 +03:00
|
|
|
args = args[:]
|
2016-02-26 18:22:46 +03:00
|
|
|
dispatch._parseconfig(newui, dispatch._earlygetopt(['--config'], args))
|
|
|
|
|
2015-12-23 16:23:56 +03:00
|
|
|
# stolen from tortoisehg.util.copydynamicconfig()
|
|
|
|
for section, name, value in srcui.walkconfig():
|
|
|
|
source = srcui.configsource(section, name)
|
2016-02-26 18:22:46 +03:00
|
|
|
if ':' in source or source == '--config':
|
|
|
|
# path:line or command line
|
2015-12-23 16:23:56 +03:00
|
|
|
continue
|
|
|
|
newui.setconfig(section, name, value, source)
|
2016-03-17 21:32:10 +03:00
|
|
|
|
|
|
|
# load wd and repo config, copied from dispatch.py
|
|
|
|
cwds = dispatch._earlygetopt(['--cwd'], args)
|
|
|
|
cwd = cwds and os.path.realpath(cwds[-1]) or None
|
|
|
|
rpath = dispatch._earlygetopt(["-R", "--repository", "--repo"], args)
|
|
|
|
path, newlui = dispatch._getlocal(newui, rpath, wd=cwd)
|
|
|
|
|
|
|
|
return (newui, newlui)
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
class channeledsystem(object):
|
|
|
|
"""Propagate ui.system() request in the following format:
|
|
|
|
|
|
|
|
payload length (unsigned int),
|
2017-01-06 19:11:03 +03:00
|
|
|
type, '\0',
|
2015-12-23 16:23:56 +03:00
|
|
|
cmd, '\0',
|
|
|
|
cwd, '\0',
|
|
|
|
envkey, '=', val, '\0',
|
|
|
|
...
|
|
|
|
envkey, '=', val
|
|
|
|
|
2017-01-06 19:11:03 +03:00
|
|
|
if type == 'system', waits for:
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
exitcode length (unsigned int),
|
|
|
|
exitcode (int)
|
2017-01-10 01:59:21 +03:00
|
|
|
|
|
|
|
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.
|
2015-12-23 16:23:56 +03:00
|
|
|
"""
|
|
|
|
def __init__(self, in_, out, channel):
|
|
|
|
self.in_ = in_
|
|
|
|
self.out = out
|
|
|
|
self.channel = channel
|
|
|
|
|
2017-01-10 01:59:21 +03:00
|
|
|
def __call__(self, cmd, environ, cwd=None, type='system', cmdtable=None):
|
2017-01-06 19:11:03 +03:00
|
|
|
args = [type, util.quotecommand(cmd), os.path.abspath(cwd or '.')]
|
2015-12-23 16:23:56 +03:00
|
|
|
args.extend('%s=%s' % (k, v) for k, v in environ.iteritems())
|
|
|
|
data = '\0'.join(args)
|
|
|
|
self.out.write(struct.pack('>cI', self.channel, len(data)))
|
|
|
|
self.out.write(data)
|
|
|
|
self.out.flush()
|
|
|
|
|
2017-01-06 19:12:25 +03:00
|
|
|
if type == 'system':
|
|
|
|
length = self.in_.read(4)
|
|
|
|
length, = struct.unpack('>I', length)
|
|
|
|
if length != 4:
|
|
|
|
raise error.Abort(_('invalid response'))
|
|
|
|
rc, = struct.unpack('>i', self.in_.read(4))
|
|
|
|
return rc
|
2017-01-10 01:59:21 +03:00
|
|
|
elif type == 'pager':
|
|
|
|
while True:
|
|
|
|
cmd = self.in_.readline()[:-1]
|
|
|
|
if not cmd:
|
|
|
|
break
|
|
|
|
if cmdtable and cmd in cmdtable:
|
|
|
|
_log('pager subcommand: %s' % cmd)
|
|
|
|
cmdtable[cmd]()
|
|
|
|
else:
|
|
|
|
raise error.Abort(_('unexpected command: %s') % cmd)
|
2017-01-06 19:12:25 +03:00
|
|
|
else:
|
|
|
|
raise error.ProgrammingError('invalid S channel type: %s' % type)
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
_iochannels = [
|
|
|
|
# server.ch, ui.fp, mode
|
2017-02-13 17:36:38 +03:00
|
|
|
('cin', 'fin', pycompat.sysstr('rb')),
|
|
|
|
('cout', 'fout', pycompat.sysstr('wb')),
|
|
|
|
('cerr', 'ferr', pycompat.sysstr('wb')),
|
2015-12-23 16:23:56 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
class chgcmdserver(commandserver.server):
|
2016-02-29 16:46:54 +03:00
|
|
|
def __init__(self, ui, repo, fin, fout, sock, hashstate, baseaddress):
|
2015-12-23 16:23:56 +03:00
|
|
|
super(chgcmdserver, self).__init__(
|
2017-01-10 01:59:31 +03:00
|
|
|
_newchgui(ui, channeledsystem(fin, fout, 'S'), self.attachio),
|
|
|
|
repo, fin, fout)
|
2015-12-23 16:23:56 +03:00
|
|
|
self.clientsock = sock
|
|
|
|
self._oldios = [] # original (self.ch, ui.fp, fd) before "attachio"
|
2016-02-29 16:46:54 +03:00
|
|
|
self.hashstate = hashstate
|
|
|
|
self.baseaddress = baseaddress
|
2016-03-05 16:56:59 +03:00
|
|
|
if hashstate is not None:
|
|
|
|
self.capabilities = self.capabilities.copy()
|
|
|
|
self.capabilities['validate'] = chgcmdserver.validate
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
def cleanup(self):
|
2016-05-21 09:18:23 +03:00
|
|
|
super(chgcmdserver, self).cleanup()
|
2015-12-23 16:23:56 +03:00
|
|
|
# dispatch._runcatch() does not flush outputs if exception is not
|
|
|
|
# handled by dispatch._dispatch()
|
|
|
|
self.ui.flush()
|
|
|
|
self._restoreio()
|
|
|
|
|
|
|
|
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('>cI', 'I', 1))
|
|
|
|
clientfds = osutil.recvfds(self.clientsock.fileno())
|
|
|
|
_log('received fds: %r\n' % clientfds)
|
|
|
|
|
|
|
|
ui = self.ui
|
|
|
|
ui.flush()
|
|
|
|
first = 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 not first:
|
|
|
|
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 == 'ferr':
|
|
|
|
newfp = fp
|
|
|
|
else:
|
|
|
|
# make it line buffered explicitly because the default is
|
|
|
|
# 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)
|
|
|
|
setattr(ui, fn, newfp)
|
|
|
|
setattr(self, cn, newfp)
|
|
|
|
|
|
|
|
self.cresult.write(struct.pack('>i', len(clientfds)))
|
|
|
|
|
|
|
|
def _saveio(self):
|
|
|
|
if self._oldios:
|
|
|
|
return False
|
|
|
|
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))
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _restoreio(self):
|
|
|
|
ui = self.ui
|
|
|
|
for (ch, fp, fd), (cn, fn, _mode) in zip(self._oldios, _iochannels):
|
|
|
|
newfp = getattr(ui, fn)
|
|
|
|
# close newfp while it's associated with client; otherwise it
|
|
|
|
# would be closed when newfp is deleted
|
|
|
|
if newfp is not fp:
|
|
|
|
newfp.close()
|
|
|
|
# restore original fd: fp is open again
|
|
|
|
os.dup2(fd, fp.fileno())
|
|
|
|
os.close(fd)
|
|
|
|
setattr(self, cn, ch)
|
|
|
|
setattr(ui, fn, fp)
|
|
|
|
del self._oldios[:]
|
|
|
|
|
2016-03-05 16:56:59 +03:00
|
|
|
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.
|
2016-03-14 16:48:33 +03:00
|
|
|
- "redirect $path", the client should attempt to connect to $path
|
|
|
|
first. If it does not work, start a new server. It implies
|
|
|
|
"reconnect".
|
2016-03-14 15:52:35 +03:00
|
|
|
- "exit $n", the client should exit directly with code n.
|
|
|
|
This may happen if we cannot parse the config.
|
2016-03-14 16:48:33 +03:00
|
|
|
- "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.
|
2016-03-05 16:56:59 +03:00
|
|
|
"""
|
2016-10-15 08:30:16 +03:00
|
|
|
from . import dispatch # avoid cycle
|
2016-10-15 08:37:18 +03:00
|
|
|
|
2016-03-05 16:56:59 +03:00
|
|
|
args = self._readlist()
|
2016-03-14 15:52:35 +03:00
|
|
|
try:
|
2016-03-17 21:32:10 +03:00
|
|
|
self.ui, lui = _loadnewui(self.ui, args)
|
2016-03-14 15:52:35 +03:00
|
|
|
except error.ParseError as inst:
|
|
|
|
dispatch._formatparse(self.ui.warn, inst)
|
|
|
|
self.ui.flush()
|
|
|
|
self.cresult.write('exit 255')
|
|
|
|
return
|
2016-03-17 21:32:10 +03:00
|
|
|
newhash = hashstate.fromui(lui, self.hashstate.mtimepaths)
|
2016-03-05 16:56:59 +03:00
|
|
|
insts = []
|
|
|
|
if newhash.mtimehash != self.hashstate.mtimehash:
|
|
|
|
addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
|
|
|
|
insts.append('unlink %s' % addr)
|
2016-03-12 07:24:11 +03:00
|
|
|
# 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('reconnect')
|
2016-03-05 16:56:59 +03:00
|
|
|
if newhash.confighash != self.hashstate.confighash:
|
|
|
|
addr = _hashaddress(self.baseaddress, newhash.confighash)
|
|
|
|
insts.append('redirect %s' % addr)
|
|
|
|
_log('validate: %s\n' % insts)
|
|
|
|
self.cresult.write('\0'.join(insts) or '\0')
|
|
|
|
|
2015-12-23 16:23:56 +03:00
|
|
|
def chdir(self):
|
|
|
|
"""Change current directory
|
|
|
|
|
|
|
|
Note that the behavior of --cwd option is bit different from this.
|
|
|
|
It does not affect --config parameter.
|
|
|
|
"""
|
2016-02-16 22:21:05 +03:00
|
|
|
path = self._readstr()
|
|
|
|
if not path:
|
2015-12-23 16:23:56 +03:00
|
|
|
return
|
|
|
|
_log('chdir to %r\n' % path)
|
|
|
|
os.chdir(path)
|
|
|
|
|
2016-02-15 17:28:17 +03:00
|
|
|
def setumask(self):
|
|
|
|
"""Change umask"""
|
|
|
|
mask = struct.unpack('>I', self._read(4))[0]
|
|
|
|
_log('setumask %r\n' % mask)
|
|
|
|
os.umask(mask)
|
|
|
|
|
2016-12-16 17:48:37 +03:00
|
|
|
def runcommand(self):
|
|
|
|
return super(chgcmdserver, self).runcommand()
|
|
|
|
|
2015-12-23 16:23:56 +03:00
|
|
|
def setenv(self):
|
|
|
|
"""Clear and update os.environ
|
|
|
|
|
|
|
|
Note that not all variables can make an effect on the running process.
|
|
|
|
"""
|
2016-02-16 22:21:05 +03:00
|
|
|
l = self._readlist()
|
2015-12-23 16:23:56 +03:00
|
|
|
try:
|
2016-02-16 22:21:05 +03:00
|
|
|
newenv = dict(s.split('=', 1) for s in l)
|
2015-12-23 16:23:56 +03:00
|
|
|
except ValueError:
|
|
|
|
raise ValueError('unexpected value in setenv request')
|
2016-03-20 20:44:15 +03:00
|
|
|
_log('setenv: %r\n' % sorted(newenv.keys()))
|
2016-12-17 23:16:39 +03:00
|
|
|
encoding.environ.clear()
|
|
|
|
encoding.environ.update(newenv)
|
2015-12-23 16:23:56 +03:00
|
|
|
|
|
|
|
capabilities = commandserver.server.capabilities.copy()
|
|
|
|
capabilities.update({'attachio': attachio,
|
|
|
|
'chdir': chdir,
|
2016-12-16 17:48:37 +03:00
|
|
|
'runcommand': runcommand,
|
2016-02-15 17:28:17 +03:00
|
|
|
'setenv': setenv,
|
|
|
|
'setumask': setumask})
|
2015-12-23 16:23:56 +03:00
|
|
|
|
2017-01-11 02:36:48 +03:00
|
|
|
if util.safehasattr(osutil, 'setprocname'):
|
|
|
|
def setprocname(self):
|
|
|
|
"""Change process title"""
|
|
|
|
name = self._readstr()
|
|
|
|
_log('setprocname: %r\n' % name)
|
|
|
|
osutil.setprocname(name)
|
|
|
|
capabilities['setprocname'] = setprocname
|
|
|
|
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
def _tempaddress(address):
|
|
|
|
return '%s.%d.tmp' % (address, os.getpid())
|
|
|
|
|
2016-03-02 13:10:06 +03:00
|
|
|
def _hashaddress(address, hashstr):
|
2016-12-20 01:07:41 +03:00
|
|
|
# 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('.', 1)[0]
|
|
|
|
return '%s-%s' % (os.path.join(dirname, basename), hashstr)
|
2016-03-02 13:10:06 +03:00
|
|
|
|
2016-05-22 07:36:37 +03:00
|
|
|
class chgunixservicehandler(object):
|
|
|
|
"""Set of operations for chg services"""
|
|
|
|
|
|
|
|
pollinterval = 1 # [sec]
|
|
|
|
|
|
|
|
def __init__(self, ui):
|
|
|
|
self.ui = ui
|
2016-05-21 12:16:39 +03:00
|
|
|
self._idletimeout = ui.configint('chgserver', 'idletimeout', 3600)
|
|
|
|
self._lastactive = time.time()
|
2016-05-22 07:36:37 +03:00
|
|
|
|
|
|
|
def bindsocket(self, sock, address):
|
2016-05-22 08:06:37 +03:00
|
|
|
self._inithashstate(address)
|
2016-05-22 07:08:30 +03:00
|
|
|
self._checkextensions()
|
2016-05-22 07:36:37 +03:00
|
|
|
self._bind(sock)
|
2016-05-22 07:08:30 +03:00
|
|
|
self._createsymlink()
|
|
|
|
|
2016-05-22 08:06:37 +03:00
|
|
|
def _inithashstate(self, address):
|
2016-05-21 12:16:39 +03:00
|
|
|
self._baseaddress = address
|
2016-05-22 07:08:30 +03:00
|
|
|
if self.ui.configbool('chgserver', 'skiphash', False):
|
2016-05-21 12:16:39 +03:00
|
|
|
self._hashstate = None
|
|
|
|
self._realaddress = address
|
2016-05-22 07:08:30 +03:00
|
|
|
return
|
2016-05-21 12:16:39 +03:00
|
|
|
self._hashstate = hashstate.fromui(self.ui)
|
|
|
|
self._realaddress = _hashaddress(address, self._hashstate.confighash)
|
2016-05-22 07:08:30 +03:00
|
|
|
|
|
|
|
def _checkextensions(self):
|
2016-05-21 12:16:39 +03:00
|
|
|
if not self._hashstate:
|
2016-05-22 07:08:30 +03:00
|
|
|
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.
|
2016-05-21 12:16:39 +03:00
|
|
|
self._hashstate.mtimehash = ''
|
2016-05-22 07:08:30 +03:00
|
|
|
|
2016-05-22 07:36:37 +03:00
|
|
|
def _bind(self, sock):
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
# use a unique temp address so we can stat the file and do ownership
|
|
|
|
# check later
|
2016-05-21 12:16:39 +03:00
|
|
|
tempaddress = _tempaddress(self._realaddress)
|
2016-05-22 07:36:37 +03:00
|
|
|
util.bindunixsocket(sock, tempaddress)
|
2016-05-21 10:42:59 +03:00
|
|
|
self._socketstat = os.stat(tempaddress)
|
|
|
|
# rename will replace the old socket file if exists atomically. the
|
|
|
|
# old server will detect ownership change and exit.
|
2016-05-21 12:16:39 +03:00
|
|
|
util.rename(tempaddress, self._realaddress)
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
|
2016-05-22 08:05:34 +03:00
|
|
|
def _createsymlink(self):
|
2016-05-21 12:16:39 +03:00
|
|
|
if self._baseaddress == self._realaddress:
|
2016-05-22 08:05:34 +03:00
|
|
|
return
|
2016-05-21 12:16:39 +03:00
|
|
|
tempaddress = _tempaddress(self._baseaddress)
|
|
|
|
os.symlink(os.path.basename(self._realaddress), tempaddress)
|
|
|
|
util.rename(tempaddress, self._baseaddress)
|
2016-05-22 08:05:34 +03:00
|
|
|
|
2016-05-21 12:16:39 +03:00
|
|
|
def _issocketowner(self):
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
try:
|
2016-05-21 12:16:39 +03:00
|
|
|
stat = os.stat(self._realaddress)
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
return (stat.st_ino == self._socketstat.st_ino and
|
|
|
|
stat.st_mtime == self._socketstat.st_mtime)
|
|
|
|
except OSError:
|
|
|
|
return False
|
|
|
|
|
2016-05-22 07:36:37 +03:00
|
|
|
def unlinksocket(self, address):
|
2016-05-21 12:16:39 +03:00
|
|
|
if not self._issocketowner():
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
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.
|
|
|
|
try:
|
2016-05-21 12:16:39 +03:00
|
|
|
os.unlink(self._realaddress)
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
except OSError as exc:
|
|
|
|
if exc.errno != errno.ENOENT:
|
|
|
|
raise
|
|
|
|
|
2016-05-22 08:05:34 +03:00
|
|
|
def printbanner(self, address):
|
|
|
|
# no "listening at" message should be printed to simulate hg behavior
|
|
|
|
pass
|
|
|
|
|
|
|
|
def shouldexit(self):
|
2016-05-21 12:16:39 +03:00
|
|
|
if not self._issocketowner():
|
|
|
|
self.ui.debug('%s is not owned, exiting.\n' % self._realaddress)
|
2016-05-22 08:05:34 +03:00
|
|
|
return True
|
2016-05-21 12:16:39 +03:00
|
|
|
if time.time() - self._lastactive > self._idletimeout:
|
2016-05-22 08:05:34 +03:00
|
|
|
self.ui.debug('being idle too long. exiting.\n')
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def newconnection(self):
|
2016-05-21 12:16:39 +03:00
|
|
|
self._lastactive = time.time()
|
2016-05-22 08:05:34 +03:00
|
|
|
|
2016-05-22 07:36:37 +03:00
|
|
|
def createcmdserver(self, repo, conn, fin, fout):
|
|
|
|
return chgcmdserver(self.ui, repo, fin, fout, conn,
|
2016-05-21 12:16:39 +03:00
|
|
|
self._hashstate, self._baseaddress)
|
chgserver: auto exit after being idle for too long or lose the socket file
This is a part of the one server per config series. In multiple-server setup,
new server may be started for a temporary config change like in command line,
--config extensions.foo=bar.py. This may end up with a lot of not so useful
server processes. Other questions are about socket file and process management,
How to stop these processes? What if a new server wants to listen on a same
address, replacing the old one?
This patch introduces AutoExitMixIn, which will:
1. Exit after being idle for too long. So useless servers won't run forever.
2. Periodically check the ownership of socket file, exit if it is no longer
owned. This brings strong consistency between the filesystem and the
process, and handles some race conditions neatly.
Since rename is atomic, a new server can just have a same server address
with an old one and won't worry about how to make sure the old server is
killed, address conflict, service downtime issues.
The user can safely stop all servers by simply removing the socket files,
without worrying about outdated or accidentally removed pidfiles.
2016-02-24 21:42:59 +03:00
|
|
|
|
2016-05-22 07:13:04 +03:00
|
|
|
def chgunixservice(ui, repo, opts):
|
2016-10-15 08:24:29 +03:00
|
|
|
# CHGINTERNALMARK is temporarily set by chg client to detect if chg will
|
|
|
|
# start another chg. drop it to avoid possible side effects.
|
2016-12-17 23:16:39 +03:00
|
|
|
if 'CHGINTERNALMARK' in encoding.environ:
|
|
|
|
del encoding.environ['CHGINTERNALMARK']
|
2016-10-15 08:24:29 +03:00
|
|
|
|
2016-05-22 07:13:04 +03:00
|
|
|
if repo:
|
2016-10-18 00:16:55 +03:00
|
|
|
# one chgserver can serve multiple repos. drop repo information
|
2016-05-22 07:13:04 +03:00
|
|
|
ui.setconfig('bundle', 'mainreporoot', '', 'repo')
|
2016-05-22 07:36:37 +03:00
|
|
|
h = chgunixservicehandler(ui)
|
|
|
|
return commandserver.unixforkingservice(ui, repo=None, opts=opts, handler=h)
|