1 from ws4py.client.threadedclient import WebSocketClient
11 _logger = logging.getLogger('arvados.events')
13 class EventClient(WebSocketClient):
14 def __init__(self, url, filters, on_event):
16 if re.match(r'(?i)^(true|1|yes)$',
17 config.get('ARVADOS_API_HOST_INSECURE', 'no')):
18 ssl_options={'cert_reqs': ssl.CERT_NONE}
20 ssl_options={'cert_reqs': ssl.CERT_REQUIRED}
21 super(EventClient, self).__init__(url, ssl_options=ssl_options)
22 self.filters = filters
23 self.on_event = on_event
26 self.subscribe(self.filters)
28 def received_message(self, m):
29 self.on_event(json.loads(str(m)))
31 def close_connection(self):
33 self.sock.shutdown(socket.SHUT_RDWR)
38 def subscribe(self, filters, last_log_id=None):
39 m = {"method": "subscribe", "filters": filters}
40 if last_log_id is not None:
41 m["last_log_id"] = last_log_id
42 self.send(json.dumps(m))
44 def unsubscribe(self, filters):
45 self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
47 class PollClient(threading.Thread):
48 def __init__(self, api, filters, on_event, poll_time):
49 super(PollClient, self).__init__()
51 self.filters = [filters]
52 self.on_event = on_event
53 items = self.api.logs().list(limit=1, order="id desc", filters=filters).execute()['items']
55 self.id = items[0]["id"]
58 self.poll_time = poll_time
59 self.stop = threading.Event()
60 self.on_event({'status': 200})
63 while not self.stop.isSet():
65 for f in self.filters:
66 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
72 self.stop.wait(self.poll_time)
78 def subscribe(self, filters):
79 self.on_event({'status': 200})
80 self.filters.append(filters)
82 def unsubscribe(self, filters):
83 del self.filters[self.filters.index(filters)]
85 def subscribe(api, filters, on_event, poll_fallback=15):
87 if 'websocketUrl' in api._rootDesc:
89 url = "{}?api_token={}".format(api._rootDesc['websocketUrl'], api.api_token)
90 ws = EventClient(url, filters, on_event)
93 except Exception as e:
94 _logger.warn("Got exception %s trying to connect to web sockets at %s" % (e, api._rootDesc['websocketUrl']))
98 _logger.warn("Web sockets not available, falling back to log table polling")
99 p = PollClient(api, filters, on_event, poll_fallback)
103 _logger.error("Web sockets not available")