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 # Prefer system's CA certificates (if available)
20 certs_path = '/etc/ssl/certs/ca-certificates.crt'
21 if os.path.exists(certs_path):
22 ssl_options['ca_certs'] = certs_path
23 if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
24 ssl_options['cert_reqs'] = ssl.CERT_NONE
26 ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
28 # Warning: If the host part of url resolves to both IPv6 and
29 # IPv4 addresses (common with "localhost"), only one of them
30 # will be attempted -- and it might not be the right one. See
31 # ws4py's WebSocketBaseClient.__init__.
32 super(EventClient, self).__init__(url, ssl_options=ssl_options)
33 self.filters = filters
34 self.on_event = on_event
37 self.subscribe(self.filters)
39 def received_message(self, m):
40 self.on_event(json.loads(str(m)))
42 def close_connection(self):
44 self.sock.shutdown(socket.SHUT_RDWR)
49 def subscribe(self, filters, last_log_id=None):
50 m = {"method": "subscribe", "filters": filters}
51 if last_log_id is not None:
52 m["last_log_id"] = last_log_id
53 self.send(json.dumps(m))
55 def unsubscribe(self, filters):
56 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
58 class PollClient(threading.Thread):
59 def __init__(self, api, filters, on_event, poll_time):
60 super(PollClient, self).__init__()
63 self.filters = [filters]
66 self.on_event = on_event
67 self.poll_time = poll_time
68 self.stop = threading.Event()
72 for f in self.filters:
73 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
75 if items[0]['id'] > self.id:
76 self.id = items[0]['id']
78 self.on_event({'status': 200})
80 while not self.stop.isSet():
82 for f in self.filters:
83 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
89 self.stop.wait(self.poll_time)
91 def run_forever(self):
92 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
93 while not self.stop.is_set():
101 # "join() raises a RuntimeError if an attempt is made to join the
102 # current thread as that would cause a deadlock. It is also an
103 # error to join() a thread before it has been started and attempts
104 # to do so raises the same exception."
107 def subscribe(self, filters):
108 self.on_event({'status': 200})
109 self.filters.append(filters)
111 def unsubscribe(self, filters):
112 del self.filters[self.filters.index(filters)]
115 def _subscribe_websocket(api, filters, on_event):
116 endpoint = api._rootDesc.get('websocketUrl', None)
118 raise errors.FeatureNotEnabledError(
119 "Server does not advertise a websocket endpoint")
120 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
121 client = EventClient(uri_with_token, filters, on_event)
129 client.close_connection()
131 def subscribe(api, filters, on_event, poll_fallback=15):
133 api: a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
134 filters: Initial subscription filters.
135 on_event: The callback when a message is received.
136 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.
138 if not poll_fallback:
139 return _subscribe_websocket(api, filters, on_event)
142 return _subscribe_websocket(api, filters, on_event)
143 except Exception as e:
144 _logger.warn("Falling back to polling after websocket error: %s" % e)
145 p = PollClient(api, filters, on_event, poll_fallback)