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.
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
31 "git.arvados.org/arvados.git/sdk/go/httpserver"
34 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
35 const BLOCKSIZE = 64 * 1024 * 1024
38 DefaultRequestTimeout = 20 * time.Second
39 DefaultConnectTimeout = 2 * time.Second
40 DefaultTLSHandshakeTimeout = 4 * time.Second
41 DefaultKeepAlive = 180 * time.Second
43 DefaultProxyRequestTimeout = 300 * time.Second
44 DefaultProxyConnectTimeout = 30 * time.Second
45 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
46 DefaultProxyKeepAlive = 120 * time.Second
48 DefaultRetryDelay = 2 * time.Second // see KeepClient.RetryDelay
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 type InsufficientReplicasError struct{ error }
83 type OversizeBlockError struct{ error }
85 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
86 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
87 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
88 var InvalidLocatorError = errors.New("Invalid locator")
90 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
91 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
93 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
94 var ErrIncompleteIndex = errors.New("Got incomplete index")
97 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
98 XKeepReplicasStored = "X-Keep-Replicas-Stored"
99 XKeepStorageClasses = "X-Keep-Storage-Classes"
100 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
103 type HTTPClient interface {
104 Do(*http.Request) (*http.Response, error)
107 const DiskCacheDisabled = arvados.ByteSizeOrPercent(1)
109 // KeepClient holds information about Arvados and Keep servers.
110 type KeepClient struct {
111 Arvados *arvadosclient.ArvadosClient
113 localRoots map[string]string
114 writableLocalRoots map[string]string
115 gatewayRoots map[string]string
117 HTTPClient HTTPClient
119 // Number of times to automatically retry a read/write
120 // operation after a transient failure.
123 // Initial delay after first attempt, used when automatic
124 // retry is invoked. If zero, DefaultRetryDelay is used.
125 // Delays after subsequent attempts are increased by a random
126 // factor between 1.75x and 2x, up to a maximum of 10x the
128 RetryDelay time.Duration
131 StorageClasses []string
132 DefaultStorageClasses []string // Set by cluster's exported config
133 DiskCacheSize arvados.ByteSizeOrPercent // See also DiskCacheDisabled
135 // set to 1 if all writable services are of disk type, otherwise 0
136 replicasPerService int
138 // Any non-disk typed services found in the list of keepservers?
141 // Disable automatic discovery of keep services
142 disableDiscovery bool
144 gatewayStack arvados.KeepGateway
147 func (kc *KeepClient) Clone() *KeepClient {
149 defer kc.lock.Unlock()
152 Want_replicas: kc.Want_replicas,
153 localRoots: kc.localRoots,
154 writableLocalRoots: kc.writableLocalRoots,
155 gatewayRoots: kc.gatewayRoots,
156 HTTPClient: kc.HTTPClient,
158 RetryDelay: kc.RetryDelay,
159 RequestID: kc.RequestID,
160 StorageClasses: kc.StorageClasses,
161 DefaultStorageClasses: kc.DefaultStorageClasses,
162 DiskCacheSize: kc.DiskCacheSize,
163 replicasPerService: kc.replicasPerService,
164 foundNonDiskSvc: kc.foundNonDiskSvc,
165 disableDiscovery: kc.disableDiscovery,
169 func (kc *KeepClient) loadDefaultClasses() error {
170 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
174 classes := scData.(map[string]interface{})
175 for scName := range classes {
176 scConf, _ := classes[scName].(map[string]interface{})
177 isDefault, ok := scConf["Default"].(bool)
179 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
185 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
186 // DiscoverKeepServices(), and returns when the client is ready to
188 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
190 return kc, kc.discoverServices()
193 // New creates a new KeepClient. Service discovery will occur on the
194 // next read/write operation.
195 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
196 defaultReplicationLevel := 2
197 value, err := arv.Discovery("defaultCollectionReplication")
199 v, ok := value.(float64)
201 defaultReplicationLevel = int(v)
206 Want_replicas: defaultReplicationLevel,
209 err = kc.loadDefaultClasses()
211 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
216 // PutHR puts a block given the block hash, a reader, and the number of bytes
217 // to read from the reader (which must be between 0 and BLOCKSIZE).
219 // Returns the locator for the written block, the number of replicas
220 // written, and an error.
222 // Returns an InsufficientReplicasError if 0 <= replicas <
223 // kc.Wants_replicas.
224 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
225 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
228 DataSize: int(dataBytes),
230 return resp.Locator, resp.Replicas, err
233 // PutHB writes a block to Keep. The hash of the bytes is given in
234 // hash, and the data is given in buf.
236 // Return values are the same as for PutHR.
237 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
238 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
242 return resp.Locator, resp.Replicas, err
245 // PutB writes a block to Keep. It computes the hash itself.
247 // Return values are the same as for PutHR.
248 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
249 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
252 return resp.Locator, resp.Replicas, err
255 // PutR writes a block to Keep. It first reads all data from r into a buffer
256 // in order to compute the hash.
258 // Return values are the same as for PutHR.
260 // If the block hash and data size are known, PutHR is more efficient.
261 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
262 buffer, err := ioutil.ReadAll(r)
266 return kc.PutB(buffer)
269 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
270 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
271 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
274 reqid := kc.getRequestID()
276 var expectLength int64
277 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
279 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
287 retryDelay := kc.RetryDelay
289 retryDelay = DefaultRetryDelay
291 maxRetryDelay := retryDelay * 10
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", "OAuth2 "+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(retryDelay)
373 // Increase delay by a random factor between
375 retryDelay = time.Duration((2 - rand.Float64()/4) * float64(retryDelay))
376 if retryDelay > maxRetryDelay {
377 retryDelay = maxRetryDelay
381 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
384 if count404 == numServers {
387 err = &ErrNotFound{multipleResponseError{
388 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
389 isTemp: len(serversToTry) > 0,
392 return nil, 0, "", nil, err
395 // attempt to create dir/subdir/ and its parents, up to but not
396 // including dir itself, using mode 0700.
397 func makedirs(dir, subdir string) {
398 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
399 dir = filepath.Join(dir, part)
404 // upstreamGateway creates/returns the KeepGateway stack used to read
405 // and write data: a disk-backed cache on top of an http backend.
406 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
408 defer kc.lock.Unlock()
409 if kc.gatewayStack != nil {
410 return kc.gatewayStack
413 if os.Geteuid() == 0 {
414 cachedir = rootCacheDir
415 makedirs("/", cachedir)
417 home := "/" + os.Getenv("HOME")
418 makedirs(home, userCacheDir)
419 cachedir = filepath.Join(home, userCacheDir)
421 backend := &keepViaHTTP{kc}
422 if kc.DiskCacheSize == DiskCacheDisabled {
423 kc.gatewayStack = backend
425 kc.gatewayStack = &arvados.DiskCache{
427 MaxSize: kc.DiskCacheSize,
428 KeepGateway: backend,
431 return kc.gatewayStack
434 // LocalLocator returns a locator equivalent to the one supplied, but
435 // with a valid signature from the local cluster. If the given locator
436 // already has a local signature, it is returned unchanged.
437 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
438 return kc.upstreamGateway().LocalLocator(locator)
441 // Get retrieves the specified block from the local cache or a backend
442 // server. Returns a reader, the expected data length (or -1 if not
443 // known), and an error.
445 // The third return value (formerly a source URL in previous versions)
446 // is an empty string.
448 // If the block checksum does not match, the final Read() on the
449 // reader returned by this method will return a BadChecksum error
452 // New code should use BlockRead and/or ReadAt instead of Get.
453 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
454 loc, err := MakeLocator(locator)
456 return nil, 0, "", err
460 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
465 pw.CloseWithError(err)
466 } else if loc.Size >= 0 && n != loc.Size {
467 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
472 // Wait for the first byte to arrive, so that, if there's an
473 // error before we receive any data, we can return the error
474 // directly, instead of indirectly via a reader that returns
476 bufr := bufio.NewReader(pr)
477 _, err = bufr.Peek(1)
478 if err != nil && err != io.EOF {
479 pr.CloseWithError(err)
480 return nil, 0, "", err
482 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
483 // In the special case of the zero-length block, EOF
484 // error from Peek() is normal.
485 return pr, 0, "", nil
493 }, int64(loc.Size), "", err
496 // BlockRead retrieves a block from the cache if it's present, otherwise
498 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
499 return kc.upstreamGateway().BlockRead(ctx, opts)
502 // ReadAt retrieves a portion of block from the cache if it's
503 // present, otherwise from the network.
504 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
505 return kc.upstreamGateway().ReadAt(locator, p, off)
508 // BlockWrite writes a full block to upstream servers and saves a copy
509 // in the local cache.
510 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
511 return kc.upstreamGateway().BlockWrite(ctx, req)
514 // Ask verifies that a block with the given hash is available and
515 // readable, according to at least one Keep service. Unlike Get, it
516 // does not retrieve the data or verify that the data content matches
517 // the hash specified by the locator.
519 // Returns the data size (content length) reported by the Keep service
520 // and the URI reporting the data size.
521 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
522 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
523 return size, url, err
526 // GetIndex retrieves a list of blocks stored on the given server whose hashes
527 // begin with the given prefix. The returned reader will return an error (other
528 // than EOF) if the complete index cannot be retrieved.
530 // This is meant to be used only by system components and admin tools.
531 // It will return an error unless the client is using a "data manager token"
532 // recognized by the Keep services.
533 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
534 url := kc.LocalRoots()[keepServiceUUID]
536 return nil, ErrNoSuchKeepServer
544 req, err := http.NewRequest("GET", url, nil)
549 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
550 req.Header.Set("X-Request-Id", kc.getRequestID())
551 resp, err := kc.httpClient().Do(req)
556 defer resp.Body.Close()
558 if resp.StatusCode != http.StatusOK {
559 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
563 respBody, err = ioutil.ReadAll(resp.Body)
568 // Got index; verify that it is complete
569 // The response should be "\n" if no locators matched the prefix
570 // Else, it should be a list of locators followed by a blank line
571 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
572 return nil, ErrIncompleteIndex
575 // Got complete index; strip the trailing newline and send
576 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
579 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
580 // services: uuid -> baseURI.
581 func (kc *KeepClient) LocalRoots() map[string]string {
582 kc.discoverServices()
584 defer kc.lock.RUnlock()
588 // GatewayRoots returns the map of Keep remote gateway services:
590 func (kc *KeepClient) GatewayRoots() map[string]string {
591 kc.discoverServices()
593 defer kc.lock.RUnlock()
594 return kc.gatewayRoots
597 // WritableLocalRoots returns the map of writable local Keep services:
599 func (kc *KeepClient) WritableLocalRoots() map[string]string {
600 kc.discoverServices()
602 defer kc.lock.RUnlock()
603 return kc.writableLocalRoots
606 // SetServiceRoots disables service discovery and updates the
607 // localRoots and gatewayRoots maps, without disrupting operations
608 // that are already in progress.
610 // The supplied maps must not be modified after calling
612 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
613 kc.disableDiscovery = true
614 kc.setServiceRoots(locals, writables, gateways)
617 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
619 defer kc.lock.Unlock()
620 kc.localRoots = locals
621 kc.writableLocalRoots = writables
622 kc.gatewayRoots = gateways
625 // getSortedRoots returns a list of base URIs of Keep services, in the
626 // order they should be attempted in order to retrieve content for the
628 func (kc *KeepClient) getSortedRoots(locator string) []string {
630 for _, hint := range strings.Split(locator, "+") {
631 if len(hint) < 7 || hint[0:2] != "K@" {
632 // Not a service hint.
636 // +K@abcde means fetch from proxy at
637 // keep.abcde.arvadosapi.com
638 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
639 } else if len(hint) == 29 {
640 // +K@abcde-abcde-abcdeabcdeabcde means fetch
641 // from gateway with given uuid
642 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
643 found = append(found, gwURI)
645 // else this hint is no use to us; carry on.
648 // After trying all usable service hints, fall back to local roots.
649 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
653 func (kc *KeepClient) SetStorageClasses(sc []string) {
654 // make a copy so the caller can't mess with it.
655 kc.StorageClasses = append([]string{}, sc...)
659 // There are four global http.Client objects for the four
660 // possible permutations of TLS behavior (verify/skip-verify)
661 // and timeout settings (proxy/non-proxy).
662 defaultClient = map[bool]map[bool]HTTPClient{
663 // defaultClient[false] is used for verified TLS reqs
665 // defaultClient[true] is used for unverified
666 // (insecure) TLS reqs
669 defaultClientMtx sync.Mutex
672 // httpClient returns the HTTPClient field if it's not nil, otherwise
673 // whichever of the four global http.Client objects is suitable for
674 // the current environment (i.e., TLS verification on/off, keep
675 // services are/aren't proxies).
676 func (kc *KeepClient) httpClient() HTTPClient {
677 if kc.HTTPClient != nil {
680 defaultClientMtx.Lock()
681 defer defaultClientMtx.Unlock()
682 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
686 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
687 if kc.foundNonDiskSvc {
688 // Use longer timeouts when connecting to a proxy,
689 // because this usually means the intervening network
691 requestTimeout = DefaultProxyRequestTimeout
692 connectTimeout = DefaultProxyConnectTimeout
693 tlsTimeout = DefaultProxyTLSHandshakeTimeout
694 keepAlive = DefaultProxyKeepAlive
696 requestTimeout = DefaultRequestTimeout
697 connectTimeout = DefaultConnectTimeout
698 tlsTimeout = DefaultTLSHandshakeTimeout
699 keepAlive = DefaultKeepAlive
703 Timeout: requestTimeout,
704 // It's not safe to copy *http.DefaultTransport
705 // because it has a mutex (which might be locked)
706 // protecting a private map (which might not be nil).
707 // So we build our own, using the Go 1.12 default
708 // values, ignoring any changes the application has
709 // made to http.DefaultTransport.
710 Transport: &http.Transport{
711 DialContext: (&net.Dialer{
712 Timeout: connectTimeout,
713 KeepAlive: keepAlive,
717 IdleConnTimeout: 90 * time.Second,
718 TLSHandshakeTimeout: tlsTimeout,
719 ExpectContinueTimeout: 1 * time.Second,
720 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
723 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
727 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
729 func (kc *KeepClient) getRequestID() string {
730 if kc.RequestID != "" {
733 return reqIDGen.Next()
736 type Locator struct {
738 Size int // -1 if data size is not known
739 Hints []string // Including the size hint, if any
742 func (loc *Locator) String() string {
744 if len(loc.Hints) > 0 {
745 s = s + "+" + strings.Join(loc.Hints, "+")
750 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
752 func MakeLocator(path string) (*Locator, error) {
753 sm := locatorMatcher.FindStringSubmatch(path)
755 return nil, InvalidLocatorError
757 loc := Locator{Hash: sm[1], Size: -1}
759 loc.Hints = strings.Split(sm[3], "+")
761 loc.Hints = []string{}
763 if len(loc.Hints) > 0 {
764 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {