##// END OF EJS Templates
commandserver: separate initialization and cleanup of forked process...
Yuya Nishihara -
r29586:42cdba9c default
parent child Browse files
Show More
@@ -1,533 +1,536 b''
1 # commandserver.py - communicate with Mercurial's API over a pipe
1 # commandserver.py - communicate with Mercurial's API over a pipe
2 #
2 #
3 # Copyright Matt Mackall <mpm@selenic.com>
3 # Copyright Matt Mackall <mpm@selenic.com>
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 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import gc
11 import gc
12 import os
12 import os
13 import random
13 import random
14 import select
14 import select
15 import signal
15 import signal
16 import socket
16 import socket
17 import struct
17 import struct
18 import sys
18 import sys
19 import traceback
19 import traceback
20
20
21 from .i18n import _
21 from .i18n import _
22 from . import (
22 from . import (
23 encoding,
23 encoding,
24 error,
24 error,
25 util,
25 util,
26 )
26 )
27
27
28 logfile = None
28 logfile = None
29
29
30 def log(*args):
30 def log(*args):
31 if not logfile:
31 if not logfile:
32 return
32 return
33
33
34 for a in args:
34 for a in args:
35 logfile.write(str(a))
35 logfile.write(str(a))
36
36
37 logfile.flush()
37 logfile.flush()
38
38
39 class channeledoutput(object):
39 class channeledoutput(object):
40 """
40 """
41 Write data to out in the following format:
41 Write data to out in the following format:
42
42
43 data length (unsigned int),
43 data length (unsigned int),
44 data
44 data
45 """
45 """
46 def __init__(self, out, channel):
46 def __init__(self, out, channel):
47 self.out = out
47 self.out = out
48 self.channel = channel
48 self.channel = channel
49
49
50 @property
50 @property
51 def name(self):
51 def name(self):
52 return '<%c-channel>' % self.channel
52 return '<%c-channel>' % self.channel
53
53
54 def write(self, data):
54 def write(self, data):
55 if not data:
55 if not data:
56 return
56 return
57 self.out.write(struct.pack('>cI', self.channel, len(data)))
57 self.out.write(struct.pack('>cI', self.channel, len(data)))
58 self.out.write(data)
58 self.out.write(data)
59 self.out.flush()
59 self.out.flush()
60
60
61 def __getattr__(self, attr):
61 def __getattr__(self, attr):
62 if attr in ('isatty', 'fileno', 'tell', 'seek'):
62 if attr in ('isatty', 'fileno', 'tell', 'seek'):
63 raise AttributeError(attr)
63 raise AttributeError(attr)
64 return getattr(self.out, attr)
64 return getattr(self.out, attr)
65
65
66 class channeledinput(object):
66 class channeledinput(object):
67 """
67 """
68 Read data from in_.
68 Read data from in_.
69
69
70 Requests for input are written to out in the following format:
70 Requests for input are written to out in the following format:
71 channel identifier - 'I' for plain input, 'L' line based (1 byte)
71 channel identifier - 'I' for plain input, 'L' line based (1 byte)
72 how many bytes to send at most (unsigned int),
72 how many bytes to send at most (unsigned int),
73
73
74 The client replies with:
74 The client replies with:
75 data length (unsigned int), 0 meaning EOF
75 data length (unsigned int), 0 meaning EOF
76 data
76 data
77 """
77 """
78
78
79 maxchunksize = 4 * 1024
79 maxchunksize = 4 * 1024
80
80
81 def __init__(self, in_, out, channel):
81 def __init__(self, in_, out, channel):
82 self.in_ = in_
82 self.in_ = in_
83 self.out = out
83 self.out = out
84 self.channel = channel
84 self.channel = channel
85
85
86 @property
86 @property
87 def name(self):
87 def name(self):
88 return '<%c-channel>' % self.channel
88 return '<%c-channel>' % self.channel
89
89
90 def read(self, size=-1):
90 def read(self, size=-1):
91 if size < 0:
91 if size < 0:
92 # if we need to consume all the clients input, ask for 4k chunks
92 # if we need to consume all the clients input, ask for 4k chunks
93 # so the pipe doesn't fill up risking a deadlock
93 # so the pipe doesn't fill up risking a deadlock
94 size = self.maxchunksize
94 size = self.maxchunksize
95 s = self._read(size, self.channel)
95 s = self._read(size, self.channel)
96 buf = s
96 buf = s
97 while s:
97 while s:
98 s = self._read(size, self.channel)
98 s = self._read(size, self.channel)
99 buf += s
99 buf += s
100
100
101 return buf
101 return buf
102 else:
102 else:
103 return self._read(size, self.channel)
103 return self._read(size, self.channel)
104
104
105 def _read(self, size, channel):
105 def _read(self, size, channel):
106 if not size:
106 if not size:
107 return ''
107 return ''
108 assert size > 0
108 assert size > 0
109
109
110 # tell the client we need at most size bytes
110 # tell the client we need at most size bytes
111 self.out.write(struct.pack('>cI', channel, size))
111 self.out.write(struct.pack('>cI', channel, size))
112 self.out.flush()
112 self.out.flush()
113
113
114 length = self.in_.read(4)
114 length = self.in_.read(4)
115 length = struct.unpack('>I', length)[0]
115 length = struct.unpack('>I', length)[0]
116 if not length:
116 if not length:
117 return ''
117 return ''
118 else:
118 else:
119 return self.in_.read(length)
119 return self.in_.read(length)
120
120
121 def readline(self, size=-1):
121 def readline(self, size=-1):
122 if size < 0:
122 if size < 0:
123 size = self.maxchunksize
123 size = self.maxchunksize
124 s = self._read(size, 'L')
124 s = self._read(size, 'L')
125 buf = s
125 buf = s
126 # keep asking for more until there's either no more or
126 # keep asking for more until there's either no more or
127 # we got a full line
127 # we got a full line
128 while s and s[-1] != '\n':
128 while s and s[-1] != '\n':
129 s = self._read(size, 'L')
129 s = self._read(size, 'L')
130 buf += s
130 buf += s
131
131
132 return buf
132 return buf
133 else:
133 else:
134 return self._read(size, 'L')
134 return self._read(size, 'L')
135
135
136 def __iter__(self):
136 def __iter__(self):
137 return self
137 return self
138
138
139 def next(self):
139 def next(self):
140 l = self.readline()
140 l = self.readline()
141 if not l:
141 if not l:
142 raise StopIteration
142 raise StopIteration
143 return l
143 return l
144
144
145 def __getattr__(self, attr):
145 def __getattr__(self, attr):
146 if attr in ('isatty', 'fileno', 'tell', 'seek'):
146 if attr in ('isatty', 'fileno', 'tell', 'seek'):
147 raise AttributeError(attr)
147 raise AttributeError(attr)
148 return getattr(self.in_, attr)
148 return getattr(self.in_, attr)
149
149
150 class server(object):
150 class server(object):
151 """
151 """
152 Listens for commands on fin, runs them and writes the output on a channel
152 Listens for commands on fin, runs them and writes the output on a channel
153 based stream to fout.
153 based stream to fout.
154 """
154 """
155 def __init__(self, ui, repo, fin, fout):
155 def __init__(self, ui, repo, fin, fout):
156 self.cwd = os.getcwd()
156 self.cwd = os.getcwd()
157
157
158 # developer config: cmdserver.log
158 # developer config: cmdserver.log
159 logpath = ui.config("cmdserver", "log", None)
159 logpath = ui.config("cmdserver", "log", None)
160 if logpath:
160 if logpath:
161 global logfile
161 global logfile
162 if logpath == '-':
162 if logpath == '-':
163 # write log on a special 'd' (debug) channel
163 # write log on a special 'd' (debug) channel
164 logfile = channeledoutput(fout, 'd')
164 logfile = channeledoutput(fout, 'd')
165 else:
165 else:
166 logfile = open(logpath, 'a')
166 logfile = open(logpath, 'a')
167
167
168 if repo:
168 if repo:
169 # the ui here is really the repo ui so take its baseui so we don't
169 # the ui here is really the repo ui so take its baseui so we don't
170 # end up with its local configuration
170 # end up with its local configuration
171 self.ui = repo.baseui
171 self.ui = repo.baseui
172 self.repo = repo
172 self.repo = repo
173 self.repoui = repo.ui
173 self.repoui = repo.ui
174 else:
174 else:
175 self.ui = ui
175 self.ui = ui
176 self.repo = self.repoui = None
176 self.repo = self.repoui = None
177
177
178 self.cerr = channeledoutput(fout, 'e')
178 self.cerr = channeledoutput(fout, 'e')
179 self.cout = channeledoutput(fout, 'o')
179 self.cout = channeledoutput(fout, 'o')
180 self.cin = channeledinput(fin, fout, 'I')
180 self.cin = channeledinput(fin, fout, 'I')
181 self.cresult = channeledoutput(fout, 'r')
181 self.cresult = channeledoutput(fout, 'r')
182
182
183 self.client = fin
183 self.client = fin
184
184
185 def cleanup(self):
185 def cleanup(self):
186 """release and restore resources taken during server session"""
186 """release and restore resources taken during server session"""
187 pass
187 pass
188
188
189 def _read(self, size):
189 def _read(self, size):
190 if not size:
190 if not size:
191 return ''
191 return ''
192
192
193 data = self.client.read(size)
193 data = self.client.read(size)
194
194
195 # is the other end closed?
195 # is the other end closed?
196 if not data:
196 if not data:
197 raise EOFError
197 raise EOFError
198
198
199 return data
199 return data
200
200
201 def _readstr(self):
201 def _readstr(self):
202 """read a string from the channel
202 """read a string from the channel
203
203
204 format:
204 format:
205 data length (uint32), data
205 data length (uint32), data
206 """
206 """
207 length = struct.unpack('>I', self._read(4))[0]
207 length = struct.unpack('>I', self._read(4))[0]
208 if not length:
208 if not length:
209 return ''
209 return ''
210 return self._read(length)
210 return self._read(length)
211
211
212 def _readlist(self):
212 def _readlist(self):
213 """read a list of NULL separated strings from the channel"""
213 """read a list of NULL separated strings from the channel"""
214 s = self._readstr()
214 s = self._readstr()
215 if s:
215 if s:
216 return s.split('\0')
216 return s.split('\0')
217 else:
217 else:
218 return []
218 return []
219
219
220 def runcommand(self):
220 def runcommand(self):
221 """ reads a list of \0 terminated arguments, executes
221 """ reads a list of \0 terminated arguments, executes
222 and writes the return code to the result channel """
222 and writes the return code to the result channel """
223 from . import dispatch # avoid cycle
223 from . import dispatch # avoid cycle
224
224
225 args = self._readlist()
225 args = self._readlist()
226
226
227 # copy the uis so changes (e.g. --config or --verbose) don't
227 # copy the uis so changes (e.g. --config or --verbose) don't
228 # persist between requests
228 # persist between requests
229 copiedui = self.ui.copy()
229 copiedui = self.ui.copy()
230 uis = [copiedui]
230 uis = [copiedui]
231 if self.repo:
231 if self.repo:
232 self.repo.baseui = copiedui
232 self.repo.baseui = copiedui
233 # clone ui without using ui.copy because this is protected
233 # clone ui without using ui.copy because this is protected
234 repoui = self.repoui.__class__(self.repoui)
234 repoui = self.repoui.__class__(self.repoui)
235 repoui.copy = copiedui.copy # redo copy protection
235 repoui.copy = copiedui.copy # redo copy protection
236 uis.append(repoui)
236 uis.append(repoui)
237 self.repo.ui = self.repo.dirstate._ui = repoui
237 self.repo.ui = self.repo.dirstate._ui = repoui
238 self.repo.invalidateall()
238 self.repo.invalidateall()
239
239
240 for ui in uis:
240 for ui in uis:
241 ui.resetstate()
241 ui.resetstate()
242 # any kind of interaction must use server channels, but chg may
242 # any kind of interaction must use server channels, but chg may
243 # replace channels by fully functional tty files. so nontty is
243 # replace channels by fully functional tty files. so nontty is
244 # enforced only if cin is a channel.
244 # enforced only if cin is a channel.
245 if not util.safehasattr(self.cin, 'fileno'):
245 if not util.safehasattr(self.cin, 'fileno'):
246 ui.setconfig('ui', 'nontty', 'true', 'commandserver')
246 ui.setconfig('ui', 'nontty', 'true', 'commandserver')
247
247
248 req = dispatch.request(args[:], copiedui, self.repo, self.cin,
248 req = dispatch.request(args[:], copiedui, self.repo, self.cin,
249 self.cout, self.cerr)
249 self.cout, self.cerr)
250
250
251 ret = (dispatch.dispatch(req) or 0) & 255 # might return None
251 ret = (dispatch.dispatch(req) or 0) & 255 # might return None
252
252
253 # restore old cwd
253 # restore old cwd
254 if '--cwd' in args:
254 if '--cwd' in args:
255 os.chdir(self.cwd)
255 os.chdir(self.cwd)
256
256
257 self.cresult.write(struct.pack('>i', int(ret)))
257 self.cresult.write(struct.pack('>i', int(ret)))
258
258
259 def getencoding(self):
259 def getencoding(self):
260 """ writes the current encoding to the result channel """
260 """ writes the current encoding to the result channel """
261 self.cresult.write(encoding.encoding)
261 self.cresult.write(encoding.encoding)
262
262
263 def serveone(self):
263 def serveone(self):
264 cmd = self.client.readline()[:-1]
264 cmd = self.client.readline()[:-1]
265 if cmd:
265 if cmd:
266 handler = self.capabilities.get(cmd)
266 handler = self.capabilities.get(cmd)
267 if handler:
267 if handler:
268 handler(self)
268 handler(self)
269 else:
269 else:
270 # clients are expected to check what commands are supported by
270 # clients are expected to check what commands are supported by
271 # looking at the servers capabilities
271 # looking at the servers capabilities
272 raise error.Abort(_('unknown command %s') % cmd)
272 raise error.Abort(_('unknown command %s') % cmd)
273
273
274 return cmd != ''
274 return cmd != ''
275
275
276 capabilities = {'runcommand' : runcommand,
276 capabilities = {'runcommand' : runcommand,
277 'getencoding' : getencoding}
277 'getencoding' : getencoding}
278
278
279 def serve(self):
279 def serve(self):
280 hellomsg = 'capabilities: ' + ' '.join(sorted(self.capabilities))
280 hellomsg = 'capabilities: ' + ' '.join(sorted(self.capabilities))
281 hellomsg += '\n'
281 hellomsg += '\n'
282 hellomsg += 'encoding: ' + encoding.encoding
282 hellomsg += 'encoding: ' + encoding.encoding
283 hellomsg += '\n'
283 hellomsg += '\n'
284 hellomsg += 'pid: %d' % util.getpid()
284 hellomsg += 'pid: %d' % util.getpid()
285 if util.safehasattr(os, 'getpgid'):
285 if util.safehasattr(os, 'getpgid'):
286 hellomsg += '\n'
286 hellomsg += '\n'
287 hellomsg += 'pgid: %d' % os.getpgid(0)
287 hellomsg += 'pgid: %d' % os.getpgid(0)
288
288
289 # write the hello msg in -one- chunk
289 # write the hello msg in -one- chunk
290 self.cout.write(hellomsg)
290 self.cout.write(hellomsg)
291
291
292 try:
292 try:
293 while self.serveone():
293 while self.serveone():
294 pass
294 pass
295 except EOFError:
295 except EOFError:
296 # we'll get here if the client disconnected while we were reading
296 # we'll get here if the client disconnected while we were reading
297 # its request
297 # its request
298 return 1
298 return 1
299
299
300 return 0
300 return 0
301
301
302 def _protectio(ui):
302 def _protectio(ui):
303 """ duplicates streams and redirect original to null if ui uses stdio """
303 """ duplicates streams and redirect original to null if ui uses stdio """
304 ui.flush()
304 ui.flush()
305 newfiles = []
305 newfiles = []
306 nullfd = os.open(os.devnull, os.O_RDWR)
306 nullfd = os.open(os.devnull, os.O_RDWR)
307 for f, sysf, mode in [(ui.fin, sys.stdin, 'rb'),
307 for f, sysf, mode in [(ui.fin, sys.stdin, 'rb'),
308 (ui.fout, sys.stdout, 'wb')]:
308 (ui.fout, sys.stdout, 'wb')]:
309 if f is sysf:
309 if f is sysf:
310 newfd = os.dup(f.fileno())
310 newfd = os.dup(f.fileno())
311 os.dup2(nullfd, f.fileno())
311 os.dup2(nullfd, f.fileno())
312 f = os.fdopen(newfd, mode)
312 f = os.fdopen(newfd, mode)
313 newfiles.append(f)
313 newfiles.append(f)
314 os.close(nullfd)
314 os.close(nullfd)
315 return tuple(newfiles)
315 return tuple(newfiles)
316
316
317 def _restoreio(ui, fin, fout):
317 def _restoreio(ui, fin, fout):
318 """ restores streams from duplicated ones """
318 """ restores streams from duplicated ones """
319 ui.flush()
319 ui.flush()
320 for f, uif in [(fin, ui.fin), (fout, ui.fout)]:
320 for f, uif in [(fin, ui.fin), (fout, ui.fout)]:
321 if f is not uif:
321 if f is not uif:
322 os.dup2(f.fileno(), uif.fileno())
322 os.dup2(f.fileno(), uif.fileno())
323 f.close()
323 f.close()
324
324
325 class pipeservice(object):
325 class pipeservice(object):
326 def __init__(self, ui, repo, opts):
326 def __init__(self, ui, repo, opts):
327 self.ui = ui
327 self.ui = ui
328 self.repo = repo
328 self.repo = repo
329
329
330 def init(self):
330 def init(self):
331 pass
331 pass
332
332
333 def run(self):
333 def run(self):
334 ui = self.ui
334 ui = self.ui
335 # redirect stdio to null device so that broken extensions or in-process
335 # redirect stdio to null device so that broken extensions or in-process
336 # hooks will never cause corruption of channel protocol.
336 # hooks will never cause corruption of channel protocol.
337 fin, fout = _protectio(ui)
337 fin, fout = _protectio(ui)
338 try:
338 try:
339 sv = server(ui, self.repo, fin, fout)
339 sv = server(ui, self.repo, fin, fout)
340 return sv.serve()
340 return sv.serve()
341 finally:
341 finally:
342 sv.cleanup()
342 sv.cleanup()
343 _restoreio(ui, fin, fout)
343 _restoreio(ui, fin, fout)
344
344
345 def _serverequest(ui, repo, conn, createcmdserver):
345 def _initworkerprocess():
346 # use a different process group from the master process, making this
346 # use a different process group from the master process, making this
347 # process pass kernel "is_current_pgrp_orphaned" check so signals like
347 # process pass kernel "is_current_pgrp_orphaned" check so signals like
348 # SIGTSTP, SIGTTIN, SIGTTOU are not ignored.
348 # SIGTSTP, SIGTTIN, SIGTTOU are not ignored.
349 os.setpgid(0, 0)
349 os.setpgid(0, 0)
350 # change random state otherwise forked request handlers would have a
350 # change random state otherwise forked request handlers would have a
351 # same state inherited from parent.
351 # same state inherited from parent.
352 random.seed()
352 random.seed()
353
353
354 def _serverequest(ui, repo, conn, createcmdserver):
354 fin = conn.makefile('rb')
355 fin = conn.makefile('rb')
355 fout = conn.makefile('wb')
356 fout = conn.makefile('wb')
356 sv = None
357 sv = None
357 try:
358 try:
358 sv = createcmdserver(repo, conn, fin, fout)
359 sv = createcmdserver(repo, conn, fin, fout)
359 try:
360 try:
360 sv.serve()
361 sv.serve()
361 # handle exceptions that may be raised by command server. most of
362 # handle exceptions that may be raised by command server. most of
362 # known exceptions are caught by dispatch.
363 # known exceptions are caught by dispatch.
363 except error.Abort as inst:
364 except error.Abort as inst:
364 ui.warn(_('abort: %s\n') % inst)
365 ui.warn(_('abort: %s\n') % inst)
365 except IOError as inst:
366 except IOError as inst:
366 if inst.errno != errno.EPIPE:
367 if inst.errno != errno.EPIPE:
367 raise
368 raise
368 except KeyboardInterrupt:
369 except KeyboardInterrupt:
369 pass
370 pass
370 finally:
371 finally:
371 sv.cleanup()
372 sv.cleanup()
372 except: # re-raises
373 except: # re-raises
373 # also write traceback to error channel. otherwise client cannot
374 # also write traceback to error channel. otherwise client cannot
374 # see it because it is written to server's stderr by default.
375 # see it because it is written to server's stderr by default.
375 if sv:
376 if sv:
376 cerr = sv.cerr
377 cerr = sv.cerr
377 else:
378 else:
378 cerr = channeledoutput(fout, 'e')
379 cerr = channeledoutput(fout, 'e')
379 traceback.print_exc(file=cerr)
380 traceback.print_exc(file=cerr)
380 raise
381 raise
381 finally:
382 finally:
382 fin.close()
383 fin.close()
383 try:
384 try:
384 fout.close() # implicit flush() may cause another EPIPE
385 fout.close() # implicit flush() may cause another EPIPE
385 except IOError as inst:
386 except IOError as inst:
386 if inst.errno != errno.EPIPE:
387 if inst.errno != errno.EPIPE:
387 raise
388 raise
388 # trigger __del__ since ForkingMixIn uses os._exit
389 gc.collect()
390
389
391 class unixservicehandler(object):
390 class unixservicehandler(object):
392 """Set of pluggable operations for unix-mode services
391 """Set of pluggable operations for unix-mode services
393
392
394 Almost all methods except for createcmdserver() are called in the main
393 Almost all methods except for createcmdserver() are called in the main
395 process. You can't pass mutable resource back from createcmdserver().
394 process. You can't pass mutable resource back from createcmdserver().
396 """
395 """
397
396
398 pollinterval = None
397 pollinterval = None
399
398
400 def __init__(self, ui):
399 def __init__(self, ui):
401 self.ui = ui
400 self.ui = ui
402
401
403 def bindsocket(self, sock, address):
402 def bindsocket(self, sock, address):
404 util.bindunixsocket(sock, address)
403 util.bindunixsocket(sock, address)
405
404
406 def unlinksocket(self, address):
405 def unlinksocket(self, address):
407 os.unlink(address)
406 os.unlink(address)
408
407
409 def printbanner(self, address):
408 def printbanner(self, address):
410 self.ui.status(_('listening at %s\n') % address)
409 self.ui.status(_('listening at %s\n') % address)
411 self.ui.flush() # avoid buffering of status message
410 self.ui.flush() # avoid buffering of status message
412
411
413 def shouldexit(self):
412 def shouldexit(self):
414 """True if server should shut down; checked per pollinterval"""
413 """True if server should shut down; checked per pollinterval"""
415 return False
414 return False
416
415
417 def newconnection(self):
416 def newconnection(self):
418 """Called when main process notices new connection"""
417 """Called when main process notices new connection"""
419 pass
418 pass
420
419
421 def createcmdserver(self, repo, conn, fin, fout):
420 def createcmdserver(self, repo, conn, fin, fout):
422 """Create new command server instance; called in the process that
421 """Create new command server instance; called in the process that
423 serves for the current connection"""
422 serves for the current connection"""
424 return server(self.ui, repo, fin, fout)
423 return server(self.ui, repo, fin, fout)
425
424
426 class unixforkingservice(object):
425 class unixforkingservice(object):
427 """
426 """
428 Listens on unix domain socket and forks server per connection
427 Listens on unix domain socket and forks server per connection
429 """
428 """
430
429
431 def __init__(self, ui, repo, opts, handler=None):
430 def __init__(self, ui, repo, opts, handler=None):
432 self.ui = ui
431 self.ui = ui
433 self.repo = repo
432 self.repo = repo
434 self.address = opts['address']
433 self.address = opts['address']
435 if not util.safehasattr(socket, 'AF_UNIX'):
434 if not util.safehasattr(socket, 'AF_UNIX'):
436 raise error.Abort(_('unsupported platform'))
435 raise error.Abort(_('unsupported platform'))
437 if not self.address:
436 if not self.address:
438 raise error.Abort(_('no socket path specified with --address'))
437 raise error.Abort(_('no socket path specified with --address'))
439 self._servicehandler = handler or unixservicehandler(ui)
438 self._servicehandler = handler or unixservicehandler(ui)
440 self._sock = None
439 self._sock = None
441 self._oldsigchldhandler = None
440 self._oldsigchldhandler = None
442 self._workerpids = set() # updated by signal handler; do not iterate
441 self._workerpids = set() # updated by signal handler; do not iterate
443
442
444 def init(self):
443 def init(self):
445 self._sock = socket.socket(socket.AF_UNIX)
444 self._sock = socket.socket(socket.AF_UNIX)
446 self._servicehandler.bindsocket(self._sock, self.address)
445 self._servicehandler.bindsocket(self._sock, self.address)
447 self._sock.listen(5)
446 self._sock.listen(5)
448 o = signal.signal(signal.SIGCHLD, self._sigchldhandler)
447 o = signal.signal(signal.SIGCHLD, self._sigchldhandler)
449 self._oldsigchldhandler = o
448 self._oldsigchldhandler = o
450 self._servicehandler.printbanner(self.address)
449 self._servicehandler.printbanner(self.address)
451
450
452 def _cleanup(self):
451 def _cleanup(self):
453 signal.signal(signal.SIGCHLD, self._oldsigchldhandler)
452 signal.signal(signal.SIGCHLD, self._oldsigchldhandler)
454 self._sock.close()
453 self._sock.close()
455 self._servicehandler.unlinksocket(self.address)
454 self._servicehandler.unlinksocket(self.address)
456 # don't kill child processes as they have active clients, just wait
455 # don't kill child processes as they have active clients, just wait
457 self._reapworkers(0)
456 self._reapworkers(0)
458
457
459 def run(self):
458 def run(self):
460 try:
459 try:
461 self._mainloop()
460 self._mainloop()
462 finally:
461 finally:
463 self._cleanup()
462 self._cleanup()
464
463
465 def _mainloop(self):
464 def _mainloop(self):
466 h = self._servicehandler
465 h = self._servicehandler
467 while not h.shouldexit():
466 while not h.shouldexit():
468 try:
467 try:
469 ready = select.select([self._sock], [], [], h.pollinterval)[0]
468 ready = select.select([self._sock], [], [], h.pollinterval)[0]
470 if not ready:
469 if not ready:
471 continue
470 continue
472 conn, _addr = self._sock.accept()
471 conn, _addr = self._sock.accept()
473 except (select.error, socket.error) as inst:
472 except (select.error, socket.error) as inst:
474 if inst.args[0] == errno.EINTR:
473 if inst.args[0] == errno.EINTR:
475 continue
474 continue
476 raise
475 raise
477
476
478 pid = os.fork()
477 pid = os.fork()
479 if pid:
478 if pid:
480 try:
479 try:
481 self.ui.debug('forked worker process (pid=%d)\n' % pid)
480 self.ui.debug('forked worker process (pid=%d)\n' % pid)
482 self._workerpids.add(pid)
481 self._workerpids.add(pid)
483 h.newconnection()
482 h.newconnection()
484 finally:
483 finally:
485 conn.close() # release handle in parent process
484 conn.close() # release handle in parent process
486 else:
485 else:
487 try:
486 try:
488 self._serveworker(conn)
487 self._serveworker(conn)
489 conn.close()
488 conn.close()
490 os._exit(0)
489 os._exit(0)
491 except: # never return, hence no re-raises
490 except: # never return, hence no re-raises
492 try:
491 try:
493 self.ui.traceback(force=True)
492 self.ui.traceback(force=True)
494 finally:
493 finally:
495 os._exit(255)
494 os._exit(255)
496
495
497 def _sigchldhandler(self, signal, frame):
496 def _sigchldhandler(self, signal, frame):
498 self._reapworkers(os.WNOHANG)
497 self._reapworkers(os.WNOHANG)
499
498
500 def _reapworkers(self, options):
499 def _reapworkers(self, options):
501 while self._workerpids:
500 while self._workerpids:
502 try:
501 try:
503 pid, _status = os.waitpid(-1, options)
502 pid, _status = os.waitpid(-1, options)
504 except OSError as inst:
503 except OSError as inst:
505 if inst.errno == errno.EINTR:
504 if inst.errno == errno.EINTR:
506 continue
505 continue
507 if inst.errno != errno.ECHILD:
506 if inst.errno != errno.ECHILD:
508 raise
507 raise
509 # no child processes at all (reaped by other waitpid()?)
508 # no child processes at all (reaped by other waitpid()?)
510 self._workerpids.clear()
509 self._workerpids.clear()
511 return
510 return
512 if pid == 0:
511 if pid == 0:
513 # no waitable child processes
512 # no waitable child processes
514 return
513 return
515 self.ui.debug('worker process exited (pid=%d)\n' % pid)
514 self.ui.debug('worker process exited (pid=%d)\n' % pid)
516 self._workerpids.discard(pid)
515 self._workerpids.discard(pid)
517
516
518 def _serveworker(self, conn):
517 def _serveworker(self, conn):
519 signal.signal(signal.SIGCHLD, self._oldsigchldhandler)
518 signal.signal(signal.SIGCHLD, self._oldsigchldhandler)
519 _initworkerprocess()
520 h = self._servicehandler
520 h = self._servicehandler
521 _serverequest(self.ui, self.repo, conn, h.createcmdserver)
521 try:
522 _serverequest(self.ui, self.repo, conn, h.createcmdserver)
523 finally:
524 gc.collect() # trigger __del__ since worker process uses os._exit
522
525
523 _servicemap = {
526 _servicemap = {
524 'pipe': pipeservice,
527 'pipe': pipeservice,
525 'unix': unixforkingservice,
528 'unix': unixforkingservice,
526 }
529 }
527
530
528 def createservice(ui, repo, opts):
531 def createservice(ui, repo, opts):
529 mode = opts['cmdserver']
532 mode = opts['cmdserver']
530 try:
533 try:
531 return _servicemap[mode](ui, repo, opts)
534 return _servicemap[mode](ui, repo, opts)
532 except KeyError:
535 except KeyError:
533 raise error.Abort(_('unknown mode %s') % mode)
536 raise error.Abort(_('unknown mode %s') % mode)
General Comments 0
You need to be logged in to leave comments. Login now