Pyinotify behaves oddly when the stdio file descriptors are closed.
[htsworkflow.git] / htsworkflow / automation / spoolwatcher.py
1 #!/usr/bin/env python
2 import logging
3 import os
4 import re
5 import shlex
6 import sys
7 import time
8
9 from htsworkflow.util import mount
10
11 # this uses pyinotify
12 import pyinotify
13 from pyinotify import EventsCodes
14
15 from benderjab import rpc
16
17 def get_top_dir(root, path):
18     """
19     Return the directory in path that is a subdirectory of root.
20     e.g.
21
22     >>> print get_top_dir('/a/b/c', '/a/b/c/d/e/f')
23     d
24     >>> print get_top_dir('/a/b/c/', '/a/b/c/d/e/f')
25     d
26     >>> print get_top_dir('/a/b/c', '/g/e/f')
27     None
28     >>> print get_top_dir('/a/b/c', '/a/b/c')
29     <BLANKLINE>
30     """
31     if path.startswith(root):
32         subpath = path[len(root):]
33         if subpath.startswith('/'):
34             subpath = subpath[1:]
35         return subpath.split(os.path.sep)[0]
36     else:
37         return None
38
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
44     #  cycles
45     # this should be per runfolder. 
46     # read the xml files 
47     def __init__(self):
48         pass
49         
50
51 class Handler(pyinotify.ProcessEvent):
52     def __init__(self, watchmanager, bot, ipar=False):
53         """
54         ipar flag indicates we should wait for ipar to finish, instead of 
55              just the run finishing
56         """
57         self.last_event = {}
58         self.watchmanager = watchmanager
59         self.bot = bot
60         self.ipar_mode = ipar
61         if self.ipar_mode:
62             self.last_file = 'IPAR_Netcopy_Complete.txt'.lower()
63         else:
64             self.last_file = "run.completed".lower()
65
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()
72
73                     msg = "Create: %s %s" % (event.path, event.name)
74
75                     if event.name.lower() == self.last_file:
76                         try:
77                             self.bot.sequencingFinished(event.path)
78                         except IOError, e:
79                             pass
80                             logging.error("Couldn't send sequencingFinished")
81                     logging.debug(msg)
82
83     def process_IN_DELETE(self, event):
84         logging.debug("Remove: %s" %  os.path.join(event.path, event.name))
85         pass
86
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)
91
92 class SpoolWatcher(rpc.XmlRpcBot):
93     """
94     Watch a directory and send a message when another process is done writing.
95     
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.
99     
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
102     
103     """
104     # these params need to be in the config file
105     # I wonder where I should put the documentation
106     #:Parameters:
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
110     #                      the spool
111     #    `notify_timeout` - how often to timeout from notify
112     
113     def __init__(self, section=None, configfile=None):
114         #if configfile is None:
115         #    self.configfile = "~/.htsworkflow"
116         super(SpoolWatcher, self).__init__(section, configfile)
117         
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
123        
124         self.watchdirs = []
125         self.watchdir_url_map = {}
126         self.notify_timeout = 0.001
127
128         self.wm = None 
129         self.notify_users = None
130         self.notify_runner = None
131         self.wdds = []
132
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 = {}
138         
139         self.eventTasks.append(self.process_notify)
140
141     def read_config(self, section=None, configfile=None):
142         super(SpoolWatcher, self).read_config(section, configfile)
143         
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)
148
149         self.write_timeout = int(self.cfg['write_timeout'])
150         self.wait_for_ipar = int(self.cfg['wait_for_ipar'])
151         
152         self.notify_users = self._parse_user_list(self.cfg['notify_users'])
153         try:
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)
160
161         self.handler = None
162         self.notifier = None
163
164     def add_watch(self, watchdirs=None):
165         """
166         start watching watchdir or self.watchdir
167         we're currently limited to watching one directory tree.
168         """
169         # create the watch managers if we need them
170         if self.wm is None:
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)
174
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
179
180         mask = EventsCodes.IN_CREATE | EventsCodes.IN_UNMOUNT
181         # rec traverses the tree and adds all the directories that are there
182         # at the start.
183         # auto_add will add in new directories as they are created
184         for w in watchdirs:
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, [])
188             if w not in mounts:
189                 mounts.append(w)
190                 self.mounts_to_watches[mount_location] = mounts
191
192             logging.info(u"Watching:"+unicode(w))
193             self.wdds.append(self.wm.add_watch(w, mask, rec=True, auto_add=True))
194
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):
199             wdd = self.wdds[i]
200             logging.info(u'unmounting: '+unicode(wdd.items()))
201             self.wm.rm_watch(wdd.values())
202             del self.wdds[i]
203         self.mounted = False
204             
205     def process_notify(self, *args):
206         if self.notifier is None:
207             # nothing to do yet
208             return
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!
228                 # restart the watch
229                 for watch in self.mounts_to_watches[mount_point]:
230                     self.add_watch(watch)
231                     logging.info(
232                         "%s was remounted, restarting watch" % \
233                             (mount_point)
234                     )
235                 self.mounted_points[mount_point] = True
236
237     def _parser(self, msg, who):
238         """
239         Parse xmpp chat messages
240         """
241         help = u"I can send [copy] message, or squencer [finished]"
242         if re.match(u"help", msg):
243             reply = help
244         elif re.match("copy", msg):            
245             self.startCopy()
246             reply = u"sent copy message"
247         elif re.match(u"finished", msg):
248             words = msg.split()
249             if len(words) == 2:
250                 self.sequencingFinished(words[1])
251                 reply = u"sending sequencing finished for %s" % (words[1])
252             else:
253                 reply = u"need runfolder name"
254         else:
255             reply = u"I didn't understand '%s'" %(msg)            
256         return reply
257         
258     def run(self):
259         """
260         Start application
261         """
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.
265         self.add_watch()
266         super(SpoolWatcher, self).run()
267         
268     def stop(self):
269         """
270         shutdown application
271         """
272         # destroy the inotify's instance on this interrupt (stop monitoring)
273         if self.notifier is not None:
274             self.notifier.stop()
275         super(SpoolWatcher, self).stop()
276     
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))
285         
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')
300         
301 def main(args=None):
302     bot = SpoolWatcher()
303     return bot.main(args)
304     
305 if __name__ == "__main__":
306     ret = main(sys.argv[1:])
307     #sys.exit(ret)
308
309 # TODO:
310 # send messages to copier specifying which mount to copy