Source

chg / hgext / chgsupport.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# chgsupport - functionality to support 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.

"""functionality to support cHg

hg serve --cmdserver=unix
    communicate with cmdserver via unix domain socket

This extends channels and commands of cmdserver:

's'-channel
    handles util.system() request

'P'-channel
    handles getpass() request

'chdir' command
    change current directory

'getpager' command
    checks if pager is enabled and which pager should be executed

'getpid' command
    get process id of the server (worker, master)

'setchguiattr' command
    set initial value of ui attributes

'setenv' command
    replace os.environ completely

Configuration::

    [chg]
    maxworkers = 2    # the number of the worker processes which run cmdserver
    #maxrequests = n  # reload the worker after the specified num of requests
    #gcfreq = n       # run a full GC per the specified num of requests

If `maxworkers = 0`, it serves the worker functionality on the master process.
This mode is only available for debugging purpose.

`maxrequests = 1` may be useful if some extension changes global data and
causes unexpected behavior.
"""

import errno, gc, itertools, os, signal, socket, struct, tempfile
from mercurial import cmdutil, commands, commandserver, dispatch, encoding, \
                      error, extensions, i18n, scmutil, util
from mercurial.i18n import _

class channeledinput(commandserver.channeledinput):
    def readpass(self):
        return self._read(self.maxchunksize, 'P').rstrip('\n')

class channeledsystem(object):
    """Request to execute system() in the following format:

    command length (unsigned int),
    cmd

    and waits:

    exitcode length (unsigned int),
    exitcode (int)
    """
    def __init__(self, in_, out, channel):
        self.in_ = in_
        self.out = out
        self.channel = channel

    # copied from mercurial/util.py
    def __call__(self, cmd, environ={}, cwd=None, onerr=None, errprefix=None,
                 out=None):
        # XXX no support for environ, cwd and out

        origcmd = cmd
        cmd = util.quotecommand(cmd)

        self.out.write(struct.pack('>cI', self.channel, len(cmd)))
        self.out.write(cmd)
        self.out.flush()

        length = self.in_.read(4)
        length = struct.unpack('>I', length)[0]
        if length != 4:
            rc = 255
        else:
            rc = struct.unpack('>i', self.in_.read(4))[0]

        if rc and onerr:
            errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
                                util.explainexit(rc)[0])
            if errprefix:
                errmsg = '%s: %s' % (errprefix, errmsg)
            try:
                onerr.warn(errmsg + '\n')
            except AttributeError:
                raise onerr(errmsg)
        return rc

class nulldirstate(object):
    pass

class nullrepo(object):
    def __init__(self, baseui):
        self.baseui = baseui
        self.ui = baseui.copy()
        self.dirstate = nulldirstate()

    def invalidate(self):
        pass

    def invalidatedirstate(self):
        pass

    def __nonzero__(self):
        return False

_envmodstoreload = [
    # recreate gettext 't' by reloading i18n
    ('LANG LANGUAGE LC_MESSAGES'.split(), [encoding, i18n]),
    ('HGENCODING HGENCODINGMODE HGENCODINGAMBIGUOUS'.split(), [encoding]),
    ]

def _listmodstoreload(newenv):
    """List modules must be reloaded after os.environ change"""
    toreload = set()
    for envkeys, mods in _envmodstoreload:
        if util.any(newenv.get(k) != os.environ.get(k) for k in envkeys):
            toreload.update(mods)
    return toreload

def _fixdefaultencoding():
    """Apply new default encoding to commands table"""
    newdefaults = {'encoding': encoding.encoding,
                   'encodingmode': encoding.encodingmode}
    for i, opt in enumerate(commands.globalopts):
        name = opt[1]
        newdef = newdefaults.get(name)
        if newdef is not None:
            commands.globalopts[i] = opt[:2] + (newdef,) + opt[3:]

class chgcmdserver(commandserver.server):
    def __init__(self, sui, ui, repo, fin, fout, masterpid):
        super(chgcmdserver, self).__init__(ui, repo, mode='pipe')
        self._sui = sui  # ui for server output
        self.cerr = commandserver.channeledoutput(fout, fout, 'e')
        self.cout = commandserver.channeledoutput(fout, fout, 'o')
        self.cin = channeledinput(fin, fout, 'I')
        self.cresult = commandserver.channeledoutput(fout, fout, 'r')
        self.csystem = channeledsystem(fin, fout, 's')
        self.client = fin
        self._masterpid = masterpid

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

        Note that the behavior of --cwd option is bit different from this.
        It does not affect --config parameter.
        """
        length = struct.unpack('>I', self._read(4))[0]
        if not length:
            return
        path = self._read(length)
        self._sui.debug('chdir to %r\n' % path)
        os.chdir(path)

    def getpager(self):
        """Read cmdargs and write pager command to r-channel if enabled

        If pager isn't enabled, this writes '\0' because channeledoutput
        does not allow to write empty data.
        """
        length = struct.unpack('>I', self._read(4))[0]
        if not length:
            args = []
        else:
            args = self._read(length).split('\0')

        try:
            pagermod = extensions.find('pager')
        except KeyError:
            self.cresult.write('\0')
            return

        pagercmd = self.ui.config('pager', 'pager', os.environ.get('PAGER'))
        if not pagercmd:
            self.cresult.write('\0')
            return

        try:
            cmd, _func, args, options, _cmdoptions = dispatch._parse(self.ui,
                                                                     args)
        except (error.AmbiguousCommand, error.CommandError,
                error.UnknownCommand):
            self.cresult.write('\0')
            return

        # duplicated from hgext/pager.py
        attend = self.ui.configlist('pager', 'attend', pagermod.attended)
        auto = options['pager'] == 'auto'
        always = util.parsebool(options['pager'])
        if (always or auto and
            (cmd in attend or
             (cmd not in self.ui.configlist('pager', 'ignore')
              and not attend))):
            self.cresult.write(pagercmd)
        else:
            self.cresult.write('\0')

    def getpid(self):
        """Write pid of the server (worker, master)"""
        self.cresult.write(struct.pack('>ii', os.getpid(), self._masterpid))

    def setchguiattr(self):
        """Set ui attributes if not configured"""
        length = struct.unpack('>I', self._read(4))[0]
        if not length:
            return
        s = self._read(length)
        for l in s.splitlines():
            k, v = l.split(': ', 1)
            if self.ui.config('ui', k) is None:
                self._sui.debug('set ui %r: %r\n' % (k, v))
                self.ui.setconfig('ui', k, v)

        # reload config so that ui.plain() takes effect
        for f in scmutil.rcpath():
            self.ui.readconfig(f, trust=True)

        # skip initial uisetup() by 'mode=chgauto'
        if self.ui.config('color', 'mode') == 'chgauto':
            self.ui.setconfig('color', 'mode', 'auto')

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

        Note that not all variables can make an effect on the running process.
        """
        length = struct.unpack('>I', self._read(4))[0]
        if not length:
            return
        s = self._read(length)
        try:
            newenv = dict(l.split('=', 1) for l in s.split('\0'))
        except ValueError:
            raise ValueError('unexpected value in setenv request')

        modstoreload = _listmodstoreload(newenv)

        if self._sui.debugflag:
            for k in sorted(set(os.environ.keys() + newenv.keys())):
                ov, nv = os.environ.get(k), newenv.get(k)
                if ov != nv:
                    self._sui.debug('change env %r: %r -> %r\n' % (k, ov, nv))
        os.environ.clear()
        os.environ.update(newenv)

        for mod in modstoreload:
            self._sui.debug('reload %s module\n' % mod.__name__)
            reload(mod)
        if encoding in modstoreload:
            _fixdefaultencoding()

    capabilities = commandserver.server.capabilities.copy()
    capabilities.update({'chdir': chdir,
                         'getpager': getpager,
                         'getpid': getpid,
                         'setchguiattr': setchguiattr,
                         'setenv': setenv})

def _wrapui(ui):
    class chgui(ui.__class__):
        csystem = None  # should be assigned later

        def copy(self):
            o = super(chgui, self).copy()
            o.csystem = self.csystem
            return o

        def termwidth(self):
            n = self.configint('ui', '_termwidth')
            if n and n > 0:
                return n
            else:
                return super(chgui, self).termwidth()

        # copied from mercurial/ui.py
        def edit(self, text, user):
            (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
                                          text=True)
            try:
                f = os.fdopen(fd, "w")
                f.write(text)
                f.close()

                editor = self.geteditor()

                self.csystem("%s \"%s\"" % (editor, name),
                             environ={'HGUSER': user},
                             onerr=util.Abort, errprefix=_("edit failed"),
                             out=self.fout)

                f = open(name)
                t = f.read()
                f.close()
            finally:
                os.unlink(name)

            return t

        # copied from mercurial/ui.py
        def getpass(self, prompt=None, default=None):
            if not self.interactive():
                return default
            try:
                self.fout.write(prompt or _('password: '))
                self.fout.flush()
                return self.fin.readpass()
            except EOFError:
                raise util.Abort(_('response expected'))

        # copied from mercurial/ui.py
        def plain(self, feature=None):
            plain = self.configbool('ui', '_plain')
            plainexcept = self.configlist('ui', '_plainexcept')
            if not plain and not plainexcept:
                return False
            if feature and plainexcept:
                return feature not in plainexcept
            return True

    ui.__class__ = chgui

class TaintedWorkerError(error.Abort):
    pass

class service(object):
    """Prefork server for handling connection from cHg client"""
    def __init__(self, ui, sockpath):
        self._ui = ui
        self._sockpath = sockpath
        self._maxworkers = self._ui.configint('chg', 'maxworkers', 2)
        self._maxrequests = self._ui.configint('chg', 'maxrequests')
        self._gcfreq = self._ui.configint('chg', 'gcfreq')

    def init(self):
        util.setsignalhandler()
        self._sock = socket.socket(socket.AF_UNIX)
        self._sock.bind(self._sockpath)

    def run(self):
        self._sock.listen(1)
        self._masterpid = os.getpid()
        self._ui.note(_('listening at %s (pid=%d)\n')
                      % (self._sockpath, self._masterpid))

        self._workerpids = []
        master = self._maxworkers > 0
        try:
            try:
                while master:
                    master = self._servemaster()
                if not master:
                    self._initworkerui()
                    for n in itertools.count(1):
                        self._serveworker(n)
            except (error.SignalInterrupt, KeyboardInterrupt):
                if master:
                    self._killworkers()
        finally:
            self._sock.close()
            if os.getpid() == self._masterpid:
                os.unlink(self._sockpath)

    def _servemaster(self):
        for _i in xrange(self._maxworkers - len(self._workerpids)):
            pid = os.fork()
            if pid == 0:
                return False
            self._ui.debug('forked worker process (pid=%d)\n' % pid)
            self._workerpids.append(pid)

        pid, _status = os.wait()
        self._workerpids.remove(pid)
        return True

    def _killworkers(self):
        for pid in self._workerpids:
            self._ui.debug('terminate worker process (pid=%d)\n' % pid)
            os.kill(pid, signal.SIGTERM)

        try:
            while self._workerpids:
                pid, _status = os.wait()
                self._workerpids.remove(pid)
            self._ui.debug('terminated all worker processes\n')
        except OSError, err:
            if err.errno != errno.ECHILD:
                raise
            self._ui.debug('got ECHILD while terminating worker processes\n')

    def _initworkerui(self):
        self._workerui = self._ui.copy()
        # don't retain command-line opts of the service
        for opt in ('verbose', 'debug', 'quiet', 'traceback'):
            self._workerui.setconfig('ui', opt, None)
        self._workerui.fixconfig()
        _wrapui(self._workerui)

    def _serveworker(self, nreqs):
        conn, _addr = self._sock.accept()
        try:
            self._ui.note('accepted connection (pid=%d, nreqs=%d)\n'
                          % (os.getpid(), nreqs))
            fin = conn.makefile('rb')
            fout = conn.makefile('wb')
            try:
                self._runcmdserver(fin, fout)
            finally:
                fin.close()
                # implicit flush() may cause another EPIPE
                try:
                    fout.close()
                except IOError, err:
                    if err.errno != errno.EPIPE:
                        raise
        finally:
            conn.close()

        if nreqs == self._maxrequests:
            raise TaintedWorkerError('served %d requests' % nreqs)
        if self._gcfreq and nreqs % self._gcfreq == 0:
            found = gc.collect()
            self._ui.debug('collected %d unreachable objects (pid=%d)\n'
                           % (found, os.getpid()))

    def _runcmdserver(self, fin, fout):
        ui = self._workerui.copy()
        sv = chgcmdserver(self._ui, ui, nullrepo(ui), fin, fout,
                          masterpid=self._masterpid)
        ui.csystem = sv.csystem

        origcwd = os.getcwd()
        origcmdcnt = len(commands.table)
        origextcnt = len(extensions._extensions)
        try:
            try:
                sv.serve()
                self._ui.debug('finished (pid=%d)\n' % os.getpid())
            except IOError, err:
                if err.errno == errno.EPIPE:
                    self._ui.debug('finished by broken pipe (pid=%d)\n'
                                   % os.getpid())
                else:
                    raise
        finally:
            os.chdir(origcwd)
        if origcmdcnt != len(commands.table):
            raise TaintedWorkerError('loaded local command or alias')
        if origextcnt != len(extensions._extensions):
            raise TaintedWorkerError('loaded local extension')
        if _extensionsloadedbypath:
            raise TaintedWorkerError('loaded unwanted extension')

def _disablepager():
    try:
        pagermod = extensions.find('pager')
    except KeyError:
        return
    # _runpager(p) or _runpager(ui, p)
    extensions.wrapfunction(pagermod, '_runpager', lambda orig, *args: None)

# extensions.disabledcmd() uses .loadpath(), but .loadpath() does not
# remember loaded extension in _extensions list. Since bad-mannered extension
# may mangle global object, we need to restart cmdserver process even if
# uisetup() or extsetup() is not called.
_extensionsloadedbypath = False
def _extensionsloadpath(orig, path, module_name):
    global _extensionsloadedbypath
    ext = orig(path, module_name)
    _extensionsloadedbypath = True
    return ext

def _serve(orig, ui, repo, **opts):
    mode = opts['cmdserver']
    if not mode or mode != 'unix':
        return orig(ui, repo, **opts)

    _disablepager()
    extensions.wrapfunction(extensions, 'loadpath', _extensionsloadpath)

    # it might be confusing to reuse --port option
    sockpath = opts['port']
    if not sockpath:
        raise util.Abort(_('no socket path specified with --port'))

    svc = service(ui, sockpath)
    cmdutil.service(opts, initfn=svc.init, runfn=svc.run)

def uisetup(ui):
    extensions.wrapcommand(commands.table, 'serve', _serve)