Merge branch 'master' into 4823-python-sdk-writable-collection-api
[arvados.git] / sdk / python / arvados / events.py
1 import arvados
2 import config
3 import errors
4
5 import logging
6 import json
7 import threading
8 import time
9 import os
10 import re
11 import ssl
12 from ws4py.client.threadedclient import WebSocketClient
13
14 _logger = logging.getLogger('arvados.events')
15
16 class EventClient(WebSocketClient):
17     def __init__(self, url, filters, on_event):
18         # Prefer system's CA certificates (if available)
19         ssl_options = {}
20         certs_path = '/etc/ssl/certs/ca-certificates.crt'
21         if os.path.exists(certs_path):
22             ssl_options['ca_certs'] = certs_path
23         if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
24             ssl_options['cert_reqs'] = ssl.CERT_NONE
25         else:
26             ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
27
28         # Warning: If the host part of url resolves to both IPv6 and
29         # IPv4 addresses (common with "localhost"), only one of them
30         # will be attempted -- and it might not be the right one. See
31         # ws4py's WebSocketBaseClient.__init__.
32         super(EventClient, self).__init__(url, ssl_options=ssl_options)
33         self.filters = filters
34         self.on_event = on_event
35
36     def opened(self):
37         self.subscribe(self.filters)
38
39     def received_message(self, m):
40         self.on_event(json.loads(str(m)))
41
42     def close_connection(self):
43         try:
44             self.sock.shutdown(socket.SHUT_RDWR)
45             self.sock.close()
46         except:
47             pass
48
49     def subscribe(self, filters, last_log_id=None):
50         m = {"method": "subscribe", "filters": filters}
51         if last_log_id is not None:
52             m["last_log_id"] = last_log_id
53         self.send(json.dumps(m))
54
55     def unsubscribe(self, filters):
56         self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
57
58 class PollClient(threading.Thread):
59     def __init__(self, api, filters, on_event, poll_time):
60         super(PollClient, self).__init__()
61         self.api = api
62         if filters:
63             self.filters = [filters]
64         else:
65             self.filters = [[]]
66         self.on_event = on_event
67         self.poll_time = poll_time
68         self.daemon = True
69         self.stop = threading.Event()
70
71     def run(self):
72         self.id = 0
73         for f in self.filters:
74             items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
75             if items:
76                 if items[0]['id'] > self.id:
77                     self.id = items[0]['id']
78
79         self.on_event({'status': 200})
80
81         while not self.stop.isSet():
82             max_id = self.id
83             for f in self.filters:
84                 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
85                 for i in items:
86                     if i['id'] > max_id:
87                         max_id = i['id']
88                     self.on_event(i)
89             self.id = max_id
90             self.stop.wait(self.poll_time)
91
92     def run_forever(self):
93         # Have to poll here, otherwise KeyboardInterrupt will never get processed.
94         while not self.stop.is_set():
95             self.stop.wait(1)
96
97     def close(self):
98         self.stop.set()
99         try:
100             self.join()
101         except RuntimeError:
102             # "join() raises a RuntimeError if an attempt is made to join the
103             # current thread as that would cause a deadlock. It is also an
104             # error to join() a thread before it has been started and attempts
105             # to do so raises the same exception."
106             pass
107
108     def subscribe(self, filters):
109         self.on_event({'status': 200})
110         self.filters.append(filters)
111
112     def unsubscribe(self, filters):
113         del self.filters[self.filters.index(filters)]
114
115
116 def _subscribe_websocket(api, filters, on_event):
117     endpoint = api._rootDesc.get('websocketUrl', None)
118     if not endpoint:
119         raise errors.FeatureNotEnabledError(
120             "Server does not advertise a websocket endpoint")
121     uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
122     client = EventClient(uri_with_token, filters, on_event)
123     ok = False
124     try:
125         client.connect()
126         ok = True
127         return client
128     finally:
129         if not ok:
130             client.close_connection()
131
132 def subscribe(api, filters, on_event, poll_fallback=15):
133     """
134     :api:
135       a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
136     :filters:
137       Initial subscription filters.
138     :on_event:
139       The callback when a message is received.
140     :poll_fallback:
141       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.
142     """
143
144     if not poll_fallback:
145         return _subscribe_websocket(api, filters, on_event)
146
147     try:
148         return _subscribe_websocket(api, filters, on_event)
149     except Exception as e:
150         _logger.warn("Falling back to polling after websocket error: %s" % e)
151     p = PollClient(api, filters, on_event, poll_fallback)
152     p.start()
153     return p