1 from __future__ import print_function
2 from __future__ import absolute_import
3 from __future__ import division
4 from future import standard_library
5 standard_library.install_aliases()
6 from builtins import range
7 from builtins import object
17 from . import arvados_testutil as tutil
18 from . import run_test_server
21 class WebsocketTest(run_test_server.TestCaseWithServers):
24 TIME_PAST = time.time()-3600
25 TIME_FUTURE = time.time()+3600
26 MOCK_WS_URL = 'wss://[{}]/'.format(tutil.TEST_HOST)
37 except Exception as e:
38 print("Error in teardown: ", e)
39 super(WebsocketTest, self).tearDown()
40 run_test_server.reset()
42 def _test_subscribe(self, poll_fallback, expect_type, start_time=None, expected=1):
43 run_test_server.authorize_with('active')
44 events = queue.Queue(100)
46 # Create ancestor before subscribing.
47 # When listening with start_time in the past, this should also be retrieved.
48 # However, when start_time is omitted in subscribe, this should not be fetched.
49 ancestor = arvados.api('v1').humans().create(body={}).execute()
51 filters = [['object_uuid', 'is_a', 'arvados#human']]
53 filters.append(['created_at', '>=', start_time])
55 self.ws = arvados.events.subscribe(
56 arvados.api('v1'), filters,
58 poll_fallback=poll_fallback,
59 last_log_id=(1 if start_time else None))
60 self.assertIsInstance(self.ws, expect_type)
61 self.assertEqual(200, events.get(True, 5)['status'])
62 human = arvados.api('v1').humans().create(body={}).execute()
66 want_uuids.append(human['uuid'])
68 want_uuids.append(ancestor['uuid'])
70 while set(want_uuids) - set(log_object_uuids):
71 log_object_uuids.append(events.get(True, 5)['object_uuid'])
74 with self.assertRaises(queue.Empty):
75 # assertEqual just serves to show us what unexpected
76 # thing comes out of the queue when the assertRaises
77 # fails; when the test passes, this assertEqual
79 self.assertEqual(events.get(True, 2), None)
81 def test_subscribe_websocket(self):
83 poll_fallback=False, expect_type=arvados.events.EventClient, expected=1)
85 @mock.patch('arvados.events.EventClient.__init__')
86 def test_subscribe_poll(self, event_client_constr):
87 event_client_constr.side_effect = Exception('All is well')
89 poll_fallback=0.25, expect_type=arvados.events.PollClient, expected=1)
91 def test_subscribe_poll_retry(self):
92 api_mock = mock.MagicMock()
97 error_mock = mock.MagicMock()
98 error_mock.resp.status = 0
99 error_mock._get_reason.return_value = "testing"
100 api_mock.logs().list().execute.side_effect = (
101 arvados.errors.ApiError(error_mock, b""),
102 {"items": [{"id": 1}], "items_available": 1},
103 arvados.errors.ApiError(error_mock, b""),
104 {"items": [{"id": 1}], "items_available": 1},
106 pc = arvados.events.PollClient(api_mock, [], on_ev, 15, None)
112 def test_subscribe_websocket_with_start_time_past(self):
113 self._test_subscribe(
114 poll_fallback=False, expect_type=arvados.events.EventClient,
115 start_time=self.localiso(self.TIME_PAST),
118 @mock.patch('arvados.events.EventClient.__init__')
119 def test_subscribe_poll_with_start_time_past(self, event_client_constr):
120 event_client_constr.side_effect = Exception('All is well')
121 self._test_subscribe(
122 poll_fallback=0.25, expect_type=arvados.events.PollClient,
123 start_time=self.localiso(self.TIME_PAST),
126 def test_subscribe_websocket_with_start_time_future(self):
127 self._test_subscribe(
128 poll_fallback=False, expect_type=arvados.events.EventClient,
129 start_time=self.localiso(self.TIME_FUTURE),
132 @mock.patch('arvados.events.EventClient.__init__')
133 def test_subscribe_poll_with_start_time_future(self, event_client_constr):
134 event_client_constr.side_effect = Exception('All is well')
135 self._test_subscribe(
136 poll_fallback=0.25, expect_type=arvados.events.PollClient,
137 start_time=self.localiso(self.TIME_FUTURE),
140 def test_subscribe_websocket_with_start_time_past_utc(self):
141 self._test_subscribe(
142 poll_fallback=False, expect_type=arvados.events.EventClient,
143 start_time=self.utciso(self.TIME_PAST),
146 def test_subscribe_websocket_with_start_time_future_utc(self):
147 self._test_subscribe(
148 poll_fallback=False, expect_type=arvados.events.EventClient,
149 start_time=self.utciso(self.TIME_FUTURE),
153 return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(t))
155 def localiso(self, t):
156 return time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(t)) + self.isotz(-time.timezone//60)
158 def isotz(self, offset):
159 """Convert minutes-east-of-UTC to RFC3339- and ISO-compatible time zone designator"""
160 return '{:+03d}:{:02d}'.format(offset//60, offset%60)
162 # Test websocket reconnection on (un)execpted close
163 def _test_websocket_reconnect(self, close_unexpected):
164 run_test_server.authorize_with('active')
165 events = queue.Queue(100)
167 logstream = tutil.StringIO()
168 rootLogger = logging.getLogger()
169 streamHandler = logging.StreamHandler(logstream)
170 rootLogger.addHandler(streamHandler)
172 filters = [['object_uuid', 'is_a', 'arvados#human']]
173 filters.append(['created_at', '>=', self.localiso(self.TIME_PAST)])
174 self.ws = arvados.events.subscribe(
175 arvados.api('v1'), filters,
179 self.assertIsInstance(self.ws, arvados.events.EventClient)
180 self.assertEqual(200, events.get(True, 5)['status'])
183 human = arvados.api('v1').humans().create(body={}).execute()
186 self.assertIn(human['uuid'], events.get(True, 5)['object_uuid'])
187 with self.assertRaises(queue.Empty):
188 self.assertEqual(events.get(True, 2), None)
192 self.ws.ec.close_connection()
196 # create one more obj
197 human2 = arvados.api('v1').humans().create(body={}).execute()
199 # (un)expect the object creation event
201 log_object_uuids = []
202 for i in range(0, 2):
203 event = events.get(True, 5)
204 if event.get('object_uuid') != None:
205 log_object_uuids.append(event['object_uuid'])
206 with self.assertRaises(queue.Empty):
207 self.assertEqual(events.get(True, 2), None)
208 self.assertNotIn(human['uuid'], log_object_uuids)
209 self.assertIn(human2['uuid'], log_object_uuids)
211 with self.assertRaises(queue.Empty):
212 self.assertEqual(events.get(True, 2), None)
214 # verify log message to ensure that an (un)expected close
215 log_messages = logstream.getvalue()
216 closeLogFound = log_messages.find("Unexpected close. Reconnecting.")
217 retryLogFound = log_messages.find("Error during websocket reconnect. Will retry")
219 self.assertNotEqual(closeLogFound, -1)
221 self.assertEqual(closeLogFound, -1)
222 rootLogger.removeHandler(streamHandler)
224 def test_websocket_reconnect_on_unexpected_close(self):
225 self._test_websocket_reconnect(True)
227 def test_websocket_no_reconnect_on_close_by_user(self):
228 self._test_websocket_reconnect(False)
230 # Test websocket reconnection retry
231 @mock.patch('arvados.events._EventClient.connect')
232 def test_websocket_reconnect_retry(self, event_client_connect):
233 event_client_connect.side_effect = [None, Exception('EventClient.connect error'), None]
235 logstream = tutil.StringIO()
236 rootLogger = logging.getLogger()
237 streamHandler = logging.StreamHandler(logstream)
238 rootLogger.addHandler(streamHandler)
240 run_test_server.authorize_with('active')
241 events = queue.Queue(100)
243 filters = [['object_uuid', 'is_a', 'arvados#human']]
244 self.ws = arvados.events.subscribe(
245 arvados.api('v1'), filters,
249 self.assertIsInstance(self.ws, arvados.events.EventClient)
251 # simulate improper close
254 # verify log messages to ensure retry happened
255 log_messages = logstream.getvalue()
256 found = log_messages.find("Error 'EventClient.connect error' during websocket reconnect.")
257 self.assertNotEqual(found, -1)
258 rootLogger.removeHandler(streamHandler)
260 @mock.patch('arvados.events._EventClient')
261 def test_subscribe_method(self, websocket_client):
262 filters = [['object_uuid', 'is_a', 'arvados#human']]
263 client = arvados.events.EventClient(
264 self.MOCK_WS_URL, [], lambda event: None, None)
265 client.subscribe(filters[:], 99)
266 websocket_client().subscribe.assert_called_with(filters, 99)
268 @mock.patch('arvados.events._EventClient')
269 def test_unsubscribe(self, websocket_client):
270 filters = [['object_uuid', 'is_a', 'arvados#human']]
271 client = arvados.events.EventClient(
272 self.MOCK_WS_URL, filters[:], lambda event: None, None)
273 client.unsubscribe(filters[:])
274 websocket_client().unsubscribe.assert_called_with(filters)
276 @mock.patch('arvados.events._EventClient')
277 def test_run_forever_survives_reconnects(self, websocket_client):
278 connected = threading.Event()
279 websocket_client().connect.side_effect = connected.set
280 client = arvados.events.EventClient(
281 self.MOCK_WS_URL, [], lambda event: None, None)
282 forever_thread = threading.Thread(target=client.run_forever)
283 forever_thread.start()
284 # Simulate an unexpected disconnect, and wait for reconnect.
285 close_thread = threading.Thread(target=client.on_closed)
287 self.assertTrue(connected.wait(timeout=self.TEST_TIMEOUT))
289 run_forever_alive = forever_thread.is_alive()
291 forever_thread.join()
292 self.assertTrue(run_forever_alive)
293 self.assertEqual(2, websocket_client().connect.call_count)
296 class PollClientTestCase(unittest.TestCase):
299 class MockLogs(object):
303 self.lock = threading.Lock()
304 self.api_called = threading.Event()
308 self.logs.append(log)
310 def return_list(self, num_retries=None):
311 self.api_called.set()
312 args, kwargs = self.list_func.call_args_list[-1]
313 filters = kwargs.get('filters', [])
314 if not any(True for f in filters if f[0] == 'id' and f[1] == '>'):
315 # No 'id' filter was given -- this must be the probe
316 # to determine the most recent id.
317 return {'items': [{'id': 1}], 'items_available': 1}
321 return {'items': retval, 'items_available': len(retval)}
324 self.logs = self.MockLogs()
325 self.arv = mock.MagicMock(name='arvados.api()')
326 self.arv.logs().list().execute.side_effect = self.logs.return_list
327 # our MockLogs object's "execute" stub will need to inspect
328 # the call history to determine X in
329 # ....logs().list(filters=X).execute():
330 self.logs.list_func = self.arv.logs().list
331 self.status_ok = threading.Event()
332 self.event_received = threading.Event()
333 self.recv_events = []
336 if hasattr(self, 'client'):
337 self.client.close(timeout=None)
339 def callback(self, event):
340 if event.get('status') == 200:
343 self.recv_events.append(event)
344 self.event_received.set()
346 def build_client(self, filters=None, callback=None, last_log_id=None, poll_time=99):
350 callback = self.callback
351 self.client = arvados.events.PollClient(
352 self.arv, filters, callback, poll_time, last_log_id)
354 def was_filter_used(self, target):
355 return any(target in call[-1].get('filters', [])
356 for call in self.arv.logs().list.call_args_list)
358 def test_callback(self):
359 test_log = {'id': 12345, 'testkey': 'testtext'}
360 self.logs.add({'id': 123})
361 self.build_client(poll_time=.01)
363 self.assertTrue(self.status_ok.wait(self.TEST_TIMEOUT))
364 self.assertTrue(self.event_received.wait(self.TEST_TIMEOUT))
365 self.event_received.clear()
366 self.logs.add(test_log.copy())
367 self.assertTrue(self.event_received.wait(self.TEST_TIMEOUT))
368 self.assertIn(test_log, self.recv_events)
370 def test_subscribe(self):
371 client_filter = ['kind', '=', 'arvados#test']
373 self.client.unsubscribe([])
374 self.client.subscribe([client_filter[:]])
376 self.assertTrue(self.status_ok.wait(self.TEST_TIMEOUT))
377 self.assertTrue(self.logs.api_called.wait(self.TEST_TIMEOUT))
378 self.assertTrue(self.was_filter_used(client_filter))
380 def test_unsubscribe(self):
381 should_filter = ['foo', '=', 'foo']
382 should_not_filter = ['foo', '=', 'bar']
383 self.build_client(poll_time=0.01)
384 self.client.unsubscribe([])
385 self.client.subscribe([should_not_filter[:]])
386 self.client.subscribe([should_filter[:]])
387 self.client.unsubscribe([should_not_filter[:]])
389 self.logs.add({'id': 123})
390 self.assertTrue(self.status_ok.wait(self.TEST_TIMEOUT))
391 self.assertTrue(self.event_received.wait(self.TEST_TIMEOUT))
392 self.assertTrue(self.was_filter_used(should_filter))
393 self.assertFalse(self.was_filter_used(should_not_filter))
395 def test_run_forever(self):
398 forever_thread = threading.Thread(target=self.client.run_forever)
399 forever_thread.start()
400 self.assertTrue(self.status_ok.wait(self.TEST_TIMEOUT))
401 self.assertTrue(forever_thread.is_alive())
403 forever_thread.join()