3699: more help text for --src and --dst options
[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 import logging
10
11 _logger = logging.getLogger('arvados.events')
12
13 class EventClient(WebSocketClient):
14     def __init__(self, url, filters, on_event):
15         ssl_options = None
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}
19         else:
20             ssl_options={'cert_reqs': ssl.CERT_REQUIRED}
21
22         super(EventClient, self).__init__(url, ssl_options)
23         self.filters = filters
24         self.on_event = on_event
25
26     def opened(self):
27         self.send(json.dumps({"method": "subscribe", "filters": self.filters}))
28
29     def received_message(self, m):
30         self.on_event(json.loads(str(m)))
31
32     def close_connection(self):
33         try:
34             self.sock.shutdown(socket.SHUT_RDWR)
35             self.sock.close()
36         except:
37             pass
38
39 def subscribe(api, filters, on_event):
40     ws = None
41     try:
42         url = "{}?api_token={}".format(api._rootDesc['websocketUrl'], config.get('ARVADOS_API_TOKEN'))
43         ws = EventClient(url, filters, on_event)
44         ws.connect()
45         return ws
46     except Exception:
47         if (ws):
48           ws.close_connection()
49         raise