9 from htsworkflow.util import mount
13 from pyinotify import EventsCodes
15 from benderjab import rpc
17 def get_top_dir(root, path):
19 Return the directory in path that is a subdirectory of root.
22 >>> print get_top_dir('/a/b/c', '/a/b/c/d/e/f')
24 >>> print get_top_dir('/a/b/c/', '/a/b/c/d/e/f')
26 >>> print get_top_dir('/a/b/c', '/g/e/f')
28 >>> print get_top_dir('/a/b/c', '/a/b/c')
31 if path.startswith(root):
32 subpath = path[len(root):]
33 if subpath.startswith('/'):
35 return subpath.split(os.path.sep)[0]
39 class WatcherEvents(object):
40 # two events need to be tracked
41 # one to send startCopy
42 # one to send OMG its broken
43 # OMG its broken needs to stop when we've seen enough
45 # this should be per runfolder.
51 class Handler(pyinotify.ProcessEvent):
52 def __init__(self, watchmanager, bot, ipar=False):
54 ipar flag indicates we should wait for ipar to finish, instead of
55 just the run finishing
58 self.watchmanager = watchmanager
62 self.last_file = 'IPAR_Netcopy_Complete.txt'.lower()
64 self.last_file = "run.completed".lower()
66 def process_IN_CREATE(self, event):
67 for wdd in self.bot.wdds:
68 for watch_path in self.bot.watchdirs:
69 if event.path.startswith(watch_path):
70 target = get_top_dir(watch_path, event.path)
71 self.last_event.setdefault(watch_path, {})[target] = time.time()
73 msg = "Create: %s %s" % (event.path, event.name)
75 if event.name.lower() == self.last_file:
77 self.bot.sequencingFinished(event.path)
80 logging.error("Couldn't send sequencingFinished")
83 def process_IN_DELETE(self, event):
84 logging.debug("Remove: %s" % os.path.join(event.path, event.name))
87 def process_IN_UNMOUNT(self, event):
88 pathname = os.path.join(event.path, event.name)
89 logging.debug("IN_UNMOUNT: %s" % (pathname,))
90 self.bot.unmount_watch(event.path)
92 class SpoolWatcher(rpc.XmlRpcBot):
94 Watch a directory and send a message when another process is done writing.
96 This monitors a directory tree using inotify (linux specific) and
97 after some files having been written will send a message after <timeout>
98 seconds of no file writing.
100 (Basically when the solexa machine finishes dumping a round of data
101 this'll hopefully send out a message saying hey look theres data available
104 # these params need to be in the config file
105 # I wonder where I should put the documentation
107 # `watchdirs` - list of directories to monitor for modifications
108 # `profile` - specify which .htsworkflow profile to use
109 # `write_timeout` - how many seconds to wait for writes to finish to
111 # `notify_timeout` - how often to timeout from notify
113 def __init__(self, section=None, configfile=None):
114 #if configfile is None:
115 # self.configfile = "~/.htsworkflow"
116 super(SpoolWatcher, self).__init__(section, configfile)
118 self.cfg['watchdirs'] = None
119 self.cfg['write_timeout'] = 10
120 self.cfg['notify_users'] = None
121 self.cfg['notify_runner'] = None
122 self.cfg['wait_for_ipar'] = 0
125 self.watchdir_url_map = {}
126 self.notify_timeout = 0.001
129 self.notify_users = None
130 self.notify_runner = None
133 # keep track if the specified mount point is currently mounted
134 self.mounted_points = {}
135 # keep track of which mount points tie to which watch directories
136 # so maybe we can remount them.
137 self.mounts_to_watches = {}
139 self.eventTasks.append(self.process_notify)
141 def read_config(self, section=None, configfile=None):
142 super(SpoolWatcher, self).read_config(section, configfile)
144 self.watchdirs = shlex.split(self._check_required_option('watchdirs'))
145 # see if there's an alternate url that should be used for the watchdir
146 for watchdir in self.watchdirs:
147 self.watchdir_url_map[watchdir] = self.cfg.get(watchdir, watchdir)
149 self.write_timeout = int(self.cfg['write_timeout'])
150 self.wait_for_ipar = int(self.cfg['wait_for_ipar'])
152 self.notify_users = self._parse_user_list(self.cfg['notify_users'])
154 self.notify_runner = \
155 self._parse_user_list(self.cfg['notify_runner'],
156 require_resource=True)
157 except bot.JIDMissingResource:
158 msg = 'need a full jabber ID + resource for xml-rpc destinations'
159 raise bot.JIDMissingResource(msg)
164 def add_watch(self, watchdirs=None):
166 start watching watchdir or self.watchdir
167 we're currently limited to watching one directory tree.
169 # create the watch managers if we need them
171 self.wm = pyinotify.WatchManager()
172 self.handler = Handler(self.wm, self, self.wait_for_ipar)
173 self.notifier = pyinotify.Notifier(self.wm, self.handler)
175 # the one tree limit is mostly because self.wdd is a single item
176 # but managing it as a list might be a bit more annoying
177 if watchdirs is None:
178 watchdirs = self.watchdirs
180 mask = EventsCodes.IN_CREATE | EventsCodes.IN_UNMOUNT
181 # rec traverses the tree and adds all the directories that are there
183 # auto_add will add in new directories as they are created
185 mount_location = mount.find_mount_point_for(w)
186 self.mounted_points[mount_location] = True
187 mounts = self.mounts_to_watches.get(mount_location, [])
190 self.mounts_to_watches[mount_location] = mounts
192 logging.info(u"Watching:"+unicode(w))
193 self.wdds.append(self.wm.add_watch(w, mask, rec=True, auto_add=True))
195 def unmount_watch(self, event_path):
196 # remove backwards so we don't get weirdness from
197 # the list getting shorter
198 for i in range(len(self.wdds),0, -1):
200 logging.info(u'unmounting: '+unicode(wdd.items()))
201 self.wm.rm_watch(wdd.values())
205 def process_notify(self, *args):
206 if self.notifier is None:
209 # process the queue of events as explained above
210 self.notifier.process_events()
211 #check events waits timeout
212 if self.notifier.check_events(self.notify_timeout):
213 # read notified events and enqeue them
214 self.notifier.read_events()
215 # should we do something?
216 # has something happened?
217 for watchdir, last_events in self.handler.last_event.items():
218 #logging.debug('last_events: %s %s' % (watchdir, last_events))
219 for last_event_dir, last_event_time in last_events.items():
220 time_delta = time.time() - last_event_time
221 if time_delta > self.write_timeout:
222 self.startCopy(watchdir, last_event_dir)
223 self.handler.last_event[watchdir] = {}
224 # handle unmounted filesystems
225 for mount_point, was_mounted in self.mounted_points.items():
226 if not was_mounted and mount.is_mounted(mount_point):
227 # we've been remounted. Huzzah!
229 for watch in self.mounts_to_watches[mount_point]:
230 self.add_watch(watch)
232 "%s was remounted, restarting watch" % \
235 self.mounted_points[mount_point] = True
237 def _parser(self, msg, who):
239 Parse xmpp chat messages
241 help = u"I can send [copy] message, or squencer [finished]"
242 if re.match(u"help", msg):
244 elif re.match("copy", msg):
246 reply = u"sent copy message"
247 elif re.match(u"finished", msg):
250 self.sequencingFinished(words[1])
251 reply = u"sending sequencing finished for %s" % (words[1])
253 reply = u"need runfolder name"
255 reply = u"I didn't understand '%s'" %(msg)
262 # we have to configure pyinotify after BenderJab.start is called
263 # as weird things happen to pyinotify if the stdio is closed
264 # after it's initialized.
266 super(SpoolWatcher, self).run()
272 # destroy the inotify's instance on this interrupt (stop monitoring)
273 if self.notifier is not None:
275 super(SpoolWatcher, self).stop()
277 def startCopy(self, watchdir=None, event_path=None):
278 logging.debug("writes seem to have stopped")
279 if self.notify_runner is not None:
280 for r in self.notify_runner:
281 self.rpc_send(r, tuple(), 'startCopy')
282 if self.notify_users is not None:
283 for u in self.notify_users:
284 self.send(u, 'startCopy %s %s' % (watchdir, event_path))
286 def sequencingFinished(self, run_dir):
287 # need to strip off self.watchdirs from rundir I suspect.
288 logging.info("run.completed in " + str(run_dir))
289 pattern = self.watch_dir
290 if pattern[-1] != os.path.sep:
291 pattern += os.path.sep
292 stripped_run_dir = re.sub(pattern, "", run_dir)
293 logging.debug("stripped to " + stripped_run_dir)
294 if self.notify_users is not None:
295 for u in self.notify_users:
296 self.send(u, 'Sequencing run %s finished' % (stripped_run_dir))
297 if self.notify_runner is not None:
298 for r in self.notify_runner:
299 self.rpc_send(r, (stripped_run_dir,), 'sequencingFinished')
303 return bot.main(args)
305 if __name__ == "__main__":
306 ret = main(sys.argv[1:])
310 # send messages to copier specifying which mount to copy