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"
105 type HTTPClient interface {
106 Do(*http.Request) (*http.Response, error)
109 const DiskCacheDisabled = arvados.ByteSizeOrPercent(1)
111 // KeepClient holds information about Arvados and Keep servers.
112 type KeepClient struct {
113 Arvados *arvadosclient.ArvadosClient
115 localRoots map[string]string
116 writableLocalRoots map[string]string
117 gatewayRoots map[string]string
119 HTTPClient HTTPClient
121 // Number of times to automatically retry a read/write
122 // operation after a transient failure.
125 // Initial maximum delay for automatic retry. If zero,
126 // DefaultRetryDelay is used. The delay after attempt N
127 // (0-based) will be a random duration between
128 // MinimumRetryDelay and RetryDelay * 2^N, not to exceed a cap
129 // of RetryDelay * 10.
130 RetryDelay time.Duration
133 StorageClasses []string
134 DefaultStorageClasses []string // Set by cluster's exported config
135 DiskCacheSize arvados.ByteSizeOrPercent // See also DiskCacheDisabled
137 // set to 1 if all writable services are of disk type, otherwise 0
138 replicasPerService int
140 // Any non-disk typed services found in the list of keepservers?
143 // Disable automatic discovery of keep services
144 disableDiscovery bool
146 gatewayStack arvados.KeepGateway
149 func (kc *KeepClient) Clone() *KeepClient {
151 defer kc.lock.Unlock()
154 Want_replicas: kc.Want_replicas,
155 localRoots: kc.localRoots,
156 writableLocalRoots: kc.writableLocalRoots,
157 gatewayRoots: kc.gatewayRoots,
158 HTTPClient: kc.HTTPClient,
160 RetryDelay: kc.RetryDelay,
161 RequestID: kc.RequestID,
162 StorageClasses: kc.StorageClasses,
163 DefaultStorageClasses: kc.DefaultStorageClasses,
164 DiskCacheSize: kc.DiskCacheSize,
165 replicasPerService: kc.replicasPerService,
166 foundNonDiskSvc: kc.foundNonDiskSvc,
167 disableDiscovery: kc.disableDiscovery,
171 func (kc *KeepClient) loadDefaultClasses() error {
172 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
176 classes := scData.(map[string]interface{})
177 for scName := range classes {
178 scConf, _ := classes[scName].(map[string]interface{})
179 isDefault, ok := scConf["Default"].(bool)
181 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
187 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
188 // DiscoverKeepServices(), and returns when the client is ready to
190 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
192 return kc, kc.discoverServices()
195 // New creates a new KeepClient. Service discovery will occur on the
196 // next read/write operation.
197 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
198 defaultReplicationLevel := 2
199 value, err := arv.Discovery("defaultCollectionReplication")
201 v, ok := value.(float64)
203 defaultReplicationLevel = int(v)
208 Want_replicas: defaultReplicationLevel,
211 err = kc.loadDefaultClasses()
213 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
218 // PutHR puts a block given the block hash, a reader, and the number of bytes
219 // to read from the reader (which must be between 0 and BLOCKSIZE).
221 // Returns the locator for the written block, the number of replicas
222 // written, and an error.
224 // Returns an InsufficientReplicasError if 0 <= replicas <
225 // kc.Wants_replicas.
226 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
227 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
230 DataSize: int(dataBytes),
232 return resp.Locator, resp.Replicas, err
235 // PutHB writes a block to Keep. The hash of the bytes is given in
236 // hash, and the data is given in buf.
238 // Return values are the same as for PutHR.
239 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
240 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
244 return resp.Locator, resp.Replicas, err
247 // PutB writes a block to Keep. It computes the hash itself.
249 // Return values are the same as for PutHR.
250 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
251 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
254 return resp.Locator, resp.Replicas, err
257 // PutR writes a block to Keep. It first reads all data from r into a buffer
258 // in order to compute the hash.
260 // Return values are the same as for PutHR.
262 // If the block hash and data size are known, PutHR is more efficient.
263 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
264 buffer, err := ioutil.ReadAll(r)
268 return kc.PutB(buffer)
271 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
272 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
273 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
276 reqid := kc.getRequestID()
278 var expectLength int64
279 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
281 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
289 delay := delayCalculator{InitialMaxDelay: kc.RetryDelay}
290 triesRemaining := 1 + kc.Retries
292 serversToTry := kc.getSortedRoots(locator)
294 numServers := len(serversToTry)
297 var retryList []string
299 for triesRemaining > 0 {
303 for _, host := range serversToTry {
304 url := host + "/" + locator
306 req, err := http.NewRequest(method, url, nil)
308 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
311 for k, v := range header {
312 req.Header[k] = append([]string(nil), v...)
314 if req.Header.Get("Authorization") == "" {
315 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
317 if req.Header.Get("X-Request-Id") == "" {
318 req.Header.Set("X-Request-Id", reqid)
320 resp, err := kc.httpClient().Do(req)
322 // Probably a network error, may be transient,
324 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
325 retryList = append(retryList, host)
328 if resp.StatusCode != http.StatusOK {
330 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
332 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
333 url, resp.StatusCode, bytes.TrimSpace(respbody)))
335 if resp.StatusCode == 408 ||
336 resp.StatusCode == 429 ||
337 resp.StatusCode >= 500 {
338 // Timeout, too many requests, or other
339 // server side failure, transient
340 // error, can try again.
341 retryList = append(retryList, host)
342 } else if resp.StatusCode == 404 {
347 if expectLength < 0 {
348 if resp.ContentLength < 0 {
350 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
352 expectLength = resp.ContentLength
353 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
355 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
359 return HashCheckingReader{
362 Check: locator[0:32],
363 }, expectLength, url, resp.Header, nil
366 return nil, expectLength, url, resp.Header, nil
368 serversToTry = retryList
369 if len(serversToTry) > 0 && triesRemaining > 0 {
370 time.Sleep(delay.Next())
373 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
376 if count404 == numServers {
379 err = &ErrNotFound{multipleResponseError{
380 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
381 isTemp: len(serversToTry) > 0,
384 return nil, 0, "", nil, err
387 // attempt to create dir/subdir/ and its parents, up to but not
388 // including dir itself, using mode 0700.
389 func makedirs(dir, subdir string) {
390 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
391 dir = filepath.Join(dir, part)
396 // upstreamGateway creates/returns the KeepGateway stack used to read
397 // and write data: a disk-backed cache on top of an http backend.
398 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
400 defer kc.lock.Unlock()
401 if kc.gatewayStack != nil {
402 return kc.gatewayStack
405 if os.Geteuid() == 0 {
406 cachedir = rootCacheDir
407 makedirs("/", cachedir)
409 home := "/" + os.Getenv("HOME")
410 makedirs(home, userCacheDir)
411 cachedir = filepath.Join(home, userCacheDir)
413 backend := &keepViaHTTP{kc}
414 if kc.DiskCacheSize == DiskCacheDisabled {
415 kc.gatewayStack = backend
417 kc.gatewayStack = &arvados.DiskCache{
419 MaxSize: kc.DiskCacheSize,
420 KeepGateway: backend,
423 return kc.gatewayStack
426 // LocalLocator returns a locator equivalent to the one supplied, but
427 // with a valid signature from the local cluster. If the given locator
428 // already has a local signature, it is returned unchanged.
429 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
430 return kc.upstreamGateway().LocalLocator(locator)
433 // Get retrieves the specified block from the local cache or a backend
434 // server. Returns a reader, the expected data length (or -1 if not
435 // known), and an error.
437 // The third return value (formerly a source URL in previous versions)
438 // is an empty string.
440 // If the block checksum does not match, the final Read() on the
441 // reader returned by this method will return a BadChecksum error
444 // New code should use BlockRead and/or ReadAt instead of Get.
445 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
446 loc, err := MakeLocator(locator)
448 return nil, 0, "", err
452 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
457 pw.CloseWithError(err)
458 } else if loc.Size >= 0 && n != loc.Size {
459 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
464 // Wait for the first byte to arrive, so that, if there's an
465 // error before we receive any data, we can return the error
466 // directly, instead of indirectly via a reader that returns
468 bufr := bufio.NewReader(pr)
469 _, err = bufr.Peek(1)
470 if err != nil && err != io.EOF {
471 pr.CloseWithError(err)
472 return nil, 0, "", err
474 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
475 // In the special case of the zero-length block, EOF
476 // error from Peek() is normal.
477 return pr, 0, "", nil
485 }, int64(loc.Size), "", err
488 // BlockRead retrieves a block from the cache if it's present, otherwise
490 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
491 return kc.upstreamGateway().BlockRead(ctx, opts)
494 // ReadAt retrieves a portion of block from the cache if it's
495 // present, otherwise from the network.
496 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
497 return kc.upstreamGateway().ReadAt(locator, p, off)
500 // BlockWrite writes a full block to upstream servers and saves a copy
501 // in the local cache.
502 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
503 return kc.upstreamGateway().BlockWrite(ctx, req)
506 // Ask verifies that a block with the given hash is available and
507 // readable, according to at least one Keep service. Unlike Get, it
508 // does not retrieve the data or verify that the data content matches
509 // the hash specified by the locator.
511 // Returns the data size (content length) reported by the Keep service
512 // and the URI reporting the data size.
513 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
514 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
515 return size, url, err
518 // GetIndex retrieves a list of blocks stored on the given server whose hashes
519 // begin with the given prefix. The returned reader will return an error (other
520 // than EOF) if the complete index cannot be retrieved.
522 // This is meant to be used only by system components and admin tools.
523 // It will return an error unless the client is using a "data manager token"
524 // recognized by the Keep services.
525 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
526 url := kc.LocalRoots()[keepServiceUUID]
528 return nil, ErrNoSuchKeepServer
536 req, err := http.NewRequest("GET", url, nil)
541 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
542 req.Header.Set("X-Request-Id", kc.getRequestID())
543 resp, err := kc.httpClient().Do(req)
548 defer resp.Body.Close()
550 if resp.StatusCode != http.StatusOK {
551 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
555 respBody, err = ioutil.ReadAll(resp.Body)
560 // Got index; verify that it is complete
561 // The response should be "\n" if no locators matched the prefix
562 // Else, it should be a list of locators followed by a blank line
563 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
564 return nil, ErrIncompleteIndex
567 // Got complete index; strip the trailing newline and send
568 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
571 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
572 // services: uuid -> baseURI.
573 func (kc *KeepClient) LocalRoots() map[string]string {
574 kc.discoverServices()
576 defer kc.lock.RUnlock()
580 // GatewayRoots returns the map of Keep remote gateway services:
582 func (kc *KeepClient) GatewayRoots() map[string]string {
583 kc.discoverServices()
585 defer kc.lock.RUnlock()
586 return kc.gatewayRoots
589 // WritableLocalRoots returns the map of writable local Keep services:
591 func (kc *KeepClient) WritableLocalRoots() map[string]string {
592 kc.discoverServices()
594 defer kc.lock.RUnlock()
595 return kc.writableLocalRoots
598 // SetServiceRoots disables service discovery and updates the
599 // localRoots and gatewayRoots maps, without disrupting operations
600 // that are already in progress.
602 // The supplied maps must not be modified after calling
604 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
605 kc.disableDiscovery = true
606 kc.setServiceRoots(locals, writables, gateways)
609 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
611 defer kc.lock.Unlock()
612 kc.localRoots = locals
613 kc.writableLocalRoots = writables
614 kc.gatewayRoots = gateways
617 // getSortedRoots returns a list of base URIs of Keep services, in the
618 // order they should be attempted in order to retrieve content for the
620 func (kc *KeepClient) getSortedRoots(locator string) []string {
622 for _, hint := range strings.Split(locator, "+") {
623 if len(hint) < 7 || hint[0:2] != "K@" {
624 // Not a service hint.
628 // +K@abcde means fetch from proxy at
629 // keep.abcde.arvadosapi.com
630 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
631 } else if len(hint) == 29 {
632 // +K@abcde-abcde-abcdeabcdeabcde means fetch
633 // from gateway with given uuid
634 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
635 found = append(found, gwURI)
637 // else this hint is no use to us; carry on.
640 // After trying all usable service hints, fall back to local roots.
641 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
645 func (kc *KeepClient) SetStorageClasses(sc []string) {
646 // make a copy so the caller can't mess with it.
647 kc.StorageClasses = append([]string{}, sc...)
651 // There are four global http.Client objects for the four
652 // possible permutations of TLS behavior (verify/skip-verify)
653 // and timeout settings (proxy/non-proxy).
654 defaultClient = map[bool]map[bool]HTTPClient{
655 // defaultClient[false] is used for verified TLS reqs
657 // defaultClient[true] is used for unverified
658 // (insecure) TLS reqs
661 defaultClientMtx sync.Mutex
664 // httpClient returns the HTTPClient field if it's not nil, otherwise
665 // whichever of the four global http.Client objects is suitable for
666 // the current environment (i.e., TLS verification on/off, keep
667 // services are/aren't proxies).
668 func (kc *KeepClient) httpClient() HTTPClient {
669 if kc.HTTPClient != nil {
672 defaultClientMtx.Lock()
673 defer defaultClientMtx.Unlock()
674 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
678 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
679 if kc.foundNonDiskSvc {
680 // Use longer timeouts when connecting to a proxy,
681 // because this usually means the intervening network
683 requestTimeout = DefaultProxyRequestTimeout
684 connectTimeout = DefaultProxyConnectTimeout
685 tlsTimeout = DefaultProxyTLSHandshakeTimeout
686 keepAlive = DefaultProxyKeepAlive
688 requestTimeout = DefaultRequestTimeout
689 connectTimeout = DefaultConnectTimeout
690 tlsTimeout = DefaultTLSHandshakeTimeout
691 keepAlive = DefaultKeepAlive
695 Timeout: requestTimeout,
696 // It's not safe to copy *http.DefaultTransport
697 // because it has a mutex (which might be locked)
698 // protecting a private map (which might not be nil).
699 // So we build our own, using the Go 1.12 default
700 // values, ignoring any changes the application has
701 // made to http.DefaultTransport.
702 Transport: &http.Transport{
703 DialContext: (&net.Dialer{
704 Timeout: connectTimeout,
705 KeepAlive: keepAlive,
709 IdleConnTimeout: 90 * time.Second,
710 TLSHandshakeTimeout: tlsTimeout,
711 ExpectContinueTimeout: 1 * time.Second,
712 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
715 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
719 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
721 func (kc *KeepClient) getRequestID() string {
722 if kc.RequestID != "" {
725 return reqIDGen.Next()
728 type Locator struct {
730 Size int // -1 if data size is not known
731 Hints []string // Including the size hint, if any
734 func (loc *Locator) String() string {
736 if len(loc.Hints) > 0 {
737 s = s + "+" + strings.Join(loc.Hints, "+")
742 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
744 func MakeLocator(path string) (*Locator, error) {
745 sm := locatorMatcher.FindStringSubmatch(path)
747 return nil, InvalidLocatorError
749 loc := Locator{Hash: sm[1], Size: -1}
751 loc.Hints = strings.Split(sm[3], "+")
753 loc.Hints = []string{}
755 if len(loc.Hints) > 0 {
756 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {