1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // Package keepclient provides low-level Get/Put primitives for accessing
6 // Arvados Keep blocks.
28 "git.arvados.org/arvados.git/sdk/go/arvados"
29 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
30 "git.arvados.org/arvados.git/sdk/go/httpserver"
33 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
34 const BLOCKSIZE = 64 * 1024 * 1024
37 DefaultRequestTimeout = 20 * time.Second
38 DefaultConnectTimeout = 2 * time.Second
39 DefaultTLSHandshakeTimeout = 4 * time.Second
40 DefaultKeepAlive = 180 * time.Second
42 DefaultProxyRequestTimeout = 300 * time.Second
43 DefaultProxyConnectTimeout = 30 * time.Second
44 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
45 DefaultProxyKeepAlive = 120 * time.Second
47 DefaultRetryDelay = 2 * time.Second // see KeepClient.RetryDelay
48 MinimumRetryDelay = time.Millisecond
50 rootCacheDir = "/var/cache/arvados/keep"
51 userCacheDir = ".cache/arvados/keep" // relative to HOME
54 // Error interface with an error and boolean indicating whether the error is temporary
55 type Error interface {
60 // multipleResponseError is of type Error
61 type multipleResponseError struct {
66 func (e *multipleResponseError) Temporary() bool {
70 // BlockNotFound is a multipleResponseError where isTemp is false
71 var BlockNotFound = &ErrNotFound{multipleResponseError{
72 error: errors.New("Block not found"),
76 // ErrNotFound is a multipleResponseError where isTemp can be true or false
77 type ErrNotFound struct {
81 func (*ErrNotFound) HTTPStatus() int { return http.StatusNotFound }
83 type InsufficientReplicasError struct{ error }
85 type OversizeBlockError struct{ error }
87 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
88 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
89 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
90 var InvalidLocatorError = errors.New("Invalid locator")
92 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
93 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
95 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
96 var ErrIncompleteIndex = errors.New("Got incomplete index")
99 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
100 XKeepReplicasStored = "X-Keep-Replicas-Stored"
101 XKeepStorageClasses = "X-Keep-Storage-Classes"
102 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
103 XKeepSignature = "X-Keep-Signature"
104 XKeepLocator = "X-Keep-Locator"
107 type HTTPClient interface {
108 Do(*http.Request) (*http.Response, error)
111 const DiskCacheDisabled = arvados.ByteSizeOrPercent(1)
113 // KeepClient holds information about Arvados and Keep servers.
114 type KeepClient struct {
115 Arvados *arvadosclient.ArvadosClient
117 localRoots map[string]string
118 writableLocalRoots map[string]string
119 gatewayRoots map[string]string
121 HTTPClient HTTPClient
123 // Number of times to automatically retry a read/write
124 // operation after a transient failure.
127 // Initial maximum delay for automatic retry. If zero,
128 // DefaultRetryDelay is used. The delay after attempt N
129 // (0-based) will be a random duration between
130 // MinimumRetryDelay and RetryDelay * 2^N, not to exceed a cap
131 // of RetryDelay * 10.
132 RetryDelay time.Duration
135 StorageClasses []string
136 DefaultStorageClasses []string // Set by cluster's exported config
137 DiskCacheSize arvados.ByteSizeOrPercent // See also DiskCacheDisabled
139 // set to 1 if all writable services are of disk type, otherwise 0
140 replicasPerService int
142 // Any non-disk typed services found in the list of keepservers?
145 // Disable automatic discovery of keep services
146 disableDiscovery bool
148 gatewayStack arvados.KeepGateway
151 func (kc *KeepClient) Clone() *KeepClient {
153 defer kc.lock.Unlock()
156 Want_replicas: kc.Want_replicas,
157 localRoots: kc.localRoots,
158 writableLocalRoots: kc.writableLocalRoots,
159 gatewayRoots: kc.gatewayRoots,
160 HTTPClient: kc.HTTPClient,
162 RetryDelay: kc.RetryDelay,
163 RequestID: kc.RequestID,
164 StorageClasses: kc.StorageClasses,
165 DefaultStorageClasses: kc.DefaultStorageClasses,
166 DiskCacheSize: kc.DiskCacheSize,
167 replicasPerService: kc.replicasPerService,
168 foundNonDiskSvc: kc.foundNonDiskSvc,
169 disableDiscovery: kc.disableDiscovery,
173 func (kc *KeepClient) loadDefaultClasses() error {
174 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
178 classes := scData.(map[string]interface{})
179 for scName := range classes {
180 scConf, _ := classes[scName].(map[string]interface{})
181 isDefault, ok := scConf["Default"].(bool)
183 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
189 // MakeKeepClient creates a new KeepClient, loads default storage
190 // classes, calls discoverServices(), and returns when the client is
192 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
194 return kc, kc.discoverServices()
197 // New creates a new KeepClient. Service discovery will occur on the
198 // next read/write operation.
199 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
200 defaultReplicationLevel := 2
201 value, err := arv.Discovery("defaultCollectionReplication")
203 v, ok := value.(float64)
205 defaultReplicationLevel = int(v)
210 Want_replicas: defaultReplicationLevel,
213 err = kc.loadDefaultClasses()
214 if err != nil && arv.Logger != nil {
215 arv.Logger.WithError(err).Debug("unable to load the default storage classes cluster config")
220 // PutHR puts a block given the block hash, a reader, and the number of bytes
221 // to read from the reader (which must be between 0 and BLOCKSIZE).
223 // Returns the locator for the written block, the number of replicas
224 // written, and an error.
226 // Returns an InsufficientReplicasError if 0 <= replicas <
227 // kc.Wants_replicas.
228 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
229 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
232 DataSize: int(dataBytes),
234 return resp.Locator, resp.Replicas, err
237 // PutHB writes a block to Keep. The hash of the bytes is given in
238 // hash, and the data is given in buf.
240 // Return values are the same as for PutHR.
241 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
242 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
246 return resp.Locator, resp.Replicas, err
249 // PutB writes a block to Keep. It computes the hash itself.
251 // Return values are the same as for PutHR.
252 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
253 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
256 return resp.Locator, resp.Replicas, err
259 // PutR writes a block to Keep. It first reads all data from r into a buffer
260 // in order to compute the hash.
262 // Return values are the same as for PutHR.
264 // If the block hash and data size are known, PutHR is more efficient.
265 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
266 buffer, err := ioutil.ReadAll(r)
270 return kc.PutB(buffer)
273 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
274 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
275 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
278 reqid := kc.getRequestID()
280 var expectLength int64
281 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
283 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
291 delay := delayCalculator{InitialMaxDelay: kc.RetryDelay}
292 triesRemaining := 1 + kc.Retries
294 serversToTry := kc.getSortedRoots(locator)
296 numServers := len(serversToTry)
299 var retryList []string
301 for triesRemaining > 0 {
305 for _, host := range serversToTry {
306 url := host + "/" + locator
308 req, err := http.NewRequest(method, url, nil)
310 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
313 for k, v := range header {
314 req.Header[k] = append([]string(nil), v...)
316 if req.Header.Get("Authorization") == "" {
317 req.Header.Set("Authorization", "Bearer "+kc.Arvados.ApiToken)
319 if req.Header.Get("X-Request-Id") == "" {
320 req.Header.Set("X-Request-Id", reqid)
322 resp, err := kc.httpClient().Do(req)
324 // Probably a network error, may be transient,
326 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
327 retryList = append(retryList, host)
330 if resp.StatusCode != http.StatusOK {
332 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
334 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
335 url, resp.StatusCode, bytes.TrimSpace(respbody)))
337 if resp.StatusCode == 408 ||
338 resp.StatusCode == 429 ||
339 resp.StatusCode >= 500 {
340 // Timeout, too many requests, or other
341 // server side failure, transient
342 // error, can try again.
343 retryList = append(retryList, host)
344 } else if resp.StatusCode == 404 {
349 if expectLength < 0 {
350 if resp.ContentLength < 0 {
352 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
354 expectLength = resp.ContentLength
355 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
357 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
361 return HashCheckingReader{
364 Check: locator[0:32],
365 }, expectLength, url, resp.Header, nil
368 return nil, expectLength, url, resp.Header, nil
370 serversToTry = retryList
371 if len(serversToTry) > 0 && triesRemaining > 0 {
372 time.Sleep(delay.Next())
375 if kc.Arvados.Logger != nil {
376 kc.Arvados.Logger.Debugf("DEBUG: %s %s failed: %v", method, locator, errs)
380 if count404 == numServers {
383 err = &ErrNotFound{multipleResponseError{
384 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
385 isTemp: len(serversToTry) > 0,
388 return nil, 0, "", nil, err
391 // attempt to create dir/subdir/ and its parents, up to but not
392 // including dir itself, using mode 0700.
393 func makedirs(dir, subdir string) {
394 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
395 dir = filepath.Join(dir, part)
400 // upstreamGateway creates/returns the KeepGateway stack used to read
401 // and write data: a disk-backed cache on top of an http backend.
402 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
404 defer kc.lock.Unlock()
405 if kc.gatewayStack != nil {
406 return kc.gatewayStack
409 if os.Geteuid() == 0 {
410 cachedir = rootCacheDir
411 makedirs("/", cachedir)
413 home := "/" + os.Getenv("HOME")
414 makedirs(home, userCacheDir)
415 cachedir = filepath.Join(home, userCacheDir)
417 backend := &keepViaHTTP{kc}
418 if kc.DiskCacheSize == DiskCacheDisabled {
419 kc.gatewayStack = backend
421 kc.gatewayStack = &arvados.DiskCache{
423 MaxSize: kc.DiskCacheSize,
424 KeepGateway: backend,
425 Logger: kc.Arvados.Logger,
428 return kc.gatewayStack
431 // LocalLocator returns a locator equivalent to the one supplied, but
432 // with a valid signature from the local cluster. If the given locator
433 // already has a local signature, it is returned unchanged.
434 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
435 return kc.upstreamGateway().LocalLocator(locator)
438 // Get retrieves the specified block from the local cache or a backend
439 // server. Returns a reader, the expected data length (or -1 if not
440 // known), and an error.
442 // The third return value (formerly a source URL in previous versions)
443 // is an empty string.
445 // If the block checksum does not match, the final Read() on the
446 // reader returned by this method will return a BadChecksum error
449 // New code should use BlockRead and/or ReadAt instead of Get.
450 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
451 loc, err := MakeLocator(locator)
453 return nil, 0, "", err
457 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
462 pw.CloseWithError(err)
463 } else if loc.Size >= 0 && n != loc.Size {
464 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
469 // Wait for the first byte to arrive, so that, if there's an
470 // error before we receive any data, we can return the error
471 // directly, instead of indirectly via a reader that returns
473 bufr := bufio.NewReader(pr)
474 _, err = bufr.Peek(1)
475 if err != nil && err != io.EOF {
476 pr.CloseWithError(err)
477 return nil, 0, "", err
479 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
480 // In the special case of the zero-length block, EOF
481 // error from Peek() is normal.
482 return pr, 0, "", nil
490 }, int64(loc.Size), "", err
493 // BlockRead retrieves a block from the cache if it's present, otherwise
495 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
496 return kc.upstreamGateway().BlockRead(ctx, opts)
499 // ReadAt retrieves a portion of block from the cache if it's
500 // present, otherwise from the network.
501 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
502 return kc.upstreamGateway().ReadAt(locator, p, off)
505 // BlockWrite writes a full block to upstream servers and saves a copy
506 // in the local cache.
507 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
508 return kc.upstreamGateway().BlockWrite(ctx, req)
511 // Ask verifies that a block with the given hash is available and
512 // readable, according to at least one Keep service. Unlike Get, it
513 // does not retrieve the data or verify that the data content matches
514 // the hash specified by the locator.
516 // Returns the data size (content length) reported by the Keep service
517 // and the URI reporting the data size.
518 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
519 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
520 return size, url, err
523 // GetIndex retrieves a list of blocks stored on the given server whose hashes
524 // begin with the given prefix. The returned reader will return an error (other
525 // than EOF) if the complete index cannot be retrieved.
527 // This is meant to be used only by system components and admin tools.
528 // It will return an error unless the client is using a "data manager token"
529 // recognized by the Keep services.
530 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
531 url := kc.LocalRoots()[keepServiceUUID]
533 return nil, ErrNoSuchKeepServer
541 req, err := http.NewRequest("GET", url, nil)
546 req.Header.Add("Authorization", "Bearer "+kc.Arvados.ApiToken)
547 req.Header.Set("X-Request-Id", kc.getRequestID())
548 resp, err := kc.httpClient().Do(req)
553 defer resp.Body.Close()
555 if resp.StatusCode != http.StatusOK {
556 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
560 respBody, err = ioutil.ReadAll(resp.Body)
565 // Got index; verify that it is complete
566 // The response should be "\n" if no locators matched the prefix
567 // Else, it should be a list of locators followed by a blank line
568 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
569 return nil, ErrIncompleteIndex
572 // Got complete index; strip the trailing newline and send
573 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
576 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
577 // services: uuid -> baseURI.
578 func (kc *KeepClient) LocalRoots() map[string]string {
579 kc.discoverServices()
581 defer kc.lock.RUnlock()
585 // GatewayRoots returns the map of Keep remote gateway services:
587 func (kc *KeepClient) GatewayRoots() map[string]string {
588 kc.discoverServices()
590 defer kc.lock.RUnlock()
591 return kc.gatewayRoots
594 // WritableLocalRoots returns the map of writable local Keep services:
596 func (kc *KeepClient) WritableLocalRoots() map[string]string {
597 kc.discoverServices()
599 defer kc.lock.RUnlock()
600 return kc.writableLocalRoots
603 // SetServiceRoots disables service discovery and updates the
604 // localRoots and gatewayRoots maps, without disrupting operations
605 // that are already in progress.
607 // The supplied maps must not be modified after calling
609 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
610 kc.disableDiscovery = true
611 kc.setServiceRoots(locals, writables, gateways)
614 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
616 defer kc.lock.Unlock()
617 kc.localRoots = locals
618 kc.writableLocalRoots = writables
619 kc.gatewayRoots = gateways
622 // getSortedRoots returns a list of base URIs of Keep services, in the
623 // order they should be attempted in order to retrieve content for the
625 func (kc *KeepClient) getSortedRoots(locator string) []string {
627 for _, hint := range strings.Split(locator, "+") {
628 if len(hint) < 7 || hint[0:2] != "K@" {
629 // Not a service hint.
633 // +K@abcde means fetch from proxy at
634 // keep.abcde.arvadosapi.com
635 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
636 } else if len(hint) == 29 {
637 // +K@abcde-abcde-abcdeabcdeabcde means fetch
638 // from gateway with given uuid
639 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
640 found = append(found, gwURI)
642 // else this hint is no use to us; carry on.
645 // After trying all usable service hints, fall back to local roots.
646 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
650 func (kc *KeepClient) SetStorageClasses(sc []string) {
651 // make a copy so the caller can't mess with it.
652 kc.StorageClasses = append([]string{}, sc...)
656 // There are four global http.Client objects for the four
657 // possible permutations of TLS behavior (verify/skip-verify)
658 // and timeout settings (proxy/non-proxy).
659 defaultClient = map[bool]map[bool]HTTPClient{
660 // defaultClient[false] is used for verified TLS reqs
662 // defaultClient[true] is used for unverified
663 // (insecure) TLS reqs
666 defaultClientMtx sync.Mutex
669 // httpClient returns the HTTPClient field if it's not nil, otherwise
670 // whichever of the four global http.Client objects is suitable for
671 // the current environment (i.e., TLS verification on/off, keep
672 // services are/aren't proxies).
673 func (kc *KeepClient) httpClient() HTTPClient {
674 if kc.HTTPClient != nil {
677 defaultClientMtx.Lock()
678 defer defaultClientMtx.Unlock()
679 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
683 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
684 if kc.foundNonDiskSvc {
685 // Use longer timeouts when connecting to a proxy,
686 // because this usually means the intervening network
688 requestTimeout = DefaultProxyRequestTimeout
689 connectTimeout = DefaultProxyConnectTimeout
690 tlsTimeout = DefaultProxyTLSHandshakeTimeout
691 keepAlive = DefaultProxyKeepAlive
693 requestTimeout = DefaultRequestTimeout
694 connectTimeout = DefaultConnectTimeout
695 tlsTimeout = DefaultTLSHandshakeTimeout
696 keepAlive = DefaultKeepAlive
700 Timeout: requestTimeout,
701 // It's not safe to copy *http.DefaultTransport
702 // because it has a mutex (which might be locked)
703 // protecting a private map (which might not be nil).
704 // So we build our own, using the Go 1.12 default
705 // values, ignoring any changes the application has
706 // made to http.DefaultTransport.
707 Transport: &http.Transport{
708 DialContext: (&net.Dialer{
709 Timeout: connectTimeout,
710 KeepAlive: keepAlive,
714 IdleConnTimeout: 90 * time.Second,
715 TLSHandshakeTimeout: tlsTimeout,
716 ExpectContinueTimeout: 1 * time.Second,
717 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
720 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
724 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
726 func (kc *KeepClient) getRequestID() string {
727 if kc.RequestID != "" {
730 return reqIDGen.Next()
733 func (kc *KeepClient) debugf(format string, args ...interface{}) {
734 if kc.Arvados.Logger == nil {
737 kc.Arvados.Logger.Debugf(format, args...)
740 type Locator struct {
742 Size int // -1 if data size is not known
743 Hints []string // Including the size hint, if any
746 func (loc *Locator) String() string {
748 if len(loc.Hints) > 0 {
749 s = s + "+" + strings.Join(loc.Hints, "+")
754 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
756 func MakeLocator(path string) (*Locator, error) {
757 sm := locatorMatcher.FindStringSubmatch(path)
759 return nil, InvalidLocatorError
761 loc := Locator{Hash: sm[1], Size: -1}
763 loc.Hints = strings.Split(sm[3], "+")
765 loc.Hints = []string{}
767 if len(loc.Hints) > 0 {
768 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {