##// END OF EJS Templates
inotify: proper fix for issue1542 (partially reverting 67e59a9886d5)...
Nicolas Dumazet -
r8600:d46cdfce default
parent child Browse files
Show More
@@ -1,791 +1,791 b''
1 1 # server.py - inotify status server
2 2 #
3 3 # Copyright 2006, 2007, 2008 Bryan O'Sullivan <bos@serpentine.com>
4 4 # Copyright 2007, 2008 Brendan Cully <brendan@kublai.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2, incorporated herein by reference.
8 8
9 9 from mercurial.i18n import _
10 10 from mercurial import osutil, util
11 11 import common
12 12 import errno, os, select, socket, stat, struct, sys, tempfile, time
13 13
14 14 try:
15 15 import linux as inotify
16 16 from linux import watcher
17 17 except ImportError:
18 18 raise
19 19
20 20 class AlreadyStartedException(Exception): pass
21 21
22 22 def join(a, b):
23 23 if a:
24 24 if a[-1] == '/':
25 25 return a + b
26 26 return a + '/' + b
27 27 return b
28 28
29 29 walk_ignored_errors = (errno.ENOENT, errno.ENAMETOOLONG)
30 30
31 31 def walkrepodirs(repo):
32 32 '''Iterate over all subdirectories of this repo.
33 33 Exclude the .hg directory, any nested repos, and ignored dirs.'''
34 34 rootslash = repo.root + os.sep
35 35
36 36 def walkit(dirname, top):
37 37 fullpath = rootslash + dirname
38 38 try:
39 39 for name, kind in osutil.listdir(fullpath):
40 40 if kind == stat.S_IFDIR:
41 41 if name == '.hg':
42 42 if not top:
43 43 return
44 44 else:
45 45 d = join(dirname, name)
46 46 if repo.dirstate._ignore(d):
47 47 continue
48 48 for subdir in walkit(d, False):
49 49 yield subdir
50 50 except OSError, err:
51 51 if err.errno not in walk_ignored_errors:
52 52 raise
53 53 yield fullpath
54 54
55 55 return walkit('', True)
56 56
57 57 def walk(repo, root):
58 58 '''Like os.walk, but only yields regular files.'''
59 59
60 60 # This function is critical to performance during startup.
61 61
62 62 rootslash = repo.root + os.sep
63 63
64 64 def walkit(root, reporoot):
65 65 files, dirs = [], []
66 66
67 67 try:
68 68 fullpath = rootslash + root
69 69 for name, kind in osutil.listdir(fullpath):
70 70 if kind == stat.S_IFDIR:
71 71 if name == '.hg':
72 72 if not reporoot:
73 73 return
74 74 else:
75 75 dirs.append(name)
76 76 path = join(root, name)
77 77 if repo.dirstate._ignore(path):
78 78 continue
79 79 for result in walkit(path, False):
80 80 yield result
81 81 elif kind in (stat.S_IFREG, stat.S_IFLNK):
82 82 files.append(name)
83 83 yield fullpath, dirs, files
84 84
85 85 except OSError, err:
86 86 if err.errno not in walk_ignored_errors:
87 87 raise
88 88
89 89 return walkit(root, root == '')
90 90
91 91 def _explain_watch_limit(ui, repo, count):
92 92 path = '/proc/sys/fs/inotify/max_user_watches'
93 93 try:
94 94 limit = int(file(path).read())
95 95 except IOError, err:
96 96 if err.errno != errno.ENOENT:
97 97 raise
98 98 raise util.Abort(_('this system does not seem to '
99 99 'support inotify'))
100 100 ui.warn(_('*** the current per-user limit on the number '
101 101 'of inotify watches is %s\n') % limit)
102 102 ui.warn(_('*** this limit is too low to watch every '
103 103 'directory in this repository\n'))
104 104 ui.warn(_('*** counting directories: '))
105 105 ndirs = len(list(walkrepodirs(repo)))
106 106 ui.warn(_('found %d\n') % ndirs)
107 107 newlimit = min(limit, 1024)
108 108 while newlimit < ((limit + ndirs) * 1.1):
109 109 newlimit *= 2
110 110 ui.warn(_('*** to raise the limit from %d to %d (run as root):\n') %
111 111 (limit, newlimit))
112 112 ui.warn(_('*** echo %d > %s\n') % (newlimit, path))
113 113 raise util.Abort(_('cannot watch %s until inotify watch limit is raised')
114 114 % repo.root)
115 115
116 116 class repowatcher(object):
117 117 poll_events = select.POLLIN
118 118 statuskeys = 'almr!?'
119 119 mask = (
120 120 inotify.IN_ATTRIB |
121 121 inotify.IN_CREATE |
122 122 inotify.IN_DELETE |
123 123 inotify.IN_DELETE_SELF |
124 124 inotify.IN_MODIFY |
125 125 inotify.IN_MOVED_FROM |
126 126 inotify.IN_MOVED_TO |
127 127 inotify.IN_MOVE_SELF |
128 128 inotify.IN_ONLYDIR |
129 129 inotify.IN_UNMOUNT |
130 130 0)
131 131
132 132 def __init__(self, ui, repo, master):
133 133 self.ui = ui
134 134 self.repo = repo
135 135 self.wprefix = self.repo.wjoin('')
136 136 self.timeout = None
137 137 self.master = master
138 138 try:
139 139 self.watcher = watcher.watcher()
140 140 except OSError, err:
141 141 raise util.Abort(_('inotify service not available: %s') %
142 142 err.strerror)
143 143 self.threshold = watcher.threshold(self.watcher)
144 144 self.registered = True
145 145 self.fileno = self.watcher.fileno
146 146
147 147 self.tree = {}
148 148 self.statcache = {}
149 149 self.statustrees = dict([(s, {}) for s in self.statuskeys])
150 150
151 151 self.watches = 0
152 152 self.last_event = None
153 153
154 154 self.eventq = {}
155 155 self.deferred = 0
156 156
157 157 self.ds_info = self.dirstate_info()
158 158 self.scan()
159 159
160 160 def event_time(self):
161 161 last = self.last_event
162 162 now = time.time()
163 163 self.last_event = now
164 164
165 165 if last is None:
166 166 return 'start'
167 167 delta = now - last
168 168 if delta < 5:
169 169 return '+%.3f' % delta
170 170 if delta < 50:
171 171 return '+%.2f' % delta
172 172 return '+%.1f' % delta
173 173
174 174 def dirstate_info(self):
175 175 try:
176 176 st = os.lstat(self.repo.join('dirstate'))
177 177 return st.st_mtime, st.st_ino
178 178 except OSError, err:
179 179 if err.errno != errno.ENOENT:
180 180 raise
181 181 return 0, 0
182 182
183 183 def add_watch(self, path, mask):
184 184 if not path:
185 185 return
186 186 if self.watcher.path(path) is None:
187 187 if self.ui.debugflag:
188 188 self.ui.note(_('watching %r\n') % path[len(self.wprefix):])
189 189 try:
190 190 self.watcher.add(path, mask)
191 191 self.watches += 1
192 192 except OSError, err:
193 193 if err.errno in (errno.ENOENT, errno.ENOTDIR):
194 194 return
195 195 if err.errno != errno.ENOSPC:
196 196 raise
197 197 _explain_watch_limit(self.ui, self.repo, self.watches)
198 198
199 199 def setup(self):
200 200 self.ui.note(_('watching directories under %r\n') % self.repo.root)
201 201 self.add_watch(self.repo.path, inotify.IN_DELETE)
202 202 self.check_dirstate()
203 203
204 204 def wpath(self, evt):
205 205 path = evt.fullpath
206 206 if path == self.repo.root:
207 207 return ''
208 208 if path.startswith(self.wprefix):
209 209 return path[len(self.wprefix):]
210 210 raise 'wtf? ' + path
211 211
212 212 def dir(self, tree, path):
213 213 if path:
214 214 for name in path.split('/'):
215 215 tree = tree.setdefault(name, {})
216 216 return tree
217 217
218 218 def lookup(self, path, tree):
219 219 if path:
220 220 try:
221 221 for name in path.split('/'):
222 222 tree = tree[name]
223 223 except KeyError:
224 224 return 'x'
225 225 except TypeError:
226 226 return 'd'
227 227 return tree
228 228
229 229 def split(self, path):
230 230 c = path.rfind('/')
231 231 if c == -1:
232 232 return '', path
233 233 return path[:c], path[c+1:]
234 234
235 235 def filestatus(self, fn, st):
236 236 try:
237 237 type_, mode, size, time = self.repo.dirstate._map[fn][:4]
238 238 except KeyError:
239 239 type_ = '?'
240 240 if type_ == 'n':
241 241 st_mode, st_size, st_mtime = st
242 242 if size == -1:
243 243 return 'l'
244 244 if size and (size != st_size or (mode ^ st_mode) & 0100):
245 245 return 'm'
246 246 if time != int(st_mtime):
247 247 return 'l'
248 248 return 'n'
249 249 if type_ == '?' and self.repo.dirstate._ignore(fn):
250 250 return 'i'
251 251 return type_
252 252
253 253 def updatefile(self, wfn, osstat):
254 254 '''
255 255 update the file entry of an existing file.
256 256
257 257 osstat: (mode, size, time) tuple, as returned by os.lstat(wfn)
258 258 '''
259 259
260 260 self._updatestatus(wfn, self.filestatus(wfn, osstat))
261 261
262 262 def deletefile(self, wfn, oldstatus):
263 263 '''
264 264 update the entry of a file which has been deleted.
265 265
266 266 oldstatus: char in statuskeys, status of the file before deletion
267 267 '''
268 268 if oldstatus == 'r':
269 269 newstatus = 'r'
270 270 elif oldstatus in 'almn':
271 271 newstatus = '!'
272 272 else:
273 273 newstatus = None
274 274
275 275 self.statcache.pop(wfn, None)
276 276 self._updatestatus(wfn, newstatus)
277 277
278 278 def _updatestatus(self, wfn, newstatus):
279 279 '''
280 280 Update the stored status of a file or directory.
281 281
282 282 newstatus: - char in (statuskeys + 'ni'), new status to apply.
283 283 - or None, to stop tracking wfn
284 284 '''
285 285 root, fn = self.split(wfn)
286 286 d = self.dir(self.tree, root)
287 287
288 288 oldstatus = d.get(fn)
289 289 # oldstatus can be either:
290 290 # - None : fn is new
291 291 # - a char in statuskeys: fn is a (tracked) file
292 292 # - a dict: fn is a directory
293 293 isdir = isinstance(oldstatus, dict)
294 294
295 295 if self.ui.debugflag and oldstatus != newstatus:
296 296 if isdir:
297 297 self.ui.note(_('status: %r dir(%d) -> %s\n') %
298 298 (wfn, len(oldstatus), newstatus))
299 299 else:
300 300 self.ui.note(_('status: %r %s -> %s\n') %
301 301 (wfn, oldstatus, newstatus))
302 302 if not isdir:
303 303 if oldstatus and oldstatus in self.statuskeys \
304 304 and oldstatus != newstatus:
305 305 del self.dir(self.statustrees[oldstatus], root)[fn]
306 306 if newstatus and newstatus != 'i':
307 307 d[fn] = newstatus
308 308 if newstatus in self.statuskeys:
309 309 dd = self.dir(self.statustrees[newstatus], root)
310 310 if oldstatus != newstatus or fn not in dd:
311 311 dd[fn] = newstatus
312 312 else:
313 313 d.pop(fn, None)
314 elif not newstatus:
315 # a directory is being removed, check its contents
316 for subfile, b in oldstatus.copy().iteritems():
317 self._updatestatus(wfn + '/' + subfile, None)
318 314
319 315
320 316 def check_deleted(self, key):
321 317 # Files that had been deleted but were present in the dirstate
322 318 # may have vanished from the dirstate; we must clean them up.
323 319 nuke = []
324 320 for wfn, ignore in self.walk(key, self.statustrees[key]):
325 321 if wfn not in self.repo.dirstate:
326 322 nuke.append(wfn)
327 323 for wfn in nuke:
328 324 root, fn = self.split(wfn)
329 325 del self.dir(self.statustrees[key], root)[fn]
330 326 del self.dir(self.tree, root)[fn]
331 327
332 328 def scan(self, topdir=''):
333 329 self.handle_timeout()
334 330 ds = self.repo.dirstate._map.copy()
335 331 self.add_watch(join(self.repo.root, topdir), self.mask)
336 332 for root, dirs, files in walk(self.repo, topdir):
337 333 for d in dirs:
338 334 self.add_watch(join(root, d), self.mask)
339 335 wroot = root[len(self.wprefix):]
340 336 d = self.dir(self.tree, wroot)
341 337 for fn in files:
342 338 wfn = join(wroot, fn)
343 339 self.updatefile(wfn, self.getstat(wfn))
344 340 ds.pop(wfn, None)
345 341 wtopdir = topdir
346 342 if wtopdir and wtopdir[-1] != '/':
347 343 wtopdir += '/'
348 344 for wfn, state in ds.iteritems():
349 345 if not wfn.startswith(wtopdir):
350 346 continue
351 347 try:
352 348 st = self.stat(wfn)
353 349 except OSError:
354 350 status = state[0]
355 351 self.deletefile(wfn, status)
356 352 else:
357 353 self.updatefile(wfn, st)
358 354 self.check_deleted('!')
359 355 self.check_deleted('r')
360 356
361 357 def check_dirstate(self):
362 358 ds_info = self.dirstate_info()
363 359 if ds_info == self.ds_info:
364 360 return
365 361 self.ds_info = ds_info
366 362 if not self.ui.debugflag:
367 363 self.last_event = None
368 364 self.ui.note(_('%s dirstate reload\n') % self.event_time())
369 365 self.repo.dirstate.invalidate()
370 366 self.scan()
371 367 self.ui.note(_('%s end dirstate reload\n') % self.event_time())
372 368
373 369 def walk(self, states, tree, prefix=''):
374 370 # This is the "inner loop" when talking to the client.
375 371
376 372 for name, val in tree.iteritems():
377 373 path = join(prefix, name)
378 374 try:
379 375 if val in states:
380 376 yield path, val
381 377 except TypeError:
382 378 for p in self.walk(states, val, path):
383 379 yield p
384 380
385 381 def update_hgignore(self):
386 382 # An update of the ignore file can potentially change the
387 383 # states of all unknown and ignored files.
388 384
389 385 # XXX If the user has other ignore files outside the repo, or
390 386 # changes their list of ignore files at run time, we'll
391 387 # potentially never see changes to them. We could get the
392 388 # client to report to us what ignore data they're using.
393 389 # But it's easier to do nothing than to open that can of
394 390 # worms.
395 391
396 392 if '_ignore' in self.repo.dirstate.__dict__:
397 393 delattr(self.repo.dirstate, '_ignore')
398 394 self.ui.note(_('rescanning due to .hgignore change\n'))
399 395 self.scan()
400 396
401 397 def getstat(self, wpath):
402 398 try:
403 399 return self.statcache[wpath]
404 400 except KeyError:
405 401 try:
406 402 return self.stat(wpath)
407 403 except OSError, err:
408 404 if err.errno != errno.ENOENT:
409 405 raise
410 406
411 407 def stat(self, wpath):
412 408 try:
413 409 st = os.lstat(join(self.wprefix, wpath))
414 410 ret = st.st_mode, st.st_size, st.st_mtime
415 411 self.statcache[wpath] = ret
416 412 return ret
417 413 except OSError:
418 414 self.statcache.pop(wpath, None)
419 415 raise
420 416
421 417 def created(self, wpath):
422 418 if wpath == '.hgignore':
423 419 self.update_hgignore()
424 420 try:
425 421 st = self.stat(wpath)
426 422 if stat.S_ISREG(st[0]):
427 423 self.updatefile(wpath, st)
428 424 except OSError:
429 425 pass
430 426
431 427 def modified(self, wpath):
432 428 if wpath == '.hgignore':
433 429 self.update_hgignore()
434 430 try:
435 431 st = self.stat(wpath)
436 432 if stat.S_ISREG(st[0]):
437 433 if self.repo.dirstate[wpath] in 'lmn':
438 434 self.updatefile(wpath, st)
439 435 except OSError:
440 436 pass
441 437
442 438 def deleted(self, wpath):
443 439 if wpath == '.hgignore':
444 440 self.update_hgignore()
445 441 elif wpath.startswith('.hg/'):
446 442 if wpath == '.hg/wlock':
447 443 self.check_dirstate()
448 444 return
449 445
450 446 self.deletefile(wpath, self.repo.dirstate[wpath])
451 447
452 448 def schedule_work(self, wpath, evt):
453 449 prev = self.eventq.setdefault(wpath, [])
454 450 try:
455 451 if prev and evt == 'm' and prev[-1] in 'cm':
456 452 return
457 453 self.eventq[wpath].append(evt)
458 454 finally:
459 455 self.deferred += 1
460 456 self.timeout = 250
461 457
462 458 def deferred_event(self, wpath, evt):
463 459 if evt == 'c':
464 460 self.created(wpath)
465 461 elif evt == 'm':
466 462 self.modified(wpath)
467 463 elif evt == 'd':
468 464 self.deleted(wpath)
469 465
470 466 def process_create(self, wpath, evt):
471 467 if self.ui.debugflag:
472 468 self.ui.note(_('%s event: created %s\n') %
473 469 (self.event_time(), wpath))
474 470
475 471 if evt.mask & inotify.IN_ISDIR:
476 472 self.scan(wpath)
477 473 else:
478 474 self.schedule_work(wpath, 'c')
479 475
480 476 def process_delete(self, wpath, evt):
481 477 if self.ui.debugflag:
482 478 self.ui.note(_('%s event: deleted %s\n') %
483 479 (self.event_time(), wpath))
484 480
485 481 if evt.mask & inotify.IN_ISDIR:
482 tree = self.dir(self.tree, wpath).copy()
483 for wfn, ignore in self.walk('?', tree):
484 self.deletefile(join(wpath, wfn), '?')
486 485 self.scan(wpath)
487 self.schedule_work(wpath, 'd')
486 else:
487 self.schedule_work(wpath, 'd')
488 488
489 489 def process_modify(self, wpath, evt):
490 490 if self.ui.debugflag:
491 491 self.ui.note(_('%s event: modified %s\n') %
492 492 (self.event_time(), wpath))
493 493
494 494 if not (evt.mask & inotify.IN_ISDIR):
495 495 self.schedule_work(wpath, 'm')
496 496
497 497 def process_unmount(self, evt):
498 498 self.ui.warn(_('filesystem containing %s was unmounted\n') %
499 499 evt.fullpath)
500 500 sys.exit(0)
501 501
502 502 def handle_event(self, fd, event):
503 503 if self.ui.debugflag:
504 504 self.ui.note(_('%s readable: %d bytes\n') %
505 505 (self.event_time(), self.threshold.readable()))
506 506 if not self.threshold():
507 507 if self.registered:
508 508 if self.ui.debugflag:
509 509 self.ui.note(_('%s below threshold - unhooking\n') %
510 510 (self.event_time()))
511 511 self.master.poll.unregister(fd)
512 512 self.registered = False
513 513 self.timeout = 250
514 514 else:
515 515 self.read_events()
516 516
517 517 def read_events(self, bufsize=None):
518 518 events = self.watcher.read(bufsize)
519 519 if self.ui.debugflag:
520 520 self.ui.note(_('%s reading %d events\n') %
521 521 (self.event_time(), len(events)))
522 522 for evt in events:
523 523 wpath = self.wpath(evt)
524 524 if evt.mask & inotify.IN_UNMOUNT:
525 525 self.process_unmount(wpath, evt)
526 526 elif evt.mask & (inotify.IN_MODIFY | inotify.IN_ATTRIB):
527 527 self.process_modify(wpath, evt)
528 528 elif evt.mask & (inotify.IN_DELETE | inotify.IN_DELETE_SELF |
529 529 inotify.IN_MOVED_FROM):
530 530 self.process_delete(wpath, evt)
531 531 elif evt.mask & (inotify.IN_CREATE | inotify.IN_MOVED_TO):
532 532 self.process_create(wpath, evt)
533 533
534 534 def handle_timeout(self):
535 535 if not self.registered:
536 536 if self.ui.debugflag:
537 537 self.ui.note(_('%s hooking back up with %d bytes readable\n') %
538 538 (self.event_time(), self.threshold.readable()))
539 539 self.read_events(0)
540 540 self.master.poll.register(self, select.POLLIN)
541 541 self.registered = True
542 542
543 543 if self.eventq:
544 544 if self.ui.debugflag:
545 545 self.ui.note(_('%s processing %d deferred events as %d\n') %
546 546 (self.event_time(), self.deferred,
547 547 len(self.eventq)))
548 548 for wpath, evts in sorted(self.eventq.iteritems()):
549 549 for evt in evts:
550 550 self.deferred_event(wpath, evt)
551 551 self.eventq.clear()
552 552 self.deferred = 0
553 553 self.timeout = None
554 554
555 555 def shutdown(self):
556 556 self.watcher.close()
557 557
558 558 def debug(self):
559 559 """
560 560 Returns a sorted list of relatives paths currently watched,
561 561 for debugging purposes.
562 562 """
563 563 return sorted(tuple[0][len(self.wprefix):] for tuple in self.watcher)
564 564
565 565 class server(object):
566 566 poll_events = select.POLLIN
567 567
568 568 def __init__(self, ui, repo, repowatcher, timeout):
569 569 self.ui = ui
570 570 self.repo = repo
571 571 self.repowatcher = repowatcher
572 572 self.timeout = timeout
573 573 self.sock = socket.socket(socket.AF_UNIX)
574 574 self.sockpath = self.repo.join('inotify.sock')
575 575 self.realsockpath = None
576 576 try:
577 577 self.sock.bind(self.sockpath)
578 578 except socket.error, err:
579 579 if err[0] == errno.EADDRINUSE:
580 580 raise AlreadyStartedException(_('could not start server: %s')
581 581 % err[1])
582 582 if err[0] == "AF_UNIX path too long":
583 583 tempdir = tempfile.mkdtemp(prefix="hg-inotify-")
584 584 self.realsockpath = os.path.join(tempdir, "inotify.sock")
585 585 try:
586 586 self.sock.bind(self.realsockpath)
587 587 os.symlink(self.realsockpath, self.sockpath)
588 588 except (OSError, socket.error), inst:
589 589 try:
590 590 os.unlink(self.realsockpath)
591 591 except:
592 592 pass
593 593 os.rmdir(tempdir)
594 594 if inst.errno == errno.EEXIST:
595 595 raise AlreadyStartedException(_('could not start server: %s')
596 596 % inst.strerror)
597 597 raise
598 598 else:
599 599 raise
600 600 self.sock.listen(5)
601 601 self.fileno = self.sock.fileno
602 602
603 603 def handle_timeout(self):
604 604 pass
605 605
606 606 def answer_stat_query(self, cs):
607 607 names = cs.read().split('\0')
608 608
609 609 states = names.pop()
610 610
611 611 self.ui.note(_('answering query for %r\n') % states)
612 612
613 613 if self.repowatcher.timeout:
614 614 # We got a query while a rescan is pending. Make sure we
615 615 # rescan before responding, or we could give back a wrong
616 616 # answer.
617 617 self.repowatcher.handle_timeout()
618 618
619 619 if not names:
620 620 def genresult(states, tree):
621 621 for fn, state in self.repowatcher.walk(states, tree):
622 622 yield fn
623 623 else:
624 624 def genresult(states, tree):
625 625 for fn in names:
626 626 l = self.repowatcher.lookup(fn, tree)
627 627 try:
628 628 if l in states:
629 629 yield fn
630 630 except TypeError:
631 631 for f, s in self.repowatcher.walk(states, l, fn):
632 632 yield f
633 633
634 634 return ['\0'.join(r) for r in [
635 635 genresult('l', self.repowatcher.statustrees['l']),
636 636 genresult('m', self.repowatcher.statustrees['m']),
637 637 genresult('a', self.repowatcher.statustrees['a']),
638 638 genresult('r', self.repowatcher.statustrees['r']),
639 639 genresult('!', self.repowatcher.statustrees['!']),
640 640 '?' in states
641 641 and genresult('?', self.repowatcher.statustrees['?'])
642 642 or [],
643 643 [],
644 644 'c' in states and genresult('n', self.repowatcher.tree) or [],
645 645 ]]
646 646
647 647 def answer_dbug_query(self):
648 648 return ['\0'.join(self.repowatcher.debug())]
649 649
650 650 def handle_event(self, fd, event):
651 651 sock, addr = self.sock.accept()
652 652
653 653 cs = common.recvcs(sock)
654 654 version = ord(cs.read(1))
655 655
656 656 if version != common.version:
657 657 self.ui.warn(_('received query from incompatible client '
658 658 'version %d\n') % version)
659 659 return
660 660
661 661 type = cs.read(4)
662 662
663 663 if type == 'STAT':
664 664 results = self.answer_stat_query(cs)
665 665 elif type == 'DBUG':
666 666 results = self.answer_dbug_query()
667 667 else:
668 668 self.ui.warn(_('unrecognized query type: %s\n') % type)
669 669 return
670 670
671 671 try:
672 672 try:
673 673 v = chr(common.version)
674 674
675 675 sock.sendall(v + type + struct.pack(common.resphdrfmts[type],
676 676 *map(len, results)))
677 677 sock.sendall(''.join(results))
678 678 finally:
679 679 sock.shutdown(socket.SHUT_WR)
680 680 except socket.error, err:
681 681 if err[0] != errno.EPIPE:
682 682 raise
683 683
684 684 def shutdown(self):
685 685 self.sock.close()
686 686 try:
687 687 os.unlink(self.sockpath)
688 688 if self.realsockpath:
689 689 os.unlink(self.realsockpath)
690 690 os.rmdir(os.path.dirname(self.realsockpath))
691 691 except OSError, err:
692 692 if err.errno != errno.ENOENT:
693 693 raise
694 694
695 695 class master(object):
696 696 def __init__(self, ui, repo, timeout=None):
697 697 self.ui = ui
698 698 self.repo = repo
699 699 self.poll = select.poll()
700 700 self.repowatcher = repowatcher(ui, repo, self)
701 701 self.server = server(ui, repo, self.repowatcher, timeout)
702 702 self.table = {}
703 703 for obj in (self.repowatcher, self.server):
704 704 fd = obj.fileno()
705 705 self.table[fd] = obj
706 706 self.poll.register(fd, obj.poll_events)
707 707
708 708 def register(self, fd, mask):
709 709 self.poll.register(fd, mask)
710 710
711 711 def shutdown(self):
712 712 for obj in self.table.itervalues():
713 713 obj.shutdown()
714 714
715 715 def run(self):
716 716 self.repowatcher.setup()
717 717 self.ui.note(_('finished setup\n'))
718 718 if os.getenv('TIME_STARTUP'):
719 719 sys.exit(0)
720 720 while True:
721 721 timeout = None
722 722 timeobj = None
723 723 for obj in self.table.itervalues():
724 724 if obj.timeout is not None and (timeout is None or obj.timeout < timeout):
725 725 timeout, timeobj = obj.timeout, obj
726 726 try:
727 727 if self.ui.debugflag:
728 728 if timeout is None:
729 729 self.ui.note(_('polling: no timeout\n'))
730 730 else:
731 731 self.ui.note(_('polling: %sms timeout\n') % timeout)
732 732 events = self.poll.poll(timeout)
733 733 except select.error, err:
734 734 if err[0] == errno.EINTR:
735 735 continue
736 736 raise
737 737 if events:
738 738 for fd, event in events:
739 739 self.table[fd].handle_event(fd, event)
740 740 elif timeobj:
741 741 timeobj.handle_timeout()
742 742
743 743 def start(ui, repo):
744 744 def closefds(ignore):
745 745 # (from python bug #1177468)
746 746 # close all inherited file descriptors
747 747 # Python 2.4.1 and later use /dev/urandom to seed the random module's RNG
748 748 # a file descriptor is kept internally as os._urandomfd (created on demand
749 749 # the first time os.urandom() is called), and should not be closed
750 750 try:
751 751 os.urandom(4)
752 752 urandom_fd = getattr(os, '_urandomfd', None)
753 753 except AttributeError:
754 754 urandom_fd = None
755 755 ignore.append(urandom_fd)
756 756 for fd in range(3, 256):
757 757 if fd in ignore:
758 758 continue
759 759 try:
760 760 os.close(fd)
761 761 except OSError:
762 762 pass
763 763
764 764 m = master(ui, repo)
765 765 sys.stdout.flush()
766 766 sys.stderr.flush()
767 767
768 768 pid = os.fork()
769 769 if pid:
770 770 return pid
771 771
772 772 closefds([m.server.fileno(), m.repowatcher.fileno()])
773 773 os.setsid()
774 774
775 775 fd = os.open('/dev/null', os.O_RDONLY)
776 776 os.dup2(fd, 0)
777 777 if fd > 0:
778 778 os.close(fd)
779 779
780 780 fd = os.open(ui.config('inotify', 'log', '/dev/null'),
781 781 os.O_RDWR | os.O_CREAT | os.O_TRUNC)
782 782 os.dup2(fd, 1)
783 783 os.dup2(fd, 2)
784 784 if fd > 2:
785 785 os.close(fd)
786 786
787 787 try:
788 788 m.run()
789 789 finally:
790 790 m.shutdown()
791 791 os._exit(0)
General Comments 0
You need to be logged in to leave comments. Login now