308ea3e07c39ea017443c970d368d67bd4ea57c9
[htsworkflow.git] / gaworkflow / automation / spoolwatcher.py
1 #!/usr/bin/env python
2 import logging
3 import os
4 import re
5 import sys
6 import time
7
8 # this uses pyinotify
9 import pyinotify
10 from pyinotify import EventsCodes
11
12 from benderjab import rpc
13
14 class WatcherEvents(object):
15     # two events need to be tracked
16     # one to send startCopy
17     # one to send OMG its broken
18     # OMG its broken needs to stop when we've seen enough
19     #  cycles
20     # this should be per runfolder. 
21     # read the xml files 
22     def __init__(self):
23         pass
24         
25
26 class Handler(pyinotify.ProcessEvent):
27     def __init__(self, watchmanager, bot):
28         self.last_event_time = None
29         self.watchmanager = watchmanager
30         self.bot = bot
31
32     def process_IN_CREATE(self, event):
33         self.last_event_time = time.time()
34         msg = "Create: %s" %  os.path.join(event.path, event.name)
35         if event.name.lower() == "run.completed":
36             try:
37                 self.bot.sequencingFinished(event.path)
38             except IOError, e:
39                 logging.error("Couldn't send sequencingFinished")
40         logging.debug(msg)
41
42     def process_IN_DELETE(self, event):
43         logging.debug("Remove: %s" %  os.path.join(event.path, event.name))
44
45     def process_IN_UNMOUNT(self, event):
46         self.bot.unmount_watch()
47
48 class SpoolWatcher(rpc.XmlRpcBot):
49     """
50     Watch a directory and send a message when another process is done writing.
51     
52     This monitors a directory tree using inotify (linux specific) and
53     after some files having been written will send a message after <timeout>
54     seconds of no file writing.
55     
56     (Basically when the solexa machine finishes dumping a round of data
57     this'll hopefully send out a message saying hey look theres data available
58     
59     """
60     # these params need to be in the config file
61     # I wonder where I should put the documentation
62     #:Parameters:
63     #    `watchdir` - which directory tree to monitor for modifications
64     #    `profile` - specify which .gaworkflow profile to use
65     #    `write_timeout` - how many seconds to wait for writes to finish to
66     #                      the spool
67     #    `notify_timeout` - how often to timeout from notify
68     
69     def __init__(self, section=None, configfile=None):
70         #if configfile is None:
71         #    self.configfile = "~/.gaworkflow"
72         super(SpoolWatcher, self).__init__(section, configfile)
73         
74         self.cfg['watchdir'] = None
75         self.cfg['write_timeout'] = 10
76         self.cfg['notify_users'] = None
77         self.cfg['notify_runner'] = None
78         
79         self.notify_timeout = 0.001
80         self.wm = pyinotify.WatchManager()
81         self.handler = Handler(self.wm, self)
82         self.notifier = pyinotify.Notifier(self.wm, self.handler)
83         self.wdd = None
84         
85         self.notify_users = None
86         self.notify_runner = None
87         
88         self.eventTasks.append(self.process_notify)
89
90     def read_config(self, section=None, configfile=None):
91         super(SpoolWatcher, self).read_config(section, configfile)
92         
93         self.watch_dir = self._check_required_option('watchdir')
94         self.write_timeout = int(self.cfg['write_timeout'])
95         
96         self.notify_users = self._parse_user_list(self.cfg['notify_users'])
97         try:
98           self.notify_runner = \
99              self._parse_user_list(self.cfg['notify_runner'],
100                                    require_resource=True)
101         except bot.JIDMissingResource:
102             msg = 'need a full jabber ID + resource for xml-rpc destinations'
103             logging.FATAL(msg)
104             raise bot.JIDMissingResource(msg)
105             
106     def add_watch(self, watchdir=None):
107         """
108         start watching watchdir or self.watch_dir
109         we're currently limited to watching one directory tree.
110         """
111         # the one tree limit is mostly because self.wdd is a single item
112         # but managing it as a list might be a bit more annoying
113         if watchdir is None:
114             watchdir = self.watch_dir
115         logging.info("Watching:"+str(watchdir))
116         mask = EventsCodes.IN_CREATE | EventsCodes.IN_UNMOUNT
117         # rec traverses the tree and adds all the directories that are there
118         # at the start.
119         # auto_add will add in new directories as they are created
120         self.wdd = self.wm.add_watch(watchdir, mask, rec=True, auto_add=True)
121
122     def unmount_watch(self):
123         if self.wdd is not None:
124             logging.debug("disabling watch")
125             logging.debug(str(self.wdd))
126             self.wm.rm_watch(self.wdd.values())
127             self.wdd = None
128             
129     def process_notify(self, *args):
130         # process the queue of events as explained above
131         self.notifier.process_events()
132         #check events waits timeout
133         if self.notifier.check_events(self.notify_timeout):
134             # read notified events and enqeue them
135             self.notifier.read_events()
136             # should we do something?
137         last_event_time = self.handler.last_event_time
138         if last_event_time is not None:
139             time_delta = time.time() - last_event_time
140             if time_delta > self.write_timeout:
141                 self.startCopy()
142                 self.handler.last_event_time = None
143     
144     def _parser(self, msg, who):
145         """
146         Parse xmpp chat messages
147         """
148         help = u"I can send [copy] message, or squencer [finished]"
149         if re.match(u"help", msg):
150             reply = help
151         elif re.match("copy", msg):            
152             self.startCopy()
153             reply = u"sent copy message"
154         elif re.match(u"finished", msg):
155             words = msg.split()
156             if len(words) == 2:
157                 self.sequencingFinished(words[1])
158                 reply = u"sending sequencing finished for %s" % (words[1])
159             else:
160                 reply = u"need runfolder name"
161         else:
162             reply = u"I didn't understand '%s'" %(msg)            
163         return reply
164         
165     def start(self, daemonize):
166         """
167         Start application
168         """
169         self.add_watch()
170         super(SpoolWatcher, self).start(daemonize)
171         
172     def stop(self):
173         """
174         shutdown application
175         """
176         # destroy the inotify's instance on this interrupt (stop monitoring)
177         self.notifier.stop()
178         super(SpoolWatcher, self).stop()
179     
180     def startCopy(self):
181         logging.debug("writes seem to have stopped")
182         if self.notify_runner is not None:
183             for r in self.notify_runner:
184                 self.rpc_send(r, tuple(), 'startCopy')
185         
186     def sequencingFinished(self, run_dir):
187         # need to strip off self.watch_dir from rundir I suspect.
188         logging.info("run.completed in " + str(run_dir))
189         pattern = self.watch_dir
190         if pattern[-1] != os.path.sep:
191             pattern += os.path.sep
192         stripped_run_dir = re.sub(pattern, "", run_dir)
193         logging.debug("stripped to " + stripped_run_dir)
194         if self.notify_users is not None:
195             for u in self.notify_users:
196                 self.send(u, 'Sequencing run %s finished' % (stripped_run_dir))
197         if self.notify_runner is not None:
198             for r in self.notify_runner:
199                 self.rpc_send(r, (stripped_run_dir,), 'sequencingFinished')
200         
201 def main(args=None):
202     bot = SpoolWatcher()
203     return bot.main(args)
204     
205 if __name__ == "__main__":
206     sys.exit(main(sys.argv[1:]))
207