debuggers.hg

view tools/python/xen/xend/xenstore/xswatch.py @ 0:7d21f7218375

Exact replica of unstable on 051908 + README-this
author Mukesh Rathor
date Mon May 19 15:34:57 2008 -0700 (2008-05-19)
parents
children 5c0bf00e371d
line source
1 # Copyright (C) 2005 Christian Limpach <Christian.Limpach@cl.cam.ac.uk>
2 # Copyright (C) 2005 XenSource Ltd
4 # This file is subject to the terms and conditions of the GNU General
5 # Public License. See the file "COPYING" in the main directory of
6 # this archive for more details.
8 import errno
9 import threading
10 from xen.xend.xenstore.xsutil import xshandle
12 from xen.xend.XendLogging import log
15 class xswatch:
17 ##
18 # Create a watch on the given path in the store. The watch will fire
19 # immediately, then subsequently each time the watched path is changed,
20 # until the watch is deregistered, either by the return value from the
21 # watch callback being False, or by an explicit call to unwatch.
22 #
23 # @param fn The function to be called when the watch fires. This function
24 # should take the path that has changed as its first argument, followed by
25 # the extra arguments given to this constructor, if any. It should return
26 # True if the watch is to remain registered, or False if it is to be
27 # deregistered.
28 #
29 def __init__(self, path, fn, *args, **kwargs):
30 self.path = path
31 self.fn = fn
32 self.args = args
33 self.kwargs = kwargs
34 watchStart()
35 xs.watch(path, self)
38 def unwatch(self):
39 xs.unwatch(self.path, self)
42 watchThread = None
43 xs = None
44 xslock = threading.Lock()
46 def watchStart():
47 global watchThread
48 global xs
50 xslock.acquire()
51 try:
52 if watchThread:
53 return
54 xs = xshandle()
55 watchThread = threading.Thread(name="Watcher", target=watchMain)
56 watchThread.setDaemon(True)
57 watchThread.start()
58 finally:
59 xslock.release()
62 def watchMain():
63 while True:
64 try:
65 we = xs.read_watch()
66 watch = we[1]
67 res = watch.fn(we[0], *watch.args, **watch.kwargs)
68 if not res:
69 try:
70 watch.unwatch()
71 except RuntimeError, exn:
72 if exn.args[0] == errno.ENOENT:
73 # The watch has already been unregistered -- that's
74 # fine.
75 pass
76 else:
77 raise
78 except:
79 log.exception("read_watch failed")
80 # Ignore this exception -- there's no point throwing it
81 # further on because that will just kill the watcher thread,
82 # which achieves nothing.