11308: Remove superfluous parens.
[arvados.git] / sdk / python / tests / test_events.py
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
8 import logging
9 import mock
10 import queue
11 import sys
12 import threading
13 import time
14 import unittest
15
16 import arvados
17 from . import arvados_testutil as tutil
18 from . import run_test_server
19
20
21 class WebsocketTest(run_test_server.TestCaseWithServers):
22     MAIN_SERVER = {}
23
24     TIME_PAST = time.time()-3600
25     TIME_FUTURE = time.time()+3600
26     MOCK_WS_URL = 'wss://[{}]/'.format(tutil.TEST_HOST)
27
28     TEST_TIMEOUT = 10.0
29
30     def setUp(self):
31         self.ws = None
32
33     def tearDown(self):
34         try:
35             if self.ws:
36                 self.ws.close()
37         except Exception as e:
38             print("Error in teardown: ", e)
39         super(WebsocketTest, self).tearDown()
40         run_test_server.reset()
41
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)
45
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()
50
51         filters = [['object_uuid', 'is_a', 'arvados#human']]
52         if start_time:
53             filters.append(['created_at', '>=', start_time])
54
55         self.ws = arvados.events.subscribe(
56             arvados.api('v1'), filters,
57             events.put_nowait,
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()
63
64         want_uuids = []
65         if expected > 0:
66             want_uuids.append(human['uuid'])
67         if expected > 1:
68             want_uuids.append(ancestor['uuid'])
69         log_object_uuids = []
70         while set(want_uuids) - set(log_object_uuids):
71             log_object_uuids.append(events.get(True, 5)['object_uuid'])
72
73         if expected < 2:
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
78                 # doesn't get called.
79                 self.assertEqual(events.get(True, 2), None)
80
81     def test_subscribe_websocket(self):
82         self._test_subscribe(
83             poll_fallback=False, expect_type=arvados.events.EventClient, expected=1)
84
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')
88         self._test_subscribe(
89             poll_fallback=0.25, expect_type=arvados.events.PollClient, expected=1)
90
91     def test_subscribe_poll_retry(self):
92         api_mock = mock.MagicMock()
93         n = []
94         def on_ev(ev):
95             n.append(ev)
96
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},
105         )
106         pc = arvados.events.PollClient(api_mock, [], on_ev, 15, None)
107         pc.start()
108         while len(n) < 2:
109             time.sleep(.1)
110         pc.close()
111
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),
116             expected=2)
117
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),
124             expected=2)
125
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),
130             expected=0)
131
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),
138             expected=0)
139
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),
144             expected=2)
145
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),
150             expected=0)
151
152     def utciso(self, t):
153         return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(t))
154
155     def localiso(self, t):
156         return time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(t)) + self.isotz(-time.timezone//60)
157
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)
161
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)
166
167         logstream = tutil.StringIO()
168         rootLogger = logging.getLogger()
169         streamHandler = logging.StreamHandler(logstream)
170         rootLogger.addHandler(streamHandler)
171
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,
176             events.put_nowait,
177             poll_fallback=False,
178             last_log_id=None)
179         self.assertIsInstance(self.ws, arvados.events.EventClient)
180         self.assertEqual(200, events.get(True, 5)['status'])
181
182         # create obj
183         human = arvados.api('v1').humans().create(body={}).execute()
184
185         # expect an event
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)
189
190         # close (im)properly
191         if close_unexpected:
192             self.ws.ec.close_connection()
193         else:
194             self.ws.close()
195
196         # create one more obj
197         human2 = arvados.api('v1').humans().create(body={}).execute()
198
199         # (un)expect the object creation event
200         if close_unexpected:
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)
210         else:
211             with self.assertRaises(queue.Empty):
212                 self.assertEqual(events.get(True, 2), None)
213
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")
218         if close_unexpected:
219             self.assertNotEqual(closeLogFound, -1)
220         else:
221             self.assertEqual(closeLogFound, -1)
222         rootLogger.removeHandler(streamHandler)
223
224     def test_websocket_reconnect_on_unexpected_close(self):
225         self._test_websocket_reconnect(True)
226
227     def test_websocket_no_reconnect_on_close_by_user(self):
228         self._test_websocket_reconnect(False)
229
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]
234
235         logstream = tutil.StringIO()
236         rootLogger = logging.getLogger()
237         streamHandler = logging.StreamHandler(logstream)
238         rootLogger.addHandler(streamHandler)
239
240         run_test_server.authorize_with('active')
241         events = queue.Queue(100)
242
243         filters = [['object_uuid', 'is_a', 'arvados#human']]
244         self.ws = arvados.events.subscribe(
245             arvados.api('v1'), filters,
246             events.put_nowait,
247             poll_fallback=False,
248             last_log_id=None)
249         self.assertIsInstance(self.ws, arvados.events.EventClient)
250
251         # simulate improper close
252         self.ws.on_closed()
253
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)
259
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)
267
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)
275
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)
286         close_thread.start()
287         self.assertTrue(connected.wait(timeout=self.TEST_TIMEOUT))
288         close_thread.join()
289         run_forever_alive = forever_thread.is_alive()
290         client.close()
291         forever_thread.join()
292         self.assertTrue(run_forever_alive)
293         self.assertEqual(2, websocket_client().connect.call_count)
294
295
296 class PollClientTestCase(unittest.TestCase):
297     TEST_TIMEOUT = 10.0
298
299     class MockLogs(object):
300
301         def __init__(self):
302             self.logs = []
303             self.lock = threading.Lock()
304             self.api_called = threading.Event()
305
306         def add(self, log):
307             with self.lock:
308                 self.logs.append(log)
309
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}
318             with self.lock:
319                 retval = self.logs
320                 self.logs = []
321             return {'items': retval, 'items_available': len(retval)}
322
323     def setUp(self):
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 = []
334
335     def tearDown(self):
336         if hasattr(self, 'client'):
337             self.client.close(timeout=None)
338
339     def callback(self, event):
340         if event.get('status') == 200:
341             self.status_ok.set()
342         else:
343             self.recv_events.append(event)
344             self.event_received.set()
345
346     def build_client(self, filters=None, callback=None, last_log_id=None, poll_time=99):
347         if filters is None:
348             filters = []
349         if callback is None:
350             callback = self.callback
351         self.client = arvados.events.PollClient(
352             self.arv, filters, callback, poll_time, last_log_id)
353
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)
357
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)
362         self.client.start()
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)
369
370     def test_subscribe(self):
371         client_filter = ['kind', '=', 'arvados#test']
372         self.build_client()
373         self.client.unsubscribe([])
374         self.client.subscribe([client_filter[:]])
375         self.client.start()
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))
379
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[:]])
388         self.client.start()
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))
394
395     def test_run_forever(self):
396         self.build_client()
397         self.client.start()
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())
402         self.client.close()
403         forever_thread.join()
404         del self.client