4 from retry import RetryLoop
14 from ws4py.client.threadedclient import WebSocketClient
16 _logger = logging.getLogger('arvados.events')
19 class _EventClient(WebSocketClient):
20 def __init__(self, url, filters, on_event, last_log_id, on_closed):
21 ssl_options = {'ca_certs': arvados.util.ca_certs_path()}
22 if config.flag_is_true('ARVADOS_API_HOST_INSECURE'):
23 ssl_options['cert_reqs'] = ssl.CERT_NONE
25 ssl_options['cert_reqs'] = ssl.CERT_REQUIRED
27 # Warning: If the host part of url resolves to both IPv6 and
28 # IPv4 addresses (common with "localhost"), only one of them
29 # will be attempted -- and it might not be the right one. See
30 # ws4py's WebSocketBaseClient.__init__.
31 super(_EventClient, self).__init__(url, ssl_options=ssl_options)
33 self.filters = filters
34 self.on_event = on_event
35 self.last_log_id = last_log_id
36 self._closing_lock = threading.RLock()
38 self._closed = threading.Event()
39 self.on_closed = on_closed
42 for f in self.filters:
43 self.subscribe(f, self.last_log_id)
45 def closed(self, code, reason=None):
49 def received_message(self, m):
50 with self._closing_lock:
52 self.on_event(json.loads(str(m)))
54 def close(self, code=1000, reason='', timeout=0):
55 """Close event client and optionally wait for it to finish.
57 :timeout: is the number of seconds to wait for ws4py to
58 indicate that the connection has closed.
60 super(_EventClient, self).close(code, reason)
61 with self._closing_lock:
62 # make sure we don't process any more messages.
64 # wait for ws4py to tell us the connection is closed.
65 self._closed.wait(timeout=timeout)
67 def subscribe(self, f, last_log_id=None):
68 m = {"method": "subscribe", "filters": f}
69 if last_log_id is not None:
70 m["last_log_id"] = last_log_id
71 self.send(json.dumps(m))
73 def unsubscribe(self, f):
74 self.send(json.dumps({"method": "unsubscribe", "filters": f}))
77 class EventClient(object):
78 def __init__(self, url, filters, on_event_cb, last_log_id):
81 self.filters = [filters]
84 self.on_event_cb = on_event_cb
85 self.last_log_id = last_log_id
86 self.is_closed = False
87 self.ec = _EventClient(url, self.filters, self.on_event, last_log_id, self.on_closed)
92 def close_connection(self):
93 self.ec.close_connection()
95 def subscribe(self, f, last_log_id=None):
96 self.filters.append(f)
97 self.ec.subscribe(f, last_log_id)
99 def unsubscribe(self, f):
100 del self.filters[self.filters.index(f)]
101 self.ec.unsubscribe(f)
103 def close(self, code=1000, reason='', timeout=0):
104 self.is_closed = True
105 self.ec.close(code, reason, timeout)
107 def on_event(self, m):
108 if m.get('id') != None:
109 self.last_log_id = m.get('id')
112 except Exception as e:
113 _logger.exception("Unexpected exception from event callback.")
114 thread.interrupt_main()
117 if self.is_closed == False:
118 _logger.warn("Unexpected close. Reconnecting.")
119 self.ec = _EventClient(self.url, self.filters, self.on_event, self.last_log_id, self.on_closed)
124 except Exception as e:
125 _logger.warn("Error '%s' during websocket reconnect. Will retry after 5s.", e, exc_info=e)
129 class PollClient(threading.Thread):
130 def __init__(self, api, filters, on_event, poll_time, last_log_id):
131 super(PollClient, self).__init__()
134 self.filters = [filters]
137 self.on_event = on_event
138 self.poll_time = poll_time
140 self.last_log_id = last_log_id
141 self._closing = threading.Event()
142 self._closing_lock = threading.RLock()
146 if self.last_log_id != None:
147 self.id = self.last_log_id
149 for f in self.filters:
150 for tries_left in RetryLoop(num_retries=25, backoff_start=.1, max_wait=self.poll_time):
152 items = self.api.logs().list(limit=1, order="id desc", filters=f).execute()['items']
154 except errors.ApiError as error:
160 _logger.exception("PollClient thread could not contact API server.")
161 with self._closing_lock:
163 thread.interrupt_main()
166 if items[0]['id'] > self.id:
167 self.id = items[0]['id']
169 self.on_event({'status': 200})
171 while not self._closing.is_set():
174 for f in self.filters:
175 for tries_left in RetryLoop(num_retries=25, backoff_start=.1, max_wait=self.poll_time):
177 items = self.api.logs().list(order="id asc", filters=f+[["id", ">", str(self.id)]]).execute()
179 except errors.ApiError as error:
182 _logger.exception("PollClient thread could not contact API server.")
183 with self._closing_lock:
185 thread.interrupt_main()
187 for i in items["items"]:
190 with self._closing_lock:
191 if self._closing.is_set():
195 except Exception as e:
196 _logger.exception("Unexpected exception from event callback.")
197 thread.interrupt_main()
198 if items["items_available"] > len(items["items"]):
202 self._closing.wait(self.poll_time)
204 def run_forever(self):
205 # Have to poll here, otherwise KeyboardInterrupt will never get processed.
206 while not self._closing.is_set():
207 self._closing.wait(1)
209 def close(self, code=None, reason=None, timeout=0):
210 """Close poll client and optionally wait for it to finish.
212 If an :on_event: handler is running in a different thread,
213 first wait (indefinitely) for it to return.
215 After closing, wait up to :timeout: seconds for the thread to
216 finish the poll request in progress (if any).
218 :code: and :reason: are ignored. They are present for
219 interface compatibility with EventClient.
222 with self._closing_lock:
225 self.join(timeout=timeout)
227 # "join() raises a RuntimeError if an attempt is made to join the
228 # current thread as that would cause a deadlock. It is also an
229 # error to join() a thread before it has been started and attempts
230 # to do so raises the same exception."
233 def subscribe(self, f):
234 self.on_event({'status': 200})
235 self.filters.append(f)
237 def unsubscribe(self, f):
238 del self.filters[self.filters.index(f)]
241 def _subscribe_websocket(api, filters, on_event, last_log_id=None):
242 endpoint = api._rootDesc.get('websocketUrl', None)
244 raise errors.FeatureNotEnabledError(
245 "Server does not advertise a websocket endpoint")
247 uri_with_token = "{}?api_token={}".format(endpoint, api.api_token)
248 client = EventClient(uri_with_token, filters, on_event, last_log_id)
256 client.close_connection()
258 _logger.warn("Failed to connect to websockets on %s" % endpoint)
262 def subscribe(api, filters, on_event, poll_fallback=15, last_log_id=None):
265 a client object retrieved from arvados.api(). The caller should not use this client object for anything else after calling subscribe().
267 Initial subscription filters.
269 The callback when a message is received.
271 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.
273 Log rows that are newer than the log id
276 if not poll_fallback:
277 return _subscribe_websocket(api, filters, on_event, last_log_id)
280 if not config.flag_is_true('ARVADOS_DISABLE_WEBSOCKETS'):
281 return _subscribe_websocket(api, filters, on_event, last_log_id)
283 _logger.info("Using polling because ARVADOS_DISABLE_WEBSOCKETS is true")
284 except Exception as e:
285 _logger.warn("Falling back to polling after websocket error: %s" % e)
286 p = PollClient(api, filters, on_event, poll_fallback, last_log_id)