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