2853: Merge branch 'master' into 2853-rendezvous
[arvados.git] / sdk / python / tests / test_keep_client.py
index 4ac9df17ecf838b4b65685636af0f8ab5b59c3b1..bb0022eb432628dbf0c21b9b9fc2bd20a73f1fb1 100644 (file)
@@ -1,11 +1,93 @@
+import hashlib
 import mock
 import os
+import re
+import socket
 import unittest
+import urlparse
 
 import arvados
 import arvados.retry
+import arvados_testutil as tutil
 import run_test_server
-from arvados_testutil import fake_httplib2_response
+
+class KeepRendezvousWeightTestCase(unittest.TestCase):
+    def setUp(self):
+        self.keep_client = arvados.KeepClient(
+            api_client=mock.MagicMock(name='api_client'),
+            proxy='', local_store='')
+        self.keep_client._keep_services = []
+        self.n_services = 0
+
+    def addServices(self, n):
+        for x in range(n):
+            uuid = "zzzzz-bi6l4-{:015x}".format(self.n_services)
+            uri = "https://keep0x{:x}.zzzzz.arvadosapi.com:25107/".format(self.n_services)
+            self.keep_client._keep_services.append(
+                {'uuid': uuid, '_service_root': uri})
+            self.n_services += 1
+
+    def test_ProbeOrderReferenceSet(self):
+        # expected_order[i] is the probe order for
+        # hash=md5(sprintf("%064x",i)) where there are 16 services
+        # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
+        # the first probe for the block consisting of 64 "0"
+        # characters is the service whose uuid is
+        # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
+        expected_order = [
+            list('3eab2d5fc9681074'),
+            list('097dba52e648f1c3'),
+            list('c5b4e023f8a7d691'),
+            list('9d81c02e76a3bf54'),
+            ]
+        hashes = [
+            hashlib.md5("{:064x}".format(x)).hexdigest()
+            for x in range(len(expected_order))]
+        self.addServices(16)
+        for i, hash in enumerate(hashes):
+            roots = self.keep_client.weighted_service_roots(hash)
+            got_order = [
+                re.search(r'//keep0x([0-9a-f]+)', root).group(1)
+                for root in roots]
+            self.assertEqual(got_order, expected_order[i])
+
+    def test_ProbeWasteAddingOneServer(self):
+        hashes = [
+            hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
+        initial_services = 12
+        self.addServices(initial_services)
+        probes_before = [
+            self.keep_client.weighted_service_roots(hash) for hash in hashes]
+        for added_services in range(1, 12):
+            self.addServices(1)
+            total_penalty = 0
+            for hash_index in range(len(hashes)):
+                probe_after = self.keep_client.weighted_service_roots(
+                    hashes[hash_index])
+                penalty = probe_after.index(probes_before[hash_index][0])
+                self.assertLessEqual(penalty, added_services)
+                total_penalty += penalty
+            # Average penalty per block should not exceed
+            # N(added)/N(orig) by more than 20%, and should get closer
+            # to the ideal as we add data points.
+            expect_penalty = (
+                added_services *
+                len(hashes) / initial_services)
+            max_penalty = (
+                expect_penalty *
+                (120 - added_services)/100)
+            min_penalty = (
+                expect_penalty * 8/10)
+            self.assertTrue(
+                min_penalty <= total_penalty <= max_penalty,
+                "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
+                    initial_services,
+                    added_services,
+                    len(hashes),
+                    total_penalty,
+                    min_penalty,
+                    max_penalty))
+
 
 class KeepTestCase(run_test_server.TestCaseWithServers):
     MAIN_SERVER = {}
@@ -64,6 +146,13 @@ class KeepTestCase(run_test_server.TestCaseWithServers):
                          blob_str,
                          'wrong content from Keep.get(md5(<binarydata>))')
 
+    def test_KeepEmptyCollectionTest(self):
+        blob_locator = self.keep_client.put('', copies=1)
+        self.assertRegexpMatches(
+            blob_locator,
+            '^d41d8cd98f00b204e9800998ecf8427e\+0',
+            ('wrong locator from Keep.put(""): ' + blob_locator))
+
 
 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
     MAIN_SERVER = {}
@@ -220,6 +309,101 @@ class KeepProxyTestCase(run_test_server.TestCaseWithServers):
         self.assertTrue(keep_client.using_proxy)
 
 
+class KeepClientServiceTestCase(unittest.TestCase):
+    def mock_keep_services(self, *services):
+        api_client = mock.MagicMock(name='api_client')
+        api_client.keep_services().accessible().execute.return_value = {
+            'items_available': len(services),
+            'items': [{
+                    'uuid': 'zzzzz-bi6l4-mockservice{:04x}'.format(index),
+                    'owner_uuid': 'zzzzz-tpzed-mockownerabcdef',
+                    'service_host': host,
+                    'service_port': port,
+                    'service_ssl_flag': ssl,
+                    'service_type': servtype,
+                    } for index, (host, port, ssl, servtype)
+                      in enumerate(services)],
+            }
+        return api_client
+
+    def get_service_roots(self, *services):
+        api_client = self.mock_keep_services(*services)
+        keep_client = arvados.KeepClient(api_client=api_client)
+        services = keep_client.weighted_service_roots('000000')
+        return [urlparse.urlparse(url) for url in sorted(services)]
+
+    def test_ssl_flag_respected_in_roots(self):
+        services = self.get_service_roots(('keep', 10, False, 'disk'),
+                                          ('keep', 20, True, 'disk'))
+        self.assertEqual(10, services[0].port)
+        self.assertEqual('http', services[0].scheme)
+        self.assertEqual(20, services[1].port)
+        self.assertEqual('https', services[1].scheme)
+
+    def test_correct_ports_with_ipv6_addresses(self):
+        service = self.get_service_roots(('100::1', 10, True, 'proxy'))[0]
+        self.assertEqual('100::1', service.hostname)
+        self.assertEqual(10, service.port)
+
+    # test_get_timeout and test_put_timeout test that
+    # KeepClient.get and KeepClient.put use the appropriate timeouts
+    # when connected directly to a Keep server (i.e. non-proxy timeout)
+
+    def test_get_timeout(self):
+        api_client = self.mock_keep_services(('keep', 10, False, 'disk'))
+        keep_client = arvados.KeepClient(api_client=api_client)
+        force_timeout = [socket.timeout("timed out")]
+        with mock.patch('requests.get', side_effect=force_timeout) as mock_request:
+            with self.assertRaises(arvados.errors.KeepReadError):
+                keep_client.get('ffffffffffffffffffffffffffffffff')
+            self.assertTrue(mock_request.called)
+            self.assertEqual(
+                arvados.KeepClient.DEFAULT_TIMEOUT,
+                mock_request.call_args[1]['timeout'])
+
+    def test_put_timeout(self):
+        api_client = self.mock_keep_services(('keep', 10, False, 'disk'))
+        keep_client = arvados.KeepClient(api_client=api_client)
+        force_timeout = [socket.timeout("timed out")]
+        with mock.patch('requests.put', side_effect=force_timeout) as mock_request:
+            with self.assertRaises(arvados.errors.KeepWriteError):
+                keep_client.put('foo')
+            self.assertTrue(mock_request.called)
+            self.assertEqual(
+                arvados.KeepClient.DEFAULT_TIMEOUT,
+                mock_request.call_args[1]['timeout'])
+
+    def test_proxy_get_timeout(self):
+        # Force a timeout, verifying that the requests.get or
+        # requests.put method was called with the proxy_timeout
+        # setting rather than the default timeout.
+        api_client = self.mock_keep_services(('keep', 10, False, 'proxy'))
+        keep_client = arvados.KeepClient(api_client=api_client)
+        force_timeout = [socket.timeout("timed out")]
+        with mock.patch('requests.get', side_effect=force_timeout) as mock_request:
+            with self.assertRaises(arvados.errors.KeepReadError):
+                keep_client.get('ffffffffffffffffffffffffffffffff')
+            self.assertTrue(mock_request.called)
+            self.assertEqual(
+                arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
+                mock_request.call_args[1]['timeout'])
+
+    def test_proxy_put_timeout(self):
+        # Force a timeout, verifying that the requests.get or
+        # requests.put method was called with the proxy_timeout
+        # setting rather than the default timeout.
+        api_client = self.mock_keep_services(('keep', 10, False, 'proxy'))
+        keep_client = arvados.KeepClient(api_client=api_client)
+        force_timeout = [socket.timeout("timed out")]
+        with mock.patch('requests.put', side_effect=force_timeout) as mock_request:
+            with self.assertRaises(arvados.errors.KeepWriteError):
+                keep_client.put('foo')
+            self.assertTrue(mock_request.called)
+            self.assertEqual(
+                arvados.KeepClient.DEFAULT_PROXY_TIMEOUT,
+                mock_request.call_args[1]['timeout'])
+
+
 class KeepClientRetryTestMixin(object):
     # Testing with a local Keep store won't exercise the retry behavior.
     # Instead, our strategy is:
@@ -231,17 +415,21 @@ class KeepClientRetryTestMixin(object):
     # supporting servers, and prevents side effects in case something hiccups.
     # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
     # run_method().
-    PROXY_ADDR = 'http://[100::]/'
+    #
+    # Test classes must define TEST_PATCHER to a method that mocks
+    # out appropriate methods in the client.
+
+    PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
     TEST_DATA = 'testdata'
     TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
 
-    @staticmethod
-    def mock_responses(body, *codes):
-        return mock.patch('httplib2.Http.request', side_effect=(
-                (fake_httplib2_response(code), body) for code in codes))
+    def setUp(self):
+        self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
 
-    def new_client(self):
-        return arvados.KeepClient(proxy=self.PROXY_ADDR, local_store='')
+    def new_client(self, **caller_kwargs):
+        kwargs = self.client_kwargs.copy()
+        kwargs.update(caller_kwargs)
+        return arvados.KeepClient(**kwargs)
 
     def run_method(self, *args, **kwargs):
         raise NotImplementedError("test subclasses must define run_method")
@@ -257,40 +445,44 @@ class KeepClientRetryTestMixin(object):
         self.assertRaises(error_class, self.run_method, *args, **kwargs)
 
     def test_immediate_success(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 200):
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
             self.check_success()
 
     def test_retry_then_success(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 500, 200):
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
             self.check_success(num_retries=3)
 
     def test_no_default_retry(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 500, 200):
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
             self.check_exception()
 
     def test_no_retry_after_permanent_error(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 403, 200):
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
             self.check_exception(num_retries=3)
 
     def test_error_after_retries_exhausted(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 500, 500, 200):
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
             self.check_exception(num_retries=1)
 
+    def test_num_retries_instance_fallback(self):
+        self.client_kwargs['num_retries'] = 3
+        with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
+            self.check_success()
+
 
-# Don't delay from HTTPRetryLoop's exponential backoff.
-no_backoff = mock.patch('time.sleep', lambda n: None)
-@no_backoff
-class KeepClientRetryGetTestCase(unittest.TestCase, KeepClientRetryTestMixin):
+@tutil.skip_sleep
+class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
     DEFAULT_EXCEPTION = arvados.errors.KeepReadError
     HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
+    TEST_PATCHER = staticmethod(tutil.mock_get_responses)
 
     def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
                    *args, **kwargs):
         return self.new_client().get(locator, *args, **kwargs)
 
     def test_specific_exception_when_not_found(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 404, 200):
+        with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200):
             self.check_exception(arvados.errors.NotFoundError, num_retries=3)
 
     def test_general_exception_with_mixed_errors(self):
@@ -299,7 +491,7 @@ class KeepClientRetryGetTestCase(unittest.TestCase, KeepClientRetryTestMixin):
         # This test rigs up 50/50 disagreement between two servers, and
         # checks that it does not become a NotFoundError.
         client = self.new_client()
-        with self.mock_responses(self.DEFAULT_EXPECT, 404, 500):
+        with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 500):
             with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
                 client.get(self.HINTED_LOCATOR)
             self.assertNotIsInstance(
@@ -307,19 +499,34 @@ class KeepClientRetryGetTestCase(unittest.TestCase, KeepClientRetryTestMixin):
                 "mixed errors raised NotFoundError")
 
     def test_hint_server_can_succeed_without_retries(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 404, 200, 500):
+        with tutil.mock_get_responses(self.DEFAULT_EXPECT, 404, 200, 500):
+            self.check_success(locator=self.HINTED_LOCATOR)
+
+    def test_try_next_server_after_timeout(self):
+        side_effects = [
+            socket.timeout("timed out"),
+            tutil.fake_requests_response(200, self.DEFAULT_EXPECT)]
+        with mock.patch('requests.get',
+                        side_effect=iter(side_effects)):
+            self.check_success(locator=self.HINTED_LOCATOR)
+
+    def test_retry_data_with_wrong_checksum(self):
+        side_effects = (tutil.fake_requests_response(200, s)
+                        for s in ['baddata', self.TEST_DATA])
+        with mock.patch('requests.get', side_effect=side_effects):
             self.check_success(locator=self.HINTED_LOCATOR)
 
 
-@no_backoff
-class KeepClientRetryPutTestCase(unittest.TestCase, KeepClientRetryTestMixin):
+@tutil.skip_sleep
+class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
     DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
+    TEST_PATCHER = staticmethod(tutil.mock_put_responses)
 
     def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
                    copies=1, *args, **kwargs):
         return self.new_client().put(data, copies, *args, **kwargs)
 
     def test_do_not_send_multiple_copies_to_same_server(self):
-        with self.mock_responses(self.DEFAULT_EXPECT, 200):
+        with tutil.mock_put_responses(self.DEFAULT_EXPECT, 200):
             self.check_exception(copies=2, num_retries=3)