15 import arvados_testutil as tutil
17 import run_test_server
19 class KeepTestCase(run_test_server.TestCaseWithServers):
25 super(KeepTestCase, cls).setUpClass()
26 run_test_server.authorize_with("admin")
27 cls.api_client = arvados.api('v1')
28 cls.keep_client = arvados.KeepClient(api_client=cls.api_client,
29 proxy='', local_store='')
31 def test_KeepBasicRWTest(self):
32 self.assertEqual(0, self.keep_client.upload_counter.get())
33 foo_locator = self.keep_client.put('foo')
34 self.assertRegexpMatches(
36 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
37 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
39 # 6 bytes because uploaded 2 copies
40 self.assertEqual(6, self.keep_client.upload_counter.get())
42 self.assertEqual(0, self.keep_client.download_counter.get())
43 self.assertEqual(self.keep_client.get(foo_locator),
45 'wrong content from Keep.get(md5("foo"))')
46 self.assertEqual(3, self.keep_client.download_counter.get())
48 def test_KeepBinaryRWTest(self):
49 blob_str = '\xff\xfe\xf7\x00\x01\x02'
50 blob_locator = self.keep_client.put(blob_str)
51 self.assertRegexpMatches(
53 '^7fc7c53b45e53926ba52821140fef396\+6',
54 ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
55 self.assertEqual(self.keep_client.get(blob_locator),
57 'wrong content from Keep.get(md5(<binarydata>))')
59 def test_KeepLongBinaryRWTest(self):
60 blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
62 blob_str = blob_str + blob_str
63 blob_locator = self.keep_client.put(blob_str)
64 self.assertRegexpMatches(
66 '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
67 ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
68 self.assertEqual(self.keep_client.get(blob_locator),
70 'wrong content from Keep.get(md5(<binarydata>))')
72 @unittest.skip("unreliable test - please fix and close #8752")
73 def test_KeepSingleCopyRWTest(self):
74 blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
75 blob_locator = self.keep_client.put(blob_str, copies=1)
76 self.assertRegexpMatches(
78 '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
79 ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
80 self.assertEqual(self.keep_client.get(blob_locator),
82 'wrong content from Keep.get(md5(<binarydata>))')
84 def test_KeepEmptyCollectionTest(self):
85 blob_locator = self.keep_client.put('', copies=1)
86 self.assertRegexpMatches(
88 '^d41d8cd98f00b204e9800998ecf8427e\+0',
89 ('wrong locator from Keep.put(""): ' + blob_locator))
91 def test_unicode_must_be_ascii(self):
92 # If unicode type, must only consist of valid ASCII
93 foo_locator = self.keep_client.put(u'foo')
94 self.assertRegexpMatches(
96 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
97 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
99 with self.assertRaises(UnicodeEncodeError):
100 # Error if it is not ASCII
101 self.keep_client.put(u'\xe2')
103 with self.assertRaises(arvados.errors.ArgumentError):
104 # Must be a string type
105 self.keep_client.put({})
107 def test_KeepHeadTest(self):
108 locator = self.keep_client.put('test_head')
109 self.assertRegexpMatches(
111 '^b9a772c7049325feb7130fff1f8333e9\+9',
112 'wrong md5 hash from Keep.put for "test_head": ' + locator)
113 self.assertEqual(True, self.keep_client.head(locator))
114 self.assertEqual(self.keep_client.get(locator),
116 'wrong content from Keep.get for "test_head"')
118 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
120 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
121 'enforce_permissions': True}
123 def test_KeepBasicRWTest(self):
124 run_test_server.authorize_with('active')
125 keep_client = arvados.KeepClient()
126 foo_locator = keep_client.put('foo')
127 self.assertRegexpMatches(
129 r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
130 'invalid locator from Keep.put("foo"): ' + foo_locator)
131 self.assertEqual(keep_client.get(foo_locator),
133 'wrong content from Keep.get(md5("foo"))')
135 # GET with an unsigned locator => NotFound
136 bar_locator = keep_client.put('bar')
137 unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
138 self.assertRegexpMatches(
140 r'^37b51d194a7513e45b56f6524f2d51f2\+3\+A[a-f0-9]+@[a-f0-9]+$',
141 'invalid locator from Keep.put("bar"): ' + bar_locator)
142 self.assertRaises(arvados.errors.NotFoundError,
144 unsigned_bar_locator)
146 # GET from a different user => NotFound
147 run_test_server.authorize_with('spectator')
148 self.assertRaises(arvados.errors.NotFoundError,
152 # Unauthenticated GET for a signed locator => NotFound
153 # Unauthenticated GET for an unsigned locator => NotFound
154 keep_client.api_token = ''
155 self.assertRaises(arvados.errors.NotFoundError,
158 self.assertRaises(arvados.errors.NotFoundError,
160 unsigned_bar_locator)
163 # KeepOptionalPermission: starts Keep with --permission-key-file
164 # but not --enforce-permissions (i.e. generate signatures on PUT
165 # requests, but do not require them for GET requests)
167 # All of these requests should succeed when permissions are optional:
168 # * authenticated request, signed locator
169 # * authenticated request, unsigned locator
170 # * unauthenticated request, signed locator
171 # * unauthenticated request, unsigned locator
172 class KeepOptionalPermission(run_test_server.TestCaseWithServers):
174 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
175 'enforce_permissions': False}
179 super(KeepOptionalPermission, cls).setUpClass()
180 run_test_server.authorize_with("admin")
181 cls.api_client = arvados.api('v1')
184 super(KeepOptionalPermission, self).setUp()
185 self.keep_client = arvados.KeepClient(api_client=self.api_client,
186 proxy='', local_store='')
188 def _put_foo_and_check(self):
189 signed_locator = self.keep_client.put('foo')
190 self.assertRegexpMatches(
192 r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
193 'invalid locator from Keep.put("foo"): ' + signed_locator)
194 return signed_locator
196 def test_KeepAuthenticatedSignedTest(self):
197 signed_locator = self._put_foo_and_check()
198 self.assertEqual(self.keep_client.get(signed_locator),
200 'wrong content from Keep.get(md5("foo"))')
202 def test_KeepAuthenticatedUnsignedTest(self):
203 signed_locator = self._put_foo_and_check()
204 self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
206 'wrong content from Keep.get(md5("foo"))')
208 def test_KeepUnauthenticatedSignedTest(self):
209 # Check that signed GET requests work even when permissions
210 # enforcement is off.
211 signed_locator = self._put_foo_and_check()
212 self.keep_client.api_token = ''
213 self.assertEqual(self.keep_client.get(signed_locator),
215 'wrong content from Keep.get(md5("foo"))')
217 def test_KeepUnauthenticatedUnsignedTest(self):
218 # Since --enforce-permissions is not in effect, GET requests
219 # need not be authenticated.
220 signed_locator = self._put_foo_and_check()
221 self.keep_client.api_token = ''
222 self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
224 'wrong content from Keep.get(md5("foo"))')
227 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
230 KEEP_PROXY_SERVER = {}
234 super(KeepProxyTestCase, cls).setUpClass()
235 run_test_server.authorize_with('active')
236 cls.api_client = arvados.api('v1')
239 arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
240 super(KeepProxyTestCase, self).tearDown()
242 def test_KeepProxyTest1(self):
243 # Will use ARVADOS_KEEP_SERVICES environment variable that
244 # is set by setUpClass().
245 keep_client = arvados.KeepClient(api_client=self.api_client,
247 baz_locator = keep_client.put('baz')
248 self.assertRegexpMatches(
250 '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
251 'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
252 self.assertEqual(keep_client.get(baz_locator),
254 'wrong content from Keep.get(md5("baz"))')
255 self.assertTrue(keep_client.using_proxy)
257 def test_KeepProxyTest2(self):
258 # Don't instantiate the proxy directly, but set the X-External-Client
259 # header. The API server should direct us to the proxy.
260 arvados.config.settings()['ARVADOS_EXTERNAL_CLIENT'] = 'true'
261 keep_client = arvados.KeepClient(api_client=self.api_client,
262 proxy='', local_store='')
263 baz_locator = keep_client.put('baz2')
264 self.assertRegexpMatches(
266 '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
267 'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
268 self.assertEqual(keep_client.get(baz_locator),
270 'wrong content from Keep.get(md5("baz2"))')
271 self.assertTrue(keep_client.using_proxy)
273 def test_KeepProxyTestMultipleURIs(self):
274 # Test using ARVADOS_KEEP_SERVICES env var overriding any
275 # existing proxy setting and setting multiple proxies
276 arvados.config.settings()['ARVADOS_KEEP_SERVICES'] = 'http://10.0.0.1 https://foo.example.org:1234/'
277 keep_client = arvados.KeepClient(api_client=self.api_client,
279 uris = [x['_service_root'] for x in keep_client._keep_services]
280 self.assertEqual(uris, ['http://10.0.0.1/',
281 'https://foo.example.org:1234/'])
283 def test_KeepProxyTestInvalidURI(self):
284 arvados.config.settings()['ARVADOS_KEEP_SERVICES'] = 'bad.uri.org'
285 with self.assertRaises(arvados.errors.ArgumentError):
286 keep_client = arvados.KeepClient(api_client=self.api_client,
290 class KeepClientServiceTestCase(unittest.TestCase, tutil.ApiClientMock):
291 def get_service_roots(self, api_client):
292 keep_client = arvados.KeepClient(api_client=api_client)
293 services = keep_client.weighted_service_roots(arvados.KeepLocator('0'*32))
294 return [urlparse.urlparse(url) for url in sorted(services)]
296 def test_ssl_flag_respected_in_roots(self):
297 for ssl_flag in [False, True]:
298 services = self.get_service_roots(self.mock_keep_services(
299 service_ssl_flag=ssl_flag))
301 ('https' if ssl_flag else 'http'), services[0].scheme)
303 def test_correct_ports_with_ipv6_addresses(self):
304 service = self.get_service_roots(self.mock_keep_services(
305 service_type='proxy', service_host='100::1', service_port=10, count=1))[0]
306 self.assertEqual('100::1', service.hostname)
307 self.assertEqual(10, service.port)
309 # test_*_timeout verify that KeepClient instructs pycurl to use
310 # the appropriate connection and read timeouts. They don't care
311 # whether pycurl actually exhibits the expected timeout behavior
312 # -- those tests are in the KeepClientTimeout test class.
314 def test_get_timeout(self):
315 api_client = self.mock_keep_services(count=1)
316 force_timeout = socket.timeout("timed out")
317 with tutil.mock_keep_responses(force_timeout, 0) as mock:
318 keep_client = arvados.KeepClient(api_client=api_client)
319 with self.assertRaises(arvados.errors.KeepReadError):
320 keep_client.get('ffffffffffffffffffffffffffffffff')
322 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
323 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
325 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
326 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]))
328 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
329 int(arvados.KeepClient.DEFAULT_TIMEOUT[2]))
331 def test_put_timeout(self):
332 api_client = self.mock_keep_services(count=1)
333 force_timeout = socket.timeout("timed out")
334 with tutil.mock_keep_responses(force_timeout, 0) as mock:
335 keep_client = arvados.KeepClient(api_client=api_client)
336 with self.assertRaises(arvados.errors.KeepWriteError):
337 keep_client.put('foo')
339 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
340 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
342 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
343 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]))
345 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
346 int(arvados.KeepClient.DEFAULT_TIMEOUT[2]))
348 def test_head_timeout(self):
349 api_client = self.mock_keep_services(count=1)
350 force_timeout = socket.timeout("timed out")
351 with tutil.mock_keep_responses(force_timeout, 0) as mock:
352 keep_client = arvados.KeepClient(api_client=api_client)
353 with self.assertRaises(arvados.errors.KeepReadError):
354 keep_client.head('ffffffffffffffffffffffffffffffff')
356 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
357 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
359 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
360 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]))
362 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
363 int(arvados.KeepClient.DEFAULT_TIMEOUT[2]))
365 def test_proxy_get_timeout(self):
366 api_client = self.mock_keep_services(service_type='proxy', count=1)
367 force_timeout = socket.timeout("timed out")
368 with tutil.mock_keep_responses(force_timeout, 0) as mock:
369 keep_client = arvados.KeepClient(api_client=api_client)
370 with self.assertRaises(arvados.errors.KeepReadError):
371 keep_client.get('ffffffffffffffffffffffffffffffff')
373 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
374 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
376 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
377 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]))
379 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
380 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[2]))
382 def test_proxy_head_timeout(self):
383 api_client = self.mock_keep_services(service_type='proxy', count=1)
384 force_timeout = socket.timeout("timed out")
385 with tutil.mock_keep_responses(force_timeout, 0) as mock:
386 keep_client = arvados.KeepClient(api_client=api_client)
387 with self.assertRaises(arvados.errors.KeepReadError):
388 keep_client.head('ffffffffffffffffffffffffffffffff')
390 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
391 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
393 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
394 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]))
396 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
397 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[2]))
399 def test_proxy_put_timeout(self):
400 api_client = self.mock_keep_services(service_type='proxy', count=1)
401 force_timeout = socket.timeout("timed out")
402 with tutil.mock_keep_responses(force_timeout, 0) as mock:
403 keep_client = arvados.KeepClient(api_client=api_client)
404 with self.assertRaises(arvados.errors.KeepWriteError):
405 keep_client.put('foo')
407 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
408 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
410 mock.responses[0].getopt(pycurl.LOW_SPEED_TIME),
411 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]))
413 mock.responses[0].getopt(pycurl.LOW_SPEED_LIMIT),
414 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[2]))
416 def check_no_services_error(self, verb, exc_class):
417 api_client = mock.MagicMock(name='api_client')
418 api_client.keep_services().accessible().execute.side_effect = (
419 arvados.errors.ApiError)
420 keep_client = arvados.KeepClient(api_client=api_client)
421 with self.assertRaises(exc_class) as err_check:
422 getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0')
423 self.assertEqual(0, len(err_check.exception.request_errors()))
425 def test_get_error_with_no_services(self):
426 self.check_no_services_error('get', arvados.errors.KeepReadError)
428 def test_head_error_with_no_services(self):
429 self.check_no_services_error('head', arvados.errors.KeepReadError)
431 def test_put_error_with_no_services(self):
432 self.check_no_services_error('put', arvados.errors.KeepWriteError)
434 def check_errors_from_last_retry(self, verb, exc_class):
435 api_client = self.mock_keep_services(count=2)
436 req_mock = tutil.mock_keep_responses(
437 "retry error reporting test", 500, 500, 403, 403)
438 with req_mock, tutil.skip_sleep, \
439 self.assertRaises(exc_class) as err_check:
440 keep_client = arvados.KeepClient(api_client=api_client)
441 getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0',
443 self.assertEqual([403, 403], [
444 getattr(error, 'status_code', None)
445 for error in err_check.exception.request_errors().itervalues()])
447 def test_get_error_reflects_last_retry(self):
448 self.check_errors_from_last_retry('get', arvados.errors.KeepReadError)
450 def test_head_error_reflects_last_retry(self):
451 self.check_errors_from_last_retry('head', arvados.errors.KeepReadError)
453 def test_put_error_reflects_last_retry(self):
454 self.check_errors_from_last_retry('put', arvados.errors.KeepWriteError)
456 def test_put_error_does_not_include_successful_puts(self):
457 data = 'partial failure test'
458 data_loc = tutil.str_keep_locator(data)
459 api_client = self.mock_keep_services(count=3)
460 with tutil.mock_keep_responses(data_loc, 200, 500, 500) as req_mock, \
461 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
462 keep_client = arvados.KeepClient(api_client=api_client)
463 keep_client.put(data)
464 self.assertEqual(2, len(exc_check.exception.request_errors()))
466 def test_proxy_put_with_no_writable_services(self):
467 data = 'test with no writable services'
468 data_loc = tutil.str_keep_locator(data)
469 api_client = self.mock_keep_services(service_type='proxy', read_only=True, count=1)
470 with tutil.mock_keep_responses(data_loc, 200, 500, 500) as req_mock, \
471 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
472 keep_client = arvados.KeepClient(api_client=api_client)
473 keep_client.put(data)
474 self.assertEqual(True, ("no Keep services available" in str(exc_check.exception)))
475 self.assertEqual(0, len(exc_check.exception.request_errors()))
477 def test_oddball_service_get(self):
478 body = 'oddball service get'
479 api_client = self.mock_keep_services(service_type='fancynewblobstore')
480 with tutil.mock_keep_responses(body, 200):
481 keep_client = arvados.KeepClient(api_client=api_client)
482 actual = keep_client.get(tutil.str_keep_locator(body))
483 self.assertEqual(body, actual)
485 def test_oddball_service_put(self):
486 body = 'oddball service put'
487 pdh = tutil.str_keep_locator(body)
488 api_client = self.mock_keep_services(service_type='fancynewblobstore')
489 with tutil.mock_keep_responses(pdh, 200):
490 keep_client = arvados.KeepClient(api_client=api_client)
491 actual = keep_client.put(body, copies=1)
492 self.assertEqual(pdh, actual)
494 def test_oddball_service_writer_count(self):
495 body = 'oddball service writer count'
496 pdh = tutil.str_keep_locator(body)
497 api_client = self.mock_keep_services(service_type='fancynewblobstore',
499 headers = {'x-keep-replicas-stored': 3}
500 with tutil.mock_keep_responses(pdh, 200, 418, 418, 418,
501 **headers) as req_mock:
502 keep_client = arvados.KeepClient(api_client=api_client)
503 actual = keep_client.put(body, copies=2)
504 self.assertEqual(pdh, actual)
505 self.assertEqual(1, req_mock.call_count)
509 class KeepClientRendezvousTestCase(unittest.TestCase, tutil.ApiClientMock):
512 # expected_order[i] is the probe order for
513 # hash=md5(sprintf("%064x",i)) where there are 16 services
514 # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
515 # the first probe for the block consisting of 64 "0"
516 # characters is the service whose uuid is
517 # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
519 self.expected_order = [
520 list('3eab2d5fc9681074'),
521 list('097dba52e648f1c3'),
522 list('c5b4e023f8a7d691'),
523 list('9d81c02e76a3bf54'),
527 for x in range(len(self.expected_order))]
529 hashlib.md5(self.blocks[x]).hexdigest()
530 for x in range(len(self.expected_order))]
531 self.api_client = self.mock_keep_services(count=self.services)
532 self.keep_client = arvados.KeepClient(api_client=self.api_client)
534 def test_weighted_service_roots_against_reference_set(self):
535 # Confirm weighted_service_roots() returns the correct order
536 for i, hash in enumerate(self.hashes):
537 roots = self.keep_client.weighted_service_roots(arvados.KeepLocator(hash))
539 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
541 self.assertEqual(self.expected_order[i], got_order)
543 def test_get_probe_order_against_reference_set(self):
544 self._test_probe_order_against_reference_set(
545 lambda i: self.keep_client.get(self.hashes[i], num_retries=1))
547 def test_head_probe_order_against_reference_set(self):
548 self._test_probe_order_against_reference_set(
549 lambda i: self.keep_client.head(self.hashes[i], num_retries=1))
551 def test_put_probe_order_against_reference_set(self):
552 # copies=1 prevents the test from being sensitive to races
553 # between writer threads.
554 self._test_probe_order_against_reference_set(
555 lambda i: self.keep_client.put(self.blocks[i], num_retries=1, copies=1))
557 def _test_probe_order_against_reference_set(self, op):
558 for i in range(len(self.blocks)):
559 with tutil.mock_keep_responses('', *[500 for _ in range(self.services*2)]) as mock, \
560 self.assertRaises(arvados.errors.KeepRequestError):
563 re.search(r'//\[?keep0x([0-9a-f]+)', resp.getopt(pycurl.URL)).group(1)
564 for resp in mock.responses]
565 self.assertEqual(self.expected_order[i]*2, got_order)
567 def test_put_probe_order_multiple_copies(self):
568 for copies in range(2, 4):
569 for i in range(len(self.blocks)):
570 with tutil.mock_keep_responses('', *[500 for _ in range(self.services*3)]) as mock, \
571 self.assertRaises(arvados.errors.KeepWriteError):
572 self.keep_client.put(self.blocks[i], num_retries=2, copies=copies)
574 re.search(r'//\[?keep0x([0-9a-f]+)', resp.getopt(pycurl.URL)).group(1)
575 for resp in mock.responses]
576 # With T threads racing to make requests, the position
577 # of a given server in the sequence of HTTP requests
578 # (got_order) cannot be more than T-1 positions
579 # earlier than that server's position in the reference
580 # probe sequence (expected_order).
582 # Loop invariant: we have accounted for +pos+ expected
583 # probes, either by seeing them in +got_order+ or by
584 # putting them in +pending+ in the hope of seeing them
585 # later. As long as +len(pending)<T+, we haven't
586 # started a request too early.
588 for pos, expected in enumerate(self.expected_order[i]*3):
589 got = got_order[pos-len(pending)]
590 while got in pending:
591 del pending[pending.index(got)]
592 got = got_order[pos-len(pending)]
594 pending.append(expected)
596 len(pending), copies,
597 "pending={}, with copies={}, got {}, expected {}".format(
598 pending, copies, repr(got_order), repr(self.expected_order[i]*3)))
600 def test_probe_waste_adding_one_server(self):
602 hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
603 initial_services = 12
604 self.api_client = self.mock_keep_services(count=initial_services)
605 self.keep_client = arvados.KeepClient(api_client=self.api_client)
607 self.keep_client.weighted_service_roots(arvados.KeepLocator(hash)) for hash in hashes]
608 for added_services in range(1, 12):
609 api_client = self.mock_keep_services(count=initial_services+added_services)
610 keep_client = arvados.KeepClient(api_client=api_client)
612 for hash_index in range(len(hashes)):
613 probe_after = keep_client.weighted_service_roots(
614 arvados.KeepLocator(hashes[hash_index]))
615 penalty = probe_after.index(probes_before[hash_index][0])
616 self.assertLessEqual(penalty, added_services)
617 total_penalty += penalty
618 # Average penalty per block should not exceed
619 # N(added)/N(orig) by more than 20%, and should get closer
620 # to the ideal as we add data points.
623 len(hashes) / initial_services)
626 (120 - added_services)/100)
628 expect_penalty * 8/10)
630 min_penalty <= total_penalty <= max_penalty,
631 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
639 def check_64_zeros_error_order(self, verb, exc_class):
642 data = tutil.str_keep_locator(data)
643 # Arbitrary port number:
644 aport = random.randint(1024,65535)
645 api_client = self.mock_keep_services(service_port=aport, count=self.services)
646 keep_client = arvados.KeepClient(api_client=api_client)
647 with mock.patch('pycurl.Curl') as curl_mock, \
648 self.assertRaises(exc_class) as err_check:
649 curl_mock.return_value.side_effect = socket.timeout
650 getattr(keep_client, verb)(data)
651 urls = [urlparse.urlparse(url)
652 for url in err_check.exception.request_errors()]
653 self.assertEqual([('keep0x' + c, aport) for c in '3eab2d5fc9681074'],
654 [(url.hostname, url.port) for url in urls])
656 def test_get_error_shows_probe_order(self):
657 self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
659 def test_put_error_shows_probe_order(self):
660 self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
663 class KeepClientTimeout(unittest.TestCase, tutil.ApiClientMock):
664 # BANDWIDTH_LOW_LIM must be less than len(DATA) so we can transfer
665 # 1s worth of data and then trigger bandwidth errors before running
668 BANDWIDTH_LOW_LIM = 1024
671 class assertTakesBetween(unittest.TestCase):
672 def __init__(self, tmin, tmax):
677 self.t0 = time.time()
679 def __exit__(self, *args, **kwargs):
680 # Round times to milliseconds, like CURL. Otherwise, we
681 # fail when CURL reaches a 1s timeout at 0.9998s.
682 delta = round(time.time() - self.t0, 3)
683 self.assertGreaterEqual(delta, self.tmin)
684 self.assertLessEqual(delta, self.tmax)
686 class assertTakesGreater(unittest.TestCase):
687 def __init__(self, tmin):
691 self.t0 = time.time()
693 def __exit__(self, *args, **kwargs):
694 delta = round(time.time() - self.t0, 3)
695 self.assertGreaterEqual(delta, self.tmin)
698 sock = socket.socket()
699 sock.bind(('0.0.0.0', 0))
700 self.port = sock.getsockname()[1]
702 self.server = keepstub.Server(('0.0.0.0', self.port), keepstub.Handler)
703 self.thread = threading.Thread(target=self.server.serve_forever)
704 self.thread.daemon = True # Exit thread if main proc exits
706 self.api_client = self.mock_keep_services(
708 service_host='localhost',
709 service_port=self.port,
713 self.server.shutdown()
715 def keepClient(self, timeouts=(0.1, TIMEOUT_TIME, BANDWIDTH_LOW_LIM)):
716 return arvados.KeepClient(
717 api_client=self.api_client,
720 def test_timeout_slow_connect(self):
721 # Can't simulate TCP delays with our own socket. Leave our
722 # stub server running uselessly, and try to connect to an
723 # unroutable IP address instead.
724 self.api_client = self.mock_keep_services(
726 service_host='240.0.0.0',
728 with self.assertTakesBetween(0.1, 0.5):
729 with self.assertRaises(arvados.errors.KeepWriteError):
730 self.keepClient().put(self.DATA, copies=1, num_retries=0)
732 def test_low_bandwidth_no_delays_success(self):
733 self.server.setbandwidth(2*self.BANDWIDTH_LOW_LIM)
734 kc = self.keepClient()
735 loc = kc.put(self.DATA, copies=1, num_retries=0)
736 self.assertEqual(self.DATA, kc.get(loc, num_retries=0))
738 def test_too_low_bandwidth_no_delays_failure(self):
739 # Check that lessening bandwidth corresponds to failing
740 kc = self.keepClient()
741 loc = kc.put(self.DATA, copies=1, num_retries=0)
742 self.server.setbandwidth(0.5*self.BANDWIDTH_LOW_LIM)
743 with self.assertTakesGreater(self.TIMEOUT_TIME):
744 with self.assertRaises(arvados.errors.KeepReadError) as e:
745 kc.get(loc, num_retries=0)
746 with self.assertTakesGreater(self.TIMEOUT_TIME):
747 with self.assertRaises(arvados.errors.KeepWriteError):
748 kc.put(self.DATA, copies=1, num_retries=0)
750 def test_low_bandwidth_with_server_response_delay_failure(self):
751 kc = self.keepClient()
752 loc = kc.put(self.DATA, copies=1, num_retries=0)
753 self.server.setbandwidth(self.BANDWIDTH_LOW_LIM)
754 self.server.setdelays(response=self.TIMEOUT_TIME)
755 with self.assertTakesGreater(self.TIMEOUT_TIME):
756 with self.assertRaises(arvados.errors.KeepReadError) as e:
757 kc.get(loc, num_retries=0)
758 with self.assertTakesGreater(self.TIMEOUT_TIME):
759 with self.assertRaises(arvados.errors.KeepWriteError):
760 kc.put(self.DATA, copies=1, num_retries=0)
761 with self.assertTakesGreater(self.TIMEOUT_TIME):
762 with self.assertRaises(arvados.errors.KeepReadError) as e:
763 kc.head(loc, num_retries=0)
765 def test_low_bandwidth_with_server_mid_delay_failure(self):
766 kc = self.keepClient()
767 loc = kc.put(self.DATA, copies=1, num_retries=0)
768 self.server.setbandwidth(self.BANDWIDTH_LOW_LIM)
769 self.server.setdelays(mid_write=self.TIMEOUT_TIME, mid_read=self.TIMEOUT_TIME)
770 with self.assertTakesGreater(self.TIMEOUT_TIME):
771 with self.assertRaises(arvados.errors.KeepReadError) as e:
772 kc.get(loc, num_retries=0)
773 with self.assertTakesGreater(self.TIMEOUT_TIME):
774 with self.assertRaises(arvados.errors.KeepWriteError):
775 kc.put(self.DATA, copies=1, num_retries=0)
777 def test_timeout_slow_request(self):
778 loc = self.keepClient().put(self.DATA, copies=1, num_retries=0)
779 self.server.setdelays(request=.2)
780 self._test_connect_timeout_under_200ms(loc)
781 self.server.setdelays(request=2)
782 self._test_response_timeout_under_2s(loc)
784 def test_timeout_slow_response(self):
785 loc = self.keepClient().put(self.DATA, copies=1, num_retries=0)
786 self.server.setdelays(response=.2)
787 self._test_connect_timeout_under_200ms(loc)
788 self.server.setdelays(response=2)
789 self._test_response_timeout_under_2s(loc)
791 def test_timeout_slow_response_body(self):
792 loc = self.keepClient().put(self.DATA, copies=1, num_retries=0)
793 self.server.setdelays(response_body=.2)
794 self._test_connect_timeout_under_200ms(loc)
795 self.server.setdelays(response_body=2)
796 self._test_response_timeout_under_2s(loc)
798 def _test_connect_timeout_under_200ms(self, loc):
799 # Allow 100ms to connect, then 1s for response. Everything
800 # should work, and everything should take at least 200ms to
802 kc = self.keepClient(timeouts=(.1, 1))
803 with self.assertTakesBetween(.2, .3):
804 kc.put(self.DATA, copies=1, num_retries=0)
805 with self.assertTakesBetween(.2, .3):
806 self.assertEqual(self.DATA, kc.get(loc, num_retries=0))
808 def _test_response_timeout_under_2s(self, loc):
809 # Allow 10s to connect, then 1s for response. Nothing should
810 # work, and everything should take at least 1s to return.
811 kc = self.keepClient(timeouts=(10, 1))
812 with self.assertTakesBetween(1, 9):
813 with self.assertRaises(arvados.errors.KeepReadError):
814 kc.get(loc, num_retries=0)
815 with self.assertTakesBetween(1, 9):
816 with self.assertRaises(arvados.errors.KeepWriteError):
817 kc.put(self.DATA, copies=1, num_retries=0)
820 class KeepClientGatewayTestCase(unittest.TestCase, tutil.ApiClientMock):
821 def mock_disks_and_gateways(self, disks=3, gateways=1):
823 'uuid': 'zzzzz-bi6l4-gateway{:08d}'.format(i),
824 'owner_uuid': 'zzzzz-tpzed-000000000000000',
825 'service_host': 'gatewayhost{}'.format(i),
826 'service_port': 12345,
827 'service_ssl_flag': True,
828 'service_type': 'gateway:test',
829 } for i in range(gateways)]
830 self.gateway_roots = [
831 "https://{service_host}:{service_port}/".format(**gw)
832 for gw in self.gateways]
833 self.api_client = self.mock_keep_services(
834 count=disks, additional_services=self.gateways)
835 self.keepClient = arvados.KeepClient(api_client=self.api_client)
837 @mock.patch('pycurl.Curl')
838 def test_get_with_gateway_hint_first(self, MockCurl):
839 MockCurl.return_value = tutil.FakeCurl.make(
840 code=200, body='foo', headers={'Content-Length': 3})
841 self.mock_disks_and_gateways()
842 locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@' + self.gateways[0]['uuid']
843 self.assertEqual('foo', self.keepClient.get(locator))
844 self.assertEqual(self.gateway_roots[0]+locator,
845 MockCurl.return_value.getopt(pycurl.URL))
846 self.assertEqual(True, self.keepClient.head(locator))
848 @mock.patch('pycurl.Curl')
849 def test_get_with_gateway_hints_in_order(self, MockCurl):
853 tutil.FakeCurl.make(code=404, body='')
854 for _ in range(gateways+disks)
856 MockCurl.side_effect = tutil.queue_with(mocks)
857 self.mock_disks_and_gateways(gateways=gateways, disks=disks)
858 locator = '+'.join(['acbd18db4cc2f85cedef654fccc4a4d8+3'] +
859 ['K@'+gw['uuid'] for gw in self.gateways])
860 with self.assertRaises(arvados.errors.NotFoundError):
861 self.keepClient.get(locator)
862 # Gateways are tried first, in the order given.
863 for i, root in enumerate(self.gateway_roots):
864 self.assertEqual(root+locator,
865 mocks[i].getopt(pycurl.URL))
866 # Disk services are tried next.
867 for i in range(gateways, gateways+disks):
868 self.assertRegexpMatches(
869 mocks[i].getopt(pycurl.URL),
872 @mock.patch('pycurl.Curl')
873 def test_head_with_gateway_hints_in_order(self, MockCurl):
877 tutil.FakeCurl.make(code=404, body='')
878 for _ in range(gateways+disks)
880 MockCurl.side_effect = tutil.queue_with(mocks)
881 self.mock_disks_and_gateways(gateways=gateways, disks=disks)
882 locator = '+'.join(['acbd18db4cc2f85cedef654fccc4a4d8+3'] +
883 ['K@'+gw['uuid'] for gw in self.gateways])
884 with self.assertRaises(arvados.errors.NotFoundError):
885 self.keepClient.head(locator)
886 # Gateways are tried first, in the order given.
887 for i, root in enumerate(self.gateway_roots):
888 self.assertEqual(root+locator,
889 mocks[i].getopt(pycurl.URL))
890 # Disk services are tried next.
891 for i in range(gateways, gateways+disks):
892 self.assertRegexpMatches(
893 mocks[i].getopt(pycurl.URL),
896 @mock.patch('pycurl.Curl')
897 def test_get_with_remote_proxy_hint(self, MockCurl):
898 MockCurl.return_value = tutil.FakeCurl.make(
899 code=200, body='foo', headers={'Content-Length': 3})
900 self.mock_disks_and_gateways()
901 locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@xyzzy'
902 self.assertEqual('foo', self.keepClient.get(locator))
903 self.assertEqual('https://keep.xyzzy.arvadosapi.com/'+locator,
904 MockCurl.return_value.getopt(pycurl.URL))
906 @mock.patch('pycurl.Curl')
907 def test_head_with_remote_proxy_hint(self, MockCurl):
908 MockCurl.return_value = tutil.FakeCurl.make(
909 code=200, body='foo', headers={'Content-Length': 3})
910 self.mock_disks_and_gateways()
911 locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@xyzzy'
912 self.assertEqual(True, self.keepClient.head(locator))
913 self.assertEqual('https://keep.xyzzy.arvadosapi.com/'+locator,
914 MockCurl.return_value.getopt(pycurl.URL))
917 class KeepClientRetryTestMixin(object):
918 # Testing with a local Keep store won't exercise the retry behavior.
919 # Instead, our strategy is:
920 # * Create a client with one proxy specified (pointed at a black
921 # hole), so there's no need to instantiate an API client, and
922 # all HTTP requests come from one place.
923 # * Mock httplib's request method to provide simulated responses.
924 # This lets us test the retry logic extensively without relying on any
925 # supporting servers, and prevents side effects in case something hiccups.
926 # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
929 # Test classes must define TEST_PATCHER to a method that mocks
930 # out appropriate methods in the client.
932 PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
933 TEST_DATA = 'testdata'
934 TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
937 self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
939 def new_client(self, **caller_kwargs):
940 kwargs = self.client_kwargs.copy()
941 kwargs.update(caller_kwargs)
942 return arvados.KeepClient(**kwargs)
944 def run_method(self, *args, **kwargs):
945 raise NotImplementedError("test subclasses must define run_method")
947 def check_success(self, expected=None, *args, **kwargs):
949 expected = self.DEFAULT_EXPECT
950 self.assertEqual(expected, self.run_method(*args, **kwargs))
952 def check_exception(self, error_class=None, *args, **kwargs):
953 if error_class is None:
954 error_class = self.DEFAULT_EXCEPTION
955 self.assertRaises(error_class, self.run_method, *args, **kwargs)
957 def test_immediate_success(self):
958 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
961 def test_retry_then_success(self):
962 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
963 self.check_success(num_retries=3)
965 def test_exception_then_success(self):
966 with self.TEST_PATCHER(self.DEFAULT_EXPECT, Exception('mock err'), 200):
967 self.check_success(num_retries=3)
969 def test_no_default_retry(self):
970 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
971 self.check_exception()
973 def test_no_retry_after_permanent_error(self):
974 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
975 self.check_exception(num_retries=3)
977 def test_error_after_retries_exhausted(self):
978 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
979 self.check_exception(num_retries=1)
981 def test_num_retries_instance_fallback(self):
982 self.client_kwargs['num_retries'] = 3
983 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
988 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
989 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
990 DEFAULT_EXCEPTION = arvados.errors.KeepReadError
991 HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
992 TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
994 def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
996 return self.new_client().get(locator, *args, **kwargs)
998 def test_specific_exception_when_not_found(self):
999 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200):
1000 self.check_exception(arvados.errors.NotFoundError, num_retries=3)
1002 def test_general_exception_with_mixed_errors(self):
1003 # get should raise a NotFoundError if no server returns the block,
1004 # and a high threshold of servers report that it's not found.
1005 # This test rigs up 50/50 disagreement between two servers, and
1006 # checks that it does not become a NotFoundError.
1007 client = self.new_client()
1008 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 500):
1009 with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
1010 client.get(self.HINTED_LOCATOR)
1011 self.assertNotIsInstance(
1012 exc_check.exception, arvados.errors.NotFoundError,
1013 "mixed errors raised NotFoundError")
1015 def test_hint_server_can_succeed_without_retries(self):
1016 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200, 500):
1017 self.check_success(locator=self.HINTED_LOCATOR)
1019 def test_try_next_server_after_timeout(self):
1020 with tutil.mock_keep_responses(
1021 (socket.timeout("timed out"), 200),
1022 (self.DEFAULT_EXPECT, 200)):
1023 self.check_success(locator=self.HINTED_LOCATOR)
1025 def test_retry_data_with_wrong_checksum(self):
1026 with tutil.mock_keep_responses(
1028 (self.DEFAULT_EXPECT, 200)):
1029 self.check_success(locator=self.HINTED_LOCATOR)
1032 class KeepClientRetryHeadTestCase(KeepClientRetryTestMixin, unittest.TestCase):
1033 DEFAULT_EXPECT = True
1034 DEFAULT_EXCEPTION = arvados.errors.KeepReadError
1035 HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
1036 TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
1038 def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
1040 return self.new_client().head(locator, *args, **kwargs)
1042 def test_specific_exception_when_not_found(self):
1043 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200):
1044 self.check_exception(arvados.errors.NotFoundError, num_retries=3)
1046 def test_general_exception_with_mixed_errors(self):
1047 # head should raise a NotFoundError if no server returns the block,
1048 # and a high threshold of servers report that it's not found.
1049 # This test rigs up 50/50 disagreement between two servers, and
1050 # checks that it does not become a NotFoundError.
1051 client = self.new_client()
1052 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 500):
1053 with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
1054 client.head(self.HINTED_LOCATOR)
1055 self.assertNotIsInstance(
1056 exc_check.exception, arvados.errors.NotFoundError,
1057 "mixed errors raised NotFoundError")
1059 def test_hint_server_can_succeed_without_retries(self):
1060 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200, 500):
1061 self.check_success(locator=self.HINTED_LOCATOR)
1063 def test_try_next_server_after_timeout(self):
1064 with tutil.mock_keep_responses(
1065 (socket.timeout("timed out"), 200),
1066 (self.DEFAULT_EXPECT, 200)):
1067 self.check_success(locator=self.HINTED_LOCATOR)
1070 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
1071 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
1072 DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
1073 TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
1075 def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
1076 copies=1, *args, **kwargs):
1077 return self.new_client().put(data, copies, *args, **kwargs)
1079 def test_do_not_send_multiple_copies_to_same_server(self):
1080 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 200):
1081 self.check_exception(copies=2, num_retries=3)
1084 class AvoidOverreplication(unittest.TestCase, tutil.ApiClientMock):
1086 class FakeKeepService(object):
1087 def __init__(self, delay, will_succeed=False, will_raise=None, replicas=1):
1089 self.will_succeed = will_succeed
1090 self.will_raise = will_raise
1092 self._result['headers'] = {}
1093 self._result['headers']['x-keep-replicas-stored'] = str(replicas)
1094 self._result['body'] = 'foobar'
1096 def put(self, data_hash, data, timeout):
1097 time.sleep(self.delay)
1098 if self.will_raise is not None:
1099 raise self.will_raise
1100 return self.will_succeed
1102 def last_result(self):
1103 if self.will_succeed:
1111 self.pool = arvados.KeepClient.KeepWriterThreadPool(
1113 data_hash = 'acbd18db4cc2f85cedef654fccc4a4d8+3',
1114 max_service_replicas = self.copies,
1115 copies = self.copies
1118 def test_only_write_enough_on_success(self):
1120 ks = self.FakeKeepService(delay=i/10.0, will_succeed=True)
1121 self.pool.add_task(ks, None)
1123 self.assertEqual(self.pool.done(), self.copies)
1125 def test_only_write_enough_on_partial_success(self):
1127 ks = self.FakeKeepService(delay=i/10.0, will_succeed=False)
1128 self.pool.add_task(ks, None)
1129 ks = self.FakeKeepService(delay=i/10.0, will_succeed=True)
1130 self.pool.add_task(ks, None)
1132 self.assertEqual(self.pool.done(), self.copies)
1134 def test_only_write_enough_when_some_crash(self):
1136 ks = self.FakeKeepService(delay=i/10.0, will_raise=Exception())
1137 self.pool.add_task(ks, None)
1138 ks = self.FakeKeepService(delay=i/10.0, will_succeed=True)
1139 self.pool.add_task(ks, None)
1141 self.assertEqual(self.pool.done(), self.copies)
1143 def test_fail_when_too_many_crash(self):
1144 for i in range(self.copies+1):
1145 ks = self.FakeKeepService(delay=i/10.0, will_raise=Exception())
1146 self.pool.add_task(ks, None)
1147 for i in range(self.copies-1):
1148 ks = self.FakeKeepService(delay=i/10.0, will_succeed=True)
1149 self.pool.add_task(ks, None)
1151 self.assertEqual(self.pool.done(), self.copies-1)
1155 class RetryNeedsMultipleServices(unittest.TestCase, tutil.ApiClientMock):
1156 # Test put()s that need two distinct servers to succeed, possibly
1157 # requiring multiple passes through the retry loop.
1160 self.api_client = self.mock_keep_services(count=2)
1161 self.keep_client = arvados.KeepClient(api_client=self.api_client)
1163 def test_success_after_exception(self):
1164 with tutil.mock_keep_responses(
1165 'acbd18db4cc2f85cedef654fccc4a4d8+3',
1166 Exception('mock err'), 200, 200) as req_mock:
1167 self.keep_client.put('foo', num_retries=1, copies=2)
1168 self.assertEqual(3, req_mock.call_count)
1170 def test_success_after_retryable_error(self):
1171 with tutil.mock_keep_responses(
1172 'acbd18db4cc2f85cedef654fccc4a4d8+3',
1173 500, 200, 200) as req_mock:
1174 self.keep_client.put('foo', num_retries=1, copies=2)
1175 self.assertEqual(3, req_mock.call_count)
1177 def test_fail_after_final_error(self):
1178 # First retry loop gets a 200 (can't achieve replication by
1179 # storing again on that server) and a 400 (can't retry that
1180 # server at all), so we shouldn't try a third request.
1181 with tutil.mock_keep_responses(
1182 'acbd18db4cc2f85cedef654fccc4a4d8+3',
1183 200, 400, 200) as req_mock:
1184 with self.assertRaises(arvados.errors.KeepWriteError):
1185 self.keep_client.put('foo', num_retries=1, copies=2)
1186 self.assertEqual(2, req_mock.call_count)