1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 from __future__ import absolute_import
6 from __future__ import division
7 from future import standard_library
8 from future.utils import native_str
9 standard_library.install_aliases()
10 from builtins import next
11 from builtins import str
12 from builtins import range
13 from builtins import object
31 if sys.version_info >= (3, 0):
32 from io import BytesIO
34 from cStringIO import StringIO as BytesIO
37 import arvados.config as config
39 import arvados.retry as retry
42 _logger = logging.getLogger('arvados.keep')
43 global_client_object = None
46 # Monkey patch TCP constants when not available (apple). Values sourced from:
47 # http://www.opensource.apple.com/source/xnu/xnu-2422.115.4/bsd/netinet/tcp.h
48 if sys.platform == 'darwin':
49 if not hasattr(socket, 'TCP_KEEPALIVE'):
50 socket.TCP_KEEPALIVE = 0x010
51 if not hasattr(socket, 'TCP_KEEPINTVL'):
52 socket.TCP_KEEPINTVL = 0x101
53 if not hasattr(socket, 'TCP_KEEPCNT'):
54 socket.TCP_KEEPCNT = 0x102
57 class KeepLocator(object):
58 EPOCH_DATETIME = datetime.datetime.utcfromtimestamp(0)
59 HINT_RE = re.compile(r'^[A-Z][A-Za-z0-9@_-]+$')
61 def __init__(self, locator_str):
64 self._perm_expiry = None
65 pieces = iter(locator_str.split('+'))
66 self.md5sum = next(pieces)
68 self.size = int(next(pieces))
72 if self.HINT_RE.match(hint) is None:
73 raise ValueError("invalid hint format: {}".format(hint))
74 elif hint.startswith('A'):
75 self.parse_permission_hint(hint)
77 self.hints.append(hint)
82 for s in [self.md5sum, self.size,
83 self.permission_hint()] + self.hints
87 if self.size is not None:
88 return "%s+%i" % (self.md5sum, self.size)
92 def _make_hex_prop(name, length):
93 # Build and return a new property with the given name that
94 # must be a hex string of the given length.
95 data_name = '_{}'.format(name)
97 return getattr(self, data_name)
98 def setter(self, hex_str):
99 if not arvados.util.is_hex(hex_str, length):
100 raise ValueError("{} is not a {}-digit hex string: {!r}".
101 format(name, length, hex_str))
102 setattr(self, data_name, hex_str)
103 return property(getter, setter)
105 md5sum = _make_hex_prop('md5sum', 32)
106 perm_sig = _make_hex_prop('perm_sig', 40)
109 def perm_expiry(self):
110 return self._perm_expiry
113 def perm_expiry(self, value):
114 if not arvados.util.is_hex(value, 1, 8):
116 "permission timestamp must be a hex Unix timestamp: {}".
118 self._perm_expiry = datetime.datetime.utcfromtimestamp(int(value, 16))
120 def permission_hint(self):
121 data = [self.perm_sig, self.perm_expiry]
124 data[1] = int((data[1] - self.EPOCH_DATETIME).total_seconds())
125 return "A{}@{:08x}".format(*data)
127 def parse_permission_hint(self, s):
129 self.perm_sig, self.perm_expiry = s[1:].split('@', 1)
131 raise ValueError("bad permission hint {}".format(s))
133 def permission_expired(self, as_of_dt=None):
134 if self.perm_expiry is None:
136 elif as_of_dt is None:
137 as_of_dt = datetime.datetime.now()
138 return self.perm_expiry <= as_of_dt
142 """Simple interface to a global KeepClient object.
144 THIS CLASS IS DEPRECATED. Please instantiate your own KeepClient with your
145 own API client. The global KeepClient will build an API client from the
146 current Arvados configuration, which may not match the one you built.
151 def global_client_object(cls):
152 global global_client_object
153 # Previously, KeepClient would change its behavior at runtime based
154 # on these configuration settings. We simulate that behavior here
155 # by checking the values and returning a new KeepClient if any of
157 key = (config.get('ARVADOS_API_HOST'),
158 config.get('ARVADOS_API_TOKEN'),
159 config.flag_is_true('ARVADOS_API_HOST_INSECURE'),
160 config.get('ARVADOS_KEEP_PROXY'),
161 config.get('ARVADOS_EXTERNAL_CLIENT') == 'true',
162 os.environ.get('KEEP_LOCAL_STORE'))
163 if (global_client_object is None) or (cls._last_key != key):
164 global_client_object = KeepClient()
166 return global_client_object
169 def get(locator, **kwargs):
170 return Keep.global_client_object().get(locator, **kwargs)
173 def put(data, **kwargs):
174 return Keep.global_client_object().put(data, **kwargs)
176 class KeepBlockCache(object):
177 # Default RAM cache is 256MiB
178 def __init__(self, cache_max=(256 * 1024 * 1024)):
179 self.cache_max = cache_max
181 self._cache_lock = threading.Lock()
183 class CacheSlot(object):
184 __slots__ = ("locator", "ready", "content")
186 def __init__(self, locator):
187 self.locator = locator
188 self.ready = threading.Event()
195 def set(self, value):
200 if self.content is None:
203 return len(self.content)
206 '''Cap the cache size to self.cache_max'''
207 with self._cache_lock:
208 # Select all slots except those where ready.is_set() and content is
209 # None (that means there was an error reading the block).
210 self._cache = [c for c in self._cache if not (c.ready.is_set() and c.content is None)]
211 sm = sum([slot.size() for slot in self._cache])
212 while len(self._cache) > 0 and sm > self.cache_max:
213 for i in range(len(self._cache)-1, -1, -1):
214 if self._cache[i].ready.is_set():
217 sm = sum([slot.size() for slot in self._cache])
219 def _get(self, locator):
220 # Test if the locator is already in the cache
221 for i in range(0, len(self._cache)):
222 if self._cache[i].locator == locator:
225 # move it to the front
227 self._cache.insert(0, n)
231 def get(self, locator):
232 with self._cache_lock:
233 return self._get(locator)
235 def reserve_cache(self, locator):
236 '''Reserve a cache slot for the specified locator,
237 or return the existing slot.'''
238 with self._cache_lock:
239 n = self._get(locator)
243 # Add a new cache slot for the locator
244 n = KeepBlockCache.CacheSlot(locator)
245 self._cache.insert(0, n)
248 class Counter(object):
249 def __init__(self, v=0):
250 self._lk = threading.Lock()
262 class KeepClient(object):
264 # Default Keep server connection timeout: 2 seconds
265 # Default Keep server read timeout: 256 seconds
266 # Default Keep server bandwidth minimum: 32768 bytes per second
267 # Default Keep proxy connection timeout: 20 seconds
268 # Default Keep proxy read timeout: 256 seconds
269 # Default Keep proxy bandwidth minimum: 32768 bytes per second
270 DEFAULT_TIMEOUT = (2, 256, 32768)
271 DEFAULT_PROXY_TIMEOUT = (20, 256, 32768)
274 class KeepService(object):
275 """Make requests to a single Keep service, and track results.
277 A KeepService is intended to last long enough to perform one
278 transaction (GET or PUT) against one Keep service. This can
279 involve calling either get() or put() multiple times in order
280 to retry after transient failures. However, calling both get()
281 and put() on a single instance -- or using the same instance
282 to access two different Keep services -- will not produce
289 arvados.errors.HttpError,
292 def __init__(self, root, user_agent_pool=queue.LifoQueue(),
294 download_counter=None,
298 self._user_agent_pool = user_agent_pool
299 self._result = {'error': None}
303 self.get_headers = {'Accept': 'application/octet-stream'}
304 self.get_headers.update(headers)
305 self.put_headers = headers
306 self.upload_counter = upload_counter
307 self.download_counter = download_counter
308 self.insecure = insecure
311 """Is it worth attempting a request?"""
315 """Did the request succeed or encounter permanent failure?"""
316 return self._result['error'] == False or not self._usable
318 def last_result(self):
321 def _get_user_agent(self):
323 return self._user_agent_pool.get(block=False)
327 def _put_user_agent(self, ua):
330 self._user_agent_pool.put(ua, block=False)
334 def _socket_open(self, *args, **kwargs):
335 if len(args) + len(kwargs) == 2:
336 return self._socket_open_pycurl_7_21_5(*args, **kwargs)
338 return self._socket_open_pycurl_7_19_3(*args, **kwargs)
340 def _socket_open_pycurl_7_19_3(self, family, socktype, protocol, address=None):
341 return self._socket_open_pycurl_7_21_5(
343 address=collections.namedtuple(
344 'Address', ['family', 'socktype', 'protocol', 'addr'],
345 )(family, socktype, protocol, address))
347 def _socket_open_pycurl_7_21_5(self, purpose, address):
348 """Because pycurl doesn't have CURLOPT_TCP_KEEPALIVE"""
349 s = socket.socket(address.family, address.socktype, address.protocol)
350 s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
351 # Will throw invalid protocol error on mac. This test prevents that.
352 if hasattr(socket, 'TCP_KEEPIDLE'):
353 s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 75)
354 s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75)
358 def get(self, locator, method="GET", timeout=None):
359 # locator is a KeepLocator object.
360 url = self.root + str(locator)
361 _logger.debug("Request: %s %s", method, url)
362 curl = self._get_user_agent()
365 with timer.Timer() as t:
367 response_body = BytesIO()
368 curl.setopt(pycurl.NOSIGNAL, 1)
369 curl.setopt(pycurl.OPENSOCKETFUNCTION,
370 lambda *args, **kwargs: self._socket_open(*args, **kwargs))
371 curl.setopt(pycurl.URL, url.encode('utf-8'))
372 curl.setopt(pycurl.HTTPHEADER, [
373 '{}: {}'.format(k,v) for k,v in self.get_headers.items()])
374 curl.setopt(pycurl.WRITEFUNCTION, response_body.write)
375 curl.setopt(pycurl.HEADERFUNCTION, self._headerfunction)
377 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
379 curl.setopt(pycurl.CAINFO, arvados.util.ca_certs_path())
381 curl.setopt(pycurl.NOBODY, True)
382 self._setcurltimeouts(curl, timeout, method=="HEAD")
386 except Exception as e:
387 raise arvados.errors.HttpError(0, str(e))
393 'status_code': curl.getinfo(pycurl.RESPONSE_CODE),
394 'body': response_body.getvalue(),
395 'headers': self._headers,
399 ok = retry.check_http_response_success(self._result['status_code'])
401 self._result['error'] = arvados.errors.HttpError(
402 self._result['status_code'],
403 self._headers.get('x-status-line', 'Error'))
404 except self.HTTP_ERRORS as e:
408 self._usable = ok != False
409 if self._result.get('status_code', None):
410 # The client worked well enough to get an HTTP status
411 # code, so presumably any problems are just on the
412 # server side and it's OK to reuse the client.
413 self._put_user_agent(curl)
415 # Don't return this client to the pool, in case it's
419 _logger.debug("Request fail: GET %s => %s: %s",
420 url, type(self._result['error']), str(self._result['error']))
423 _logger.info("HEAD %s: %s bytes",
424 self._result['status_code'],
425 self._result.get('content-length'))
426 if self._result['headers'].get('x-keep-locator'):
427 # This is a response to a remote block copy request, return
428 # the local copy block locator.
429 return self._result['headers'].get('x-keep-locator')
432 _logger.info("GET %s: %s bytes in %s msec (%.3f MiB/sec)",
433 self._result['status_code'],
434 len(self._result['body']),
436 1.0*len(self._result['body'])/2**20/t.secs if t.secs > 0 else 0)
438 if self.download_counter:
439 self.download_counter.add(len(self._result['body']))
440 resp_md5 = hashlib.md5(self._result['body']).hexdigest()
441 if resp_md5 != locator.md5sum:
442 _logger.warning("Checksum fail: md5(%s) = %s",
444 self._result['error'] = arvados.errors.HttpError(
447 return self._result['body']
449 def put(self, hash_s, body, timeout=None):
450 url = self.root + hash_s
451 _logger.debug("Request: PUT %s", url)
452 curl = self._get_user_agent()
455 with timer.Timer() as t:
457 body_reader = BytesIO(body)
458 response_body = BytesIO()
459 curl.setopt(pycurl.NOSIGNAL, 1)
460 curl.setopt(pycurl.OPENSOCKETFUNCTION,
461 lambda *args, **kwargs: self._socket_open(*args, **kwargs))
462 curl.setopt(pycurl.URL, url.encode('utf-8'))
463 # Using UPLOAD tells cURL to wait for a "go ahead" from the
464 # Keep server (in the form of a HTTP/1.1 "100 Continue"
465 # response) instead of sending the request body immediately.
466 # This allows the server to reject the request if the request
467 # is invalid or the server is read-only, without waiting for
468 # the client to send the entire block.
469 curl.setopt(pycurl.UPLOAD, True)
470 curl.setopt(pycurl.INFILESIZE, len(body))
471 curl.setopt(pycurl.READFUNCTION, body_reader.read)
472 curl.setopt(pycurl.HTTPHEADER, [
473 '{}: {}'.format(k,v) for k,v in self.put_headers.items()])
474 curl.setopt(pycurl.WRITEFUNCTION, response_body.write)
475 curl.setopt(pycurl.HEADERFUNCTION, self._headerfunction)
477 curl.setopt(pycurl.SSL_VERIFYPEER, 0)
479 curl.setopt(pycurl.CAINFO, arvados.util.ca_certs_path())
480 self._setcurltimeouts(curl, timeout)
483 except Exception as e:
484 raise arvados.errors.HttpError(0, str(e))
490 'status_code': curl.getinfo(pycurl.RESPONSE_CODE),
491 'body': response_body.getvalue().decode('utf-8'),
492 'headers': self._headers,
495 ok = retry.check_http_response_success(self._result['status_code'])
497 self._result['error'] = arvados.errors.HttpError(
498 self._result['status_code'],
499 self._headers.get('x-status-line', 'Error'))
500 except self.HTTP_ERRORS as e:
504 self._usable = ok != False # still usable if ok is True or None
505 if self._result.get('status_code', None):
506 # Client is functional. See comment in get().
507 self._put_user_agent(curl)
511 _logger.debug("Request fail: PUT %s => %s: %s",
512 url, type(self._result['error']), str(self._result['error']))
514 _logger.info("PUT %s: %s bytes in %s msec (%.3f MiB/sec)",
515 self._result['status_code'],
518 1.0*len(body)/2**20/t.secs if t.secs > 0 else 0)
519 if self.upload_counter:
520 self.upload_counter.add(len(body))
523 def _setcurltimeouts(self, curl, timeouts, ignore_bandwidth=False):
526 elif isinstance(timeouts, tuple):
527 if len(timeouts) == 2:
528 conn_t, xfer_t = timeouts
529 bandwidth_bps = KeepClient.DEFAULT_TIMEOUT[2]
531 conn_t, xfer_t, bandwidth_bps = timeouts
533 conn_t, xfer_t = (timeouts, timeouts)
534 bandwidth_bps = KeepClient.DEFAULT_TIMEOUT[2]
535 curl.setopt(pycurl.CONNECTTIMEOUT_MS, int(conn_t*1000))
536 if not ignore_bandwidth:
537 curl.setopt(pycurl.LOW_SPEED_TIME, int(math.ceil(xfer_t)))
538 curl.setopt(pycurl.LOW_SPEED_LIMIT, int(math.ceil(bandwidth_bps)))
540 def _headerfunction(self, header_line):
541 if isinstance(header_line, bytes):
542 header_line = header_line.decode('iso-8859-1')
543 if ':' in header_line:
544 name, value = header_line.split(':', 1)
545 name = name.strip().lower()
546 value = value.strip()
548 name = self._lastheadername
549 value = self._headers[name] + ' ' + header_line.strip()
550 elif header_line.startswith('HTTP/'):
551 name = 'x-status-line'
554 _logger.error("Unexpected header line: %s", header_line)
556 self._lastheadername = name
557 self._headers[name] = value
558 # Returning None implies all bytes were written
561 class KeepWriterQueue(queue.Queue):
562 def __init__(self, copies):
563 queue.Queue.__init__(self) # Old-style superclass
564 self.wanted_copies = copies
565 self.successful_copies = 0
567 self.successful_copies_lock = threading.Lock()
568 self.pending_tries = copies
569 self.pending_tries_notification = threading.Condition()
571 def write_success(self, response, replicas_nr):
572 with self.successful_copies_lock:
573 self.successful_copies += replicas_nr
574 self.response = response
575 with self.pending_tries_notification:
576 self.pending_tries_notification.notify_all()
578 def write_fail(self, ks):
579 with self.pending_tries_notification:
580 self.pending_tries += 1
581 self.pending_tries_notification.notify()
583 def pending_copies(self):
584 with self.successful_copies_lock:
585 return self.wanted_copies - self.successful_copies
587 def get_next_task(self):
588 with self.pending_tries_notification:
590 if self.pending_copies() < 1:
591 # This notify_all() is unnecessary --
592 # write_success() already called notify_all()
593 # when pending<1 became true, so it's not
594 # possible for any other thread to be in
595 # wait() now -- but it's cheap insurance
596 # against deadlock so we do it anyway:
597 self.pending_tries_notification.notify_all()
598 # Drain the queue and then raise Queue.Empty
602 elif self.pending_tries > 0:
603 service, service_root = self.get_nowait()
604 if service.finished():
607 self.pending_tries -= 1
608 return service, service_root
610 self.pending_tries_notification.notify_all()
613 self.pending_tries_notification.wait()
616 class KeepWriterThreadPool(object):
617 def __init__(self, data, data_hash, copies, max_service_replicas, timeout=None):
618 self.total_task_nr = 0
619 self.wanted_copies = copies
620 if (not max_service_replicas) or (max_service_replicas >= copies):
623 num_threads = int(math.ceil(1.0*copies/max_service_replicas))
624 _logger.debug("Pool max threads is %d", num_threads)
626 self.queue = KeepClient.KeepWriterQueue(copies)
628 for _ in range(num_threads):
629 w = KeepClient.KeepWriterThread(self.queue, data, data_hash, timeout)
630 self.workers.append(w)
632 def add_task(self, ks, service_root):
633 self.queue.put((ks, service_root))
634 self.total_task_nr += 1
637 return self.queue.successful_copies
641 for worker in self.workers:
643 # Wait for finished work
647 return self.queue.response
650 class KeepWriterThread(threading.Thread):
651 TaskFailed = RuntimeError()
653 def __init__(self, queue, data, data_hash, timeout=None):
654 super(KeepClient.KeepWriterThread, self).__init__()
655 self.timeout = timeout
658 self.data_hash = data_hash
664 service, service_root = self.queue.get_next_task()
668 locator, copies = self.do_task(service, service_root)
669 except Exception as e:
670 if e is not self.TaskFailed:
671 _logger.exception("Exception in KeepWriterThread")
672 self.queue.write_fail(service)
674 self.queue.write_success(locator, copies)
676 self.queue.task_done()
678 def do_task(self, service, service_root):
679 success = bool(service.put(self.data_hash,
681 timeout=self.timeout))
682 result = service.last_result()
685 if result.get('status_code', None):
686 _logger.debug("Request fail: PUT %s => %s %s",
688 result['status_code'],
690 raise self.TaskFailed
692 _logger.debug("KeepWriterThread %s succeeded %s+%i %s",
693 str(threading.current_thread()),
698 replicas_stored = int(result['headers']['x-keep-replicas-stored'])
699 except (KeyError, ValueError):
702 return result['body'].strip(), replicas_stored
705 def __init__(self, api_client=None, proxy=None,
706 timeout=DEFAULT_TIMEOUT, proxy_timeout=DEFAULT_PROXY_TIMEOUT,
707 api_token=None, local_store=None, block_cache=None,
708 num_retries=0, session=None):
709 """Initialize a new KeepClient.
713 The API client to use to find Keep services. If not
714 provided, KeepClient will build one from available Arvados
718 If specified, this KeepClient will send requests to this Keep
719 proxy. Otherwise, KeepClient will fall back to the setting of the
720 ARVADOS_KEEP_SERVICES or ARVADOS_KEEP_PROXY configuration settings.
721 If you want to KeepClient does not use a proxy, pass in an empty
725 The initial timeout (in seconds) for HTTP requests to Keep
726 non-proxy servers. A tuple of three floats is interpreted as
727 (connection_timeout, read_timeout, minimum_bandwidth). A connection
728 will be aborted if the average traffic rate falls below
729 minimum_bandwidth bytes per second over an interval of read_timeout
730 seconds. Because timeouts are often a result of transient server
731 load, the actual connection timeout will be increased by a factor
732 of two on each retry.
733 Default: (2, 256, 32768).
736 The initial timeout (in seconds) for HTTP requests to
737 Keep proxies. A tuple of three floats is interpreted as
738 (connection_timeout, read_timeout, minimum_bandwidth). The behavior
739 described above for adjusting connection timeouts on retry also
741 Default: (20, 256, 32768).
744 If you're not using an API client, but only talking
745 directly to a Keep proxy, this parameter specifies an API token
746 to authenticate Keep requests. It is an error to specify both
747 api_client and api_token. If you specify neither, KeepClient
748 will use one available from the Arvados configuration.
751 If specified, this KeepClient will bypass Keep
752 services, and save data to the named directory. If unspecified,
753 KeepClient will fall back to the setting of the $KEEP_LOCAL_STORE
754 environment variable. If you want to ensure KeepClient does not
755 use local storage, pass in an empty string. This is primarily
756 intended to mock a server for testing.
759 The default number of times to retry failed requests.
760 This will be used as the default num_retries value when get() and
761 put() are called. Default 0.
763 self.lock = threading.Lock()
765 if config.get('ARVADOS_KEEP_SERVICES'):
766 proxy = config.get('ARVADOS_KEEP_SERVICES')
768 proxy = config.get('ARVADOS_KEEP_PROXY')
769 if api_token is None:
770 if api_client is None:
771 api_token = config.get('ARVADOS_API_TOKEN')
773 api_token = api_client.api_token
774 elif api_client is not None:
776 "can't build KeepClient with both API client and token")
777 if local_store is None:
778 local_store = os.environ.get('KEEP_LOCAL_STORE')
780 if api_client is None:
781 self.insecure = config.flag_is_true('ARVADOS_API_HOST_INSECURE')
783 self.insecure = api_client.insecure
785 self.block_cache = block_cache if block_cache else KeepBlockCache()
786 self.timeout = timeout
787 self.proxy_timeout = proxy_timeout
788 self._user_agent_pool = queue.LifoQueue()
789 self.upload_counter = Counter()
790 self.download_counter = Counter()
791 self.put_counter = Counter()
792 self.get_counter = Counter()
793 self.hits_counter = Counter()
794 self.misses_counter = Counter()
797 self.local_store = local_store
798 self.head = self.local_store_head
799 self.get = self.local_store_get
800 self.put = self.local_store_put
802 self.num_retries = num_retries
803 self.max_replicas_per_service = None
805 proxy_uris = proxy.split()
806 for i in range(len(proxy_uris)):
807 if not proxy_uris[i].endswith('/'):
810 url = urllib.parse.urlparse(proxy_uris[i])
811 if not (url.scheme and url.netloc):
812 raise arvados.errors.ArgumentError("Invalid proxy URI: {}".format(proxy_uris[i]))
813 self.api_token = api_token
814 self._gateway_services = {}
815 self._keep_services = [{
816 'uuid': "00000-bi6l4-%015d" % idx,
817 'service_type': 'proxy',
818 '_service_root': uri,
819 } for idx, uri in enumerate(proxy_uris)]
820 self._writable_services = self._keep_services
821 self.using_proxy = True
822 self._static_services_list = True
824 # It's important to avoid instantiating an API client
825 # unless we actually need one, for testing's sake.
826 if api_client is None:
827 api_client = arvados.api('v1')
828 self.api_client = api_client
829 self.api_token = api_client.api_token
830 self._gateway_services = {}
831 self._keep_services = None
832 self._writable_services = None
833 self.using_proxy = None
834 self._static_services_list = False
836 def current_timeout(self, attempt_number):
837 """Return the appropriate timeout to use for this client.
839 The proxy timeout setting if the backend service is currently a proxy,
840 the regular timeout setting otherwise. The `attempt_number` indicates
841 how many times the operation has been tried already (starting from 0
842 for the first try), and scales the connection timeout portion of the
843 return value accordingly.
846 # TODO(twp): the timeout should be a property of a
847 # KeepService, not a KeepClient. See #4488.
848 t = self.proxy_timeout if self.using_proxy else self.timeout
850 return (t[0] * (1 << attempt_number), t[1])
852 return (t[0] * (1 << attempt_number), t[1], t[2])
853 def _any_nondisk_services(self, service_list):
854 return any(ks.get('service_type', 'disk') != 'disk'
855 for ks in service_list)
857 def build_services_list(self, force_rebuild=False):
858 if (self._static_services_list or
859 (self._keep_services and not force_rebuild)):
863 keep_services = self.api_client.keep_services().accessible()
864 except Exception: # API server predates Keep services.
865 keep_services = self.api_client.keep_disks().list()
867 # Gateway services are only used when specified by UUID,
868 # so there's nothing to gain by filtering them by
870 self._gateway_services = {ks['uuid']: ks for ks in
871 keep_services.execute()['items']}
872 if not self._gateway_services:
873 raise arvados.errors.NoKeepServersError()
875 # Precompute the base URI for each service.
876 for r in self._gateway_services.values():
877 host = r['service_host']
878 if not host.startswith('[') and host.find(':') >= 0:
879 # IPv6 URIs must be formatted like http://[::1]:80/...
880 host = '[' + host + ']'
881 r['_service_root'] = "{}://{}:{:d}/".format(
882 'https' if r['service_ssl_flag'] else 'http',
886 _logger.debug(str(self._gateway_services))
887 self._keep_services = [
888 ks for ks in self._gateway_services.values()
889 if not ks.get('service_type', '').startswith('gateway:')]
890 self._writable_services = [ks for ks in self._keep_services
891 if not ks.get('read_only')]
893 # For disk type services, max_replicas_per_service is 1
894 # It is unknown (unlimited) for other service types.
895 if self._any_nondisk_services(self._writable_services):
896 self.max_replicas_per_service = None
898 self.max_replicas_per_service = 1
900 def _service_weight(self, data_hash, service_uuid):
901 """Compute the weight of a Keep service endpoint for a data
902 block with a known hash.
904 The weight is md5(h + u) where u is the last 15 characters of
905 the service endpoint's UUID.
907 return hashlib.md5((data_hash + service_uuid[-15:]).encode()).hexdigest()
909 def weighted_service_roots(self, locator, force_rebuild=False, need_writable=False):
910 """Return an array of Keep service endpoints, in the order in
911 which they should be probed when reading or writing data with
912 the given hash+hints.
914 self.build_services_list(force_rebuild)
917 # Use the services indicated by the given +K@... remote
918 # service hints, if any are present and can be resolved to a
920 for hint in locator.hints:
921 if hint.startswith('K@'):
924 "https://keep.{}.arvadosapi.com/".format(hint[2:]))
925 elif len(hint) == 29:
926 svc = self._gateway_services.get(hint[2:])
928 sorted_roots.append(svc['_service_root'])
930 # Sort the available local services by weight (heaviest first)
931 # for this locator, and return their service_roots (base URIs)
933 use_services = self._keep_services
935 use_services = self._writable_services
936 self.using_proxy = self._any_nondisk_services(use_services)
937 sorted_roots.extend([
938 svc['_service_root'] for svc in sorted(
941 key=lambda svc: self._service_weight(locator.md5sum, svc['uuid']))])
942 _logger.debug("{}: {}".format(locator, sorted_roots))
945 def map_new_services(self, roots_map, locator, force_rebuild, need_writable, headers):
946 # roots_map is a dictionary, mapping Keep service root strings
947 # to KeepService objects. Poll for Keep services, and add any
948 # new ones to roots_map. Return the current list of local
950 headers.setdefault('Authorization', "OAuth2 %s" % (self.api_token,))
951 local_roots = self.weighted_service_roots(locator, force_rebuild, need_writable)
952 for root in local_roots:
953 if root not in roots_map:
954 roots_map[root] = self.KeepService(
955 root, self._user_agent_pool,
956 upload_counter=self.upload_counter,
957 download_counter=self.download_counter,
959 insecure=self.insecure)
963 def _check_loop_result(result):
964 # KeepClient RetryLoops should save results as a 2-tuple: the
965 # actual result of the request, and the number of servers available
966 # to receive the request this round.
967 # This method returns True if there's a real result, False if
968 # there are no more servers available, otherwise None.
969 if isinstance(result, Exception):
971 result, tried_server_count = result
972 if (result is not None) and (result is not False):
974 elif tried_server_count < 1:
975 _logger.info("No more Keep services to try; giving up")
980 def get_from_cache(self, loc):
981 """Fetch a block only if is in the cache, otherwise return None."""
982 slot = self.block_cache.get(loc)
983 if slot is not None and slot.ready.is_set():
988 def refresh_signature(self, loc):
989 """Ask Keep to get the remote block and return its local signature"""
990 now = datetime.datetime.utcnow().isoformat("T") + 'Z'
991 return self.head(loc, headers={'X-Keep-Signature': 'local, {}'.format(now)})
994 def head(self, loc_s, **kwargs):
995 return self._get_or_head(loc_s, method="HEAD", **kwargs)
998 def get(self, loc_s, **kwargs):
999 return self._get_or_head(loc_s, method="GET", **kwargs)
1001 def _get_or_head(self, loc_s, method="GET", num_retries=None, request_id=None, headers=None):
1002 """Get data from Keep.
1004 This method fetches one or more blocks of data from Keep. It
1005 sends a request each Keep service registered with the API
1006 server (or the proxy provided when this client was
1007 instantiated), then each service named in location hints, in
1008 sequence. As soon as one service provides the data, it's
1012 * loc_s: A string of one or more comma-separated locators to fetch.
1013 This method returns the concatenation of these blocks.
1014 * num_retries: The number of times to retry GET requests to
1015 *each* Keep server if it returns temporary failures, with
1016 exponential backoff. Note that, in each loop, the method may try
1017 to fetch data from every available Keep service, along with any
1018 that are named in location hints in the locator. The default value
1019 is set when the KeepClient is initialized.
1022 return ''.join(self.get(x) for x in loc_s.split(','))
1024 self.get_counter.add(1)
1029 locator = KeepLocator(loc_s)
1031 slot, first = self.block_cache.reserve_cache(locator.md5sum)
1033 self.hits_counter.add(1)
1036 raise arvados.errors.KeepReadError(
1037 "failed to read {}".format(loc_s))
1040 self.misses_counter.add(1)
1044 headers['X-Request-Id'] = (request_id or
1045 (hasattr(self, 'api_client') and self.api_client.request_id) or
1046 arvados.util.new_request_id())
1048 # If the locator has hints specifying a prefix (indicating a
1049 # remote keepproxy) or the UUID of a local gateway service,
1050 # read data from the indicated service(s) instead of the usual
1051 # list of local disk services.
1052 hint_roots = ['http://keep.{}.arvadosapi.com/'.format(hint[2:])
1053 for hint in locator.hints if hint.startswith('K@') and len(hint) == 7]
1054 hint_roots.extend([self._gateway_services[hint[2:]]['_service_root']
1055 for hint in locator.hints if (
1056 hint.startswith('K@') and
1058 self._gateway_services.get(hint[2:])
1060 # Map root URLs to their KeepService objects.
1062 root: self.KeepService(root, self._user_agent_pool,
1063 upload_counter=self.upload_counter,
1064 download_counter=self.download_counter,
1066 insecure=self.insecure)
1067 for root in hint_roots
1070 # See #3147 for a discussion of the loop implementation. Highlights:
1071 # * Refresh the list of Keep services after each failure, in case
1072 # it's being updated.
1073 # * Retry until we succeed, we're out of retries, or every available
1074 # service has returned permanent failure.
1077 loop = retry.RetryLoop(num_retries, self._check_loop_result,
1079 for tries_left in loop:
1081 sorted_roots = self.map_new_services(
1083 force_rebuild=(tries_left < num_retries),
1084 need_writable=False,
1086 except Exception as error:
1087 loop.save_result(error)
1090 # Query KeepService objects that haven't returned
1091 # permanent failure, in our specified shuffle order.
1092 services_to_try = [roots_map[root]
1093 for root in sorted_roots
1094 if roots_map[root].usable()]
1095 for keep_service in services_to_try:
1096 blob = keep_service.get(locator, method=method, timeout=self.current_timeout(num_retries-tries_left))
1097 if blob is not None:
1099 loop.save_result((blob, len(services_to_try)))
1101 # Always cache the result, then return it if we succeeded.
1105 if slot is not None:
1107 self.block_cache.cap_cache()
1109 # Q: Including 403 is necessary for the Keep tests to continue
1110 # passing, but maybe they should expect KeepReadError instead?
1111 not_founds = sum(1 for key in sorted_roots
1112 if roots_map[key].last_result().get('status_code', None) in {403, 404, 410})
1113 service_errors = ((key, roots_map[key].last_result()['error'])
1114 for key in sorted_roots)
1116 raise arvados.errors.KeepReadError(
1117 "failed to read {}: no Keep services available ({})".format(
1118 loc_s, loop.last_result()))
1119 elif not_founds == len(sorted_roots):
1120 raise arvados.errors.NotFoundError(
1121 "{} not found".format(loc_s), service_errors)
1123 raise arvados.errors.KeepReadError(
1124 "failed to read {} after {}".format(loc_s, loop.attempts_str()), service_errors, label="service")
1127 def put(self, data, copies=2, num_retries=None, request_id=None):
1128 """Save data in Keep.
1130 This method will get a list of Keep services from the API server, and
1131 send the data to each one simultaneously in a new thread. Once the
1132 uploads are finished, if enough copies are saved, this method returns
1133 the most recent HTTP response body. If requests fail to upload
1134 enough copies, this method raises KeepWriteError.
1137 * data: The string of data to upload.
1138 * copies: The number of copies that the user requires be saved.
1140 * num_retries: The number of times to retry PUT requests to
1141 *each* Keep server if it returns temporary failures, with
1142 exponential backoff. The default value is set when the
1143 KeepClient is initialized.
1146 if not isinstance(data, bytes):
1147 data = data.encode()
1149 self.put_counter.add(1)
1151 data_hash = hashlib.md5(data).hexdigest()
1152 loc_s = data_hash + '+' + str(len(data))
1155 locator = KeepLocator(loc_s)
1158 'X-Request-Id': (request_id or
1159 (hasattr(self, 'api_client') and self.api_client.request_id) or
1160 arvados.util.new_request_id()),
1161 'X-Keep-Desired-Replicas': str(copies),
1164 loop = retry.RetryLoop(num_retries, self._check_loop_result,
1167 for tries_left in loop:
1169 sorted_roots = self.map_new_services(
1171 force_rebuild=(tries_left < num_retries),
1174 except Exception as error:
1175 loop.save_result(error)
1178 writer_pool = KeepClient.KeepWriterThreadPool(data=data,
1179 data_hash=data_hash,
1180 copies=copies - done,
1181 max_service_replicas=self.max_replicas_per_service,
1182 timeout=self.current_timeout(num_retries - tries_left))
1183 for service_root, ks in [(root, roots_map[root])
1184 for root in sorted_roots]:
1187 writer_pool.add_task(ks, service_root)
1189 done += writer_pool.done()
1190 loop.save_result((done >= copies, writer_pool.total_task_nr))
1193 return writer_pool.response()
1195 raise arvados.errors.KeepWriteError(
1196 "failed to write {}: no Keep services available ({})".format(
1197 data_hash, loop.last_result()))
1199 service_errors = ((key, roots_map[key].last_result()['error'])
1200 for key in sorted_roots
1201 if roots_map[key].last_result()['error'])
1202 raise arvados.errors.KeepWriteError(
1203 "failed to write {} after {} (wanted {} copies but wrote {})".format(
1204 data_hash, loop.attempts_str(), copies, writer_pool.done()), service_errors, label="service")
1206 def local_store_put(self, data, copies=1, num_retries=None):
1207 """A stub for put().
1209 This method is used in place of the real put() method when
1210 using local storage (see constructor's local_store argument).
1212 copies and num_retries arguments are ignored: they are here
1213 only for the sake of offering the same call signature as
1216 Data stored this way can be retrieved via local_store_get().
1218 md5 = hashlib.md5(data).hexdigest()
1219 locator = '%s+%d' % (md5, len(data))
1220 with open(os.path.join(self.local_store, md5 + '.tmp'), 'wb') as f:
1222 os.rename(os.path.join(self.local_store, md5 + '.tmp'),
1223 os.path.join(self.local_store, md5))
1226 def local_store_get(self, loc_s, num_retries=None):
1227 """Companion to local_store_put()."""
1229 locator = KeepLocator(loc_s)
1231 raise arvados.errors.NotFoundError(
1232 "Invalid data locator: '%s'" % loc_s)
1233 if locator.md5sum == config.EMPTY_BLOCK_LOCATOR.split('+')[0]:
1235 with open(os.path.join(self.local_store, locator.md5sum), 'rb') as f:
1238 def local_store_head(self, loc_s, num_retries=None):
1239 """Companion to local_store_put()."""
1241 locator = KeepLocator(loc_s)
1243 raise arvados.errors.NotFoundError(
1244 "Invalid data locator: '%s'" % loc_s)
1245 if locator.md5sum == config.EMPTY_BLOCK_LOCATOR.split('+')[0]:
1247 if os.path.exists(os.path.join(self.local_store, locator.md5sum)):
1250 def is_cached(self, locator):
1251 return self.block_cache.reserve_cache(expect_hash)