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):
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
33 self.subscribe(self.filters)
35 def received_message(self, m):
36 self.on_event(json.loads(str(m)))
38 def close_connection(self):
40 self.sock.shutdown(socket.SHUT_RDWR)
45 def subscribe(self, filters, last_log_id=None):
46 m = {"method": "subscribe", "filters": filters}
47 if last_log_id is not None:
48 m["last_log_id"] = last_log_id
49 self.send(json.dumps(m))
51 def unsubscribe(self, filters):
52 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
54 class PollClient(threading.Thread):
55 def __init__(self, api, filters, on_event, poll_time):
56 super(PollClient, self).__init__()
59 self.filters = [filters]
62 self.on_event = on_event
63 self.poll_time = poll_time
65 self.stop = threading.Event()
69 for f in self.filters:
70 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
72 if items[0]['id'] > self.id:
73 self.id = items[0]['id']
75 self.on_event({'status': 200})
77 while not self.stop.isSet():
79 for f in self.filters:
80 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
86 self.stop.wait(self.poll_time)
88 def run_forever(self):
89 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
90 while not self.stop.is_set():
98 # "join() raises a RuntimeError if an attempt is made to join the
99 # current thread as that would cause a deadlock. It is also an
100 # error to join() a thread before it has been started and attempts
101 # to do so raises the same exception."
104 def subscribe(self, filters):
105 self.on_event({'status': 200})
106 self.filters.append(filters)
108 def unsubscribe(self, filters):
109 del self.filters[self.filters.index(filters)]
112 def _subscribe_websocket(api, filters, on_event):
113 endpoint = api._rootDesc.get('websocketUrl', None)
115 raise errors.FeatureNotEnabledError(
116 "Server does not advertise a websocket endpoint")
117 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
118 client = EventClient(uri_with_token, filters, on_event)
126 client.close_connection()
128 def subscribe(api, filters, on_event, poll_fallback=15):
131 a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
133 Initial subscription filters.
135 The callback when a message is received.
137 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.
140 if not poll_fallback:
141 return _subscribe_websocket(api, filters, on_event)
144 return _subscribe_websocket(api, filters, on_event)
145 except Exception as e:
146 _logger.warn("Falling back to polling after websocket error: %s" % e)
147 p = PollClient(api, filters, on_event, poll_fallback)