1 from ws4py.client.threadedclient import WebSocketClient
12 _logger = logging.getLogger('arvados.events')
14 class EventClient(WebSocketClient):
15 def __init__(self, url, filters, on_event):
16 # Prefer system's CA certificates (if available)
18 certs_path = '/etc/ssl/certs/ca-certificates.crt'
19 if os.path.exists(certs_path):
20 ssl_options['ca_certs'] = certs_path
21 if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
22 ssl_options['cert_reqs'] = ssl.CERT_NONE
24 ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
25 super(EventClient, self).__init__(url, ssl_options=ssl_options)
26 self.filters = filters
27 self.on_event = on_event
30 self.subscribe(self.filters)
32 def received_message(self, m):
33 self.on_event(json.loads(str(m)))
35 def close_connection(self):
37 self.sock.shutdown(socket.SHUT_RDWR)
42 def subscribe(self, filters, last_log_id=None):
43 m = {"method": "subscribe", "filters": filters}
44 if last_log_id is not None:
45 m["last_log_id"] = last_log_id
46 self.send(json.dumps(m))
48 def unsubscribe(self, filters):
49 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
51 class PollClient(threading.Thread):
52 def __init__(self, api, filters, on_event, poll_time):
53 super(PollClient, self).__init__()
56 self.filters = [filters]
59 self.on_event = on_event
60 self.poll_time = poll_time
61 self.stop = threading.Event()
65 for f in self.filters:
66 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
68 if items[0]['id'] > self.id:
69 self.id = items[0]['id']
71 self.on_event({'status': 200})
73 while not self.stop.isSet():
75 for f in self.filters:
76 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
82 self.stop.wait(self.poll_time)
84 def run_forever(self):
85 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
86 while not self.stop.is_set():
94 # "join() raises a RuntimeError if an attempt is made to join the
95 # current thread as that would cause a deadlock. It is also an
96 # error to join() a thread before it has been started and attempts
97 # to do so raises the same exception."
100 def subscribe(self, filters):
101 self.on_event({'status': 200})
102 self.filters.append(filters)
104 def unsubscribe(self, filters):
105 del self.filters[self.filters.index(filters)]
108 def subscribe(api, filters, on_event, poll_fallback=15):
110 api: a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
111 filters: Initial subscription filters.
112 on_event: The callback when a message is received.
113 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.
116 if 'websocketUrl' in api._rootDesc:
118 url = "{}?api_token={}".format(api._rootDesc['websocketUrl'], api.api_token)
119 ws = EventClient(url, filters, on_event)
122 except Exception as e:
123 _logger.warn("Got exception %s trying to connect to websockets at %s" % (e, api._rootDesc['websocketUrl']))
125 ws.close_connection()
127 _logger.warn("Websockets not available, falling back to log table polling")
128 p = PollClient(api, filters, on_event, poll_fallback)
132 _logger.error("Websockets not available")