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 foo_locator = self.keep_client.put('foo')
33 self.assertRegexpMatches(
35 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
36 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
37 self.assertEqual(self.keep_client.get(foo_locator),
39 'wrong content from Keep.get(md5("foo"))')
41 def test_KeepBinaryRWTest(self):
42 blob_str = '\xff\xfe\xf7\x00\x01\x02'
43 blob_locator = self.keep_client.put(blob_str)
44 self.assertRegexpMatches(
46 '^7fc7c53b45e53926ba52821140fef396\+6',
47 ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
48 self.assertEqual(self.keep_client.get(blob_locator),
50 'wrong content from Keep.get(md5(<binarydata>))')
52 def test_KeepLongBinaryRWTest(self):
53 blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
55 blob_str = blob_str + blob_str
56 blob_locator = self.keep_client.put(blob_str)
57 self.assertRegexpMatches(
59 '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
60 ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
61 self.assertEqual(self.keep_client.get(blob_locator),
63 'wrong content from Keep.get(md5(<binarydata>))')
65 def test_KeepSingleCopyRWTest(self):
66 blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
67 blob_locator = self.keep_client.put(blob_str, copies=1)
68 self.assertRegexpMatches(
70 '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
71 ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
72 self.assertEqual(self.keep_client.get(blob_locator),
74 'wrong content from Keep.get(md5(<binarydata>))')
76 def test_KeepEmptyCollectionTest(self):
77 blob_locator = self.keep_client.put('', copies=1)
78 self.assertRegexpMatches(
80 '^d41d8cd98f00b204e9800998ecf8427e\+0',
81 ('wrong locator from Keep.put(""): ' + blob_locator))
83 def test_unicode_must_be_ascii(self):
84 # If unicode type, must only consist of valid ASCII
85 foo_locator = self.keep_client.put(u'foo')
86 self.assertRegexpMatches(
88 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
89 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
91 with self.assertRaises(UnicodeEncodeError):
92 # Error if it is not ASCII
93 self.keep_client.put(u'\xe2')
95 with self.assertRaises(arvados.errors.ArgumentError):
96 # Must be a string type
97 self.keep_client.put({})
99 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
101 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
102 'enforce_permissions': True}
104 def test_KeepBasicRWTest(self):
105 run_test_server.authorize_with('active')
106 keep_client = arvados.KeepClient()
107 foo_locator = keep_client.put('foo')
108 self.assertRegexpMatches(
110 r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
111 'invalid locator from Keep.put("foo"): ' + foo_locator)
112 self.assertEqual(keep_client.get(foo_locator),
114 'wrong content from Keep.get(md5("foo"))')
116 # GET with an unsigned locator => NotFound
117 bar_locator = keep_client.put('bar')
118 unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
119 self.assertRegexpMatches(
121 r'^37b51d194a7513e45b56f6524f2d51f2\+3\+A[a-f0-9]+@[a-f0-9]+$',
122 'invalid locator from Keep.put("bar"): ' + bar_locator)
123 self.assertRaises(arvados.errors.NotFoundError,
125 unsigned_bar_locator)
127 # GET from a different user => NotFound
128 run_test_server.authorize_with('spectator')
129 self.assertRaises(arvados.errors.NotFoundError,
133 # Unauthenticated GET for a signed locator => NotFound
134 # Unauthenticated GET for an unsigned locator => NotFound
135 keep_client.api_token = ''
136 self.assertRaises(arvados.errors.NotFoundError,
139 self.assertRaises(arvados.errors.NotFoundError,
141 unsigned_bar_locator)
144 # KeepOptionalPermission: starts Keep with --permission-key-file
145 # but not --enforce-permissions (i.e. generate signatures on PUT
146 # requests, but do not require them for GET requests)
148 # All of these requests should succeed when permissions are optional:
149 # * authenticated request, signed locator
150 # * authenticated request, unsigned locator
151 # * unauthenticated request, signed locator
152 # * unauthenticated request, unsigned locator
153 class KeepOptionalPermission(run_test_server.TestCaseWithServers):
155 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
156 'enforce_permissions': False}
160 super(KeepOptionalPermission, cls).setUpClass()
161 run_test_server.authorize_with("admin")
162 cls.api_client = arvados.api('v1')
165 super(KeepOptionalPermission, self).setUp()
166 self.keep_client = arvados.KeepClient(api_client=self.api_client,
167 proxy='', local_store='')
169 def _put_foo_and_check(self):
170 signed_locator = self.keep_client.put('foo')
171 self.assertRegexpMatches(
173 r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
174 'invalid locator from Keep.put("foo"): ' + signed_locator)
175 return signed_locator
177 def test_KeepAuthenticatedSignedTest(self):
178 signed_locator = self._put_foo_and_check()
179 self.assertEqual(self.keep_client.get(signed_locator),
181 'wrong content from Keep.get(md5("foo"))')
183 def test_KeepAuthenticatedUnsignedTest(self):
184 signed_locator = self._put_foo_and_check()
185 self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
187 'wrong content from Keep.get(md5("foo"))')
189 def test_KeepUnauthenticatedSignedTest(self):
190 # Check that signed GET requests work even when permissions
191 # enforcement is off.
192 signed_locator = self._put_foo_and_check()
193 self.keep_client.api_token = ''
194 self.assertEqual(self.keep_client.get(signed_locator),
196 'wrong content from Keep.get(md5("foo"))')
198 def test_KeepUnauthenticatedUnsignedTest(self):
199 # Since --enforce-permissions is not in effect, GET requests
200 # need not be authenticated.
201 signed_locator = self._put_foo_and_check()
202 self.keep_client.api_token = ''
203 self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
205 'wrong content from Keep.get(md5("foo"))')
208 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
211 KEEP_PROXY_SERVER = {}
215 super(KeepProxyTestCase, cls).setUpClass()
216 run_test_server.authorize_with('active')
217 cls.api_client = arvados.api('v1')
220 arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
221 super(KeepProxyTestCase, self).tearDown()
223 def test_KeepProxyTest1(self):
224 # Will use ARVADOS_KEEP_PROXY environment variable that is set by
226 keep_client = arvados.KeepClient(api_client=self.api_client,
228 baz_locator = keep_client.put('baz')
229 self.assertRegexpMatches(
231 '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
232 'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
233 self.assertEqual(keep_client.get(baz_locator),
235 'wrong content from Keep.get(md5("baz"))')
236 self.assertTrue(keep_client.using_proxy)
238 def test_KeepProxyTest2(self):
239 # Don't instantiate the proxy directly, but set the X-External-Client
240 # header. The API server should direct us to the proxy.
241 arvados.config.settings()['ARVADOS_EXTERNAL_CLIENT'] = 'true'
242 keep_client = arvados.KeepClient(api_client=self.api_client,
243 proxy='', local_store='')
244 baz_locator = keep_client.put('baz2')
245 self.assertRegexpMatches(
247 '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
248 'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
249 self.assertEqual(keep_client.get(baz_locator),
251 'wrong content from Keep.get(md5("baz2"))')
252 self.assertTrue(keep_client.using_proxy)
255 class KeepClientServiceTestCase(unittest.TestCase, tutil.ApiClientMock):
256 def get_service_roots(self, api_client):
257 keep_client = arvados.KeepClient(api_client=api_client)
258 services = keep_client.weighted_service_roots(arvados.KeepLocator('0'*32))
259 return [urlparse.urlparse(url) for url in sorted(services)]
261 def test_ssl_flag_respected_in_roots(self):
262 for ssl_flag in [False, True]:
263 services = self.get_service_roots(self.mock_keep_services(
264 service_ssl_flag=ssl_flag))
266 ('https' if ssl_flag else 'http'), services[0].scheme)
268 def test_correct_ports_with_ipv6_addresses(self):
269 service = self.get_service_roots(self.mock_keep_services(
270 service_type='proxy', service_host='100::1', service_port=10, count=1))[0]
271 self.assertEqual('100::1', service.hostname)
272 self.assertEqual(10, service.port)
274 # test_*_timeout verify that KeepClient instructs pycurl to use
275 # the appropriate connection and read timeouts. They don't care
276 # whether pycurl actually exhibits the expected timeout behavior
277 # -- those tests are in the KeepClientTimeout test class.
279 def test_get_timeout(self):
280 api_client = self.mock_keep_services(count=1)
281 force_timeout = socket.timeout("timed out")
282 with tutil.mock_keep_responses(force_timeout, 0) as mock:
283 keep_client = arvados.KeepClient(api_client=api_client)
284 with self.assertRaises(arvados.errors.KeepReadError):
285 keep_client.get('ffffffffffffffffffffffffffffffff')
287 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
288 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
290 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
291 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]*1000))
293 def test_put_timeout(self):
294 api_client = self.mock_keep_services(count=1)
295 force_timeout = socket.timeout("timed out")
296 with tutil.mock_keep_responses(force_timeout, 0) as mock:
297 keep_client = arvados.KeepClient(api_client=api_client)
298 with self.assertRaises(arvados.errors.KeepWriteError):
299 keep_client.put('foo')
301 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
302 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
304 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
305 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]*1000))
307 def test_proxy_get_timeout(self):
308 api_client = self.mock_keep_services(service_type='proxy', count=1)
309 force_timeout = socket.timeout("timed out")
310 with tutil.mock_keep_responses(force_timeout, 0) as mock:
311 keep_client = arvados.KeepClient(api_client=api_client)
312 with self.assertRaises(arvados.errors.KeepReadError):
313 keep_client.get('ffffffffffffffffffffffffffffffff')
315 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
316 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
318 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
319 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]*1000))
321 def test_proxy_put_timeout(self):
322 api_client = self.mock_keep_services(service_type='proxy', count=1)
323 force_timeout = socket.timeout("timed out")
324 with tutil.mock_keep_responses(force_timeout, 0) as mock:
325 keep_client = arvados.KeepClient(api_client=api_client)
326 with self.assertRaises(arvados.errors.KeepWriteError):
327 keep_client.put('foo')
329 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
330 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
332 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
333 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]*1000))
335 def test_probe_order_reference_set(self):
336 # expected_order[i] is the probe order for
337 # hash=md5(sprintf("%064x",i)) where there are 16 services
338 # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
339 # the first probe for the block consisting of 64 "0"
340 # characters is the service whose uuid is
341 # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
343 list('3eab2d5fc9681074'),
344 list('097dba52e648f1c3'),
345 list('c5b4e023f8a7d691'),
346 list('9d81c02e76a3bf54'),
349 hashlib.md5("{:064x}".format(x)).hexdigest()
350 for x in range(len(expected_order))]
351 api_client = self.mock_keep_services(count=16)
352 keep_client = arvados.KeepClient(api_client=api_client)
353 for i, hash in enumerate(hashes):
354 roots = keep_client.weighted_service_roots(arvados.KeepLocator(hash))
356 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
358 self.assertEqual(expected_order[i], got_order)
360 def test_probe_waste_adding_one_server(self):
362 hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
363 initial_services = 12
364 api_client = self.mock_keep_services(count=initial_services)
365 keep_client = arvados.KeepClient(api_client=api_client)
367 keep_client.weighted_service_roots(arvados.KeepLocator(hash)) for hash in hashes]
368 for added_services in range(1, 12):
369 api_client = self.mock_keep_services(count=initial_services+added_services)
370 keep_client = arvados.KeepClient(api_client=api_client)
372 for hash_index in range(len(hashes)):
373 probe_after = keep_client.weighted_service_roots(
374 arvados.KeepLocator(hashes[hash_index]))
375 penalty = probe_after.index(probes_before[hash_index][0])
376 self.assertLessEqual(penalty, added_services)
377 total_penalty += penalty
378 # Average penalty per block should not exceed
379 # N(added)/N(orig) by more than 20%, and should get closer
380 # to the ideal as we add data points.
383 len(hashes) / initial_services)
386 (120 - added_services)/100)
388 expect_penalty * 8/10)
390 min_penalty <= total_penalty <= max_penalty,
391 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
399 def check_64_zeros_error_order(self, verb, exc_class):
402 data = hashlib.md5(data).hexdigest() + '+1234'
403 # Arbitrary port number:
404 aport = random.randint(1024,65535)
405 api_client = self.mock_keep_services(service_port=aport, count=16)
406 keep_client = arvados.KeepClient(api_client=api_client)
407 with mock.patch('pycurl.Curl') as curl_mock, \
408 self.assertRaises(exc_class) as err_check:
409 curl_mock.return_value.side_effect = socket.timeout
410 getattr(keep_client, verb)(data)
411 urls = [urlparse.urlparse(url)
412 for url in err_check.exception.request_errors()]
413 self.assertEqual([('keep0x' + c, aport) for c in '3eab2d5fc9681074'],
414 [(url.hostname, url.port) for url in urls])
416 def test_get_error_shows_probe_order(self):
417 self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
419 def test_put_error_shows_probe_order(self):
420 self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
422 def check_no_services_error(self, verb, exc_class):
423 api_client = mock.MagicMock(name='api_client')
424 api_client.keep_services().accessible().execute.side_effect = (
425 arvados.errors.ApiError)
426 keep_client = arvados.KeepClient(api_client=api_client)
427 with self.assertRaises(exc_class) as err_check:
428 getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0')
429 self.assertEqual(0, len(err_check.exception.request_errors()))
431 def test_get_error_with_no_services(self):
432 self.check_no_services_error('get', arvados.errors.KeepReadError)
434 def test_put_error_with_no_services(self):
435 self.check_no_services_error('put', arvados.errors.KeepWriteError)
437 def check_errors_from_last_retry(self, verb, exc_class):
438 api_client = self.mock_keep_services(count=2)
439 req_mock = tutil.mock_keep_responses(
440 "retry error reporting test", 500, 500, 403, 403)
441 with req_mock, tutil.skip_sleep, \
442 self.assertRaises(exc_class) as err_check:
443 keep_client = arvados.KeepClient(api_client=api_client)
444 getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0',
446 self.assertEqual([403, 403], [
447 getattr(error, 'status_code', None)
448 for error in err_check.exception.request_errors().itervalues()])
450 def test_get_error_reflects_last_retry(self):
451 self.check_errors_from_last_retry('get', 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 = '{}+{}'.format(hashlib.md5(data).hexdigest(), len(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 = '{}+{}'.format(hashlib.md5(data).hexdigest(), len(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 class KeepClientTimeout(unittest.TestCase, tutil.ApiClientMock):
480 class assertTakesBetween(unittest.TestCase):
481 def __init__(self, tmin, tmax):
486 self.t0 = time.time()
488 def __exit__(self, *args, **kwargs):
489 self.assertGreater(time.time() - self.t0, self.tmin)
490 self.assertLess(time.time() - self.t0, self.tmax)
493 sock = socket.socket()
494 sock.bind(('0.0.0.0', 0))
495 self.port = sock.getsockname()[1]
497 self.server = keepstub.Server(('0.0.0.0', self.port), keepstub.Handler)
498 self.thread = threading.Thread(target=self.server.serve_forever)
499 self.thread.daemon = True # Exit thread if main proc exits
501 self.api_client = self.mock_keep_services(
503 service_host='localhost',
504 service_port=self.port,
508 self.server.shutdown()
510 def keepClient(self, timeouts=(0.1, 1.0)):
511 return arvados.KeepClient(
512 api_client=self.api_client,
515 def test_timeout_slow_connect(self):
516 # Can't simulate TCP delays with our own socket. Leave our
517 # stub server running uselessly, and try to connect to an
518 # unroutable IP address instead.
519 self.api_client = self.mock_keep_services(
521 service_host='240.0.0.0',
523 with self.assertTakesBetween(0.1, 0.5):
524 with self.assertRaises(arvados.errors.KeepWriteError):
525 self.keepClient((0.1, 1)).put(self.DATA, copies=1, num_retries=0)
527 def test_timeout_slow_request(self):
528 self.server.setdelays(request=0.2)
531 def test_timeout_slow_response(self):
532 self.server.setdelays(response=0.2)
535 def test_timeout_slow_response_body(self):
536 self.server.setdelays(response_body=0.2)
539 def _test_200ms(self):
540 """Connect should be t<100ms, request should be 200ms <= t < 300ms"""
542 # Allow 100ms to connect, then 1s for response. Everything
543 # should work, and everything should take at least 200ms to
545 kc = self.keepClient((.1, 1))
546 with self.assertTakesBetween(.2, .3):
547 loc = kc.put(self.DATA, copies=1, num_retries=0)
548 with self.assertTakesBetween(.2, .3):
549 self.assertEqual(self.DATA, kc.get(loc, num_retries=0))
551 # Allow 1s to connect, then 100ms for response. Nothing should
552 # work, and everything should take at least 100ms to return.
553 kc = self.keepClient((1, .1))
554 with self.assertTakesBetween(.1, .2):
555 with self.assertRaises(arvados.errors.KeepReadError):
556 kc.get(loc, num_retries=0)
557 with self.assertTakesBetween(.1, .2):
558 with self.assertRaises(arvados.errors.KeepWriteError):
559 kc.put(self.DATA, copies=1, num_retries=0)
562 class KeepClientGatewayTestCase(unittest.TestCase, tutil.ApiClientMock):
563 def mock_disks_and_gateways(self, disks=3, gateways=1):
565 'uuid': 'zzzzz-bi6l4-gateway{:08d}'.format(i),
566 'owner_uuid': 'zzzzz-tpzed-000000000000000',
567 'service_host': 'gatewayhost{}'.format(i),
568 'service_port': 12345,
569 'service_ssl_flag': True,
570 'service_type': 'gateway:test',
571 } for i in range(gateways)]
572 self.gateway_roots = [
573 "https://{service_host}:{service_port}/".format(**gw)
574 for gw in self.gateways]
575 self.api_client = self.mock_keep_services(
576 count=disks, additional_services=self.gateways)
577 self.keepClient = arvados.KeepClient(api_client=self.api_client)
579 @mock.patch('pycurl.Curl')
580 def test_get_with_gateway_hint_first(self, MockCurl):
581 MockCurl.return_value = tutil.FakeCurl.make(
582 code=200, body='foo', headers={'Content-Length': 3})
583 self.mock_disks_and_gateways()
584 locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@' + self.gateways[0]['uuid']
585 self.assertEqual('foo', self.keepClient.get(locator))
586 self.assertEqual(self.gateway_roots[0]+locator,
587 MockCurl.return_value.getopt(pycurl.URL))
589 @mock.patch('pycurl.Curl')
590 def test_get_with_gateway_hints_in_order(self, MockCurl):
594 tutil.FakeCurl.make(code=404, body='')
595 for _ in range(gateways+disks)
597 MockCurl.side_effect = tutil.queue_with(mocks)
598 self.mock_disks_and_gateways(gateways=gateways, disks=disks)
599 locator = '+'.join(['acbd18db4cc2f85cedef654fccc4a4d8+3'] +
600 ['K@'+gw['uuid'] for gw in self.gateways])
601 with self.assertRaises(arvados.errors.NotFoundError):
602 self.keepClient.get(locator)
603 # Gateways are tried first, in the order given.
604 for i, root in enumerate(self.gateway_roots):
605 self.assertEqual(root+locator,
606 mocks[i].getopt(pycurl.URL))
607 # Disk services are tried next.
608 for i in range(gateways, gateways+disks):
609 self.assertRegexpMatches(
610 mocks[i].getopt(pycurl.URL),
613 @mock.patch('pycurl.Curl')
614 def test_get_with_remote_proxy_hint(self, MockCurl):
615 MockCurl.return_value = tutil.FakeCurl.make(
616 code=200, body='foo', headers={'Content-Length': 3})
617 self.mock_disks_and_gateways()
618 locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@xyzzy'
619 self.assertEqual('foo', self.keepClient.get(locator))
620 self.assertEqual('https://keep.xyzzy.arvadosapi.com/'+locator,
621 MockCurl.return_value.getopt(pycurl.URL))
624 class KeepClientRetryTestMixin(object):
625 # Testing with a local Keep store won't exercise the retry behavior.
626 # Instead, our strategy is:
627 # * Create a client with one proxy specified (pointed at a black
628 # hole), so there's no need to instantiate an API client, and
629 # all HTTP requests come from one place.
630 # * Mock httplib's request method to provide simulated responses.
631 # This lets us test the retry logic extensively without relying on any
632 # supporting servers, and prevents side effects in case something hiccups.
633 # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
636 # Test classes must define TEST_PATCHER to a method that mocks
637 # out appropriate methods in the client.
639 PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
640 TEST_DATA = 'testdata'
641 TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
644 self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
646 def new_client(self, **caller_kwargs):
647 kwargs = self.client_kwargs.copy()
648 kwargs.update(caller_kwargs)
649 return arvados.KeepClient(**kwargs)
651 def run_method(self, *args, **kwargs):
652 raise NotImplementedError("test subclasses must define run_method")
654 def check_success(self, expected=None, *args, **kwargs):
656 expected = self.DEFAULT_EXPECT
657 self.assertEqual(expected, self.run_method(*args, **kwargs))
659 def check_exception(self, error_class=None, *args, **kwargs):
660 if error_class is None:
661 error_class = self.DEFAULT_EXCEPTION
662 self.assertRaises(error_class, self.run_method, *args, **kwargs)
664 def test_immediate_success(self):
665 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
668 def test_retry_then_success(self):
669 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
670 self.check_success(num_retries=3)
672 def test_no_default_retry(self):
673 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
674 self.check_exception()
676 def test_no_retry_after_permanent_error(self):
677 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
678 self.check_exception(num_retries=3)
680 def test_error_after_retries_exhausted(self):
681 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
682 self.check_exception(num_retries=1)
684 def test_num_retries_instance_fallback(self):
685 self.client_kwargs['num_retries'] = 3
686 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
691 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
692 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
693 DEFAULT_EXCEPTION = arvados.errors.KeepReadError
694 HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
695 TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
697 def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
699 return self.new_client().get(locator, *args, **kwargs)
701 def test_specific_exception_when_not_found(self):
702 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200):
703 self.check_exception(arvados.errors.NotFoundError, num_retries=3)
705 def test_general_exception_with_mixed_errors(self):
706 # get should raise a NotFoundError if no server returns the block,
707 # and a high threshold of servers report that it's not found.
708 # This test rigs up 50/50 disagreement between two servers, and
709 # checks that it does not become a NotFoundError.
710 client = self.new_client()
711 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 500):
712 with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
713 client.get(self.HINTED_LOCATOR)
714 self.assertNotIsInstance(
715 exc_check.exception, arvados.errors.NotFoundError,
716 "mixed errors raised NotFoundError")
718 def test_hint_server_can_succeed_without_retries(self):
719 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200, 500):
720 self.check_success(locator=self.HINTED_LOCATOR)
722 def test_try_next_server_after_timeout(self):
723 with tutil.mock_keep_responses(
724 (socket.timeout("timed out"), 200),
725 (self.DEFAULT_EXPECT, 200)):
726 self.check_success(locator=self.HINTED_LOCATOR)
728 def test_retry_data_with_wrong_checksum(self):
729 with tutil.mock_keep_responses(
731 (self.DEFAULT_EXPECT, 200)):
732 self.check_success(locator=self.HINTED_LOCATOR)
736 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
737 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
738 DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
739 TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
741 def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
742 copies=1, *args, **kwargs):
743 return self.new_client().put(data, copies, *args, **kwargs)
745 def test_do_not_send_multiple_copies_to_same_server(self):
746 with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 200):
747 self.check_exception(copies=2, num_retries=3)