Merge branch 'master' into 6473-fetch-events-starting-at
[arvados.git] / sdk / python / arvados / events.py
1 import arvados
2 import config
3 import errors
4
5 import logging
6 import json
7 import threading
8 import time
9 import os
10 import re
11 import ssl
12 from ws4py.client.threadedclient import WebSocketClient
13
14 _logger = logging.getLogger('arvados.events')
15
16 class EventClient(WebSocketClient):
17     def __init__(self, url, filters, on_event, last_log_id):
18         ssl_options = {'ca_certs': arvados.util.ca_certs_path()}
19         if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
20             ssl_options['cert_reqs'] = ssl.CERT_NONE
21         else:
22             ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
23
24         # Warning: If the host part of url resolves to both IPv6 and
25         # IPv4 addresses (common with "localhost"), only one of them
26         # will be attempted -- and it might not be the right one. See
27         # ws4py's WebSocketBaseClient.__init__.
28         super(EventClient, self).__init__(url, ssl_options=ssl_options)
29         self.filters = filters
30         self.on_event = on_event
31         self.last_log_id = last_log_id
32
33     def opened(self):
34         self.subscribe(self.filters, self.last_log_id)
35
36     def received_message(self, m):
37         self.on_event(json.loads(str(m)))
38
39     def close_connection(self):
40         try:
41             self.sock.shutdown(socket.SHUT_RDWR)
42             self.sock.close()
43         except:
44             pass
45
46     def subscribe(self, filters, last_log_id=None):
47         m = {"method": "subscribe", "filters": filters}
48         if last_log_id is not None:
49             m["last_log_id"] = last_log_id
50         self.send(json.dumps(m))
51
52     def unsubscribe(self, filters):
53         self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
54
55 class PollClient(threading.Thread):
56     def __init__(self, api, filters, on_event, poll_time):
57         super(PollClient, self).__init__()
58         self.api = api
59         if filters:
60             self.filters = [filters]
61         else:
62             self.filters = [[]]
63         self.on_event = on_event
64         self.poll_time = poll_time
65         self.daemon = True
66         self.stop = threading.Event()
67
68     def run(self):
69         self.id = 0
70         for f in self.filters:
71             items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
72             if items:
73                 if items[0]['id'] > self.id:
74                     self.id = items[0]['id']
75
76         self.on_event({'status': 200})
77
78         while not self.stop.isSet():
79             max_id = self.id
80             for f in self.filters:
81                 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
82                 for i in items:
83                     if i['id'] > max_id:
84                         max_id = i['id']
85                     self.on_event(i)
86             self.id = max_id
87             self.stop.wait(self.poll_time)
88
89     def run_forever(self):
90         # Have to poll here, otherwise KeyboardInterrupt will never get processed.
91         while not self.stop.is_set():
92             self.stop.wait(1)
93
94     def close(self):
95         self.stop.set()
96         try:
97             self.join()
98         except RuntimeError:
99             # "join() raises a RuntimeError if an attempt is made to join the
100             # current thread as that would cause a deadlock. It is also an
101             # error to join() a thread before it has been started and attempts
102             # to do so raises the same exception."
103             pass
104
105     def subscribe(self, filters):
106         self.on_event({'status': 200})
107         self.filters.append(filters)
108
109     def unsubscribe(self, filters):
110         del self.filters[self.filters.index(filters)]
111
112
113 def _subscribe_websocket(api, filters, on_event, last_log_id=None):
114     endpoint = api._rootDesc.get('websocketUrl', None)
115     if not endpoint:
116         raise errors.FeatureNotEnabledError(
117             "Server does not advertise a websocket endpoint")
118     uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
119     client = EventClient(uri_with_token, filters, on_event, last_log_id)
120     ok = False
121     try:
122         client.connect()
123         ok = True
124         return client
125     finally:
126         if not ok:
127             client.close_connection()
128
129 def subscribe(api, filters, on_event, poll_fallback=15, last_log_id=None):
130     """
131     :api:
132       a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
133     :filters:
134       Initial subscription filters.
135     :on_event:
136       The callback when a message is received.
137     :poll_fallback:
138       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.
139     :last_log_id:
140       Log rows that are newer than the log id
141     """
142
143     if not poll_fallback:
144         return _subscribe_websocket(api, filters, on_event, last_log_id)
145
146     try:
147         return _subscribe_websocket(api, filters, on_event, last_log_id)
148     except Exception as e:
149         _logger.warn("Falling back to polling after websocket error: %s" % e)
150     p = PollClient(api, filters, on_event, poll_fallback)
151     p.start()
152     return p