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):
17 if re.match(r'(?i)^(true|1|yes)$',
18 config.get('ARVADOS_API_HOST_INSECURE', 'no')):
19 ssl_options={'cert_reqs': ssl.CERT_NONE}
21 ssl_options={'cert_reqs': ssl.CERT_REQUIRED}
22 super(EventClient, self).__init__(url, ssl_options=ssl_options)
23 self.filters = filters
24 self.on_event = on_event
27 self.subscribe(self.filters)
29 def received_message(self, m):
30 self.on_event(json.loads(str(m)))
32 def close_connection(self):
34 self.sock.shutdown(socket.SHUT_RDWR)
39 def subscribe(self, filters, last_log_id=None):
40 m = {"method": "subscribe", "filters": filters}
41 if last_log_id is not None:
42 m["last_log_id"] = last_log_id
43 self.send(json.dumps(m))
45 def unsubscribe(self, filters):
46 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
48 class PollClient(threading.Thread):
49 def __init__(self, api, filters, on_event, poll_time):
50 super(PollClient, self).__init__()
53 self.filters = [filters]
56 self.on_event = on_event
57 self.poll_time = poll_time
58 self.stop = threading.Event()
61 items = self.api.logs().list(limit=1, order="id desc", filters=self.filters[0]).execute()['items']
63 self.id = items[0]["id"]
67 self.on_event({'status': 200})
69 while not self.stop.isSet():
71 for f in self.filters:
72 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
78 self.stop.wait(self.poll_time)
84 def subscribe(self, filters):
85 self.on_event({'status': 200})
86 self.filters.append(filters)
88 def unsubscribe(self, filters):
89 del self.filters[self.filters.index(filters)]
92 def subscribe(api, filters, on_event, poll_fallback=15):
94 api: Must be a newly created from arvados.api(cache=False), not shared with the caller, as it may be used by a background thread.
95 filters: Initial subscription filters.
96 on_event: The callback when a message is received
97 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.
100 if 'websocketUrl' in api._rootDesc:
102 url = "{}?api_token={}".format(api._rootDesc['websocketUrl'], api.api_token)
103 ws = EventClient(url, filters, on_event)
106 except Exception as e:
107 _logger.warn("Got exception %s trying to connect to websockets at %s" % (e, api._rootDesc['websocketUrl']))
109 ws.close_connection()
111 _logger.warn("Websockets not available, falling back to log table polling")
112 p = PollClient(api, filters, on_event, poll_fallback)
116 _logger.error("Websockets not available")