12 from ws4py.client.threadedclient import WebSocketClient
14 _logger = logging.getLogger('arvados.events')
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
22 ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
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.stop = threading.Event()
32 self.last_log_id = last_log_id
35 self.subscribe(self.filters, self.last_log_id)
37 def received_message(self, m):
38 self.on_event(json.loads(str(m)))
40 def closed(self, code, reason=None):
43 def close(self, code=1000, reason=''):
44 """Close event client and wait for it to finish."""
46 # parent close() method sends a asynchronous "closed" event to the server
47 super(EventClient, self).close(code, reason)
49 # if server doesn't respond by finishing the close handshake, we'll be
50 # stuck in limbo forever. We don't need to wait for the server to
51 # respond to go ahead and actually close the socket.
52 self.close_connection()
54 # wait for websocket thread to finish up (closed() is called by
55 # websocket thread in as part of terminate())
56 while not self.stop.is_set():
59 def subscribe(self, filters, last_log_id=None):
60 m = {"method": "subscribe", "filters": filters}
61 if last_log_id is not None:
62 m["last_log_id"] = last_log_id
63 self.send(json.dumps(m))
65 def unsubscribe(self, filters):
66 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
68 class PollClient(threading.Thread):
69 def __init__(self, api, filters, on_event, poll_time, last_log_id):
70 super(PollClient, self).__init__()
73 self.filters = [filters]
76 self.on_event = on_event
77 self.poll_time = poll_time
79 self.stop = threading.Event()
80 self.last_log_id = last_log_id
84 if self.last_log_id != None:
85 self.id = self.last_log_id
87 for f in self.filters:
88 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
90 if items[0]['id'] > self.id:
91 self.id = items[0]['id']
93 self.on_event({'status': 200})
95 while not self.stop.isSet():
98 for f in self.filters:
99 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()
100 for i in items["items"]:
104 if items["items_available"] > len(items["items"]):
108 self.stop.wait(self.poll_time)
110 def run_forever(self):
111 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
112 while not self.stop.is_set():
116 """Close poll client and wait for it to finish."""
122 # "join() raises a RuntimeError if an attempt is made to join the
123 # current thread as that would cause a deadlock. It is also an
124 # error to join() a thread before it has been started and attempts
125 # to do so raises the same exception."
128 def subscribe(self, filters):
129 self.on_event({'status': 200})
130 self.filters.append(filters)
132 def unsubscribe(self, filters):
133 del self.filters[self.filters.index(filters)]
136 def _subscribe_websocket(api, filters, on_event, last_log_id=None):
137 endpoint = api._rootDesc.get('websocketUrl', None)
139 raise errors.FeatureNotEnabledError(
140 "Server does not advertise a websocket endpoint")
142 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
143 client = EventClient(uri_with_token, filters, on_event, last_log_id)
151 client.close_connection()
153 _logger.warn("Failed to connect to websockets on %s" % endpoint)
157 def subscribe(api, filters, on_event, poll_fallback=15, last_log_id=None):
160 a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
162 Initial subscription filters.
164 The callback when a message is received.
166 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.
168 Log rows that are newer than the log id
171 if not poll_fallback:
172 return _subscribe_websocket(api, filters, on_event, last_log_id)
175 return _subscribe_websocket(api, filters, on_event, last_log_id)
176 except Exception as e:
177 _logger.warn("Falling back to polling after websocket error: %s" % e)
178 p = PollClient(api, filters, on_event, poll_fallback, last_log_id)