Merge branch 'master' into 5417-not-start-pipeline-with-unreadable-inputs
[arvados.git] / sdk / python / tests / test_keep_client.py
1 import hashlib
2 import mock
3 import os
4 import random
5 import re
6 import socket
7 import unittest
8 import urlparse
9
10 import arvados
11 import arvados.retry
12 import arvados_testutil as tutil
13 import run_test_server
14
15 class KeepTestCase(run_test_server.TestCaseWithServers):
16     MAIN_SERVER = {}
17     KEEP_SERVER = {}
18
19     @classmethod
20     def setUpClass(cls):
21         super(KeepTestCase, cls).setUpClass()
22         run_test_server.authorize_with("admin")
23         cls.api_client = arvados.api('v1')
24         cls.keep_client = arvados.KeepClient(api_client=cls.api_client,
25                                              proxy='', local_store='')
26
27     def test_KeepBasicRWTest(self):
28         foo_locator = self.keep_client.put('foo')
29         self.assertRegexpMatches(
30             foo_locator,
31             '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
32             'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
33         self.assertEqual(self.keep_client.get(foo_locator),
34                          'foo',
35                          'wrong content from Keep.get(md5("foo"))')
36
37     def test_KeepBinaryRWTest(self):
38         blob_str = '\xff\xfe\xf7\x00\x01\x02'
39         blob_locator = self.keep_client.put(blob_str)
40         self.assertRegexpMatches(
41             blob_locator,
42             '^7fc7c53b45e53926ba52821140fef396\+6',
43             ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
44         self.assertEqual(self.keep_client.get(blob_locator),
45                          blob_str,
46                          'wrong content from Keep.get(md5(<binarydata>))')
47
48     def test_KeepLongBinaryRWTest(self):
49         blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
50         for i in range(0,23):
51             blob_str = blob_str + blob_str
52         blob_locator = self.keep_client.put(blob_str)
53         self.assertRegexpMatches(
54             blob_locator,
55             '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
56             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
57         self.assertEqual(self.keep_client.get(blob_locator),
58                          blob_str,
59                          'wrong content from Keep.get(md5(<binarydata>))')
60
61     def test_KeepSingleCopyRWTest(self):
62         blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
63         blob_locator = self.keep_client.put(blob_str, copies=1)
64         self.assertRegexpMatches(
65             blob_locator,
66             '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
67             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
68         self.assertEqual(self.keep_client.get(blob_locator),
69                          blob_str,
70                          'wrong content from Keep.get(md5(<binarydata>))')
71
72     def test_KeepEmptyCollectionTest(self):
73         blob_locator = self.keep_client.put('', copies=1)
74         self.assertRegexpMatches(
75             blob_locator,
76             '^d41d8cd98f00b204e9800998ecf8427e\+0',
77             ('wrong locator from Keep.put(""): ' + blob_locator))
78
79     def test_unicode_must_be_ascii(self):
80         # If unicode type, must only consist of valid ASCII
81         foo_locator = self.keep_client.put(u'foo')
82         self.assertRegexpMatches(
83             foo_locator,
84             '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
85             'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
86
87         with self.assertRaises(UnicodeEncodeError):
88             # Error if it is not ASCII
89             self.keep_client.put(u'\xe2')
90
91         with self.assertRaises(arvados.errors.ArgumentError):
92             # Must be a string type
93             self.keep_client.put({})
94
95 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
96     MAIN_SERVER = {}
97     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
98                    'enforce_permissions': True}
99
100     def test_KeepBasicRWTest(self):
101         run_test_server.authorize_with('active')
102         keep_client = arvados.KeepClient()
103         foo_locator = keep_client.put('foo')
104         self.assertRegexpMatches(
105             foo_locator,
106             r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
107             'invalid locator from Keep.put("foo"): ' + foo_locator)
108         self.assertEqual(keep_client.get(foo_locator),
109                          'foo',
110                          'wrong content from Keep.get(md5("foo"))')
111
112         # GET with an unsigned locator => NotFound
113         bar_locator = keep_client.put('bar')
114         unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
115         self.assertRegexpMatches(
116             bar_locator,
117             r'^37b51d194a7513e45b56f6524f2d51f2\+3\+A[a-f0-9]+@[a-f0-9]+$',
118             'invalid locator from Keep.put("bar"): ' + bar_locator)
119         self.assertRaises(arvados.errors.NotFoundError,
120                           keep_client.get,
121                           unsigned_bar_locator)
122
123         # GET from a different user => NotFound
124         run_test_server.authorize_with('spectator')
125         self.assertRaises(arvados.errors.NotFoundError,
126                           arvados.Keep.get,
127                           bar_locator)
128
129         # Unauthenticated GET for a signed locator => NotFound
130         # Unauthenticated GET for an unsigned locator => NotFound
131         keep_client.api_token = ''
132         self.assertRaises(arvados.errors.NotFoundError,
133                           keep_client.get,
134                           bar_locator)
135         self.assertRaises(arvados.errors.NotFoundError,
136                           keep_client.get,
137                           unsigned_bar_locator)
138
139
140 # KeepOptionalPermission: starts Keep with --permission-key-file
141 # but not --enforce-permissions (i.e. generate signatures on PUT
142 # requests, but do not require them for GET requests)
143 #
144 # All of these requests should succeed when permissions are optional:
145 # * authenticated request, signed locator
146 # * authenticated request, unsigned locator
147 # * unauthenticated request, signed locator
148 # * unauthenticated request, unsigned locator
149 class KeepOptionalPermission(run_test_server.TestCaseWithServers):
150     MAIN_SERVER = {}
151     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
152                    'enforce_permissions': False}
153
154     @classmethod
155     def setUpClass(cls):
156         super(KeepOptionalPermission, cls).setUpClass()
157         run_test_server.authorize_with("admin")
158         cls.api_client = arvados.api('v1')
159
160     def setUp(self):
161         super(KeepOptionalPermission, self).setUp()
162         self.keep_client = arvados.KeepClient(api_client=self.api_client,
163                                               proxy='', local_store='')
164
165     def _put_foo_and_check(self):
166         signed_locator = self.keep_client.put('foo')
167         self.assertRegexpMatches(
168             signed_locator,
169             r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
170             'invalid locator from Keep.put("foo"): ' + signed_locator)
171         return signed_locator
172
173     def test_KeepAuthenticatedSignedTest(self):
174         signed_locator = self._put_foo_and_check()
175         self.assertEqual(self.keep_client.get(signed_locator),
176                          'foo',
177                          'wrong content from Keep.get(md5("foo"))')
178
179     def test_KeepAuthenticatedUnsignedTest(self):
180         signed_locator = self._put_foo_and_check()
181         self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
182                          'foo',
183                          'wrong content from Keep.get(md5("foo"))')
184
185     def test_KeepUnauthenticatedSignedTest(self):
186         # Check that signed GET requests work even when permissions
187         # enforcement is off.
188         signed_locator = self._put_foo_and_check()
189         self.keep_client.api_token = ''
190         self.assertEqual(self.keep_client.get(signed_locator),
191                          'foo',
192                          'wrong content from Keep.get(md5("foo"))')
193
194     def test_KeepUnauthenticatedUnsignedTest(self):
195         # Since --enforce-permissions is not in effect, GET requests
196         # need not be authenticated.
197         signed_locator = self._put_foo_and_check()
198         self.keep_client.api_token = ''
199         self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
200                          'foo',
201                          'wrong content from Keep.get(md5("foo"))')
202
203
204 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
205     MAIN_SERVER = {}
206     KEEP_SERVER = {}
207     KEEP_PROXY_SERVER = {}
208
209     @classmethod
210     def setUpClass(cls):
211         super(KeepProxyTestCase, cls).setUpClass()
212         run_test_server.authorize_with('active')
213         cls.api_client = arvados.api('v1')
214
215     def tearDown(self):
216         arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
217         super(KeepProxyTestCase, self).tearDown()
218
219     def test_KeepProxyTest1(self):
220         # Will use ARVADOS_KEEP_PROXY environment variable that is set by
221         # setUpClass().
222         keep_client = arvados.KeepClient(api_client=self.api_client,
223                                          local_store='')
224         baz_locator = keep_client.put('baz')
225         self.assertRegexpMatches(
226             baz_locator,
227             '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
228             'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
229         self.assertEqual(keep_client.get(baz_locator),
230                          'baz',
231                          'wrong content from Keep.get(md5("baz"))')
232         self.assertTrue(keep_client.using_proxy)
233
234     def test_KeepProxyTest2(self):
235         # Don't instantiate the proxy directly, but set the X-External-Client
236         # header.  The API server should direct us to the proxy.
237         arvados.config.settings()['ARVADOS_EXTERNAL_CLIENT'] = 'true'
238         keep_client = arvados.KeepClient(api_client=self.api_client,
239                                          proxy='', local_store='')
240         baz_locator = keep_client.put('baz2')
241         self.assertRegexpMatches(
242             baz_locator,
243             '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
244             'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
245         self.assertEqual(keep_client.get(baz_locator),
246                          'baz2',
247                          'wrong content from Keep.get(md5("baz2"))')
248         self.assertTrue(keep_client.using_proxy)
249
250
251 class KeepClientServiceTestCase(unittest.TestCase, tutil.ApiClientMock):
252     def get_service_roots(self, api_client):
253         keep_client = arvados.KeepClient(api_client=api_client)
254         services = keep_client.weighted_service_roots(arvados.KeepLocator('0'*32))
255         return [urlparse.urlparse(url) for url in sorted(services)]
256
257     def test_ssl_flag_respected_in_roots(self):
258         for ssl_flag in [False, True]:
259             services = self.get_service_roots(self.mock_keep_services(
260                 service_ssl_flag=ssl_flag))
261             self.assertEqual(
262                 ('https' if ssl_flag else 'http'), services[0].scheme)
263
264     def test_correct_ports_with_ipv6_addresses(self):
265         service = self.get_service_roots(self.mock_keep_services(
266             service_type='proxy', service_host='100::1', service_port=10, count=1))[0]
267         self.assertEqual('100::1', service.hostname)
268         self.assertEqual(10, service.port)
269
270     # test_get_timeout and test_put_timeout test that
271     # KeepClient.get and KeepClient.put use the appropriate timeouts
272     # when connected directly to a Keep server (i.e. non-proxy timeout)
273
274     def test_get_timeout(self):
275         api_client = self.mock_keep_services(count=1)
276         force_timeout = [socket.timeout("timed out")]
277         with tutil.mock_get(force_timeout) as mock_session:
278             keep_client = arvados.KeepClient(api_client=api_client)
279             with self.assertRaises(arvados.errors.KeepReadError):
280                 keep_client.get('ffffffffffffffffffffffffffffffff')
281             self.assertTrue(mock_session.return_value.get.called)
282             self.assertEqual(
283                 arvados.KeepClient.DEFAULT_TIMEOUT,
284                 mock_session.return_value.get.call_args[1]['timeout'])
285
286     def test_put_timeout(self):
287         api_client = self.mock_keep_services(count=1)
288         force_timeout = [socket.timeout("timed out")]
289         with tutil.mock_put(force_timeout) as mock_session:
290             keep_client = arvados.KeepClient(api_client=api_client)
291             with self.assertRaises(arvados.errors.KeepWriteError):
292                 keep_client.put('foo')
293             self.assertTrue(mock_session.return_value.put.called)
294             self.assertEqual(
295                 arvados.KeepClient.DEFAULT_TIMEOUT,
296                 mock_session.return_value.put.call_args[1]['timeout'])
297
298     def test_proxy_get_timeout(self):
299         # Force a timeout, verifying that the requests.get or
300         # requests.put method was called with the proxy_timeout
301         # setting rather than the default timeout.
302         api_client = self.mock_keep_services(service_type='proxy', count=1)
303         force_timeout = [socket.timeout("timed out")]
304         with tutil.mock_get(force_timeout) as mock_session:
305             keep_client = arvados.KeepClient(api_client=api_client)
306             with self.assertRaises(arvados.errors.KeepReadError):
307                 keep_client.get('ffffffffffffffffffffffffffffffff')
308             self.assertTrue(mock_session.return_value.get.called)
309             self.assertEqual(
310                 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
311                 mock_session.return_value.get.call_args[1]['timeout'])
312
313     def test_proxy_put_timeout(self):
314         # Force a timeout, verifying that the requests.get or
315         # requests.put method was called with the proxy_timeout
316         # setting rather than the default timeout.
317         api_client = self.mock_keep_services(service_type='proxy', count=1)
318         force_timeout = [socket.timeout("timed out")]
319         with tutil.mock_put(force_timeout) as mock_session:
320             keep_client = arvados.KeepClient(api_client=api_client)
321             with self.assertRaises(arvados.errors.KeepWriteError):
322                 keep_client.put('foo')
323             self.assertTrue(mock_session.return_value.put.called)
324             self.assertEqual(
325                 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
326                 mock_session.return_value.put.call_args[1]['timeout'])
327
328     def test_probe_order_reference_set(self):
329         # expected_order[i] is the probe order for
330         # hash=md5(sprintf("%064x",i)) where there are 16 services
331         # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
332         # the first probe for the block consisting of 64 "0"
333         # characters is the service whose uuid is
334         # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
335         expected_order = [
336             list('3eab2d5fc9681074'),
337             list('097dba52e648f1c3'),
338             list('c5b4e023f8a7d691'),
339             list('9d81c02e76a3bf54'),
340             ]
341         hashes = [
342             hashlib.md5("{:064x}".format(x)).hexdigest()
343             for x in range(len(expected_order))]
344         api_client = self.mock_keep_services(count=16)
345         keep_client = arvados.KeepClient(api_client=api_client)
346         for i, hash in enumerate(hashes):
347             roots = keep_client.weighted_service_roots(arvados.KeepLocator(hash))
348             got_order = [
349                 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
350                 for root in roots]
351             self.assertEqual(expected_order[i], got_order)
352
353     def test_probe_waste_adding_one_server(self):
354         hashes = [
355             hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
356         initial_services = 12
357         api_client = self.mock_keep_services(count=initial_services)
358         keep_client = arvados.KeepClient(api_client=api_client)
359         probes_before = [
360             keep_client.weighted_service_roots(arvados.KeepLocator(hash)) for hash in hashes]
361         for added_services in range(1, 12):
362             api_client = self.mock_keep_services(count=initial_services+added_services)
363             keep_client = arvados.KeepClient(api_client=api_client)
364             total_penalty = 0
365             for hash_index in range(len(hashes)):
366                 probe_after = keep_client.weighted_service_roots(
367                     arvados.KeepLocator(hashes[hash_index]))
368                 penalty = probe_after.index(probes_before[hash_index][0])
369                 self.assertLessEqual(penalty, added_services)
370                 total_penalty += penalty
371             # Average penalty per block should not exceed
372             # N(added)/N(orig) by more than 20%, and should get closer
373             # to the ideal as we add data points.
374             expect_penalty = (
375                 added_services *
376                 len(hashes) / initial_services)
377             max_penalty = (
378                 expect_penalty *
379                 (120 - added_services)/100)
380             min_penalty = (
381                 expect_penalty * 8/10)
382             self.assertTrue(
383                 min_penalty <= total_penalty <= max_penalty,
384                 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
385                     initial_services,
386                     added_services,
387                     len(hashes),
388                     total_penalty,
389                     min_penalty,
390                     max_penalty))
391
392     def check_64_zeros_error_order(self, verb, exc_class):
393         data = '0' * 64
394         if verb == 'get':
395             data = hashlib.md5(data).hexdigest() + '+1234'
396         # Arbitrary port number:
397         aport = random.randint(1024,65535)
398         api_client = self.mock_keep_services(service_port=aport, count=16)
399         keep_client = arvados.KeepClient(api_client=api_client)
400         with mock.patch('requests.' + verb,
401                         side_effect=socket.timeout) as req_mock, \
402                 self.assertRaises(exc_class) as err_check:
403             getattr(keep_client, verb)(data)
404         urls = [urlparse.urlparse(url)
405                 for url in err_check.exception.request_errors()]
406         self.assertEqual([('keep0x' + c, aport) for c in '3eab2d5fc9681074'],
407                          [(url.hostname, url.port) for url in urls])
408
409     def test_get_error_shows_probe_order(self):
410         self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
411
412     def test_put_error_shows_probe_order(self):
413         self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
414
415     def check_no_services_error(self, verb, exc_class):
416         api_client = mock.MagicMock(name='api_client')
417         api_client.keep_services().accessible().execute.side_effect = (
418             arvados.errors.ApiError)
419         keep_client = arvados.KeepClient(api_client=api_client)
420         with self.assertRaises(exc_class) as err_check:
421             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0')
422         self.assertEqual(0, len(err_check.exception.request_errors()))
423
424     def test_get_error_with_no_services(self):
425         self.check_no_services_error('get', arvados.errors.KeepReadError)
426
427     def test_put_error_with_no_services(self):
428         self.check_no_services_error('put', arvados.errors.KeepWriteError)
429
430     def check_errors_from_last_retry(self, verb, exc_class):
431         api_client = self.mock_keep_services(count=2)
432         req_mock = getattr(tutil, 'mock_{}_responses'.format(verb))(
433             "retry error reporting test", 500, 500, 403, 403)
434         with req_mock, tutil.skip_sleep, \
435                 self.assertRaises(exc_class) as err_check:
436             keep_client = arvados.KeepClient(api_client=api_client)
437             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0',
438                                        num_retries=3)
439         self.assertEqual([403, 403], [
440                 getattr(error, 'status_code', None)
441                 for error in err_check.exception.request_errors().itervalues()])
442
443     def test_get_error_reflects_last_retry(self):
444         self.check_errors_from_last_retry('get', arvados.errors.KeepReadError)
445
446     def test_put_error_reflects_last_retry(self):
447         self.check_errors_from_last_retry('put', arvados.errors.KeepWriteError)
448
449     def test_put_error_does_not_include_successful_puts(self):
450         data = 'partial failure test'
451         data_loc = '{}+{}'.format(hashlib.md5(data).hexdigest(), len(data))
452         api_client = self.mock_keep_services(count=3)
453         with tutil.mock_put_responses(data_loc, 200, 500, 500) as req_mock, \
454                 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
455             keep_client = arvados.KeepClient(api_client=api_client)
456             keep_client.put(data)
457         self.assertEqual(2, len(exc_check.exception.request_errors()))
458
459
460 class KeepClientGatewayTestCase(unittest.TestCase, tutil.ApiClientMock):
461     def mock_disks_and_gateways(self, disks=3, gateways=1):
462         self.gateways = [{
463                 'uuid': 'zzzzz-bi6l4-gateway{:08d}'.format(i),
464                 'owner_uuid': 'zzzzz-tpzed-000000000000000',
465                 'service_host': 'gatewayhost{}'.format(i),
466                 'service_port': 12345,
467                 'service_ssl_flag': True,
468                 'service_type': 'gateway:test',
469         } for i in range(gateways)]
470         self.gateway_roots = [
471             "https://[{service_host}]:{service_port}/".format(**gw)
472             for gw in self.gateways]
473         self.api_client = self.mock_keep_services(
474             count=disks, additional_services=self.gateways)
475         self.keepClient = arvados.KeepClient(api_client=self.api_client)
476
477     @mock.patch('requests.Session')
478     def test_get_with_gateway_hint_first(self, MockSession):
479         MockSession.return_value.get.return_value = tutil.fake_requests_response(
480             code=200, body='foo', headers={'Content-Length': 3})
481         self.mock_disks_and_gateways()
482         locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@' + self.gateways[0]['uuid']
483         self.assertEqual('foo', self.keepClient.get(locator))
484         self.assertEqual((self.gateway_roots[0]+locator,),
485                          MockSession.return_value.get.call_args_list[0][0])
486
487     @mock.patch('requests.Session')
488     def test_get_with_gateway_hints_in_order(self, MockSession):
489         gateways = 4
490         disks = 3
491         MockSession.return_value.get.return_value = tutil.fake_requests_response(
492             code=404, body='')
493         self.mock_disks_and_gateways(gateways=gateways, disks=disks)
494         locator = '+'.join(['acbd18db4cc2f85cedef654fccc4a4d8+3'] +
495                            ['K@'+gw['uuid'] for gw in self.gateways])
496         with self.assertRaises(arvados.errors.NotFoundError):
497             self.keepClient.get(locator)
498         # Gateways are tried first, in the order given.
499         for i, root in enumerate(self.gateway_roots):
500             self.assertEqual((root+locator,),
501                              MockSession.return_value.get.call_args_list[i][0])
502         # Disk services are tried next.
503         for i in range(gateways, gateways+disks):
504             self.assertRegexpMatches(
505                 MockSession.return_value.get.call_args_list[i][0][0],
506                 r'keep0x')
507
508     @mock.patch('requests.Session')
509     def test_get_with_remote_proxy_hint(self, MockSession):
510         MockSession.return_value.get.return_value = tutil.fake_requests_response(
511             code=200, body='foo', headers={'Content-Length': 3})
512         self.mock_disks_and_gateways()
513         locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@xyzzy'
514         self.assertEqual('foo', self.keepClient.get(locator))
515         self.assertEqual(('https://keep.xyzzy.arvadosapi.com/'+locator,),
516                          MockSession.return_value.get.call_args_list[0][0])
517
518
519 class KeepClientRetryTestMixin(object):
520     # Testing with a local Keep store won't exercise the retry behavior.
521     # Instead, our strategy is:
522     # * Create a client with one proxy specified (pointed at a black
523     #   hole), so there's no need to instantiate an API client, and
524     #   all HTTP requests come from one place.
525     # * Mock httplib's request method to provide simulated responses.
526     # This lets us test the retry logic extensively without relying on any
527     # supporting servers, and prevents side effects in case something hiccups.
528     # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
529     # run_method().
530     #
531     # Test classes must define TEST_PATCHER to a method that mocks
532     # out appropriate methods in the client.
533
534     PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
535     TEST_DATA = 'testdata'
536     TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
537
538     def setUp(self):
539         self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
540
541     def new_client(self, **caller_kwargs):
542         kwargs = self.client_kwargs.copy()
543         kwargs.update(caller_kwargs)
544         return arvados.KeepClient(**kwargs)
545
546     def run_method(self, *args, **kwargs):
547         raise NotImplementedError("test subclasses must define run_method")
548
549     def check_success(self, expected=None, *args, **kwargs):
550         if expected is None:
551             expected = self.DEFAULT_EXPECT
552         self.assertEqual(expected, self.run_method(*args, **kwargs))
553
554     def check_exception(self, error_class=None, *args, **kwargs):
555         if error_class is None:
556             error_class = self.DEFAULT_EXCEPTION
557         self.assertRaises(error_class, self.run_method, *args, **kwargs)
558
559     def test_immediate_success(self):
560         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
561             self.check_success()
562
563     def test_retry_then_success(self):
564         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
565             self.check_success(num_retries=3)
566
567     def test_no_default_retry(self):
568         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
569             self.check_exception()
570
571     def test_no_retry_after_permanent_error(self):
572         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
573             self.check_exception(num_retries=3)
574
575     def test_error_after_retries_exhausted(self):
576         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
577             self.check_exception(num_retries=1)
578
579     def test_num_retries_instance_fallback(self):
580         self.client_kwargs['num_retries'] = 3
581         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
582             self.check_success()
583
584
585 @tutil.skip_sleep
586 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
587     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
588     DEFAULT_EXCEPTION = arvados.errors.KeepReadError
589     HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
590     TEST_PATCHER = staticmethod(tutil.mock_get_responses)
591
592     def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
593                    *args, **kwargs):
594         return self.new_client().get(locator, *args, **kwargs)
595
596     def test_specific_exception_when_not_found(self):
597         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200):
598             self.check_exception(arvados.errors.NotFoundError, num_retries=3)
599
600     def test_general_exception_with_mixed_errors(self):
601         # get should raise a NotFoundError if no server returns the block,
602         # and a high threshold of servers report that it's not found.
603         # This test rigs up 50/50 disagreement between two servers, and
604         # checks that it does not become a NotFoundError.
605         client = self.new_client()
606         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 500):
607             with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
608                 client.get(self.HINTED_LOCATOR)
609             self.assertNotIsInstance(
610                 exc_check.exception, arvados.errors.NotFoundError,
611                 "mixed errors raised NotFoundError")
612
613     def test_hint_server_can_succeed_without_retries(self):
614         with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200, 500):
615             self.check_success(locator=self.HINTED_LOCATOR)
616
617     def test_try_next_server_after_timeout(self):
618         with tutil.mock_get([
619                 socket.timeout("timed out"),
620                 tutil.fake_requests_response(200, self.DEFAULT_EXPECT)]):
621             self.check_success(locator=self.HINTED_LOCATOR)
622
623     def test_retry_data_with_wrong_checksum(self):
624         with tutil.mock_get((tutil.fake_requests_response(200, s) for s in ['baddata', self.TEST_DATA])):
625             self.check_success(locator=self.HINTED_LOCATOR)
626
627
628 @tutil.skip_sleep
629 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
630     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
631     DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
632     TEST_PATCHER = staticmethod(tutil.mock_put_responses)
633
634     def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
635                    copies=1, *args, **kwargs):
636         return self.new_client().put(data, copies, *args, **kwargs)
637
638     def test_do_not_send_multiple_copies_to_same_server(self):
639         with tutil.mock_put_responses(self.DEFAULT_EXPECT, 200):
640             self.check_exception(copies=2, num_retries=3)