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
69 self.stop = threading.Event()
73 for f in self.filters:
74 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
76 if items[0]['id'] > self.id:
77 self.id = items[0]['id']
79 self.on_event({'status': 200})
81 while not self.stop.isSet():
83 for f in self.filters:
84 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
90 self.stop.wait(self.poll_time)
92 def run_forever(self):
93 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
94 while not self.stop.is_set():
102 # "join() raises a RuntimeError if an attempt is made to join the
103 # current thread as that would cause a deadlock. It is also an
104 # error to join() a thread before it has been started and attempts
105 # to do so raises the same exception."
108 def subscribe(self, filters):
109 self.on_event({'status': 200})
110 self.filters.append(filters)
112 def unsubscribe(self, filters):
113 del self.filters[self.filters.index(filters)]
116 def _subscribe_websocket(api, filters, on_event):
117 endpoint = api._rootDesc.get('websocketUrl', None)
119 raise errors.FeatureNotEnabledError(
120 "Server does not advertise a websocket endpoint")
121 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
122 client = EventClient(uri_with_token, filters, on_event)
130 client.close_connection()
132 def subscribe(api, filters, on_event, poll_fallback=15):
135 a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
137 Initial subscription filters.
139 The callback when a message is received.
141 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.
144 if not poll_fallback:
145 return _subscribe_websocket(api, filters, on_event)
148 return _subscribe_websocket(api, filters, on_event)
149 except Exception as e:
150 _logger.warn("Falling back to polling after websocket error: %s" % e)
151 p = PollClient(api, filters, on_event, poll_fallback)