12 import arvados_testutil as tutil
13 import run_test_server
15 class KeepTestCase(run_test_server.TestCaseWithServers):
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='')
27 def test_KeepBasicRWTest(self):
28 foo_locator = self.keep_client.put('foo')
29 self.assertRegexpMatches(
31 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
32 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
33 self.assertEqual(self.keep_client.get(foo_locator),
35 'wrong content from Keep.get(md5("foo"))')
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(
42 '^7fc7c53b45e53926ba52821140fef396\+6',
43 ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
44 self.assertEqual(self.keep_client.get(blob_locator),
46 'wrong content from Keep.get(md5(<binarydata>))')
48 def test_KeepLongBinaryRWTest(self):
49 blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
51 blob_str = blob_str + blob_str
52 blob_locator = self.keep_client.put(blob_str)
53 self.assertRegexpMatches(
55 '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
56 ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
57 self.assertEqual(self.keep_client.get(blob_locator),
59 'wrong content from Keep.get(md5(<binarydata>))')
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(
66 '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
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 def test_KeepEmptyCollectionTest(self):
73 blob_locator = self.keep_client.put('', copies=1)
74 self.assertRegexpMatches(
76 '^d41d8cd98f00b204e9800998ecf8427e\+0',
77 ('wrong locator from Keep.put(""): ' + blob_locator))
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(
84 '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
85 'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
87 with self.assertRaises(UnicodeEncodeError):
88 # Error if it is not ASCII
89 self.keep_client.put(u'\xe2')
91 with self.assertRaises(arvados.errors.ArgumentError):
92 # Must be a string type
93 self.keep_client.put({})
95 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
97 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
98 'enforce_permissions': True}
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(
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),
110 'wrong content from Keep.get(md5("foo"))')
112 # GET with an unsigned locator => NotFound
113 bar_locator = keep_client.put('bar')
114 unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
115 self.assertRegexpMatches(
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,
121 unsigned_bar_locator)
123 # GET from a different user => NotFound
124 run_test_server.authorize_with('spectator')
125 self.assertRaises(arvados.errors.NotFoundError,
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,
135 self.assertRaises(arvados.errors.NotFoundError,
137 unsigned_bar_locator)
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)
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):
151 KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
152 'enforce_permissions': False}
156 super(KeepOptionalPermission, cls).setUpClass()
157 run_test_server.authorize_with("admin")
158 cls.api_client = arvados.api('v1')
161 super(KeepOptionalPermission, self).setUp()
162 self.keep_client = arvados.KeepClient(api_client=self.api_client,
163 proxy='', local_store='')
165 def _put_foo_and_check(self):
166 signed_locator = self.keep_client.put('foo')
167 self.assertRegexpMatches(
169 r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
170 'invalid locator from Keep.put("foo"): ' + signed_locator)
171 return signed_locator
173 def test_KeepAuthenticatedSignedTest(self):
174 signed_locator = self._put_foo_and_check()
175 self.assertEqual(self.keep_client.get(signed_locator),
177 'wrong content from Keep.get(md5("foo"))')
179 def test_KeepAuthenticatedUnsignedTest(self):
180 signed_locator = self._put_foo_and_check()
181 self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
183 'wrong content from Keep.get(md5("foo"))')
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),
192 'wrong content from Keep.get(md5("foo"))')
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"),
201 'wrong content from Keep.get(md5("foo"))')
204 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
207 KEEP_PROXY_SERVER = {}
211 super(KeepProxyTestCase, cls).setUpClass()
212 run_test_server.authorize_with('active')
213 cls.api_client = arvados.api('v1')
216 arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
217 super(KeepProxyTestCase, self).tearDown()
219 def test_KeepProxyTest1(self):
220 # Will use ARVADOS_KEEP_PROXY environment variable that is set by
222 keep_client = arvados.KeepClient(api_client=self.api_client,
224 baz_locator = keep_client.put('baz')
225 self.assertRegexpMatches(
227 '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
228 'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
229 self.assertEqual(keep_client.get(baz_locator),
231 'wrong content from Keep.get(md5("baz"))')
232 self.assertTrue(keep_client.using_proxy)
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(
243 '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
244 'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
245 self.assertEqual(keep_client.get(baz_locator),
247 'wrong content from Keep.get(md5("baz2"))')
248 self.assertTrue(keep_client.using_proxy)
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('000000')
255 return [urlparse.urlparse(url) for url in sorted(services)]
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))
262 ('https' if ssl_flag else 'http'), services[0].scheme)
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)
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)
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)
283 arvados.KeepClient.DEFAULT_TIMEOUT,
284 mock_session.return_value.get.call_args[1]['timeout'])
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)
295 arvados.KeepClient.DEFAULT_TIMEOUT,
296 mock_session.return_value.put.call_args[1]['timeout'])
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)
310 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
311 mock_session.return_value.get.call_args[1]['timeout'])
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)
325 arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
326 mock_session.return_value.put.call_args[1]['timeout'])
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'.
336 list('3eab2d5fc9681074'),
337 list('097dba52e648f1c3'),
338 list('c5b4e023f8a7d691'),
339 list('9d81c02e76a3bf54'),
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(hash)
349 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
351 self.assertEqual(expected_order[i], got_order)
353 def test_probe_waste_adding_one_server(self):
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)
360 keep_client.weighted_service_roots(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)
365 for hash_index in range(len(hashes)):
366 probe_after = keep_client.weighted_service_roots(
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.
376 len(hashes) / initial_services)
379 (120 - added_services)/100)
381 expect_penalty * 8/10)
383 min_penalty <= total_penalty <= max_penalty,
384 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
392 def check_64_zeros_error_order(self, verb, exc_class):
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])
409 def test_get_error_shows_probe_order(self):
410 self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
412 def test_put_error_shows_probe_order(self):
413 self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
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()))
424 def test_get_error_with_no_services(self):
425 self.check_no_services_error('get', arvados.errors.KeepReadError)
427 def test_put_error_with_no_services(self):
428 self.check_no_services_error('put', arvados.errors.KeepWriteError)
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',
439 self.assertEqual([403, 403], [
440 getattr(error, 'status_code', None)
441 for error in err_check.exception.request_errors().itervalues()])
443 def test_get_error_reflects_last_retry(self):
444 self.check_errors_from_last_retry('get', arvados.errors.KeepReadError)
446 def test_put_error_reflects_last_retry(self):
447 self.check_errors_from_last_retry('put', arvados.errors.KeepWriteError)
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()))
460 class KeepClientRetryTestMixin(object):
461 # Testing with a local Keep store won't exercise the retry behavior.
462 # Instead, our strategy is:
463 # * Create a client with one proxy specified (pointed at a black
464 # hole), so there's no need to instantiate an API client, and
465 # all HTTP requests come from one place.
466 # * Mock httplib's request method to provide simulated responses.
467 # This lets us test the retry logic extensively without relying on any
468 # supporting servers, and prevents side effects in case something hiccups.
469 # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
472 # Test classes must define TEST_PATCHER to a method that mocks
473 # out appropriate methods in the client.
475 PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
476 TEST_DATA = 'testdata'
477 TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
480 self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
482 def new_client(self, **caller_kwargs):
483 kwargs = self.client_kwargs.copy()
484 kwargs.update(caller_kwargs)
485 return arvados.KeepClient(**kwargs)
487 def run_method(self, *args, **kwargs):
488 raise NotImplementedError("test subclasses must define run_method")
490 def check_success(self, expected=None, *args, **kwargs):
492 expected = self.DEFAULT_EXPECT
493 self.assertEqual(expected, self.run_method(*args, **kwargs))
495 def check_exception(self, error_class=None, *args, **kwargs):
496 if error_class is None:
497 error_class = self.DEFAULT_EXCEPTION
498 self.assertRaises(error_class, self.run_method, *args, **kwargs)
500 def test_immediate_success(self):
501 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
504 def test_retry_then_success(self):
505 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
506 self.check_success(num_retries=3)
508 def test_no_default_retry(self):
509 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
510 self.check_exception()
512 def test_no_retry_after_permanent_error(self):
513 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
514 self.check_exception(num_retries=3)
516 def test_error_after_retries_exhausted(self):
517 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
518 self.check_exception(num_retries=1)
520 def test_num_retries_instance_fallback(self):
521 self.client_kwargs['num_retries'] = 3
522 with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
527 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
528 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
529 DEFAULT_EXCEPTION = arvados.errors.KeepReadError
530 HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
531 TEST_PATCHER = staticmethod(tutil.mock_get_responses)
533 def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
535 return self.new_client().get(locator, *args, **kwargs)
537 def test_specific_exception_when_not_found(self):
538 with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200):
539 self.check_exception(arvados.errors.NotFoundError, num_retries=3)
541 def test_general_exception_with_mixed_errors(self):
542 # get should raise a NotFoundError if no server returns the block,
543 # and a high threshold of servers report that it's not found.
544 # This test rigs up 50/50 disagreement between two servers, and
545 # checks that it does not become a NotFoundError.
546 client = self.new_client()
547 with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 500):
548 with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
549 client.get(self.HINTED_LOCATOR)
550 self.assertNotIsInstance(
551 exc_check.exception, arvados.errors.NotFoundError,
552 "mixed errors raised NotFoundError")
554 def test_hint_server_can_succeed_without_retries(self):
555 with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200, 500):
556 self.check_success(locator=self.HINTED_LOCATOR)
558 def test_try_next_server_after_timeout(self):
559 with tutil.mock_get([
560 socket.timeout("timed out"),
561 tutil.fake_requests_response(200, self.DEFAULT_EXPECT)]):
562 self.check_success(locator=self.HINTED_LOCATOR)
564 def test_retry_data_with_wrong_checksum(self):
565 with tutil.mock_get((tutil.fake_requests_response(200, s) for s in ['baddata', self.TEST_DATA])):
566 self.check_success(locator=self.HINTED_LOCATOR)
570 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
571 DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
572 DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
573 TEST_PATCHER = staticmethod(tutil.mock_put_responses)
575 def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
576 copies=1, *args, **kwargs):
577 return self.new_client().put(data, copies, *args, **kwargs)
579 def test_do_not_send_multiple_copies_to_same_server(self):
580 with tutil.mock_put_responses(self.DEFAULT_EXPECT, 200):
581 self.check_exception(copies=2, num_retries=3)