##// END OF EJS Templates
chg: suppress OSError in _restoreio() and add some logging (issue6330)...
Pulkit Goyal -
r45575:6118408b default draft
parent child Browse files
Show More
@@ -1,718 +1,731 b''
1 # chgserver.py - command server extension for cHg
1 # chgserver.py - command server extension for cHg
2 #
2 #
3 # Copyright 2011 Yuya Nishihara <yuya@tcha.org>
3 # Copyright 2011 Yuya Nishihara <yuya@tcha.org>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 """command server extension for cHg
8 """command server extension for cHg
9
9
10 'S' channel (read/write)
10 'S' channel (read/write)
11 propagate ui.system() request to client
11 propagate ui.system() request to client
12
12
13 'attachio' command
13 'attachio' command
14 attach client's stdio passed by sendmsg()
14 attach client's stdio passed by sendmsg()
15
15
16 'chdir' command
16 'chdir' command
17 change current directory
17 change current directory
18
18
19 'setenv' command
19 'setenv' command
20 replace os.environ completely
20 replace os.environ completely
21
21
22 'setumask' command (DEPRECATED)
22 'setumask' command (DEPRECATED)
23 'setumask2' command
23 'setumask2' command
24 set umask
24 set umask
25
25
26 'validate' command
26 'validate' command
27 reload the config and check if the server is up to date
27 reload the config and check if the server is up to date
28
28
29 Config
29 Config
30 ------
30 ------
31
31
32 ::
32 ::
33
33
34 [chgserver]
34 [chgserver]
35 # how long (in seconds) should an idle chg server exit
35 # how long (in seconds) should an idle chg server exit
36 idletimeout = 3600
36 idletimeout = 3600
37
37
38 # whether to skip config or env change checks
38 # whether to skip config or env change checks
39 skiphash = False
39 skiphash = False
40 """
40 """
41
41
42 from __future__ import absolute_import
42 from __future__ import absolute_import
43
43
44 import inspect
44 import inspect
45 import os
45 import os
46 import re
46 import re
47 import socket
47 import socket
48 import stat
48 import stat
49 import struct
49 import struct
50 import time
50 import time
51
51
52 from .i18n import _
52 from .i18n import _
53 from .pycompat import (
53 from .pycompat import (
54 getattr,
54 getattr,
55 setattr,
55 setattr,
56 )
56 )
57
57
58 from . import (
58 from . import (
59 commandserver,
59 commandserver,
60 encoding,
60 encoding,
61 error,
61 error,
62 extensions,
62 extensions,
63 node,
63 node,
64 pycompat,
64 pycompat,
65 util,
65 util,
66 )
66 )
67
67
68 from .utils import (
68 from .utils import (
69 hashutil,
69 hashutil,
70 procutil,
70 procutil,
71 stringutil,
71 stringutil,
72 )
72 )
73
73
74
74
75 def _hashlist(items):
75 def _hashlist(items):
76 """return sha1 hexdigest for a list"""
76 """return sha1 hexdigest for a list"""
77 return node.hex(hashutil.sha1(stringutil.pprint(items)).digest())
77 return node.hex(hashutil.sha1(stringutil.pprint(items)).digest())
78
78
79
79
80 # sensitive config sections affecting confighash
80 # sensitive config sections affecting confighash
81 _configsections = [
81 _configsections = [
82 b'alias', # affects global state commands.table
82 b'alias', # affects global state commands.table
83 b'diff-tools', # affects whether gui or not in extdiff's uisetup
83 b'diff-tools', # affects whether gui or not in extdiff's uisetup
84 b'eol', # uses setconfig('eol', ...)
84 b'eol', # uses setconfig('eol', ...)
85 b'extdiff', # uisetup will register new commands
85 b'extdiff', # uisetup will register new commands
86 b'extensions',
86 b'extensions',
87 b'fastannotate', # affects annotate command and adds fastannonate cmd
87 b'fastannotate', # affects annotate command and adds fastannonate cmd
88 b'merge-tools', # affects whether gui or not in extdiff's uisetup
88 b'merge-tools', # affects whether gui or not in extdiff's uisetup
89 b'schemes', # extsetup will update global hg.schemes
89 b'schemes', # extsetup will update global hg.schemes
90 ]
90 ]
91
91
92 _configsectionitems = [
92 _configsectionitems = [
93 (b'commands', b'show.aliasprefix'), # show.py reads it in extsetup
93 (b'commands', b'show.aliasprefix'), # show.py reads it in extsetup
94 ]
94 ]
95
95
96 # sensitive environment variables affecting confighash
96 # sensitive environment variables affecting confighash
97 _envre = re.compile(
97 _envre = re.compile(
98 br'''\A(?:
98 br'''\A(?:
99 CHGHG
99 CHGHG
100 |HG(?:DEMANDIMPORT|EMITWARNINGS|MODULEPOLICY|PROF|RCPATH)?
100 |HG(?:DEMANDIMPORT|EMITWARNINGS|MODULEPOLICY|PROF|RCPATH)?
101 |HG(?:ENCODING|PLAIN).*
101 |HG(?:ENCODING|PLAIN).*
102 |LANG(?:UAGE)?
102 |LANG(?:UAGE)?
103 |LC_.*
103 |LC_.*
104 |LD_.*
104 |LD_.*
105 |PATH
105 |PATH
106 |PYTHON.*
106 |PYTHON.*
107 |TERM(?:INFO)?
107 |TERM(?:INFO)?
108 |TZ
108 |TZ
109 )\Z''',
109 )\Z''',
110 re.X,
110 re.X,
111 )
111 )
112
112
113
113
114 def _confighash(ui):
114 def _confighash(ui):
115 """return a quick hash for detecting config/env changes
115 """return a quick hash for detecting config/env changes
116
116
117 confighash is the hash of sensitive config items and environment variables.
117 confighash is the hash of sensitive config items and environment variables.
118
118
119 for chgserver, it is designed that once confighash changes, the server is
119 for chgserver, it is designed that once confighash changes, the server is
120 not qualified to serve its client and should redirect the client to a new
120 not qualified to serve its client and should redirect the client to a new
121 server. different from mtimehash, confighash change will not mark the
121 server. different from mtimehash, confighash change will not mark the
122 server outdated and exit since the user can have different configs at the
122 server outdated and exit since the user can have different configs at the
123 same time.
123 same time.
124 """
124 """
125 sectionitems = []
125 sectionitems = []
126 for section in _configsections:
126 for section in _configsections:
127 sectionitems.append(ui.configitems(section))
127 sectionitems.append(ui.configitems(section))
128 for section, item in _configsectionitems:
128 for section, item in _configsectionitems:
129 sectionitems.append(ui.config(section, item))
129 sectionitems.append(ui.config(section, item))
130 sectionhash = _hashlist(sectionitems)
130 sectionhash = _hashlist(sectionitems)
131 # If $CHGHG is set, the change to $HG should not trigger a new chg server
131 # If $CHGHG is set, the change to $HG should not trigger a new chg server
132 if b'CHGHG' in encoding.environ:
132 if b'CHGHG' in encoding.environ:
133 ignored = {b'HG'}
133 ignored = {b'HG'}
134 else:
134 else:
135 ignored = set()
135 ignored = set()
136 envitems = [
136 envitems = [
137 (k, v)
137 (k, v)
138 for k, v in pycompat.iteritems(encoding.environ)
138 for k, v in pycompat.iteritems(encoding.environ)
139 if _envre.match(k) and k not in ignored
139 if _envre.match(k) and k not in ignored
140 ]
140 ]
141 envhash = _hashlist(sorted(envitems))
141 envhash = _hashlist(sorted(envitems))
142 return sectionhash[:6] + envhash[:6]
142 return sectionhash[:6] + envhash[:6]
143
143
144
144
145 def _getmtimepaths(ui):
145 def _getmtimepaths(ui):
146 """get a list of paths that should be checked to detect change
146 """get a list of paths that should be checked to detect change
147
147
148 The list will include:
148 The list will include:
149 - extensions (will not cover all files for complex extensions)
149 - extensions (will not cover all files for complex extensions)
150 - mercurial/__version__.py
150 - mercurial/__version__.py
151 - python binary
151 - python binary
152 """
152 """
153 modules = [m for n, m in extensions.extensions(ui)]
153 modules = [m for n, m in extensions.extensions(ui)]
154 try:
154 try:
155 from . import __version__
155 from . import __version__
156
156
157 modules.append(__version__)
157 modules.append(__version__)
158 except ImportError:
158 except ImportError:
159 pass
159 pass
160 files = []
160 files = []
161 if pycompat.sysexecutable:
161 if pycompat.sysexecutable:
162 files.append(pycompat.sysexecutable)
162 files.append(pycompat.sysexecutable)
163 for m in modules:
163 for m in modules:
164 try:
164 try:
165 files.append(pycompat.fsencode(inspect.getabsfile(m)))
165 files.append(pycompat.fsencode(inspect.getabsfile(m)))
166 except TypeError:
166 except TypeError:
167 pass
167 pass
168 return sorted(set(files))
168 return sorted(set(files))
169
169
170
170
171 def _mtimehash(paths):
171 def _mtimehash(paths):
172 """return a quick hash for detecting file changes
172 """return a quick hash for detecting file changes
173
173
174 mtimehash calls stat on given paths and calculate a hash based on size and
174 mtimehash calls stat on given paths and calculate a hash based on size and
175 mtime of each file. mtimehash does not read file content because reading is
175 mtime of each file. mtimehash does not read file content because reading is
176 expensive. therefore it's not 100% reliable for detecting content changes.
176 expensive. therefore it's not 100% reliable for detecting content changes.
177 it's possible to return different hashes for same file contents.
177 it's possible to return different hashes for same file contents.
178 it's also possible to return a same hash for different file contents for
178 it's also possible to return a same hash for different file contents for
179 some carefully crafted situation.
179 some carefully crafted situation.
180
180
181 for chgserver, it is designed that once mtimehash changes, the server is
181 for chgserver, it is designed that once mtimehash changes, the server is
182 considered outdated immediately and should no longer provide service.
182 considered outdated immediately and should no longer provide service.
183
183
184 mtimehash is not included in confighash because we only know the paths of
184 mtimehash is not included in confighash because we only know the paths of
185 extensions after importing them (there is imp.find_module but that faces
185 extensions after importing them (there is imp.find_module but that faces
186 race conditions). We need to calculate confighash without importing.
186 race conditions). We need to calculate confighash without importing.
187 """
187 """
188
188
189 def trystat(path):
189 def trystat(path):
190 try:
190 try:
191 st = os.stat(path)
191 st = os.stat(path)
192 return (st[stat.ST_MTIME], st.st_size)
192 return (st[stat.ST_MTIME], st.st_size)
193 except OSError:
193 except OSError:
194 # could be ENOENT, EPERM etc. not fatal in any case
194 # could be ENOENT, EPERM etc. not fatal in any case
195 pass
195 pass
196
196
197 return _hashlist(pycompat.maplist(trystat, paths))[:12]
197 return _hashlist(pycompat.maplist(trystat, paths))[:12]
198
198
199
199
200 class hashstate(object):
200 class hashstate(object):
201 """a structure storing confighash, mtimehash, paths used for mtimehash"""
201 """a structure storing confighash, mtimehash, paths used for mtimehash"""
202
202
203 def __init__(self, confighash, mtimehash, mtimepaths):
203 def __init__(self, confighash, mtimehash, mtimepaths):
204 self.confighash = confighash
204 self.confighash = confighash
205 self.mtimehash = mtimehash
205 self.mtimehash = mtimehash
206 self.mtimepaths = mtimepaths
206 self.mtimepaths = mtimepaths
207
207
208 @staticmethod
208 @staticmethod
209 def fromui(ui, mtimepaths=None):
209 def fromui(ui, mtimepaths=None):
210 if mtimepaths is None:
210 if mtimepaths is None:
211 mtimepaths = _getmtimepaths(ui)
211 mtimepaths = _getmtimepaths(ui)
212 confighash = _confighash(ui)
212 confighash = _confighash(ui)
213 mtimehash = _mtimehash(mtimepaths)
213 mtimehash = _mtimehash(mtimepaths)
214 ui.log(
214 ui.log(
215 b'cmdserver',
215 b'cmdserver',
216 b'confighash = %s mtimehash = %s\n',
216 b'confighash = %s mtimehash = %s\n',
217 confighash,
217 confighash,
218 mtimehash,
218 mtimehash,
219 )
219 )
220 return hashstate(confighash, mtimehash, mtimepaths)
220 return hashstate(confighash, mtimehash, mtimepaths)
221
221
222
222
223 def _newchgui(srcui, csystem, attachio):
223 def _newchgui(srcui, csystem, attachio):
224 class chgui(srcui.__class__):
224 class chgui(srcui.__class__):
225 def __init__(self, src=None):
225 def __init__(self, src=None):
226 super(chgui, self).__init__(src)
226 super(chgui, self).__init__(src)
227 if src:
227 if src:
228 self._csystem = getattr(src, '_csystem', csystem)
228 self._csystem = getattr(src, '_csystem', csystem)
229 else:
229 else:
230 self._csystem = csystem
230 self._csystem = csystem
231
231
232 def _runsystem(self, cmd, environ, cwd, out):
232 def _runsystem(self, cmd, environ, cwd, out):
233 # fallback to the original system method if
233 # fallback to the original system method if
234 # a. the output stream is not stdout (e.g. stderr, cStringIO),
234 # a. the output stream is not stdout (e.g. stderr, cStringIO),
235 # b. or stdout is redirected by protectfinout(),
235 # b. or stdout is redirected by protectfinout(),
236 # because the chg client is not aware of these situations and
236 # because the chg client is not aware of these situations and
237 # will behave differently (i.e. write to stdout).
237 # will behave differently (i.e. write to stdout).
238 if (
238 if (
239 out is not self.fout
239 out is not self.fout
240 or not util.safehasattr(self.fout, b'fileno')
240 or not util.safehasattr(self.fout, b'fileno')
241 or self.fout.fileno() != procutil.stdout.fileno()
241 or self.fout.fileno() != procutil.stdout.fileno()
242 or self._finoutredirected
242 or self._finoutredirected
243 ):
243 ):
244 return procutil.system(cmd, environ=environ, cwd=cwd, out=out)
244 return procutil.system(cmd, environ=environ, cwd=cwd, out=out)
245 self.flush()
245 self.flush()
246 return self._csystem(cmd, procutil.shellenviron(environ), cwd)
246 return self._csystem(cmd, procutil.shellenviron(environ), cwd)
247
247
248 def _runpager(self, cmd, env=None):
248 def _runpager(self, cmd, env=None):
249 self._csystem(
249 self._csystem(
250 cmd,
250 cmd,
251 procutil.shellenviron(env),
251 procutil.shellenviron(env),
252 type=b'pager',
252 type=b'pager',
253 cmdtable={b'attachio': attachio},
253 cmdtable={b'attachio': attachio},
254 )
254 )
255 return True
255 return True
256
256
257 return chgui(srcui)
257 return chgui(srcui)
258
258
259
259
260 def _loadnewui(srcui, args, cdebug):
260 def _loadnewui(srcui, args, cdebug):
261 from . import dispatch # avoid cycle
261 from . import dispatch # avoid cycle
262
262
263 newui = srcui.__class__.load()
263 newui = srcui.__class__.load()
264 for a in [b'fin', b'fout', b'ferr', b'environ']:
264 for a in [b'fin', b'fout', b'ferr', b'environ']:
265 setattr(newui, a, getattr(srcui, a))
265 setattr(newui, a, getattr(srcui, a))
266 if util.safehasattr(srcui, b'_csystem'):
266 if util.safehasattr(srcui, b'_csystem'):
267 newui._csystem = srcui._csystem
267 newui._csystem = srcui._csystem
268
268
269 # command line args
269 # command line args
270 options = dispatch._earlyparseopts(newui, args)
270 options = dispatch._earlyparseopts(newui, args)
271 dispatch._parseconfig(newui, options[b'config'])
271 dispatch._parseconfig(newui, options[b'config'])
272
272
273 # stolen from tortoisehg.util.copydynamicconfig()
273 # stolen from tortoisehg.util.copydynamicconfig()
274 for section, name, value in srcui.walkconfig():
274 for section, name, value in srcui.walkconfig():
275 source = srcui.configsource(section, name)
275 source = srcui.configsource(section, name)
276 if b':' in source or source == b'--config' or source.startswith(b'$'):
276 if b':' in source or source == b'--config' or source.startswith(b'$'):
277 # path:line or command line, or environ
277 # path:line or command line, or environ
278 continue
278 continue
279 newui.setconfig(section, name, value, source)
279 newui.setconfig(section, name, value, source)
280
280
281 # load wd and repo config, copied from dispatch.py
281 # load wd and repo config, copied from dispatch.py
282 cwd = options[b'cwd']
282 cwd = options[b'cwd']
283 cwd = cwd and os.path.realpath(cwd) or None
283 cwd = cwd and os.path.realpath(cwd) or None
284 rpath = options[b'repository']
284 rpath = options[b'repository']
285 path, newlui = dispatch._getlocal(newui, rpath, wd=cwd)
285 path, newlui = dispatch._getlocal(newui, rpath, wd=cwd)
286
286
287 extensions.populateui(newui)
287 extensions.populateui(newui)
288 commandserver.setuplogging(newui, fp=cdebug)
288 commandserver.setuplogging(newui, fp=cdebug)
289 if newui is not newlui:
289 if newui is not newlui:
290 extensions.populateui(newlui)
290 extensions.populateui(newlui)
291 commandserver.setuplogging(newlui, fp=cdebug)
291 commandserver.setuplogging(newlui, fp=cdebug)
292
292
293 return (newui, newlui)
293 return (newui, newlui)
294
294
295
295
296 class channeledsystem(object):
296 class channeledsystem(object):
297 """Propagate ui.system() request in the following format:
297 """Propagate ui.system() request in the following format:
298
298
299 payload length (unsigned int),
299 payload length (unsigned int),
300 type, '\0',
300 type, '\0',
301 cmd, '\0',
301 cmd, '\0',
302 cwd, '\0',
302 cwd, '\0',
303 envkey, '=', val, '\0',
303 envkey, '=', val, '\0',
304 ...
304 ...
305 envkey, '=', val
305 envkey, '=', val
306
306
307 if type == 'system', waits for:
307 if type == 'system', waits for:
308
308
309 exitcode length (unsigned int),
309 exitcode length (unsigned int),
310 exitcode (int)
310 exitcode (int)
311
311
312 if type == 'pager', repetitively waits for a command name ending with '\n'
312 if type == 'pager', repetitively waits for a command name ending with '\n'
313 and executes it defined by cmdtable, or exits the loop if the command name
313 and executes it defined by cmdtable, or exits the loop if the command name
314 is empty.
314 is empty.
315 """
315 """
316
316
317 def __init__(self, in_, out, channel):
317 def __init__(self, in_, out, channel):
318 self.in_ = in_
318 self.in_ = in_
319 self.out = out
319 self.out = out
320 self.channel = channel
320 self.channel = channel
321
321
322 def __call__(self, cmd, environ, cwd=None, type=b'system', cmdtable=None):
322 def __call__(self, cmd, environ, cwd=None, type=b'system', cmdtable=None):
323 args = [type, cmd, os.path.abspath(cwd or b'.')]
323 args = [type, cmd, os.path.abspath(cwd or b'.')]
324 args.extend(b'%s=%s' % (k, v) for k, v in pycompat.iteritems(environ))
324 args.extend(b'%s=%s' % (k, v) for k, v in pycompat.iteritems(environ))
325 data = b'\0'.join(args)
325 data = b'\0'.join(args)
326 self.out.write(struct.pack(b'>cI', self.channel, len(data)))
326 self.out.write(struct.pack(b'>cI', self.channel, len(data)))
327 self.out.write(data)
327 self.out.write(data)
328 self.out.flush()
328 self.out.flush()
329
329
330 if type == b'system':
330 if type == b'system':
331 length = self.in_.read(4)
331 length = self.in_.read(4)
332 (length,) = struct.unpack(b'>I', length)
332 (length,) = struct.unpack(b'>I', length)
333 if length != 4:
333 if length != 4:
334 raise error.Abort(_(b'invalid response'))
334 raise error.Abort(_(b'invalid response'))
335 (rc,) = struct.unpack(b'>i', self.in_.read(4))
335 (rc,) = struct.unpack(b'>i', self.in_.read(4))
336 return rc
336 return rc
337 elif type == b'pager':
337 elif type == b'pager':
338 while True:
338 while True:
339 cmd = self.in_.readline()[:-1]
339 cmd = self.in_.readline()[:-1]
340 if not cmd:
340 if not cmd:
341 break
341 break
342 if cmdtable and cmd in cmdtable:
342 if cmdtable and cmd in cmdtable:
343 cmdtable[cmd]()
343 cmdtable[cmd]()
344 else:
344 else:
345 raise error.Abort(_(b'unexpected command: %s') % cmd)
345 raise error.Abort(_(b'unexpected command: %s') % cmd)
346 else:
346 else:
347 raise error.ProgrammingError(b'invalid S channel type: %s' % type)
347 raise error.ProgrammingError(b'invalid S channel type: %s' % type)
348
348
349
349
350 _iochannels = [
350 _iochannels = [
351 # server.ch, ui.fp, mode
351 # server.ch, ui.fp, mode
352 (b'cin', b'fin', 'rb'),
352 (b'cin', b'fin', 'rb'),
353 (b'cout', b'fout', 'wb'),
353 (b'cout', b'fout', 'wb'),
354 (b'cerr', b'ferr', 'wb'),
354 (b'cerr', b'ferr', 'wb'),
355 ]
355 ]
356
356
357
357
358 class chgcmdserver(commandserver.server):
358 class chgcmdserver(commandserver.server):
359 def __init__(
359 def __init__(
360 self, ui, repo, fin, fout, sock, prereposetups, hashstate, baseaddress
360 self, ui, repo, fin, fout, sock, prereposetups, hashstate, baseaddress
361 ):
361 ):
362 super(chgcmdserver, self).__init__(
362 super(chgcmdserver, self).__init__(
363 _newchgui(ui, channeledsystem(fin, fout, b'S'), self.attachio),
363 _newchgui(ui, channeledsystem(fin, fout, b'S'), self.attachio),
364 repo,
364 repo,
365 fin,
365 fin,
366 fout,
366 fout,
367 prereposetups,
367 prereposetups,
368 )
368 )
369 self.clientsock = sock
369 self.clientsock = sock
370 self._ioattached = False
370 self._ioattached = False
371 self._oldios = [] # original (self.ch, ui.fp, fd) before "attachio"
371 self._oldios = [] # original (self.ch, ui.fp, fd) before "attachio"
372 self.hashstate = hashstate
372 self.hashstate = hashstate
373 self.baseaddress = baseaddress
373 self.baseaddress = baseaddress
374 if hashstate is not None:
374 if hashstate is not None:
375 self.capabilities = self.capabilities.copy()
375 self.capabilities = self.capabilities.copy()
376 self.capabilities[b'validate'] = chgcmdserver.validate
376 self.capabilities[b'validate'] = chgcmdserver.validate
377
377
378 def cleanup(self):
378 def cleanup(self):
379 super(chgcmdserver, self).cleanup()
379 super(chgcmdserver, self).cleanup()
380 # dispatch._runcatch() does not flush outputs if exception is not
380 # dispatch._runcatch() does not flush outputs if exception is not
381 # handled by dispatch._dispatch()
381 # handled by dispatch._dispatch()
382 self.ui.flush()
382 self.ui.flush()
383 self._restoreio()
383 self._restoreio()
384 self._ioattached = False
384 self._ioattached = False
385
385
386 def attachio(self):
386 def attachio(self):
387 """Attach to client's stdio passed via unix domain socket; all
387 """Attach to client's stdio passed via unix domain socket; all
388 channels except cresult will no longer be used
388 channels except cresult will no longer be used
389 """
389 """
390 # tell client to sendmsg() with 1-byte payload, which makes it
390 # tell client to sendmsg() with 1-byte payload, which makes it
391 # distinctive from "attachio\n" command consumed by client.read()
391 # distinctive from "attachio\n" command consumed by client.read()
392 self.clientsock.sendall(struct.pack(b'>cI', b'I', 1))
392 self.clientsock.sendall(struct.pack(b'>cI', b'I', 1))
393 clientfds = util.recvfds(self.clientsock.fileno())
393 clientfds = util.recvfds(self.clientsock.fileno())
394 self.ui.log(b'chgserver', b'received fds: %r\n', clientfds)
394 self.ui.log(b'chgserver', b'received fds: %r\n', clientfds)
395
395
396 ui = self.ui
396 ui = self.ui
397 ui.flush()
397 ui.flush()
398 self._saveio()
398 self._saveio()
399 for fd, (cn, fn, mode) in zip(clientfds, _iochannels):
399 for fd, (cn, fn, mode) in zip(clientfds, _iochannels):
400 assert fd > 0
400 assert fd > 0
401 fp = getattr(ui, fn)
401 fp = getattr(ui, fn)
402 os.dup2(fd, fp.fileno())
402 os.dup2(fd, fp.fileno())
403 os.close(fd)
403 os.close(fd)
404 if self._ioattached:
404 if self._ioattached:
405 continue
405 continue
406 # reset buffering mode when client is first attached. as we want
406 # reset buffering mode when client is first attached. as we want
407 # to see output immediately on pager, the mode stays unchanged
407 # to see output immediately on pager, the mode stays unchanged
408 # when client re-attached. ferr is unchanged because it should
408 # when client re-attached. ferr is unchanged because it should
409 # be unbuffered no matter if it is a tty or not.
409 # be unbuffered no matter if it is a tty or not.
410 if fn == b'ferr':
410 if fn == b'ferr':
411 newfp = fp
411 newfp = fp
412 else:
412 else:
413 # make it line buffered explicitly because the default is
413 # make it line buffered explicitly because the default is
414 # decided on first write(), where fout could be a pager.
414 # decided on first write(), where fout could be a pager.
415 if fp.isatty():
415 if fp.isatty():
416 bufsize = 1 # line buffered
416 bufsize = 1 # line buffered
417 else:
417 else:
418 bufsize = -1 # system default
418 bufsize = -1 # system default
419 newfp = os.fdopen(fp.fileno(), mode, bufsize)
419 newfp = os.fdopen(fp.fileno(), mode, bufsize)
420 setattr(ui, fn, newfp)
420 setattr(ui, fn, newfp)
421 setattr(self, cn, newfp)
421 setattr(self, cn, newfp)
422
422
423 self._ioattached = True
423 self._ioattached = True
424 self.cresult.write(struct.pack(b'>i', len(clientfds)))
424 self.cresult.write(struct.pack(b'>i', len(clientfds)))
425
425
426 def _saveio(self):
426 def _saveio(self):
427 if self._oldios:
427 if self._oldios:
428 return
428 return
429 ui = self.ui
429 ui = self.ui
430 for cn, fn, _mode in _iochannels:
430 for cn, fn, _mode in _iochannels:
431 ch = getattr(self, cn)
431 ch = getattr(self, cn)
432 fp = getattr(ui, fn)
432 fp = getattr(ui, fn)
433 fd = os.dup(fp.fileno())
433 fd = os.dup(fp.fileno())
434 self._oldios.append((ch, fp, fd))
434 self._oldios.append((ch, fp, fd))
435
435
436 def _restoreio(self):
436 def _restoreio(self):
437 ui = self.ui
437 ui = self.ui
438 for (ch, fp, fd), (cn, fn, _mode) in zip(self._oldios, _iochannels):
438 for (ch, fp, fd), (cn, fn, _mode) in zip(self._oldios, _iochannels):
439 newfp = getattr(ui, fn)
439 newfp = getattr(ui, fn)
440 # close newfp while it's associated with client; otherwise it
440 # close newfp while it's associated with client; otherwise it
441 # would be closed when newfp is deleted
441 # would be closed when newfp is deleted
442 if newfp is not fp:
442 if newfp is not fp:
443 newfp.close()
443 newfp.close()
444 # restore original fd: fp is open again
444 # restore original fd: fp is open again
445 os.dup2(fd, fp.fileno())
445 try:
446 os.dup2(fd, fp.fileno())
447 except OSError as err:
448 # According to issue6330, running chg on heavy loaded systems
449 # can lead to EBUSY. [man dup2] indicates that, on Linux,
450 # EBUSY comes from a race condition between open() and dup2().
451 # However it's not clear why open() race occurred for
452 # newfd=stdin/out/err.
453 self.ui.log(
454 b'chgserver',
455 b'got %s while duplicating %s\n',
456 stringutil.forcebytestr(err),
457 fn,
458 )
446 os.close(fd)
459 os.close(fd)
447 setattr(self, cn, ch)
460 setattr(self, cn, ch)
448 setattr(ui, fn, fp)
461 setattr(ui, fn, fp)
449 del self._oldios[:]
462 del self._oldios[:]
450
463
451 def validate(self):
464 def validate(self):
452 """Reload the config and check if the server is up to date
465 """Reload the config and check if the server is up to date
453
466
454 Read a list of '\0' separated arguments.
467 Read a list of '\0' separated arguments.
455 Write a non-empty list of '\0' separated instruction strings or '\0'
468 Write a non-empty list of '\0' separated instruction strings or '\0'
456 if the list is empty.
469 if the list is empty.
457 An instruction string could be either:
470 An instruction string could be either:
458 - "unlink $path", the client should unlink the path to stop the
471 - "unlink $path", the client should unlink the path to stop the
459 outdated server.
472 outdated server.
460 - "redirect $path", the client should attempt to connect to $path
473 - "redirect $path", the client should attempt to connect to $path
461 first. If it does not work, start a new server. It implies
474 first. If it does not work, start a new server. It implies
462 "reconnect".
475 "reconnect".
463 - "exit $n", the client should exit directly with code n.
476 - "exit $n", the client should exit directly with code n.
464 This may happen if we cannot parse the config.
477 This may happen if we cannot parse the config.
465 - "reconnect", the client should close the connection and
478 - "reconnect", the client should close the connection and
466 reconnect.
479 reconnect.
467 If neither "reconnect" nor "redirect" is included in the instruction
480 If neither "reconnect" nor "redirect" is included in the instruction
468 list, the client can continue with this server after completing all
481 list, the client can continue with this server after completing all
469 the instructions.
482 the instructions.
470 """
483 """
471 from . import dispatch # avoid cycle
484 from . import dispatch # avoid cycle
472
485
473 args = self._readlist()
486 args = self._readlist()
474 try:
487 try:
475 self.ui, lui = _loadnewui(self.ui, args, self.cdebug)
488 self.ui, lui = _loadnewui(self.ui, args, self.cdebug)
476 except error.ParseError as inst:
489 except error.ParseError as inst:
477 dispatch._formatparse(self.ui.warn, inst)
490 dispatch._formatparse(self.ui.warn, inst)
478 self.ui.flush()
491 self.ui.flush()
479 self.cresult.write(b'exit 255')
492 self.cresult.write(b'exit 255')
480 return
493 return
481 except error.Abort as inst:
494 except error.Abort as inst:
482 self.ui.error(_(b"abort: %s\n") % inst)
495 self.ui.error(_(b"abort: %s\n") % inst)
483 if inst.hint:
496 if inst.hint:
484 self.ui.error(_(b"(%s)\n") % inst.hint)
497 self.ui.error(_(b"(%s)\n") % inst.hint)
485 self.ui.flush()
498 self.ui.flush()
486 self.cresult.write(b'exit 255')
499 self.cresult.write(b'exit 255')
487 return
500 return
488 newhash = hashstate.fromui(lui, self.hashstate.mtimepaths)
501 newhash = hashstate.fromui(lui, self.hashstate.mtimepaths)
489 insts = []
502 insts = []
490 if newhash.mtimehash != self.hashstate.mtimehash:
503 if newhash.mtimehash != self.hashstate.mtimehash:
491 addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
504 addr = _hashaddress(self.baseaddress, self.hashstate.confighash)
492 insts.append(b'unlink %s' % addr)
505 insts.append(b'unlink %s' % addr)
493 # mtimehash is empty if one or more extensions fail to load.
506 # mtimehash is empty if one or more extensions fail to load.
494 # to be compatible with hg, still serve the client this time.
507 # to be compatible with hg, still serve the client this time.
495 if self.hashstate.mtimehash:
508 if self.hashstate.mtimehash:
496 insts.append(b'reconnect')
509 insts.append(b'reconnect')
497 if newhash.confighash != self.hashstate.confighash:
510 if newhash.confighash != self.hashstate.confighash:
498 addr = _hashaddress(self.baseaddress, newhash.confighash)
511 addr = _hashaddress(self.baseaddress, newhash.confighash)
499 insts.append(b'redirect %s' % addr)
512 insts.append(b'redirect %s' % addr)
500 self.ui.log(b'chgserver', b'validate: %s\n', stringutil.pprint(insts))
513 self.ui.log(b'chgserver', b'validate: %s\n', stringutil.pprint(insts))
501 self.cresult.write(b'\0'.join(insts) or b'\0')
514 self.cresult.write(b'\0'.join(insts) or b'\0')
502
515
503 def chdir(self):
516 def chdir(self):
504 """Change current directory
517 """Change current directory
505
518
506 Note that the behavior of --cwd option is bit different from this.
519 Note that the behavior of --cwd option is bit different from this.
507 It does not affect --config parameter.
520 It does not affect --config parameter.
508 """
521 """
509 path = self._readstr()
522 path = self._readstr()
510 if not path:
523 if not path:
511 return
524 return
512 self.ui.log(b'chgserver', b"chdir to '%s'\n", path)
525 self.ui.log(b'chgserver', b"chdir to '%s'\n", path)
513 os.chdir(path)
526 os.chdir(path)
514
527
515 def setumask(self):
528 def setumask(self):
516 """Change umask (DEPRECATED)"""
529 """Change umask (DEPRECATED)"""
517 # BUG: this does not follow the message frame structure, but kept for
530 # BUG: this does not follow the message frame structure, but kept for
518 # backward compatibility with old chg clients for some time
531 # backward compatibility with old chg clients for some time
519 self._setumask(self._read(4))
532 self._setumask(self._read(4))
520
533
521 def setumask2(self):
534 def setumask2(self):
522 """Change umask"""
535 """Change umask"""
523 data = self._readstr()
536 data = self._readstr()
524 if len(data) != 4:
537 if len(data) != 4:
525 raise ValueError(b'invalid mask length in setumask2 request')
538 raise ValueError(b'invalid mask length in setumask2 request')
526 self._setumask(data)
539 self._setumask(data)
527
540
528 def _setumask(self, data):
541 def _setumask(self, data):
529 mask = struct.unpack(b'>I', data)[0]
542 mask = struct.unpack(b'>I', data)[0]
530 self.ui.log(b'chgserver', b'setumask %r\n', mask)
543 self.ui.log(b'chgserver', b'setumask %r\n', mask)
531 util.setumask(mask)
544 util.setumask(mask)
532
545
533 def runcommand(self):
546 def runcommand(self):
534 # pager may be attached within the runcommand session, which should
547 # pager may be attached within the runcommand session, which should
535 # be detached at the end of the session. otherwise the pager wouldn't
548 # be detached at the end of the session. otherwise the pager wouldn't
536 # receive EOF.
549 # receive EOF.
537 globaloldios = self._oldios
550 globaloldios = self._oldios
538 self._oldios = []
551 self._oldios = []
539 try:
552 try:
540 return super(chgcmdserver, self).runcommand()
553 return super(chgcmdserver, self).runcommand()
541 finally:
554 finally:
542 self._restoreio()
555 self._restoreio()
543 self._oldios = globaloldios
556 self._oldios = globaloldios
544
557
545 def setenv(self):
558 def setenv(self):
546 """Clear and update os.environ
559 """Clear and update os.environ
547
560
548 Note that not all variables can make an effect on the running process.
561 Note that not all variables can make an effect on the running process.
549 """
562 """
550 l = self._readlist()
563 l = self._readlist()
551 try:
564 try:
552 newenv = dict(s.split(b'=', 1) for s in l)
565 newenv = dict(s.split(b'=', 1) for s in l)
553 except ValueError:
566 except ValueError:
554 raise ValueError(b'unexpected value in setenv request')
567 raise ValueError(b'unexpected value in setenv request')
555 self.ui.log(b'chgserver', b'setenv: %r\n', sorted(newenv.keys()))
568 self.ui.log(b'chgserver', b'setenv: %r\n', sorted(newenv.keys()))
556
569
557 encoding.environ.clear()
570 encoding.environ.clear()
558 encoding.environ.update(newenv)
571 encoding.environ.update(newenv)
559
572
560 capabilities = commandserver.server.capabilities.copy()
573 capabilities = commandserver.server.capabilities.copy()
561 capabilities.update(
574 capabilities.update(
562 {
575 {
563 b'attachio': attachio,
576 b'attachio': attachio,
564 b'chdir': chdir,
577 b'chdir': chdir,
565 b'runcommand': runcommand,
578 b'runcommand': runcommand,
566 b'setenv': setenv,
579 b'setenv': setenv,
567 b'setumask': setumask,
580 b'setumask': setumask,
568 b'setumask2': setumask2,
581 b'setumask2': setumask2,
569 }
582 }
570 )
583 )
571
584
572 if util.safehasattr(procutil, b'setprocname'):
585 if util.safehasattr(procutil, b'setprocname'):
573
586
574 def setprocname(self):
587 def setprocname(self):
575 """Change process title"""
588 """Change process title"""
576 name = self._readstr()
589 name = self._readstr()
577 self.ui.log(b'chgserver', b'setprocname: %r\n', name)
590 self.ui.log(b'chgserver', b'setprocname: %r\n', name)
578 procutil.setprocname(name)
591 procutil.setprocname(name)
579
592
580 capabilities[b'setprocname'] = setprocname
593 capabilities[b'setprocname'] = setprocname
581
594
582
595
583 def _tempaddress(address):
596 def _tempaddress(address):
584 return b'%s.%d.tmp' % (address, os.getpid())
597 return b'%s.%d.tmp' % (address, os.getpid())
585
598
586
599
587 def _hashaddress(address, hashstr):
600 def _hashaddress(address, hashstr):
588 # if the basename of address contains '.', use only the left part. this
601 # if the basename of address contains '.', use only the left part. this
589 # makes it possible for the client to pass 'server.tmp$PID' and follow by
602 # makes it possible for the client to pass 'server.tmp$PID' and follow by
590 # an atomic rename to avoid locking when spawning new servers.
603 # an atomic rename to avoid locking when spawning new servers.
591 dirname, basename = os.path.split(address)
604 dirname, basename = os.path.split(address)
592 basename = basename.split(b'.', 1)[0]
605 basename = basename.split(b'.', 1)[0]
593 return b'%s-%s' % (os.path.join(dirname, basename), hashstr)
606 return b'%s-%s' % (os.path.join(dirname, basename), hashstr)
594
607
595
608
596 class chgunixservicehandler(object):
609 class chgunixservicehandler(object):
597 """Set of operations for chg services"""
610 """Set of operations for chg services"""
598
611
599 pollinterval = 1 # [sec]
612 pollinterval = 1 # [sec]
600
613
601 def __init__(self, ui):
614 def __init__(self, ui):
602 self.ui = ui
615 self.ui = ui
603 self._idletimeout = ui.configint(b'chgserver', b'idletimeout')
616 self._idletimeout = ui.configint(b'chgserver', b'idletimeout')
604 self._lastactive = time.time()
617 self._lastactive = time.time()
605
618
606 def bindsocket(self, sock, address):
619 def bindsocket(self, sock, address):
607 self._inithashstate(address)
620 self._inithashstate(address)
608 self._checkextensions()
621 self._checkextensions()
609 self._bind(sock)
622 self._bind(sock)
610 self._createsymlink()
623 self._createsymlink()
611 # no "listening at" message should be printed to simulate hg behavior
624 # no "listening at" message should be printed to simulate hg behavior
612
625
613 def _inithashstate(self, address):
626 def _inithashstate(self, address):
614 self._baseaddress = address
627 self._baseaddress = address
615 if self.ui.configbool(b'chgserver', b'skiphash'):
628 if self.ui.configbool(b'chgserver', b'skiphash'):
616 self._hashstate = None
629 self._hashstate = None
617 self._realaddress = address
630 self._realaddress = address
618 return
631 return
619 self._hashstate = hashstate.fromui(self.ui)
632 self._hashstate = hashstate.fromui(self.ui)
620 self._realaddress = _hashaddress(address, self._hashstate.confighash)
633 self._realaddress = _hashaddress(address, self._hashstate.confighash)
621
634
622 def _checkextensions(self):
635 def _checkextensions(self):
623 if not self._hashstate:
636 if not self._hashstate:
624 return
637 return
625 if extensions.notloaded():
638 if extensions.notloaded():
626 # one or more extensions failed to load. mtimehash becomes
639 # one or more extensions failed to load. mtimehash becomes
627 # meaningless because we do not know the paths of those extensions.
640 # meaningless because we do not know the paths of those extensions.
628 # set mtimehash to an illegal hash value to invalidate the server.
641 # set mtimehash to an illegal hash value to invalidate the server.
629 self._hashstate.mtimehash = b''
642 self._hashstate.mtimehash = b''
630
643
631 def _bind(self, sock):
644 def _bind(self, sock):
632 # use a unique temp address so we can stat the file and do ownership
645 # use a unique temp address so we can stat the file and do ownership
633 # check later
646 # check later
634 tempaddress = _tempaddress(self._realaddress)
647 tempaddress = _tempaddress(self._realaddress)
635 util.bindunixsocket(sock, tempaddress)
648 util.bindunixsocket(sock, tempaddress)
636 self._socketstat = os.stat(tempaddress)
649 self._socketstat = os.stat(tempaddress)
637 sock.listen(socket.SOMAXCONN)
650 sock.listen(socket.SOMAXCONN)
638 # rename will replace the old socket file if exists atomically. the
651 # rename will replace the old socket file if exists atomically. the
639 # old server will detect ownership change and exit.
652 # old server will detect ownership change and exit.
640 util.rename(tempaddress, self._realaddress)
653 util.rename(tempaddress, self._realaddress)
641
654
642 def _createsymlink(self):
655 def _createsymlink(self):
643 if self._baseaddress == self._realaddress:
656 if self._baseaddress == self._realaddress:
644 return
657 return
645 tempaddress = _tempaddress(self._baseaddress)
658 tempaddress = _tempaddress(self._baseaddress)
646 os.symlink(os.path.basename(self._realaddress), tempaddress)
659 os.symlink(os.path.basename(self._realaddress), tempaddress)
647 util.rename(tempaddress, self._baseaddress)
660 util.rename(tempaddress, self._baseaddress)
648
661
649 def _issocketowner(self):
662 def _issocketowner(self):
650 try:
663 try:
651 st = os.stat(self._realaddress)
664 st = os.stat(self._realaddress)
652 return (
665 return (
653 st.st_ino == self._socketstat.st_ino
666 st.st_ino == self._socketstat.st_ino
654 and st[stat.ST_MTIME] == self._socketstat[stat.ST_MTIME]
667 and st[stat.ST_MTIME] == self._socketstat[stat.ST_MTIME]
655 )
668 )
656 except OSError:
669 except OSError:
657 return False
670 return False
658
671
659 def unlinksocket(self, address):
672 def unlinksocket(self, address):
660 if not self._issocketowner():
673 if not self._issocketowner():
661 return
674 return
662 # it is possible to have a race condition here that we may
675 # it is possible to have a race condition here that we may
663 # remove another server's socket file. but that's okay
676 # remove another server's socket file. but that's okay
664 # since that server will detect and exit automatically and
677 # since that server will detect and exit automatically and
665 # the client will start a new server on demand.
678 # the client will start a new server on demand.
666 util.tryunlink(self._realaddress)
679 util.tryunlink(self._realaddress)
667
680
668 def shouldexit(self):
681 def shouldexit(self):
669 if not self._issocketowner():
682 if not self._issocketowner():
670 self.ui.log(
683 self.ui.log(
671 b'chgserver', b'%s is not owned, exiting.\n', self._realaddress
684 b'chgserver', b'%s is not owned, exiting.\n', self._realaddress
672 )
685 )
673 return True
686 return True
674 if time.time() - self._lastactive > self._idletimeout:
687 if time.time() - self._lastactive > self._idletimeout:
675 self.ui.log(b'chgserver', b'being idle too long. exiting.\n')
688 self.ui.log(b'chgserver', b'being idle too long. exiting.\n')
676 return True
689 return True
677 return False
690 return False
678
691
679 def newconnection(self):
692 def newconnection(self):
680 self._lastactive = time.time()
693 self._lastactive = time.time()
681
694
682 def createcmdserver(self, repo, conn, fin, fout, prereposetups):
695 def createcmdserver(self, repo, conn, fin, fout, prereposetups):
683 return chgcmdserver(
696 return chgcmdserver(
684 self.ui,
697 self.ui,
685 repo,
698 repo,
686 fin,
699 fin,
687 fout,
700 fout,
688 conn,
701 conn,
689 prereposetups,
702 prereposetups,
690 self._hashstate,
703 self._hashstate,
691 self._baseaddress,
704 self._baseaddress,
692 )
705 )
693
706
694
707
695 def chgunixservice(ui, repo, opts):
708 def chgunixservice(ui, repo, opts):
696 # CHGINTERNALMARK is set by chg client. It is an indication of things are
709 # CHGINTERNALMARK is set by chg client. It is an indication of things are
697 # started by chg so other code can do things accordingly, like disabling
710 # started by chg so other code can do things accordingly, like disabling
698 # demandimport or detecting chg client started by chg client. When executed
711 # demandimport or detecting chg client started by chg client. When executed
699 # here, CHGINTERNALMARK is no longer useful and hence dropped to make
712 # here, CHGINTERNALMARK is no longer useful and hence dropped to make
700 # environ cleaner.
713 # environ cleaner.
701 if b'CHGINTERNALMARK' in encoding.environ:
714 if b'CHGINTERNALMARK' in encoding.environ:
702 del encoding.environ[b'CHGINTERNALMARK']
715 del encoding.environ[b'CHGINTERNALMARK']
703 # Python3.7+ "coerces" the LC_CTYPE environment variable to a UTF-8 one if
716 # Python3.7+ "coerces" the LC_CTYPE environment variable to a UTF-8 one if
704 # it thinks the current value is "C". This breaks the hash computation and
717 # it thinks the current value is "C". This breaks the hash computation and
705 # causes chg to restart loop.
718 # causes chg to restart loop.
706 if b'CHGORIG_LC_CTYPE' in encoding.environ:
719 if b'CHGORIG_LC_CTYPE' in encoding.environ:
707 encoding.environ[b'LC_CTYPE'] = encoding.environ[b'CHGORIG_LC_CTYPE']
720 encoding.environ[b'LC_CTYPE'] = encoding.environ[b'CHGORIG_LC_CTYPE']
708 del encoding.environ[b'CHGORIG_LC_CTYPE']
721 del encoding.environ[b'CHGORIG_LC_CTYPE']
709 elif b'CHG_CLEAR_LC_CTYPE' in encoding.environ:
722 elif b'CHG_CLEAR_LC_CTYPE' in encoding.environ:
710 if b'LC_CTYPE' in encoding.environ:
723 if b'LC_CTYPE' in encoding.environ:
711 del encoding.environ[b'LC_CTYPE']
724 del encoding.environ[b'LC_CTYPE']
712 del encoding.environ[b'CHG_CLEAR_LC_CTYPE']
725 del encoding.environ[b'CHG_CLEAR_LC_CTYPE']
713
726
714 if repo:
727 if repo:
715 # one chgserver can serve multiple repos. drop repo information
728 # one chgserver can serve multiple repos. drop repo information
716 ui.setconfig(b'bundle', b'mainreporoot', b'', b'repo')
729 ui.setconfig(b'bundle', b'mainreporoot', b'', b'repo')
717 h = chgunixservicehandler(ui)
730 h = chgunixservicehandler(ui)
718 return commandserver.unixforkingservice(ui, repo=None, opts=opts, handler=h)
731 return commandserver.unixforkingservice(ui, repo=None, opts=opts, handler=h)
General Comments 0
You need to be logged in to leave comments. Login now