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