6706: Add comments about what is going on with EventClient.close()
[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, last_log_id):
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         self.stop = threading.Event()
32         self.last_log_id = last_log_id
33
34     def opened(self):
35         self.subscribe(self.filters, self.last_log_id)
36
37     def received_message(self, m):
38         self.on_event(json.loads(str(m)))
39
40     def closed(self, code, reason=None):
41         self.stop.set()
42
43     def close(self, code=1000, reason=''):
44         # parent close() method sends a asynchronous "closed" event to the server
45         super(EventClient, self).close(code, reason)
46
47         # if server doesn't respond by finishing the close handshake, we'll be
48         # stuck in limbo forever.  We don't need to wait for the server to
49         # respond to go ahead and actually close the socket.
50         self.close_connection()
51
52         # wait for websocket thread to finish up (closed() is called by
53         # websocket thread in as part of terminate())
54         while not self.stop.is_set():
55             self.stop.wait(1)
56
57     def subscribe(self, filters, last_log_id=None):
58         m = {"method": "subscribe", "filters": filters}
59         if last_log_id is not None:
60             m["last_log_id"] = last_log_id
61         self.send(json.dumps(m))
62
63     def unsubscribe(self, filters):
64         self.send(json.dumps({"method": "unsubscribe", "filters": filters}))
65
66 class PollClient(threading.Thread):
67     def __init__(self, api, filters, on_event, poll_time, last_log_id):
68         super(PollClient, self).__init__()
69         self.api = api
70         if filters:
71             self.filters = [filters]
72         else:
73             self.filters = [[]]
74         self.on_event = on_event
75         self.poll_time = poll_time
76         self.daemon = True
77         self.stop = threading.Event()
78         self.last_log_id = last_log_id
79
80     def run(self):
81         self.id = 0
82         if self.last_log_id != None:
83             self.id = self.last_log_id
84         else:
85             for f in self.filters:
86                 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
87                 if items:
88                     if items[0]['id'] > self.id:
89                         self.id = items[0]['id']
90
91         self.on_event({'status': 200})
92
93         while not self.stop.isSet():
94             max_id = self.id
95             for f in self.filters:
96                 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()['items']
97                 for i in items:
98                     if i['id'] > max_id:
99                         max_id = i['id']
100                     self.on_event(i)
101             self.id = max_id
102             self.stop.wait(self.poll_time)
103
104     def run_forever(self):
105         # Have to poll here, otherwise KeyboardInterrupt will never get processed.
106         while not self.stop.is_set():
107             self.stop.wait(1)
108
109     def close(self):
110         self.stop.set()
111         try:
112             self.join()
113         except RuntimeError:
114             # "join() raises a RuntimeError if an attempt is made to join the
115             # current thread as that would cause a deadlock. It is also an
116             # error to join() a thread before it has been started and attempts
117             # to do so raises the same exception."
118             pass
119
120     def subscribe(self, filters):
121         self.on_event({'status': 200})
122         self.filters.append(filters)
123
124     def unsubscribe(self, filters):
125         del self.filters[self.filters.index(filters)]
126
127
128 def _subscribe_websocket(api, filters, on_event, last_log_id=None):
129     endpoint = api._rootDesc.get('websocketUrl', None)
130     if not endpoint:
131         raise errors.FeatureNotEnabledError(
132             "Server does not advertise a websocket endpoint")
133     uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
134     client = EventClient(uri_with_token, filters, on_event, last_log_id)
135     ok = False
136     try:
137         client.connect()
138         ok = True
139         return client
140     finally:
141         if not ok:
142             client.close_connection()
143
144 def subscribe(api, filters, on_event, poll_fallback=15, last_log_id=None):
145     """
146     :api:
147       a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
148     :filters:
149       Initial subscription filters.
150     :on_event:
151       The callback when a message is received.
152     :poll_fallback:
153       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.
154     :last_log_id:
155       Log rows that are newer than the log id
156     """
157
158     if not poll_fallback:
159         return _subscribe_websocket(api, filters, on_event, last_log_id)
160
161     try:
162         return _subscribe_websocket(api, filters, on_event, last_log_id)
163     except Exception as e:
164         _logger.warn("Falling back to polling after websocket error: %s" % e)
165     p = PollClient(api, filters, on_event, poll_fallback, last_log_id)
166     p.start()
167     return p