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 # parent close() method sends a asynchronous "closed" event to the server
45 super(EventClient, self).close(code, reason)
47 # if server doesn't respond by finishing the close handshake, we'll be
48 # stuck in limbo forever. We don't need to wait for the server to
49 # respond to go ahead and actually close the socket.
50 self.close_connection()
52 # wait for websocket thread to finish up (closed() is called by
53 # websocket thread in as part of terminate())
54 while not self.stop.is_set():
57 def subscribe(self, filters, last_log_id=None):
58 m = {"method": "subscribe", "filters": filters}
59 if last_log_id is not None:
60 m["last_log_id"] = last_log_id
61 self.send(json.dumps(m))
63 def unsubscribe(self, filters):
64 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
66 class PollClient(threading.Thread):
67 def __init__(self, api, filters, on_event, poll_time, last_log_id):
68 super(PollClient, self).__init__()
71 self.filters = [filters]
74 self.on_event = on_event
75 self.poll_time = poll_time
77 self.stop = threading.Event()
78 self.last_log_id = last_log_id
82 if self.last_log_id != None:
83 self.id = self.last_log_id
85 for f in self.filters:
86 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
88 if items[0]['id'] > self.id:
89 self.id = items[0]['id']
91 self.on_event({'status': 200})
93 while not self.stop.isSet():
95 for f in self.filters:
96 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
102 self.stop.wait(self.poll_time)
104 def run_forever(self):
105 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
106 while not self.stop.is_set():
114 # "join() raises a RuntimeError if an attempt is made to join the
115 # current thread as that would cause a deadlock. It is also an
116 # error to join() a thread before it has been started and attempts
117 # to do so raises the same exception."
120 def subscribe(self, filters):
121 self.on_event({'status': 200})
122 self.filters.append(filters)
124 def unsubscribe(self, filters):
125 del self.filters[self.filters.index(filters)]
128 def _subscribe_websocket(api, filters, on_event, last_log_id=None):
129 endpoint = api._rootDesc.get('websocketUrl', None)
131 raise errors.FeatureNotEnabledError(
132 "Server does not advertise a websocket endpoint")
133 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
134 client = EventClient(uri_with_token, filters, on_event, last_log_id)
142 client.close_connection()
144 def subscribe(api, filters, on_event, poll_fallback=15, last_log_id=None):
147 a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
149 Initial subscription filters.
151 The callback when a message is received.
153 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.
155 Log rows that are newer than the log id
158 if not poll_fallback:
159 return _subscribe_websocket(api, filters, on_event, last_log_id)
162 return _subscribe_websocket(api, filters, on_event, last_log_id)
163 except Exception as e:
164 _logger.warn("Falling back to polling after websocket error: %s" % e)
165 p = PollClient(api, filters, on_event, poll_fallback, last_log_id)