Merge branch 'origin-3609-arv-run' into master closes #3609
[arvados.git] / sdk / python / arvados / events.py
index df64b4e241ec6fdc9524e57599aa6e32ffd5a206..d1abc0f7de0cd1a7c35cffb254605be302e85fd1 100644 (file)
@@ -7,6 +7,7 @@ import ssl
 import re
 import config
 import logging
+import arvados
 
 _logger = logging.getLogger('arvados.events')
 
@@ -48,20 +49,26 @@ class PollClient(threading.Thread):
     def __init__(self, api, filters, on_event, poll_time):
         super(PollClient, self).__init__()
         self.api = api
-        self.filters = [filters]
-        self.on_event = on_event
-        items = self.api.logs().list(limit=1, order="id desc", filters=filters).execute()['items']
-        if len(items) > 0:
-            self.id = items[0]["id"]
+        if filters:
+            self.filters = [filters]
         else:
-            self.id = 0
+            self.filters = [[]]
+        self.on_event = on_event
         self.poll_time = poll_time
         self.stop = threading.Event()
-        self.on_event({'status': 200})
 
     def run(self):
+        self.id = 0
+        for f in self.filters:
+            items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
+            if items:
+                if items[0]['id'] > self.id:
+                    self.id = items[0]['id']
+
+        self.on_event({'status': 200})
+
         while not self.stop.isSet():
-            max_id = 0
+            max_id = self.id
             for f in self.filters:
                 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
                 for i in items:
@@ -71,9 +78,19 @@ class PollClient(threading.Thread):
             self.id = max_id
             self.stop.wait(self.poll_time)
 
+    def run_forever(self):
+        self.stop.wait()
+
     def close(self):
         self.stop.set()
-        self.join()
+        try:
+            self.join()
+        except RuntimeError:
+            # "join() raises a RuntimeError if an attempt is made to join the
+            # current thread as that would cause a deadlock. It is also an
+            # error to join() a thread before it has been started and attempts
+            # to do so raises the same exception."
+            pass
 
     def subscribe(self, filters):
         self.on_event({'status': 200})
@@ -82,7 +99,14 @@ class PollClient(threading.Thread):
     def unsubscribe(self, filters):
         del self.filters[self.filters.index(filters)]
 
+
 def subscribe(api, filters, on_event, poll_fallback=15):
+    '''
+    api: Must be a newly created from arvados.api(cache=False), not shared with the caller, as it may be used by a background thread.
+    filters: Initial subscription filters.
+    on_event: The callback when a message is received
+    poll_fallback: If websockets are not available, fall back to polling every N seconds.  If poll_fallback=False, this will return None if websockets are not available.
+    '''
     ws = None
     if 'websocketUrl' in api._rootDesc:
         try:
@@ -91,14 +115,14 @@ def subscribe(api, filters, on_event, poll_fallback=15):
             ws.connect()
             return ws
         except Exception as e:
-            _logger.warn("Got exception %s trying to connect to web sockets at %s" % (e, api._rootDesc['websocketUrl']))
+            _logger.warn("Got exception %s trying to connect to websockets at %s" % (e, api._rootDesc['websocketUrl']))
             if ws:
                 ws.close_connection()
     if poll_fallback:
-        _logger.warn("Web sockets not available, falling back to log table polling")
+        _logger.warn("Websockets not available, falling back to log table polling")
         p = PollClient(api, filters, on_event, poll_fallback)
         p.start()
         return p
     else:
-        _logger.error("Web sockets not available")
+        _logger.error("Websockets not available")
         return None