17465: Don't repeat warnings when storage classes aren't supported.
[arvados.git] / sdk / python / arvados / keep.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 from __future__ import absolute_import
6 from __future__ import division
7 import copy
8 from future import standard_library
9 from future.utils import native_str
10 standard_library.install_aliases()
11 from builtins import next
12 from builtins import str
13 from builtins import range
14 from builtins import object
15 import collections
16 import datetime
17 import hashlib
18 import io
19 import logging
20 import math
21 import os
22 import pycurl
23 import queue
24 import re
25 import socket
26 import ssl
27 import sys
28 import threading
29 from . import timer
30 import urllib.parse
31
32 if sys.version_info >= (3, 0):
33     from io import BytesIO
34 else:
35     from cStringIO import StringIO as BytesIO
36
37 import arvados
38 import arvados.config as config
39 import arvados.errors
40 import arvados.retry as retry
41 import arvados.util
42
43 _logger = logging.getLogger('arvados.keep')
44 global_client_object = None
45
46
47 # Monkey patch TCP constants when not available (apple). Values sourced from:
48 # http://www.opensource.apple.com/source/xnu/xnu-2422.115.4/bsd/netinet/tcp.h
49 if sys.platform == 'darwin':
50     if not hasattr(socket, 'TCP_KEEPALIVE'):
51         socket.TCP_KEEPALIVE = 0x010
52     if not hasattr(socket, 'TCP_KEEPINTVL'):
53         socket.TCP_KEEPINTVL = 0x101
54     if not hasattr(socket, 'TCP_KEEPCNT'):
55         socket.TCP_KEEPCNT = 0x102
56
57
58 class KeepLocator(object):
59     EPOCH_DATETIME = datetime.datetime.utcfromtimestamp(0)
60     HINT_RE = re.compile(r'^[A-Z][A-Za-z0-9@_-]+$')
61
62     def __init__(self, locator_str):
63         self.hints = []
64         self._perm_sig = None
65         self._perm_expiry = None
66         pieces = iter(locator_str.split('+'))
67         self.md5sum = next(pieces)
68         try:
69             self.size = int(next(pieces))
70         except StopIteration:
71             self.size = None
72         for hint in pieces:
73             if self.HINT_RE.match(hint) is None:
74                 raise ValueError("invalid hint format: {}".format(hint))
75             elif hint.startswith('A'):
76                 self.parse_permission_hint(hint)
77             else:
78                 self.hints.append(hint)
79
80     def __str__(self):
81         return '+'.join(
82             native_str(s)
83             for s in [self.md5sum, self.size,
84                       self.permission_hint()] + self.hints
85             if s is not None)
86
87     def stripped(self):
88         if self.size is not None:
89             return "%s+%i" % (self.md5sum, self.size)
90         else:
91             return self.md5sum
92
93     def _make_hex_prop(name, length):
94         # Build and return a new property with the given name that
95         # must be a hex string of the given length.
96         data_name = '_{}'.format(name)
97         def getter(self):
98             return getattr(self, data_name)
99         def setter(self, hex_str):
100             if not arvados.util.is_hex(hex_str, length):
101                 raise ValueError("{} is not a {}-digit hex string: {!r}".
102                                  format(name, length, hex_str))
103             setattr(self, data_name, hex_str)
104         return property(getter, setter)
105
106     md5sum = _make_hex_prop('md5sum', 32)
107     perm_sig = _make_hex_prop('perm_sig', 40)
108
109     @property
110     def perm_expiry(self):
111         return self._perm_expiry
112
113     @perm_expiry.setter
114     def perm_expiry(self, value):
115         if not arvados.util.is_hex(value, 1, 8):
116             raise ValueError(
117                 "permission timestamp must be a hex Unix timestamp: {}".
118                 format(value))
119         self._perm_expiry = datetime.datetime.utcfromtimestamp(int(value, 16))
120
121     def permission_hint(self):
122         data = [self.perm_sig, self.perm_expiry]
123         if None in data:
124             return None
125         data[1] = int((data[1] - self.EPOCH_DATETIME).total_seconds())
126         return "A{}@{:08x}".format(*data)
127
128     def parse_permission_hint(self, s):
129         try:
130             self.perm_sig, self.perm_expiry = s[1:].split('@', 1)
131         except IndexError:
132             raise ValueError("bad permission hint {}".format(s))
133
134     def permission_expired(self, as_of_dt=None):
135         if self.perm_expiry is None:
136             return False
137         elif as_of_dt is None:
138             as_of_dt = datetime.datetime.now()
139         return self.perm_expiry <= as_of_dt
140
141
142 class Keep(object):
143     """Simple interface to a global KeepClient object.
144
145     THIS CLASS IS DEPRECATED.  Please instantiate your own KeepClient with your
146     own API client.  The global KeepClient will build an API client from the
147     current Arvados configuration, which may not match the one you built.
148     """
149     _last_key = None
150
151     @classmethod
152     def global_client_object(cls):
153         global global_client_object
154         # Previously, KeepClient would change its behavior at runtime based
155         # on these configuration settings.  We simulate that behavior here
156         # by checking the values and returning a new KeepClient if any of
157         # them have changed.
158         key = (config.get('ARVADOS_API_HOST'),
159                config.get('ARVADOS_API_TOKEN'),
160                config.flag_is_true('ARVADOS_API_HOST_INSECURE'),
161                config.get('ARVADOS_KEEP_PROXY'),
162                config.get('ARVADOS_EXTERNAL_CLIENT') == 'true',
163                os.environ.get('KEEP_LOCAL_STORE'))
164         if (global_client_object is None) or (cls._last_key != key):
165             global_client_object = KeepClient()
166             cls._last_key = key
167         return global_client_object
168
169     @staticmethod
170     def get(locator, **kwargs):
171         return Keep.global_client_object().get(locator, **kwargs)
172
173     @staticmethod
174     def put(data, **kwargs):
175         return Keep.global_client_object().put(data, **kwargs)
176
177 class KeepBlockCache(object):
178     # Default RAM cache is 256MiB
179     def __init__(self, cache_max=(256 * 1024 * 1024)):
180         self.cache_max = cache_max
181         self._cache = []
182         self._cache_lock = threading.Lock()
183
184     class CacheSlot(object):
185         __slots__ = ("locator", "ready", "content")
186
187         def __init__(self, locator):
188             self.locator = locator
189             self.ready = threading.Event()
190             self.content = None
191
192         def get(self):
193             self.ready.wait()
194             return self.content
195
196         def set(self, value):
197             self.content = value
198             self.ready.set()
199
200         def size(self):
201             if self.content is None:
202                 return 0
203             else:
204                 return len(self.content)
205
206     def cap_cache(self):
207         '''Cap the cache size to self.cache_max'''
208         with self._cache_lock:
209             # Select all slots except those where ready.is_set() and content is
210             # None (that means there was an error reading the block).
211             self._cache = [c for c in self._cache if not (c.ready.is_set() and c.content is None)]
212             sm = sum([slot.size() for slot in self._cache])
213             while len(self._cache) > 0 and sm > self.cache_max:
214                 for i in range(len(self._cache)-1, -1, -1):
215                     if self._cache[i].ready.is_set():
216                         del self._cache[i]
217                         break
218                 sm = sum([slot.size() for slot in self._cache])
219
220     def _get(self, locator):
221         # Test if the locator is already in the cache
222         for i in range(0, len(self._cache)):
223             if self._cache[i].locator == locator:
224                 n = self._cache[i]
225                 if i != 0:
226                     # move it to the front
227                     del self._cache[i]
228                     self._cache.insert(0, n)
229                 return n
230         return None
231
232     def get(self, locator):
233         with self._cache_lock:
234             return self._get(locator)
235
236     def reserve_cache(self, locator):
237         '''Reserve a cache slot for the specified locator,
238         or return the existing slot.'''
239         with self._cache_lock:
240             n = self._get(locator)
241             if n:
242                 return n, False
243             else:
244                 # Add a new cache slot for the locator
245                 n = KeepBlockCache.CacheSlot(locator)
246                 self._cache.insert(0, n)
247                 return n, True
248
249 class Counter(object):
250     def __init__(self, v=0):
251         self._lk = threading.Lock()
252         self._val = v
253
254     def add(self, v):
255         with self._lk:
256             self._val += v
257
258     def get(self):
259         with self._lk:
260             return self._val
261
262
263 class KeepClient(object):
264
265     # Default Keep server connection timeout:  2 seconds
266     # Default Keep server read timeout:       256 seconds
267     # Default Keep server bandwidth minimum:  32768 bytes per second
268     # Default Keep proxy connection timeout:  20 seconds
269     # Default Keep proxy read timeout:        256 seconds
270     # Default Keep proxy bandwidth minimum:   32768 bytes per second
271     DEFAULT_TIMEOUT = (2, 256, 32768)
272     DEFAULT_PROXY_TIMEOUT = (20, 256, 32768)
273
274
275     class KeepService(object):
276         """Make requests to a single Keep service, and track results.
277
278         A KeepService is intended to last long enough to perform one
279         transaction (GET or PUT) against one Keep service. This can
280         involve calling either get() or put() multiple times in order
281         to retry after transient failures. However, calling both get()
282         and put() on a single instance -- or using the same instance
283         to access two different Keep services -- will not produce
284         sensible behavior.
285         """
286
287         HTTP_ERRORS = (
288             socket.error,
289             ssl.SSLError,
290             arvados.errors.HttpError,
291         )
292
293         def __init__(self, root, user_agent_pool=queue.LifoQueue(),
294                      upload_counter=None,
295                      download_counter=None,
296                      headers={},
297                      insecure=False):
298             self.root = root
299             self._user_agent_pool = user_agent_pool
300             self._result = {'error': None}
301             self._usable = True
302             self._session = None
303             self._socket = None
304             self.get_headers = {'Accept': 'application/octet-stream'}
305             self.get_headers.update(headers)
306             self.put_headers = headers
307             self.upload_counter = upload_counter
308             self.download_counter = download_counter
309             self.insecure = insecure
310
311         def usable(self):
312             """Is it worth attempting a request?"""
313             return self._usable
314
315         def finished(self):
316             """Did the request succeed or encounter permanent failure?"""
317             return self._result['error'] == False or not self._usable
318
319         def last_result(self):
320             return self._result
321
322         def _get_user_agent(self):
323             try:
324                 return self._user_agent_pool.get(block=False)
325             except queue.Empty:
326                 return pycurl.Curl()
327
328         def _put_user_agent(self, ua):
329             try:
330                 ua.reset()
331                 self._user_agent_pool.put(ua, block=False)
332             except:
333                 ua.close()
334
335         def _socket_open(self, *args, **kwargs):
336             if len(args) + len(kwargs) == 2:
337                 return self._socket_open_pycurl_7_21_5(*args, **kwargs)
338             else:
339                 return self._socket_open_pycurl_7_19_3(*args, **kwargs)
340
341         def _socket_open_pycurl_7_19_3(self, family, socktype, protocol, address=None):
342             return self._socket_open_pycurl_7_21_5(
343                 purpose=None,
344                 address=collections.namedtuple(
345                     'Address', ['family', 'socktype', 'protocol', 'addr'],
346                 )(family, socktype, protocol, address))
347
348         def _socket_open_pycurl_7_21_5(self, purpose, address):
349             """Because pycurl doesn't have CURLOPT_TCP_KEEPALIVE"""
350             s = socket.socket(address.family, address.socktype, address.protocol)
351             s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
352             # Will throw invalid protocol error on mac. This test prevents that.
353             if hasattr(socket, 'TCP_KEEPIDLE'):
354                 s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 75)
355             s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75)
356             self._socket = s
357             return s
358
359         def get(self, locator, method="GET", timeout=None):
360             # locator is a KeepLocator object.
361             url = self.root + str(locator)
362             _logger.debug("Request: %s %s", method, url)
363             curl = self._get_user_agent()
364             ok = None
365             try:
366                 with timer.Timer() as t:
367                     self._headers = {}
368                     response_body = BytesIO()
369                     curl.setopt(pycurl.NOSIGNAL, 1)
370                     curl.setopt(pycurl.OPENSOCKETFUNCTION,
371                                 lambda *args, **kwargs: self._socket_open(*args, **kwargs))
372                     curl.setopt(pycurl.URL, url.encode('utf-8'))
373                     curl.setopt(pycurl.HTTPHEADER, [
374                         '{}: {}'.format(k,v) for k,v in self.get_headers.items()])
375                     curl.setopt(pycurl.WRITEFUNCTION, response_body.write)
376                     curl.setopt(pycurl.HEADERFUNCTION, self._headerfunction)
377                     if self.insecure:
378                         curl.setopt(pycurl.SSL_VERIFYPEER, 0)
379                     else:
380                         curl.setopt(pycurl.CAINFO, arvados.util.ca_certs_path())
381                     if method == "HEAD":
382                         curl.setopt(pycurl.NOBODY, True)
383                     self._setcurltimeouts(curl, timeout, method=="HEAD")
384
385                     try:
386                         curl.perform()
387                     except Exception as e:
388                         raise arvados.errors.HttpError(0, str(e))
389                     finally:
390                         if self._socket:
391                             self._socket.close()
392                             self._socket = None
393                     self._result = {
394                         'status_code': curl.getinfo(pycurl.RESPONSE_CODE),
395                         'body': response_body.getvalue(),
396                         'headers': self._headers,
397                         'error': False,
398                     }
399
400                 ok = retry.check_http_response_success(self._result['status_code'])
401                 if not ok:
402                     self._result['error'] = arvados.errors.HttpError(
403                         self._result['status_code'],
404                         self._headers.get('x-status-line', 'Error'))
405             except self.HTTP_ERRORS as e:
406                 self._result = {
407                     'error': e,
408                 }
409             self._usable = ok != False
410             if self._result.get('status_code', None):
411                 # The client worked well enough to get an HTTP status
412                 # code, so presumably any problems are just on the
413                 # server side and it's OK to reuse the client.
414                 self._put_user_agent(curl)
415             else:
416                 # Don't return this client to the pool, in case it's
417                 # broken.
418                 curl.close()
419             if not ok:
420                 _logger.debug("Request fail: GET %s => %s: %s",
421                               url, type(self._result['error']), str(self._result['error']))
422                 return None
423             if method == "HEAD":
424                 _logger.info("HEAD %s: %s bytes",
425                          self._result['status_code'],
426                          self._result.get('content-length'))
427                 if self._result['headers'].get('x-keep-locator'):
428                     # This is a response to a remote block copy request, return
429                     # the local copy block locator.
430                     return self._result['headers'].get('x-keep-locator')
431                 return True
432
433             _logger.info("GET %s: %s bytes in %s msec (%.3f MiB/sec)",
434                          self._result['status_code'],
435                          len(self._result['body']),
436                          t.msecs,
437                          1.0*len(self._result['body'])/2**20/t.secs if t.secs > 0 else 0)
438
439             if self.download_counter:
440                 self.download_counter.add(len(self._result['body']))
441             resp_md5 = hashlib.md5(self._result['body']).hexdigest()
442             if resp_md5 != locator.md5sum:
443                 _logger.warning("Checksum fail: md5(%s) = %s",
444                                 url, resp_md5)
445                 self._result['error'] = arvados.errors.HttpError(
446                     0, 'Checksum fail')
447                 return None
448             return self._result['body']
449
450         def put(self, hash_s, body, timeout=None, headers={}):
451             put_headers = copy.copy(self.put_headers)
452             put_headers.update(headers)
453             url = self.root + hash_s
454             _logger.debug("Request: PUT %s", url)
455             curl = self._get_user_agent()
456             ok = None
457             try:
458                 with timer.Timer() as t:
459                     self._headers = {}
460                     body_reader = BytesIO(body)
461                     response_body = BytesIO()
462                     curl.setopt(pycurl.NOSIGNAL, 1)
463                     curl.setopt(pycurl.OPENSOCKETFUNCTION,
464                                 lambda *args, **kwargs: self._socket_open(*args, **kwargs))
465                     curl.setopt(pycurl.URL, url.encode('utf-8'))
466                     # Using UPLOAD tells cURL to wait for a "go ahead" from the
467                     # Keep server (in the form of a HTTP/1.1 "100 Continue"
468                     # response) instead of sending the request body immediately.
469                     # This allows the server to reject the request if the request
470                     # is invalid or the server is read-only, without waiting for
471                     # the client to send the entire block.
472                     curl.setopt(pycurl.UPLOAD, True)
473                     curl.setopt(pycurl.INFILESIZE, len(body))
474                     curl.setopt(pycurl.READFUNCTION, body_reader.read)
475                     curl.setopt(pycurl.HTTPHEADER, [
476                         '{}: {}'.format(k,v) for k,v in put_headers.items()])
477                     curl.setopt(pycurl.WRITEFUNCTION, response_body.write)
478                     curl.setopt(pycurl.HEADERFUNCTION, self._headerfunction)
479                     if self.insecure:
480                         curl.setopt(pycurl.SSL_VERIFYPEER, 0)
481                     else:
482                         curl.setopt(pycurl.CAINFO, arvados.util.ca_certs_path())
483                     self._setcurltimeouts(curl, timeout)
484                     try:
485                         curl.perform()
486                     except Exception as e:
487                         raise arvados.errors.HttpError(0, str(e))
488                     finally:
489                         if self._socket:
490                             self._socket.close()
491                             self._socket = None
492                     self._result = {
493                         'status_code': curl.getinfo(pycurl.RESPONSE_CODE),
494                         'body': response_body.getvalue().decode('utf-8'),
495                         'headers': self._headers,
496                         'error': False,
497                     }
498                 ok = retry.check_http_response_success(self._result['status_code'])
499                 if not ok:
500                     self._result['error'] = arvados.errors.HttpError(
501                         self._result['status_code'],
502                         self._headers.get('x-status-line', 'Error'))
503             except self.HTTP_ERRORS as e:
504                 self._result = {
505                     'error': e,
506                 }
507             self._usable = ok != False # still usable if ok is True or None
508             if self._result.get('status_code', None):
509                 # Client is functional. See comment in get().
510                 self._put_user_agent(curl)
511             else:
512                 curl.close()
513             if not ok:
514                 _logger.debug("Request fail: PUT %s => %s: %s",
515                               url, type(self._result['error']), str(self._result['error']))
516                 return False
517             _logger.info("PUT %s: %s bytes in %s msec (%.3f MiB/sec)",
518                          self._result['status_code'],
519                          len(body),
520                          t.msecs,
521                          1.0*len(body)/2**20/t.secs if t.secs > 0 else 0)
522             if self.upload_counter:
523                 self.upload_counter.add(len(body))
524             return True
525
526         def _setcurltimeouts(self, curl, timeouts, ignore_bandwidth=False):
527             if not timeouts:
528                 return
529             elif isinstance(timeouts, tuple):
530                 if len(timeouts) == 2:
531                     conn_t, xfer_t = timeouts
532                     bandwidth_bps = KeepClient.DEFAULT_TIMEOUT[2]
533                 else:
534                     conn_t, xfer_t, bandwidth_bps = timeouts
535             else:
536                 conn_t, xfer_t = (timeouts, timeouts)
537                 bandwidth_bps = KeepClient.DEFAULT_TIMEOUT[2]
538             curl.setopt(pycurl.CONNECTTIMEOUT_MS, int(conn_t*1000))
539             if not ignore_bandwidth:
540                 curl.setopt(pycurl.LOW_SPEED_TIME, int(math.ceil(xfer_t)))
541                 curl.setopt(pycurl.LOW_SPEED_LIMIT, int(math.ceil(bandwidth_bps)))
542
543         def _headerfunction(self, header_line):
544             if isinstance(header_line, bytes):
545                 header_line = header_line.decode('iso-8859-1')
546             if ':' in header_line:
547                 name, value = header_line.split(':', 1)
548                 name = name.strip().lower()
549                 value = value.strip()
550             elif self._headers:
551                 name = self._lastheadername
552                 value = self._headers[name] + ' ' + header_line.strip()
553             elif header_line.startswith('HTTP/'):
554                 name = 'x-status-line'
555                 value = header_line
556             else:
557                 _logger.error("Unexpected header line: %s", header_line)
558                 return
559             self._lastheadername = name
560             self._headers[name] = value
561             # Returning None implies all bytes were written
562
563
564     class KeepWriterQueue(queue.Queue):
565         def __init__(self, copies, classes=[]):
566             queue.Queue.__init__(self) # Old-style superclass
567             self.wanted_copies = copies
568             self.wanted_storage_classes = classes
569             self.successful_copies = 0
570             self.confirmed_storage_classes = {}
571             self.response = None
572             self.storage_classes_tracking = True
573             self.queue_data_lock = threading.Lock()
574             self.pending_tries = max(copies, len(classes))+1
575             self.pending_tries_notification = threading.Condition()
576
577         def write_success(self, response, replicas_nr, classes_confirmed):
578             with self.queue_data_lock:
579                 self.successful_copies += replicas_nr
580                 if classes_confirmed is None:
581                     self.storage_classes_tracking = False
582                 elif self.storage_classes_tracking:
583                     for st_class, st_copies in classes_confirmed.items():
584                         try:
585                             self.confirmed_storage_classes[st_class] += st_copies
586                         except KeyError:
587                             self.confirmed_storage_classes[st_class] = st_copies
588                 self.response = response
589             with self.pending_tries_notification:
590                 self.pending_tries_notification.notify_all()
591
592         def write_fail(self, ks):
593             with self.pending_tries_notification:
594                 self.pending_tries += 1
595                 self.pending_tries_notification.notify()
596
597         def pending_copies(self):
598             with self.queue_data_lock:
599                 return self.wanted_copies - self.successful_copies
600
601         def satisfied_classes(self):
602             with self.queue_data_lock:
603                 if not self.storage_classes_tracking:
604                     # Notifies disabled storage classes expectation to
605                     # the outer loop.
606                     return None
607             return list(set(self.wanted_storage_classes) - set(self.pending_classes()))
608
609         def pending_classes(self):
610             with self.queue_data_lock:
611                 if (not self.storage_classes_tracking) or (self.wanted_storage_classes is None):
612                     return []
613                 unsatisfied_classes = copy.copy(self.wanted_storage_classes)
614                 for st_class, st_copies in self.confirmed_storage_classes.items():
615                     if st_class in unsatisfied_classes and st_copies >= self.wanted_copies:
616                         unsatisfied_classes.remove(st_class)
617                 return unsatisfied_classes
618
619         def get_next_task(self):
620             with self.pending_tries_notification:
621                 while True:
622                     if self.pending_copies() < 1 and len(self.pending_classes()) == 0:
623                         # This notify_all() is unnecessary --
624                         # write_success() already called notify_all()
625                         # when pending<1 became true, so it's not
626                         # possible for any other thread to be in
627                         # wait() now -- but it's cheap insurance
628                         # against deadlock so we do it anyway:
629                         self.pending_tries_notification.notify_all()
630                         # Drain the queue and then raise Queue.Empty
631                         while True:
632                             self.get_nowait()
633                             self.task_done()
634                     elif self.pending_tries > 0:
635                         service, service_root = self.get_nowait()
636                         if service.finished():
637                             self.task_done()
638                             continue
639                         self.pending_tries -= 1
640                         return service, service_root
641                     elif self.empty():
642                         self.pending_tries_notification.notify_all()
643                         raise queue.Empty
644                     else:
645                         self.pending_tries_notification.wait()
646
647
648     class KeepWriterThreadPool(object):
649         def __init__(self, data, data_hash, copies, max_service_replicas, timeout=None, classes=[]):
650             self.total_task_nr = 0
651             if (not max_service_replicas) or (max_service_replicas >= copies):
652                 num_threads = 1
653             else:
654                 num_threads = int(math.ceil(1.0*copies/max_service_replicas))
655             _logger.debug("Pool max threads is %d", num_threads)
656             self.workers = []
657             self.queue = KeepClient.KeepWriterQueue(copies, classes)
658             # Create workers
659             for _ in range(num_threads):
660                 w = KeepClient.KeepWriterThread(self.queue, data, data_hash, timeout)
661                 self.workers.append(w)
662
663         def add_task(self, ks, service_root):
664             self.queue.put((ks, service_root))
665             self.total_task_nr += 1
666
667         def done(self):
668             return self.queue.successful_copies, self.queue.satisfied_classes()
669
670         def join(self):
671             # Start workers
672             for worker in self.workers:
673                 worker.start()
674             # Wait for finished work
675             self.queue.join()
676
677         def response(self):
678             return self.queue.response
679
680
681     class KeepWriterThread(threading.Thread):
682         class TaskFailed(RuntimeError): pass
683
684         def __init__(self, queue, data, data_hash, timeout=None):
685             super(KeepClient.KeepWriterThread, self).__init__()
686             self.timeout = timeout
687             self.queue = queue
688             self.data = data
689             self.data_hash = data_hash
690             self.daemon = True
691
692         def run(self):
693             while True:
694                 try:
695                     service, service_root = self.queue.get_next_task()
696                 except queue.Empty:
697                     return
698                 try:
699                     locator, copies, classes = self.do_task(service, service_root)
700                 except Exception as e:
701                     if not isinstance(e, self.TaskFailed):
702                         _logger.exception("Exception in KeepWriterThread")
703                     self.queue.write_fail(service)
704                 else:
705                     self.queue.write_success(locator, copies, classes)
706                 finally:
707                     self.queue.task_done()
708
709         def do_task(self, service, service_root):
710             classes = self.queue.pending_classes()
711             headers = {}
712             if len(classes) > 0:
713                 classes.sort()
714                 headers['X-Keep-Storage-Classes'] = ', '.join(classes)
715             success = bool(service.put(self.data_hash,
716                                         self.data,
717                                         timeout=self.timeout,
718                                         headers=headers))
719             result = service.last_result()
720
721             if not success:
722                 if result.get('status_code', None):
723                     _logger.debug("Request fail: PUT %s => %s %s",
724                                   self.data_hash,
725                                   result['status_code'],
726                                   result['body'])
727                 raise self.TaskFailed()
728
729             _logger.debug("KeepWriterThread %s succeeded %s+%i %s",
730                           str(threading.current_thread()),
731                           self.data_hash,
732                           len(self.data),
733                           service_root)
734             try:
735                 replicas_stored = int(result['headers']['x-keep-replicas-stored'])
736             except (KeyError, ValueError):
737                 replicas_stored = 1
738
739             classes_confirmed = {}
740             try:
741                 scch = result['headers']['x-keep-storage-classes-confirmed']
742                 for confirmation in scch.replace(' ', '').split(','):
743                     if '=' in confirmation:
744                         stored_class, stored_copies = confirmation.split('=')[:2]
745                         classes_confirmed[stored_class] = int(stored_copies)
746             except (KeyError, ValueError):
747                 # Storage classes confirmed header missing or corrupt
748                 classes_confirmed = None
749
750             return result['body'].strip(), replicas_stored, classes_confirmed
751
752
753     def __init__(self, api_client=None, proxy=None,
754                  timeout=DEFAULT_TIMEOUT, proxy_timeout=DEFAULT_PROXY_TIMEOUT,
755                  api_token=None, local_store=None, block_cache=None,
756                  num_retries=0, session=None):
757         """Initialize a new KeepClient.
758
759         Arguments:
760         :api_client:
761           The API client to use to find Keep services.  If not
762           provided, KeepClient will build one from available Arvados
763           configuration.
764
765         :proxy:
766           If specified, this KeepClient will send requests to this Keep
767           proxy.  Otherwise, KeepClient will fall back to the setting of the
768           ARVADOS_KEEP_SERVICES or ARVADOS_KEEP_PROXY configuration settings.
769           If you want to KeepClient does not use a proxy, pass in an empty
770           string.
771
772         :timeout:
773           The initial timeout (in seconds) for HTTP requests to Keep
774           non-proxy servers.  A tuple of three floats is interpreted as
775           (connection_timeout, read_timeout, minimum_bandwidth). A connection
776           will be aborted if the average traffic rate falls below
777           minimum_bandwidth bytes per second over an interval of read_timeout
778           seconds. Because timeouts are often a result of transient server
779           load, the actual connection timeout will be increased by a factor
780           of two on each retry.
781           Default: (2, 256, 32768).
782
783         :proxy_timeout:
784           The initial timeout (in seconds) for HTTP requests to
785           Keep proxies. A tuple of three floats is interpreted as
786           (connection_timeout, read_timeout, minimum_bandwidth). The behavior
787           described above for adjusting connection timeouts on retry also
788           applies.
789           Default: (20, 256, 32768).
790
791         :api_token:
792           If you're not using an API client, but only talking
793           directly to a Keep proxy, this parameter specifies an API token
794           to authenticate Keep requests.  It is an error to specify both
795           api_client and api_token.  If you specify neither, KeepClient
796           will use one available from the Arvados configuration.
797
798         :local_store:
799           If specified, this KeepClient will bypass Keep
800           services, and save data to the named directory.  If unspecified,
801           KeepClient will fall back to the setting of the $KEEP_LOCAL_STORE
802           environment variable.  If you want to ensure KeepClient does not
803           use local storage, pass in an empty string.  This is primarily
804           intended to mock a server for testing.
805
806         :num_retries:
807           The default number of times to retry failed requests.
808           This will be used as the default num_retries value when get() and
809           put() are called.  Default 0.
810         """
811         self.lock = threading.Lock()
812         if proxy is None:
813             if config.get('ARVADOS_KEEP_SERVICES'):
814                 proxy = config.get('ARVADOS_KEEP_SERVICES')
815             else:
816                 proxy = config.get('ARVADOS_KEEP_PROXY')
817         if api_token is None:
818             if api_client is None:
819                 api_token = config.get('ARVADOS_API_TOKEN')
820             else:
821                 api_token = api_client.api_token
822         elif api_client is not None:
823             raise ValueError(
824                 "can't build KeepClient with both API client and token")
825         if local_store is None:
826             local_store = os.environ.get('KEEP_LOCAL_STORE')
827
828         if api_client is None:
829             self.insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE')
830         else:
831             self.insecure = api_client.insecure
832
833         self.block_cache = block_cache if block_cache else KeepBlockCache()
834         self.timeout = timeout
835         self.proxy_timeout = proxy_timeout
836         self._user_agent_pool = queue.LifoQueue()
837         self.upload_counter = Counter()
838         self.download_counter = Counter()
839         self.put_counter = Counter()
840         self.get_counter = Counter()
841         self.hits_counter = Counter()
842         self.misses_counter = Counter()
843         self._storage_classes_unsupported_warning = False
844
845         if local_store:
846             self.local_store = local_store
847             self.head = self.local_store_head
848             self.get = self.local_store_get
849             self.put = self.local_store_put
850         else:
851             self.num_retries = num_retries
852             self.max_replicas_per_service = None
853             if proxy:
854                 proxy_uris = proxy.split()
855                 for i in range(len(proxy_uris)):
856                     if not proxy_uris[i].endswith('/'):
857                         proxy_uris[i] += '/'
858                     # URL validation
859                     url = urllib.parse.urlparse(proxy_uris[i])
860                     if not (url.scheme and url.netloc):
861                         raise arvados.errors.ArgumentError("Invalid proxy URI: {}".format(proxy_uris[i]))
862                 self.api_token = api_token
863                 self._gateway_services = {}
864                 self._keep_services = [{
865                     'uuid': "00000-bi6l4-%015d" % idx,
866                     'service_type': 'proxy',
867                     '_service_root': uri,
868                     } for idx, uri in enumerate(proxy_uris)]
869                 self._writable_services = self._keep_services
870                 self.using_proxy = True
871                 self._static_services_list = True
872             else:
873                 # It's important to avoid instantiating an API client
874                 # unless we actually need one, for testing's sake.
875                 if api_client is None:
876                     api_client = arvados.api('v1')
877                 self.api_client = api_client
878                 self.api_token = api_client.api_token
879                 self._gateway_services = {}
880                 self._keep_services = None
881                 self._writable_services = None
882                 self.using_proxy = None
883                 self._static_services_list = False
884
885     def current_timeout(self, attempt_number):
886         """Return the appropriate timeout to use for this client.
887
888         The proxy timeout setting if the backend service is currently a proxy,
889         the regular timeout setting otherwise.  The `attempt_number` indicates
890         how many times the operation has been tried already (starting from 0
891         for the first try), and scales the connection timeout portion of the
892         return value accordingly.
893
894         """
895         # TODO(twp): the timeout should be a property of a
896         # KeepService, not a KeepClient. See #4488.
897         t = self.proxy_timeout if self.using_proxy else self.timeout
898         if len(t) == 2:
899             return (t[0] * (1 << attempt_number), t[1])
900         else:
901             return (t[0] * (1 << attempt_number), t[1], t[2])
902     def _any_nondisk_services(self, service_list):
903         return any(ks.get('service_type', 'disk') != 'disk'
904                    for ks in service_list)
905
906     def build_services_list(self, force_rebuild=False):
907         if (self._static_services_list or
908               (self._keep_services and not force_rebuild)):
909             return
910         with self.lock:
911             try:
912                 keep_services = self.api_client.keep_services().accessible()
913             except Exception:  # API server predates Keep services.
914                 keep_services = self.api_client.keep_disks().list()
915
916             # Gateway services are only used when specified by UUID,
917             # so there's nothing to gain by filtering them by
918             # service_type.
919             self._gateway_services = {ks['uuid']: ks for ks in
920                                       keep_services.execute()['items']}
921             if not self._gateway_services:
922                 raise arvados.errors.NoKeepServersError()
923
924             # Precompute the base URI for each service.
925             for r in self._gateway_services.values():
926                 host = r['service_host']
927                 if not host.startswith('[') and host.find(':') >= 0:
928                     # IPv6 URIs must be formatted like http://[::1]:80/...
929                     host = '[' + host + ']'
930                 r['_service_root'] = "{}://{}:{:d}/".format(
931                     'https' if r['service_ssl_flag'] else 'http',
932                     host,
933                     r['service_port'])
934
935             _logger.debug(str(self._gateway_services))
936             self._keep_services = [
937                 ks for ks in self._gateway_services.values()
938                 if not ks.get('service_type', '').startswith('gateway:')]
939             self._writable_services = [ks for ks in self._keep_services
940                                        if not ks.get('read_only')]
941
942             # For disk type services, max_replicas_per_service is 1
943             # It is unknown (unlimited) for other service types.
944             if self._any_nondisk_services(self._writable_services):
945                 self.max_replicas_per_service = None
946             else:
947                 self.max_replicas_per_service = 1
948
949     def _service_weight(self, data_hash, service_uuid):
950         """Compute the weight of a Keep service endpoint for a data
951         block with a known hash.
952
953         The weight is md5(h + u) where u is the last 15 characters of
954         the service endpoint's UUID.
955         """
956         return hashlib.md5((data_hash + service_uuid[-15:]).encode()).hexdigest()
957
958     def weighted_service_roots(self, locator, force_rebuild=False, need_writable=False):
959         """Return an array of Keep service endpoints, in the order in
960         which they should be probed when reading or writing data with
961         the given hash+hints.
962         """
963         self.build_services_list(force_rebuild)
964
965         sorted_roots = []
966         # Use the services indicated by the given +K@... remote
967         # service hints, if any are present and can be resolved to a
968         # URI.
969         for hint in locator.hints:
970             if hint.startswith('K@'):
971                 if len(hint) == 7:
972                     sorted_roots.append(
973                         "https://keep.{}.arvadosapi.com/".format(hint[2:]))
974                 elif len(hint) == 29:
975                     svc = self._gateway_services.get(hint[2:])
976                     if svc:
977                         sorted_roots.append(svc['_service_root'])
978
979         # Sort the available local services by weight (heaviest first)
980         # for this locator, and return their service_roots (base URIs)
981         # in that order.
982         use_services = self._keep_services
983         if need_writable:
984             use_services = self._writable_services
985         self.using_proxy = self._any_nondisk_services(use_services)
986         sorted_roots.extend([
987             svc['_service_root'] for svc in sorted(
988                 use_services,
989                 reverse=True,
990                 key=lambda svc: self._service_weight(locator.md5sum, svc['uuid']))])
991         _logger.debug("{}: {}".format(locator, sorted_roots))
992         return sorted_roots
993
994     def map_new_services(self, roots_map, locator, force_rebuild, need_writable, headers):
995         # roots_map is a dictionary, mapping Keep service root strings
996         # to KeepService objects.  Poll for Keep services, and add any
997         # new ones to roots_map.  Return the current list of local
998         # root strings.
999         headers.setdefault('Authorization', "OAuth2 %s" % (self.api_token,))
1000         local_roots = self.weighted_service_roots(locator, force_rebuild, need_writable)
1001         for root in local_roots:
1002             if root not in roots_map:
1003                 roots_map[root] = self.KeepService(
1004                     root, self._user_agent_pool,
1005                     upload_counter=self.upload_counter,
1006                     download_counter=self.download_counter,
1007                     headers=headers,
1008                     insecure=self.insecure)
1009         return local_roots
1010
1011     @staticmethod
1012     def _check_loop_result(result):
1013         # KeepClient RetryLoops should save results as a 2-tuple: the
1014         # actual result of the request, and the number of servers available
1015         # to receive the request this round.
1016         # This method returns True if there's a real result, False if
1017         # there are no more servers available, otherwise None.
1018         if isinstance(result, Exception):
1019             return None
1020         result, tried_server_count = result
1021         if (result is not None) and (result is not False):
1022             return True
1023         elif tried_server_count < 1:
1024             _logger.info("No more Keep services to try; giving up")
1025             return False
1026         else:
1027             return None
1028
1029     def get_from_cache(self, loc):
1030         """Fetch a block only if is in the cache, otherwise return None."""
1031         slot = self.block_cache.get(loc)
1032         if slot is not None and slot.ready.is_set():
1033             return slot.get()
1034         else:
1035             return None
1036
1037     def refresh_signature(self, loc):
1038         """Ask Keep to get the remote block and return its local signature"""
1039         now = datetime.datetime.utcnow().isoformat("T") + 'Z'
1040         return self.head(loc, headers={'X-Keep-Signature': 'local, {}'.format(now)})
1041
1042     @retry.retry_method
1043     def head(self, loc_s, **kwargs):
1044         return self._get_or_head(loc_s, method="HEAD", **kwargs)
1045
1046     @retry.retry_method
1047     def get(self, loc_s, **kwargs):
1048         return self._get_or_head(loc_s, method="GET", **kwargs)
1049
1050     def _get_or_head(self, loc_s, method="GET", num_retries=None, request_id=None, headers=None):
1051         """Get data from Keep.
1052
1053         This method fetches one or more blocks of data from Keep.  It
1054         sends a request each Keep service registered with the API
1055         server (or the proxy provided when this client was
1056         instantiated), then each service named in location hints, in
1057         sequence.  As soon as one service provides the data, it's
1058         returned.
1059
1060         Arguments:
1061         * loc_s: A string of one or more comma-separated locators to fetch.
1062           This method returns the concatenation of these blocks.
1063         * num_retries: The number of times to retry GET requests to
1064           *each* Keep server if it returns temporary failures, with
1065           exponential backoff.  Note that, in each loop, the method may try
1066           to fetch data from every available Keep service, along with any
1067           that are named in location hints in the locator.  The default value
1068           is set when the KeepClient is initialized.
1069         """
1070         if ',' in loc_s:
1071             return ''.join(self.get(x) for x in loc_s.split(','))
1072
1073         self.get_counter.add(1)
1074
1075         slot = None
1076         blob = None
1077         try:
1078             locator = KeepLocator(loc_s)
1079             if method == "GET":
1080                 slot, first = self.block_cache.reserve_cache(locator.md5sum)
1081                 if not first:
1082                     self.hits_counter.add(1)
1083                     blob = slot.get()
1084                     if blob is None:
1085                         raise arvados.errors.KeepReadError(
1086                             "failed to read {}".format(loc_s))
1087                     return blob
1088
1089             self.misses_counter.add(1)
1090
1091             if headers is None:
1092                 headers = {}
1093             headers['X-Request-Id'] = (request_id or
1094                                         (hasattr(self, 'api_client') and self.api_client.request_id) or
1095                                         arvados.util.new_request_id())
1096
1097             # If the locator has hints specifying a prefix (indicating a
1098             # remote keepproxy) or the UUID of a local gateway service,
1099             # read data from the indicated service(s) instead of the usual
1100             # list of local disk services.
1101             hint_roots = ['http://keep.{}.arvadosapi.com/'.format(hint[2:])
1102                           for hint in locator.hints if hint.startswith('K@') and len(hint) == 7]
1103             hint_roots.extend([self._gateway_services[hint[2:]]['_service_root']
1104                                for hint in locator.hints if (
1105                                        hint.startswith('K@') and
1106                                        len(hint) == 29 and
1107                                        self._gateway_services.get(hint[2:])
1108                                        )])
1109             # Map root URLs to their KeepService objects.
1110             roots_map = {
1111                 root: self.KeepService(root, self._user_agent_pool,
1112                                        upload_counter=self.upload_counter,
1113                                        download_counter=self.download_counter,
1114                                        headers=headers,
1115                                        insecure=self.insecure)
1116                 for root in hint_roots
1117             }
1118
1119             # See #3147 for a discussion of the loop implementation.  Highlights:
1120             # * Refresh the list of Keep services after each failure, in case
1121             #   it's being updated.
1122             # * Retry until we succeed, we're out of retries, or every available
1123             #   service has returned permanent failure.
1124             sorted_roots = []
1125             roots_map = {}
1126             loop = retry.RetryLoop(num_retries, self._check_loop_result,
1127                                    backoff_start=2)
1128             for tries_left in loop:
1129                 try:
1130                     sorted_roots = self.map_new_services(
1131                         roots_map, locator,
1132                         force_rebuild=(tries_left < num_retries),
1133                         need_writable=False,
1134                         headers=headers)
1135                 except Exception as error:
1136                     loop.save_result(error)
1137                     continue
1138
1139                 # Query KeepService objects that haven't returned
1140                 # permanent failure, in our specified shuffle order.
1141                 services_to_try = [roots_map[root]
1142                                    for root in sorted_roots
1143                                    if roots_map[root].usable()]
1144                 for keep_service in services_to_try:
1145                     blob = keep_service.get(locator, method=method, timeout=self.current_timeout(num_retries-tries_left))
1146                     if blob is not None:
1147                         break
1148                 loop.save_result((blob, len(services_to_try)))
1149
1150             # Always cache the result, then return it if we succeeded.
1151             if loop.success():
1152                 return blob
1153         finally:
1154             if slot is not None:
1155                 slot.set(blob)
1156                 self.block_cache.cap_cache()
1157
1158         # Q: Including 403 is necessary for the Keep tests to continue
1159         # passing, but maybe they should expect KeepReadError instead?
1160         not_founds = sum(1 for key in sorted_roots
1161                          if roots_map[key].last_result().get('status_code', None) in {403, 404, 410})
1162         service_errors = ((key, roots_map[key].last_result()['error'])
1163                           for key in sorted_roots)
1164         if not roots_map:
1165             raise arvados.errors.KeepReadError(
1166                 "failed to read {}: no Keep services available ({})".format(
1167                     loc_s, loop.last_result()))
1168         elif not_founds == len(sorted_roots):
1169             raise arvados.errors.NotFoundError(
1170                 "{} not found".format(loc_s), service_errors)
1171         else:
1172             raise arvados.errors.KeepReadError(
1173                 "failed to read {} after {}".format(loc_s, loop.attempts_str()), service_errors, label="service")
1174
1175     @retry.retry_method
1176     def put(self, data, copies=2, num_retries=None, request_id=None, classes=[]):
1177         """Save data in Keep.
1178
1179         This method will get a list of Keep services from the API server, and
1180         send the data to each one simultaneously in a new thread.  Once the
1181         uploads are finished, if enough copies are saved, this method returns
1182         the most recent HTTP response body.  If requests fail to upload
1183         enough copies, this method raises KeepWriteError.
1184
1185         Arguments:
1186         * data: The string of data to upload.
1187         * copies: The number of copies that the user requires be saved.
1188           Default 2.
1189         * num_retries: The number of times to retry PUT requests to
1190           *each* Keep server if it returns temporary failures, with
1191           exponential backoff.  The default value is set when the
1192           KeepClient is initialized.
1193         * classes: An optional list of storage class names where copies should
1194           be written.
1195         """
1196
1197         if not isinstance(data, bytes):
1198             data = data.encode()
1199
1200         self.put_counter.add(1)
1201
1202         data_hash = hashlib.md5(data).hexdigest()
1203         loc_s = data_hash + '+' + str(len(data))
1204         if copies < 1:
1205             return loc_s
1206         locator = KeepLocator(loc_s)
1207
1208         headers = {
1209             'X-Request-Id': (request_id or
1210                              (hasattr(self, 'api_client') and self.api_client.request_id) or
1211                              arvados.util.new_request_id()),
1212             'X-Keep-Desired-Replicas': str(copies),
1213         }
1214         roots_map = {}
1215         loop = retry.RetryLoop(num_retries, self._check_loop_result,
1216                                backoff_start=2)
1217         done_copies = 0
1218         done_classes = []
1219         for tries_left in loop:
1220             try:
1221                 sorted_roots = self.map_new_services(
1222                     roots_map, locator,
1223                     force_rebuild=(tries_left < num_retries),
1224                     need_writable=True,
1225                     headers=headers)
1226             except Exception as error:
1227                 loop.save_result(error)
1228                 continue
1229
1230             pending_classes = []
1231             if done_classes is not None:
1232                 pending_classes = list(set(classes) - set(done_classes))
1233             writer_pool = KeepClient.KeepWriterThreadPool(data=data,
1234                                                         data_hash=data_hash,
1235                                                         copies=copies - done_copies,
1236                                                         max_service_replicas=self.max_replicas_per_service,
1237                                                         timeout=self.current_timeout(num_retries - tries_left),
1238                                                         classes=pending_classes)
1239             for service_root, ks in [(root, roots_map[root])
1240                                      for root in sorted_roots]:
1241                 if ks.finished():
1242                     continue
1243                 writer_pool.add_task(ks, service_root)
1244             writer_pool.join()
1245             pool_copies, pool_classes = writer_pool.done()
1246             done_copies += pool_copies
1247             if (done_classes is not None) and (pool_classes is not None):
1248                 done_classes += pool_classes
1249                 loop.save_result(
1250                     (done_copies >= copies and set(done_classes) == set(classes),
1251                     writer_pool.total_task_nr))
1252             else:
1253                 # Old keepstore contacted without storage classes support:
1254                 # success is determined only by successful copies.
1255                 #
1256                 # Disable storage classes tracking from this point forward.
1257                 if not self._storage_classes_unsupported_warning:
1258                     self._storage_classes_unsupported_warning = True
1259                     _logger.warning("X-Keep-Storage-Classes header not supported by the cluster")
1260                 done_classes = None
1261                 loop.save_result(
1262                     (done_copies >= copies, writer_pool.total_task_nr))
1263
1264         if loop.success():
1265             return writer_pool.response()
1266         if not roots_map:
1267             raise arvados.errors.KeepWriteError(
1268                 "failed to write {}: no Keep services available ({})".format(
1269                     data_hash, loop.last_result()))
1270         else:
1271             service_errors = ((key, roots_map[key].last_result()['error'])
1272                               for key in sorted_roots
1273                               if roots_map[key].last_result()['error'])
1274             raise arvados.errors.KeepWriteError(
1275                 "failed to write {} after {} (wanted {} copies but wrote {})".format(
1276                     data_hash, loop.attempts_str(), (copies, classes), writer_pool.done()), service_errors, label="service")
1277
1278     def local_store_put(self, data, copies=1, num_retries=None, classes=[]):
1279         """A stub for put().
1280
1281         This method is used in place of the real put() method when
1282         using local storage (see constructor's local_store argument).
1283
1284         copies and num_retries arguments are ignored: they are here
1285         only for the sake of offering the same call signature as
1286         put().
1287
1288         Data stored this way can be retrieved via local_store_get().
1289         """
1290         md5 = hashlib.md5(data).hexdigest()
1291         locator = '%s+%d' % (md5, len(data))
1292         with open(os.path.join(self.local_store, md5 + '.tmp'), 'wb') as f:
1293             f.write(data)
1294         os.rename(os.path.join(self.local_store, md5 + '.tmp'),
1295                   os.path.join(self.local_store, md5))
1296         return locator
1297
1298     def local_store_get(self, loc_s, num_retries=None):
1299         """Companion to local_store_put()."""
1300         try:
1301             locator = KeepLocator(loc_s)
1302         except ValueError:
1303             raise arvados.errors.NotFoundError(
1304                 "Invalid data locator: '%s'" % loc_s)
1305         if locator.md5sum == config.EMPTY_BLOCK_LOCATOR.split('+')[0]:
1306             return b''
1307         with open(os.path.join(self.local_store, locator.md5sum), 'rb') as f:
1308             return f.read()
1309
1310     def local_store_head(self, loc_s, num_retries=None):
1311         """Companion to local_store_put()."""
1312         try:
1313             locator = KeepLocator(loc_s)
1314         except ValueError:
1315             raise arvados.errors.NotFoundError(
1316                 "Invalid data locator: '%s'" % loc_s)
1317         if locator.md5sum == config.EMPTY_BLOCK_LOCATOR.split('+')[0]:
1318             return True
1319         if os.path.exists(os.path.join(self.local_store, locator.md5sum)):
1320             return True
1321
1322     def is_cached(self, locator):
1323         return self.block_cache.reserve_cache(expect_hash)