7696: PySDK determines max_replicas_per_service after querying services.
[arvados.git] / sdk / python / tests / test_keep_client.py
1 import hashlib
2 import mock
3 import os
4 import pycurl
5 import random
6 import re
7 import socket
8 import threading
9 import time
10 import unittest
11 import urlparse
12
13 import arvados
14 import arvados.retry
15 import arvados_testutil as tutil
16 import keepstub
17 import run_test_server
18
19 class KeepTestCase(run_test_server.TestCaseWithServers):
20     MAIN_SERVER = {}
21     KEEP_SERVER = {}
22
23     @classmethod
24     def setUpClass(cls):
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='')
30
31     def test_KeepBasicRWTest(self):
32         foo_locator = self.keep_client.put('foo')
33         self.assertRegexpMatches(
34             foo_locator,
35             '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
36             'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
37         self.assertEqual(self.keep_client.get(foo_locator),
38                          'foo',
39                          'wrong content from Keep.get(md5("foo"))')
40
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(
45             blob_locator,
46             '^7fc7c53b45e53926ba52821140fef396\+6',
47             ('wrong locator from Keep.put(<binarydata>):' + blob_locator))
48         self.assertEqual(self.keep_client.get(blob_locator),
49                          blob_str,
50                          'wrong content from Keep.get(md5(<binarydata>))')
51
52     def test_KeepLongBinaryRWTest(self):
53         blob_str = '\xff\xfe\xfd\xfc\x00\x01\x02\x03'
54         for i in range(0,23):
55             blob_str = blob_str + blob_str
56         blob_locator = self.keep_client.put(blob_str)
57         self.assertRegexpMatches(
58             blob_locator,
59             '^84d90fc0d8175dd5dcfab04b999bc956\+67108864',
60             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
61         self.assertEqual(self.keep_client.get(blob_locator),
62                          blob_str,
63                          'wrong content from Keep.get(md5(<binarydata>))')
64
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(
69             blob_locator,
70             '^c902006bc98a3eb4a3663b65ab4a6fab\+8',
71             ('wrong locator from Keep.put(<binarydata>): ' + blob_locator))
72         self.assertEqual(self.keep_client.get(blob_locator),
73                          blob_str,
74                          'wrong content from Keep.get(md5(<binarydata>))')
75
76     def test_KeepEmptyCollectionTest(self):
77         blob_locator = self.keep_client.put('', copies=1)
78         self.assertRegexpMatches(
79             blob_locator,
80             '^d41d8cd98f00b204e9800998ecf8427e\+0',
81             ('wrong locator from Keep.put(""): ' + blob_locator))
82
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(
87             foo_locator,
88             '^acbd18db4cc2f85cedef654fccc4a4d8\+3',
89             'wrong md5 hash from Keep.put("foo"): ' + foo_locator)
90
91         with self.assertRaises(UnicodeEncodeError):
92             # Error if it is not ASCII
93             self.keep_client.put(u'\xe2')
94
95         with self.assertRaises(arvados.errors.ArgumentError):
96             # Must be a string type
97             self.keep_client.put({})
98
99 class KeepPermissionTestCase(run_test_server.TestCaseWithServers):
100     MAIN_SERVER = {}
101     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
102                    'enforce_permissions': True}
103
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(
109             foo_locator,
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),
113                          'foo',
114                          'wrong content from Keep.get(md5("foo"))')
115
116         # GET with an unsigned locator => NotFound
117         bar_locator = keep_client.put('bar')
118         unsigned_bar_locator = "37b51d194a7513e45b56f6524f2d51f2+3"
119         self.assertRegexpMatches(
120             bar_locator,
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,
124                           keep_client.get,
125                           unsigned_bar_locator)
126
127         # GET from a different user => NotFound
128         run_test_server.authorize_with('spectator')
129         self.assertRaises(arvados.errors.NotFoundError,
130                           arvados.Keep.get,
131                           bar_locator)
132
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,
137                           keep_client.get,
138                           bar_locator)
139         self.assertRaises(arvados.errors.NotFoundError,
140                           keep_client.get,
141                           unsigned_bar_locator)
142
143
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)
147 #
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):
154     MAIN_SERVER = {}
155     KEEP_SERVER = {'blob_signing_key': 'abcdefghijk0123456789',
156                    'enforce_permissions': False}
157
158     @classmethod
159     def setUpClass(cls):
160         super(KeepOptionalPermission, cls).setUpClass()
161         run_test_server.authorize_with("admin")
162         cls.api_client = arvados.api('v1')
163
164     def setUp(self):
165         super(KeepOptionalPermission, self).setUp()
166         self.keep_client = arvados.KeepClient(api_client=self.api_client,
167                                               proxy='', local_store='')
168
169     def _put_foo_and_check(self):
170         signed_locator = self.keep_client.put('foo')
171         self.assertRegexpMatches(
172             signed_locator,
173             r'^acbd18db4cc2f85cedef654fccc4a4d8\+3\+A[a-f0-9]+@[a-f0-9]+$',
174             'invalid locator from Keep.put("foo"): ' + signed_locator)
175         return signed_locator
176
177     def test_KeepAuthenticatedSignedTest(self):
178         signed_locator = self._put_foo_and_check()
179         self.assertEqual(self.keep_client.get(signed_locator),
180                          'foo',
181                          'wrong content from Keep.get(md5("foo"))')
182
183     def test_KeepAuthenticatedUnsignedTest(self):
184         signed_locator = self._put_foo_and_check()
185         self.assertEqual(self.keep_client.get("acbd18db4cc2f85cedef654fccc4a4d8"),
186                          'foo',
187                          'wrong content from Keep.get(md5("foo"))')
188
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),
195                          'foo',
196                          'wrong content from Keep.get(md5("foo"))')
197
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"),
204                          'foo',
205                          'wrong content from Keep.get(md5("foo"))')
206
207
208 class KeepProxyTestCase(run_test_server.TestCaseWithServers):
209     MAIN_SERVER = {}
210     KEEP_SERVER = {}
211     KEEP_PROXY_SERVER = {}
212
213     @classmethod
214     def setUpClass(cls):
215         super(KeepProxyTestCase, cls).setUpClass()
216         run_test_server.authorize_with('active')
217         cls.api_client = arvados.api('v1')
218
219     def tearDown(self):
220         arvados.config.settings().pop('ARVADOS_EXTERNAL_CLIENT', None)
221         super(KeepProxyTestCase, self).tearDown()
222
223     def test_KeepProxyTest1(self):
224         # Will use ARVADOS_KEEP_PROXY environment variable that is set by
225         # setUpClass().
226         keep_client = arvados.KeepClient(api_client=self.api_client,
227                                          local_store='')
228         baz_locator = keep_client.put('baz')
229         self.assertRegexpMatches(
230             baz_locator,
231             '^73feffa4b7f6bb68e44cf984c85f6e88\+3',
232             'wrong md5 hash from Keep.put("baz"): ' + baz_locator)
233         self.assertEqual(keep_client.get(baz_locator),
234                          'baz',
235                          'wrong content from Keep.get(md5("baz"))')
236         self.assertTrue(keep_client.using_proxy)
237
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(
246             baz_locator,
247             '^91f372a266fe2bf2823cb8ec7fda31ce\+4',
248             'wrong md5 hash from Keep.put("baz2"): ' + baz_locator)
249         self.assertEqual(keep_client.get(baz_locator),
250                          'baz2',
251                          'wrong content from Keep.get(md5("baz2"))')
252         self.assertTrue(keep_client.using_proxy)
253
254
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)]
260
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))
265             self.assertEqual(
266                 ('https' if ssl_flag else 'http'), services[0].scheme)
267
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)
273
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.
278
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')
286             self.assertEqual(
287                 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
288                 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
289             self.assertEqual(
290                 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
291                 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]*1000))
292
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')
300             self.assertEqual(
301                 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
302                 int(arvados.KeepClient.DEFAULT_TIMEOUT[0]*1000))
303             self.assertEqual(
304                 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
305                 int(arvados.KeepClient.DEFAULT_TIMEOUT[1]*1000))
306
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')
314             self.assertEqual(
315                 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
316                 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
317             self.assertEqual(
318                 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
319                 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]*1000))
320
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')
328             self.assertEqual(
329                 mock.responses[0].getopt(pycurl.CONNECTTIMEOUT_MS),
330                 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[0]*1000))
331             self.assertEqual(
332                 mock.responses[0].getopt(pycurl.TIMEOUT_MS),
333                 int(arvados.KeepClient.DEFAULT_PROXY_TIMEOUT[1]*1000))
334
335     def check_no_services_error(self, verb, exc_class):
336         api_client = mock.MagicMock(name='api_client')
337         api_client.keep_services().accessible().execute.side_effect = (
338             arvados.errors.ApiError)
339         keep_client = arvados.KeepClient(api_client=api_client)
340         with self.assertRaises(exc_class) as err_check:
341             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0')
342         self.assertEqual(0, len(err_check.exception.request_errors()))
343
344     def test_get_error_with_no_services(self):
345         self.check_no_services_error('get', arvados.errors.KeepReadError)
346
347     def test_put_error_with_no_services(self):
348         self.check_no_services_error('put', arvados.errors.KeepWriteError)
349
350     def check_errors_from_last_retry(self, verb, exc_class):
351         api_client = self.mock_keep_services(count=2)
352         req_mock = tutil.mock_keep_responses(
353             "retry error reporting test", 500, 500, 403, 403)
354         with req_mock, tutil.skip_sleep, \
355                 self.assertRaises(exc_class) as err_check:
356             keep_client = arvados.KeepClient(api_client=api_client)
357             getattr(keep_client, verb)('d41d8cd98f00b204e9800998ecf8427e+0',
358                                        num_retries=3)
359         self.assertEqual([403, 403], [
360                 getattr(error, 'status_code', None)
361                 for error in err_check.exception.request_errors().itervalues()])
362
363     def test_get_error_reflects_last_retry(self):
364         self.check_errors_from_last_retry('get', arvados.errors.KeepReadError)
365
366     def test_put_error_reflects_last_retry(self):
367         self.check_errors_from_last_retry('put', arvados.errors.KeepWriteError)
368
369     def test_put_error_does_not_include_successful_puts(self):
370         data = 'partial failure test'
371         data_loc = tutil.str_keep_locator(data)
372         api_client = self.mock_keep_services(count=3)
373         with tutil.mock_keep_responses(data_loc, 200, 500, 500) as req_mock, \
374                 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
375             keep_client = arvados.KeepClient(api_client=api_client)
376             keep_client.put(data)
377         self.assertEqual(2, len(exc_check.exception.request_errors()))
378
379     def test_proxy_put_with_no_writable_services(self):
380         data = 'test with no writable services'
381         data_loc = tutil.str_keep_locator(data)
382         api_client = self.mock_keep_services(service_type='proxy', read_only=True, count=1)
383         with tutil.mock_keep_responses(data_loc, 200, 500, 500) as req_mock, \
384                 self.assertRaises(arvados.errors.KeepWriteError) as exc_check:
385           keep_client = arvados.KeepClient(api_client=api_client)
386           keep_client.put(data)
387         self.assertEqual(True, ("no Keep services available" in str(exc_check.exception)))
388         self.assertEqual(0, len(exc_check.exception.request_errors()))
389
390     def test_oddball_service_get(self):
391         body = 'oddball service get'
392         api_client = self.mock_keep_services(service_type='fancynewblobstore')
393         with tutil.mock_keep_responses(body, 200):
394             keep_client = arvados.KeepClient(api_client=api_client)
395             actual = keep_client.get(tutil.str_keep_locator(body))
396         self.assertEqual(body, actual)
397
398     def test_oddball_service_put(self):
399         body = 'oddball service put'
400         pdh = tutil.str_keep_locator(body)
401         api_client = self.mock_keep_services(service_type='fancynewblobstore')
402         with tutil.mock_keep_responses(pdh, 200):
403             keep_client = arvados.KeepClient(api_client=api_client)
404             actual = keep_client.put(body, copies=1)
405         self.assertEqual(pdh, actual)
406
407     def test_oddball_service_writer_count(self):
408         body = 'oddball service writer count'
409         pdh = tutil.str_keep_locator(body)
410         api_client = self.mock_keep_services(service_type='fancynewblobstore',
411                                              count=4)
412         headers = {'x-keep-replicas-stored': 3}
413         with tutil.mock_keep_responses(pdh, 200, 418, 418, 418,
414                                        **headers) as req_mock:
415             keep_client = arvados.KeepClient(api_client=api_client)
416             actual = keep_client.put(body, copies=2)
417         self.assertEqual(pdh, actual)
418         self.assertEqual(1, req_mock.call_count)
419
420
421 @tutil.skip_sleep
422 class KeepClientRendezvousTestCase(unittest.TestCase, tutil.ApiClientMock):
423
424     def setUp(self):
425         # expected_order[i] is the probe order for
426         # hash=md5(sprintf("%064x",i)) where there are 16 services
427         # with uuid sprintf("anything-%015x",j) with j in 0..15. E.g.,
428         # the first probe for the block consisting of 64 "0"
429         # characters is the service whose uuid is
430         # "zzzzz-bi6l4-000000000000003", so expected_order[0][0]=='3'.
431         self.services = 16
432         self.expected_order = [
433             list('3eab2d5fc9681074'),
434             list('097dba52e648f1c3'),
435             list('c5b4e023f8a7d691'),
436             list('9d81c02e76a3bf54'),
437             ]
438         self.blocks = [
439             "{:064x}".format(x)
440             for x in range(len(self.expected_order))]
441         self.hashes = [
442             hashlib.md5(self.blocks[x]).hexdigest()
443             for x in range(len(self.expected_order))]
444         self.api_client = self.mock_keep_services(count=self.services)
445         self.keep_client = arvados.KeepClient(api_client=self.api_client)
446
447     def test_weighted_service_roots_against_reference_set(self):
448         # Confirm weighted_service_roots() returns the correct order
449         for i, hash in enumerate(self.hashes):
450             roots = self.keep_client.weighted_service_roots(arvados.KeepLocator(hash))
451             got_order = [
452                 re.search(r'//\[?keep0x([0-9a-f]+)', root).group(1)
453                 for root in roots]
454             self.assertEqual(self.expected_order[i], got_order)
455
456     def test_get_probe_order_against_reference_set(self):
457         self._test_probe_order_against_reference_set(
458             lambda i: self.keep_client.get(self.hashes[i], num_retries=1))
459
460     def test_put_probe_order_against_reference_set(self):
461         # copies=1 prevents the test from being sensitive to races
462         # between writer threads.
463         self._test_probe_order_against_reference_set(
464             lambda i: self.keep_client.put(self.blocks[i], num_retries=1, copies=1))
465
466     def _test_probe_order_against_reference_set(self, op):
467         for i in range(len(self.blocks)):
468             with tutil.mock_keep_responses('', *[500 for _ in range(self.services*2)]) as mock, \
469                  self.assertRaises(arvados.errors.KeepRequestError):
470                 op(i)
471             got_order = [
472                 re.search(r'//\[?keep0x([0-9a-f]+)', resp.getopt(pycurl.URL)).group(1)
473                 for resp in mock.responses]
474             self.assertEqual(self.expected_order[i]*2, got_order)
475
476     def test_put_probe_order_multiple_copies(self):
477         for copies in range(2, 4):
478             for i in range(len(self.blocks)):
479                 with tutil.mock_keep_responses('', *[500 for _ in range(self.services*3)]) as mock, \
480                      self.assertRaises(arvados.errors.KeepWriteError):
481                     self.keep_client.put(self.blocks[i], num_retries=2, copies=copies)
482                 got_order = [
483                     re.search(r'//\[?keep0x([0-9a-f]+)', resp.getopt(pycurl.URL)).group(1)
484                     for resp in mock.responses]
485                 # With T threads racing to make requests, the position
486                 # of a given server in the sequence of HTTP requests
487                 # (got_order) cannot be more than T-1 positions
488                 # earlier than that server's position in the reference
489                 # probe sequence (expected_order).
490                 #
491                 # Loop invariant: we have accounted for +pos+ expected
492                 # probes, either by seeing them in +got_order+ or by
493                 # putting them in +pending+ in the hope of seeing them
494                 # later. As long as +len(pending)<T+, we haven't
495                 # started a request too early.
496                 pending = []
497                 for pos, expected in enumerate(self.expected_order[i]*3):
498                     got = got_order[pos-len(pending)]
499                     while got in pending:
500                         del pending[pending.index(got)]
501                         got = got_order[pos-len(pending)]
502                     if got != expected:
503                         pending.append(expected)
504                         self.assertLess(
505                             len(pending), copies,
506                             "pending={}, with copies={}, got {}, expected {}".format(
507                                 pending, copies, repr(got_order), repr(self.expected_order[i]*3)))
508
509     def test_probe_waste_adding_one_server(self):
510         hashes = [
511             hashlib.md5("{:064x}".format(x)).hexdigest() for x in range(100)]
512         initial_services = 12
513         self.api_client = self.mock_keep_services(count=initial_services)
514         self.keep_client = arvados.KeepClient(api_client=self.api_client)
515         probes_before = [
516             self.keep_client.weighted_service_roots(arvados.KeepLocator(hash)) for hash in hashes]
517         for added_services in range(1, 12):
518             api_client = self.mock_keep_services(count=initial_services+added_services)
519             keep_client = arvados.KeepClient(api_client=api_client)
520             total_penalty = 0
521             for hash_index in range(len(hashes)):
522                 probe_after = keep_client.weighted_service_roots(
523                     arvados.KeepLocator(hashes[hash_index]))
524                 penalty = probe_after.index(probes_before[hash_index][0])
525                 self.assertLessEqual(penalty, added_services)
526                 total_penalty += penalty
527             # Average penalty per block should not exceed
528             # N(added)/N(orig) by more than 20%, and should get closer
529             # to the ideal as we add data points.
530             expect_penalty = (
531                 added_services *
532                 len(hashes) / initial_services)
533             max_penalty = (
534                 expect_penalty *
535                 (120 - added_services)/100)
536             min_penalty = (
537                 expect_penalty * 8/10)
538             self.assertTrue(
539                 min_penalty <= total_penalty <= max_penalty,
540                 "With {}+{} services, {} blocks, penalty {} but expected {}..{}".format(
541                     initial_services,
542                     added_services,
543                     len(hashes),
544                     total_penalty,
545                     min_penalty,
546                     max_penalty))
547
548     def check_64_zeros_error_order(self, verb, exc_class):
549         data = '0' * 64
550         if verb == 'get':
551             data = tutil.str_keep_locator(data)
552         # Arbitrary port number:
553         aport = random.randint(1024,65535)
554         api_client = self.mock_keep_services(service_port=aport, count=self.services)
555         keep_client = arvados.KeepClient(api_client=api_client)
556         with mock.patch('pycurl.Curl') as curl_mock, \
557              self.assertRaises(exc_class) as err_check:
558             curl_mock.return_value.side_effect = socket.timeout
559             getattr(keep_client, verb)(data)
560         urls = [urlparse.urlparse(url)
561                 for url in err_check.exception.request_errors()]
562         self.assertEqual([('keep0x' + c, aport) for c in '3eab2d5fc9681074'],
563                          [(url.hostname, url.port) for url in urls])
564
565     def test_get_error_shows_probe_order(self):
566         self.check_64_zeros_error_order('get', arvados.errors.KeepReadError)
567
568     def test_put_error_shows_probe_order(self):
569         self.check_64_zeros_error_order('put', arvados.errors.KeepWriteError)
570
571
572 class KeepClientTimeout(unittest.TestCase, tutil.ApiClientMock):
573     DATA = 'x' * 2**10
574
575     class assertTakesBetween(unittest.TestCase):
576         def __init__(self, tmin, tmax):
577             self.tmin = tmin
578             self.tmax = tmax
579
580         def __enter__(self):
581             self.t0 = time.time()
582
583         def __exit__(self, *args, **kwargs):
584             self.assertGreater(time.time() - self.t0, self.tmin)
585             self.assertLess(time.time() - self.t0, self.tmax)
586
587     def setUp(self):
588         sock = socket.socket()
589         sock.bind(('0.0.0.0', 0))
590         self.port = sock.getsockname()[1]
591         sock.close()
592         self.server = keepstub.Server(('0.0.0.0', self.port), keepstub.Handler)
593         self.thread = threading.Thread(target=self.server.serve_forever)
594         self.thread.daemon = True # Exit thread if main proc exits
595         self.thread.start()
596         self.api_client = self.mock_keep_services(
597             count=1,
598             service_host='localhost',
599             service_port=self.port,
600         )
601
602     def tearDown(self):
603         self.server.shutdown()
604
605     def keepClient(self, timeouts=(0.1, 1.0)):
606         return arvados.KeepClient(
607             api_client=self.api_client,
608             timeout=timeouts)
609
610     def test_timeout_slow_connect(self):
611         # Can't simulate TCP delays with our own socket. Leave our
612         # stub server running uselessly, and try to connect to an
613         # unroutable IP address instead.
614         self.api_client = self.mock_keep_services(
615             count=1,
616             service_host='240.0.0.0',
617         )
618         with self.assertTakesBetween(0.1, 0.5):
619             with self.assertRaises(arvados.errors.KeepWriteError):
620                 self.keepClient((0.1, 1)).put(self.DATA, copies=1, num_retries=0)
621
622     def test_timeout_slow_request(self):
623         self.server.setdelays(request=0.2)
624         self._test_200ms()
625
626     def test_timeout_slow_response(self):
627         self.server.setdelays(response=0.2)
628         self._test_200ms()
629
630     def test_timeout_slow_response_body(self):
631         self.server.setdelays(response_body=0.2)
632         self._test_200ms()
633
634     def _test_200ms(self):
635         """Connect should be t<100ms, request should be 200ms <= t < 300ms"""
636
637         # Allow 100ms to connect, then 1s for response. Everything
638         # should work, and everything should take at least 200ms to
639         # return.
640         kc = self.keepClient((.1, 1))
641         with self.assertTakesBetween(.2, .3):
642             loc = kc.put(self.DATA, copies=1, num_retries=0)
643         with self.assertTakesBetween(.2, .3):
644             self.assertEqual(self.DATA, kc.get(loc, num_retries=0))
645
646         # Allow 1s to connect, then 100ms for response. Nothing should
647         # work, and everything should take at least 100ms to return.
648         kc = self.keepClient((1, .1))
649         with self.assertTakesBetween(.1, .2):
650             with self.assertRaises(arvados.errors.KeepReadError):
651                 kc.get(loc, num_retries=0)
652         with self.assertTakesBetween(.1, .2):
653             with self.assertRaises(arvados.errors.KeepWriteError):
654                 kc.put(self.DATA, copies=1, num_retries=0)
655
656
657 class KeepClientGatewayTestCase(unittest.TestCase, tutil.ApiClientMock):
658     def mock_disks_and_gateways(self, disks=3, gateways=1):
659         self.gateways = [{
660                 'uuid': 'zzzzz-bi6l4-gateway{:08d}'.format(i),
661                 'owner_uuid': 'zzzzz-tpzed-000000000000000',
662                 'service_host': 'gatewayhost{}'.format(i),
663                 'service_port': 12345,
664                 'service_ssl_flag': True,
665                 'service_type': 'gateway:test',
666         } for i in range(gateways)]
667         self.gateway_roots = [
668             "https://{service_host}:{service_port}/".format(**gw)
669             for gw in self.gateways]
670         self.api_client = self.mock_keep_services(
671             count=disks, additional_services=self.gateways)
672         self.keepClient = arvados.KeepClient(api_client=self.api_client)
673
674     @mock.patch('pycurl.Curl')
675     def test_get_with_gateway_hint_first(self, MockCurl):
676         MockCurl.return_value = tutil.FakeCurl.make(
677             code=200, body='foo', headers={'Content-Length': 3})
678         self.mock_disks_and_gateways()
679         locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@' + self.gateways[0]['uuid']
680         self.assertEqual('foo', self.keepClient.get(locator))
681         self.assertEqual(self.gateway_roots[0]+locator,
682                          MockCurl.return_value.getopt(pycurl.URL))
683
684     @mock.patch('pycurl.Curl')
685     def test_get_with_gateway_hints_in_order(self, MockCurl):
686         gateways = 4
687         disks = 3
688         mocks = [
689             tutil.FakeCurl.make(code=404, body='')
690             for _ in range(gateways+disks)
691         ]
692         MockCurl.side_effect = tutil.queue_with(mocks)
693         self.mock_disks_and_gateways(gateways=gateways, disks=disks)
694         locator = '+'.join(['acbd18db4cc2f85cedef654fccc4a4d8+3'] +
695                            ['K@'+gw['uuid'] for gw in self.gateways])
696         with self.assertRaises(arvados.errors.NotFoundError):
697             self.keepClient.get(locator)
698         # Gateways are tried first, in the order given.
699         for i, root in enumerate(self.gateway_roots):
700             self.assertEqual(root+locator,
701                              mocks[i].getopt(pycurl.URL))
702         # Disk services are tried next.
703         for i in range(gateways, gateways+disks):
704             self.assertRegexpMatches(
705                 mocks[i].getopt(pycurl.URL),
706                 r'keep0x')
707
708     @mock.patch('pycurl.Curl')
709     def test_get_with_remote_proxy_hint(self, MockCurl):
710         MockCurl.return_value = tutil.FakeCurl.make(
711             code=200, body='foo', headers={'Content-Length': 3})
712         self.mock_disks_and_gateways()
713         locator = 'acbd18db4cc2f85cedef654fccc4a4d8+3+K@xyzzy'
714         self.assertEqual('foo', self.keepClient.get(locator))
715         self.assertEqual('https://keep.xyzzy.arvadosapi.com/'+locator,
716                          MockCurl.return_value.getopt(pycurl.URL))
717
718
719 class KeepClientRetryTestMixin(object):
720     # Testing with a local Keep store won't exercise the retry behavior.
721     # Instead, our strategy is:
722     # * Create a client with one proxy specified (pointed at a black
723     #   hole), so there's no need to instantiate an API client, and
724     #   all HTTP requests come from one place.
725     # * Mock httplib's request method to provide simulated responses.
726     # This lets us test the retry logic extensively without relying on any
727     # supporting servers, and prevents side effects in case something hiccups.
728     # To use this mixin, define DEFAULT_EXPECT, DEFAULT_EXCEPTION, and
729     # run_method().
730     #
731     # Test classes must define TEST_PATCHER to a method that mocks
732     # out appropriate methods in the client.
733
734     PROXY_ADDR = 'http://[%s]:65535/' % (tutil.TEST_HOST,)
735     TEST_DATA = 'testdata'
736     TEST_LOCATOR = 'ef654c40ab4f1747fc699915d4f70902+8'
737
738     def setUp(self):
739         self.client_kwargs = {'proxy': self.PROXY_ADDR, 'local_store': ''}
740
741     def new_client(self, **caller_kwargs):
742         kwargs = self.client_kwargs.copy()
743         kwargs.update(caller_kwargs)
744         return arvados.KeepClient(**kwargs)
745
746     def run_method(self, *args, **kwargs):
747         raise NotImplementedError("test subclasses must define run_method")
748
749     def check_success(self, expected=None, *args, **kwargs):
750         if expected is None:
751             expected = self.DEFAULT_EXPECT
752         self.assertEqual(expected, self.run_method(*args, **kwargs))
753
754     def check_exception(self, error_class=None, *args, **kwargs):
755         if error_class is None:
756             error_class = self.DEFAULT_EXCEPTION
757         self.assertRaises(error_class, self.run_method, *args, **kwargs)
758
759     def test_immediate_success(self):
760         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 200):
761             self.check_success()
762
763     def test_retry_then_success(self):
764         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
765             self.check_success(num_retries=3)
766
767     def test_no_default_retry(self):
768         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
769             self.check_exception()
770
771     def test_no_retry_after_permanent_error(self):
772         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 403, 200):
773             self.check_exception(num_retries=3)
774
775     def test_error_after_retries_exhausted(self):
776         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 500, 200):
777             self.check_exception(num_retries=1)
778
779     def test_num_retries_instance_fallback(self):
780         self.client_kwargs['num_retries'] = 3
781         with self.TEST_PATCHER(self.DEFAULT_EXPECT, 500, 200):
782             self.check_success()
783
784
785 @tutil.skip_sleep
786 class KeepClientRetryGetTestCase(KeepClientRetryTestMixin, unittest.TestCase):
787     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_DATA
788     DEFAULT_EXCEPTION = arvados.errors.KeepReadError
789     HINTED_LOCATOR = KeepClientRetryTestMixin.TEST_LOCATOR + '+K@xyzzy'
790     TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
791
792     def run_method(self, locator=KeepClientRetryTestMixin.TEST_LOCATOR,
793                    *args, **kwargs):
794         return self.new_client().get(locator, *args, **kwargs)
795
796     def test_specific_exception_when_not_found(self):
797         with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200):
798             self.check_exception(arvados.errors.NotFoundError, num_retries=3)
799
800     def test_general_exception_with_mixed_errors(self):
801         # get should raise a NotFoundError if no server returns the block,
802         # and a high threshold of servers report that it's not found.
803         # This test rigs up 50/50 disagreement between two servers, and
804         # checks that it does not become a NotFoundError.
805         client = self.new_client()
806         with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 500):
807             with self.assertRaises(arvados.errors.KeepReadError) as exc_check:
808                 client.get(self.HINTED_LOCATOR)
809             self.assertNotIsInstance(
810                 exc_check.exception, arvados.errors.NotFoundError,
811                 "mixed errors raised NotFoundError")
812
813     def test_hint_server_can_succeed_without_retries(self):
814         with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 404, 200, 500):
815             self.check_success(locator=self.HINTED_LOCATOR)
816
817     def test_try_next_server_after_timeout(self):
818         with tutil.mock_keep_responses(
819                 (socket.timeout("timed out"), 200),
820                 (self.DEFAULT_EXPECT, 200)):
821             self.check_success(locator=self.HINTED_LOCATOR)
822
823     def test_retry_data_with_wrong_checksum(self):
824         with tutil.mock_keep_responses(
825                 ('baddata', 200),
826                 (self.DEFAULT_EXPECT, 200)):
827             self.check_success(locator=self.HINTED_LOCATOR)
828
829
830 @tutil.skip_sleep
831 class KeepClientRetryPutTestCase(KeepClientRetryTestMixin, unittest.TestCase):
832     DEFAULT_EXPECT = KeepClientRetryTestMixin.TEST_LOCATOR
833     DEFAULT_EXCEPTION = arvados.errors.KeepWriteError
834     TEST_PATCHER = staticmethod(tutil.mock_keep_responses)
835
836     def run_method(self, data=KeepClientRetryTestMixin.TEST_DATA,
837                    copies=1, *args, **kwargs):
838         return self.new_client().put(data, copies, *args, **kwargs)
839
840     def test_do_not_send_multiple_copies_to_same_server(self):
841         with tutil.mock_keep_responses(self.DEFAULT_EXPECT, 200):
842             self.check_exception(copies=2, num_retries=3)