Merge branch 'master' of git.curoverse.com:arvados into 2638-add-cache-age-disk-usage...
[arvados.git] / sdk / python / arvados / events.py
1 from ws4py.client.threadedclient import WebSocketClient
2 import thread
3 import json
4 import os
5 import time
6 import ssl
7 import re
8 import config
9
10 class EventClient(WebSocketClient):
11     def __init__(self, url, filters, on_event):
12         ssl_options = None
13         if re.match(r'(?i)^(true|1|yes)$',
14                     config.get('ARVADOS_API_HOST_INSECURE', 'no')):
15             ssl_options={'cert_reqs': ssl.CERT_NONE}
16         else:
17             ssl_options={'cert_reqs': ssl.CERT_REQUIRED}
18
19         super(EventClient, self).__init__(url, ssl_options)
20         self.filters = filters
21         self.on_event = on_event
22
23     def opened(self):
24         self.send(json.dumps({"method": "subscribe", "filters": self.filters}))
25
26     def received_message(self, m):
27         self.on_event(json.loads(str(m)))
28
29 def subscribe(api, filters, on_event):
30     url = "{}?api_token={}".format(api._rootDesc['websocketUrl'], config.get('ARVADOS_API_TOKEN'))
31     ws = EventClient(url, filters, on_event)
32     ws.connect()
33     return ws