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 classes, calls
190 // DiscoverKeepServices(), and returns when the client is ready to
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()
215 DebugPrintf("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", "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(delay.Next())
375 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
378 if count404 == numServers {
381 err = &ErrNotFound{multipleResponseError{
382 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
383 isTemp: len(serversToTry) > 0,
386 return nil, 0, "", nil, err
389 // attempt to create dir/subdir/ and its parents, up to but not
390 // including dir itself, using mode 0700.
391 func makedirs(dir, subdir string) {
392 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
393 dir = filepath.Join(dir, part)
398 // upstreamGateway creates/returns the KeepGateway stack used to read
399 // and write data: a disk-backed cache on top of an http backend.
400 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
402 defer kc.lock.Unlock()
403 if kc.gatewayStack != nil {
404 return kc.gatewayStack
407 if os.Geteuid() == 0 {
408 cachedir = rootCacheDir
409 makedirs("/", cachedir)
411 home := "/" + os.Getenv("HOME")
412 makedirs(home, userCacheDir)
413 cachedir = filepath.Join(home, userCacheDir)
415 backend := &keepViaHTTP{kc}
416 if kc.DiskCacheSize == DiskCacheDisabled {
417 kc.gatewayStack = backend
419 kc.gatewayStack = &arvados.DiskCache{
421 MaxSize: kc.DiskCacheSize,
422 KeepGateway: backend,
425 return kc.gatewayStack
428 // LocalLocator returns a locator equivalent to the one supplied, but
429 // with a valid signature from the local cluster. If the given locator
430 // already has a local signature, it is returned unchanged.
431 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
432 return kc.upstreamGateway().LocalLocator(locator)
435 // Get retrieves the specified block from the local cache or a backend
436 // server. Returns a reader, the expected data length (or -1 if not
437 // known), and an error.
439 // The third return value (formerly a source URL in previous versions)
440 // is an empty string.
442 // If the block checksum does not match, the final Read() on the
443 // reader returned by this method will return a BadChecksum error
446 // New code should use BlockRead and/or ReadAt instead of Get.
447 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
448 loc, err := MakeLocator(locator)
450 return nil, 0, "", err
454 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
459 pw.CloseWithError(err)
460 } else if loc.Size >= 0 && n != loc.Size {
461 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
466 // Wait for the first byte to arrive, so that, if there's an
467 // error before we receive any data, we can return the error
468 // directly, instead of indirectly via a reader that returns
470 bufr := bufio.NewReader(pr)
471 _, err = bufr.Peek(1)
472 if err != nil && err != io.EOF {
473 pr.CloseWithError(err)
474 return nil, 0, "", err
476 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
477 // In the special case of the zero-length block, EOF
478 // error from Peek() is normal.
479 return pr, 0, "", nil
487 }, int64(loc.Size), "", err
490 // BlockRead retrieves a block from the cache if it's present, otherwise
492 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
493 return kc.upstreamGateway().BlockRead(ctx, opts)
496 // ReadAt retrieves a portion of block from the cache if it's
497 // present, otherwise from the network.
498 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
499 return kc.upstreamGateway().ReadAt(locator, p, off)
502 // BlockWrite writes a full block to upstream servers and saves a copy
503 // in the local cache.
504 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
505 return kc.upstreamGateway().BlockWrite(ctx, req)
508 // Ask verifies that a block with the given hash is available and
509 // readable, according to at least one Keep service. Unlike Get, it
510 // does not retrieve the data or verify that the data content matches
511 // the hash specified by the locator.
513 // Returns the data size (content length) reported by the Keep service
514 // and the URI reporting the data size.
515 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
516 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
517 return size, url, err
520 // GetIndex retrieves a list of blocks stored on the given server whose hashes
521 // begin with the given prefix. The returned reader will return an error (other
522 // than EOF) if the complete index cannot be retrieved.
524 // This is meant to be used only by system components and admin tools.
525 // It will return an error unless the client is using a "data manager token"
526 // recognized by the Keep services.
527 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
528 url := kc.LocalRoots()[keepServiceUUID]
530 return nil, ErrNoSuchKeepServer
538 req, err := http.NewRequest("GET", url, nil)
543 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
544 req.Header.Set("X-Request-Id", kc.getRequestID())
545 resp, err := kc.httpClient().Do(req)
550 defer resp.Body.Close()
552 if resp.StatusCode != http.StatusOK {
553 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
557 respBody, err = ioutil.ReadAll(resp.Body)
562 // Got index; verify that it is complete
563 // The response should be "\n" if no locators matched the prefix
564 // Else, it should be a list of locators followed by a blank line
565 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
566 return nil, ErrIncompleteIndex
569 // Got complete index; strip the trailing newline and send
570 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
573 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
574 // services: uuid -> baseURI.
575 func (kc *KeepClient) LocalRoots() map[string]string {
576 kc.discoverServices()
578 defer kc.lock.RUnlock()
582 // GatewayRoots returns the map of Keep remote gateway services:
584 func (kc *KeepClient) GatewayRoots() map[string]string {
585 kc.discoverServices()
587 defer kc.lock.RUnlock()
588 return kc.gatewayRoots
591 // WritableLocalRoots returns the map of writable local Keep services:
593 func (kc *KeepClient) WritableLocalRoots() map[string]string {
594 kc.discoverServices()
596 defer kc.lock.RUnlock()
597 return kc.writableLocalRoots
600 // SetServiceRoots disables service discovery and updates the
601 // localRoots and gatewayRoots maps, without disrupting operations
602 // that are already in progress.
604 // The supplied maps must not be modified after calling
606 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
607 kc.disableDiscovery = true
608 kc.setServiceRoots(locals, writables, gateways)
611 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
613 defer kc.lock.Unlock()
614 kc.localRoots = locals
615 kc.writableLocalRoots = writables
616 kc.gatewayRoots = gateways
619 // getSortedRoots returns a list of base URIs of Keep services, in the
620 // order they should be attempted in order to retrieve content for the
622 func (kc *KeepClient) getSortedRoots(locator string) []string {
624 for _, hint := range strings.Split(locator, "+") {
625 if len(hint) < 7 || hint[0:2] != "K@" {
626 // Not a service hint.
630 // +K@abcde means fetch from proxy at
631 // keep.abcde.arvadosapi.com
632 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
633 } else if len(hint) == 29 {
634 // +K@abcde-abcde-abcdeabcdeabcde means fetch
635 // from gateway with given uuid
636 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
637 found = append(found, gwURI)
639 // else this hint is no use to us; carry on.
642 // After trying all usable service hints, fall back to local roots.
643 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
647 func (kc *KeepClient) SetStorageClasses(sc []string) {
648 // make a copy so the caller can't mess with it.
649 kc.StorageClasses = append([]string{}, sc...)
653 // There are four global http.Client objects for the four
654 // possible permutations of TLS behavior (verify/skip-verify)
655 // and timeout settings (proxy/non-proxy).
656 defaultClient = map[bool]map[bool]HTTPClient{
657 // defaultClient[false] is used for verified TLS reqs
659 // defaultClient[true] is used for unverified
660 // (insecure) TLS reqs
663 defaultClientMtx sync.Mutex
666 // httpClient returns the HTTPClient field if it's not nil, otherwise
667 // whichever of the four global http.Client objects is suitable for
668 // the current environment (i.e., TLS verification on/off, keep
669 // services are/aren't proxies).
670 func (kc *KeepClient) httpClient() HTTPClient {
671 if kc.HTTPClient != nil {
674 defaultClientMtx.Lock()
675 defer defaultClientMtx.Unlock()
676 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
680 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
681 if kc.foundNonDiskSvc {
682 // Use longer timeouts when connecting to a proxy,
683 // because this usually means the intervening network
685 requestTimeout = DefaultProxyRequestTimeout
686 connectTimeout = DefaultProxyConnectTimeout
687 tlsTimeout = DefaultProxyTLSHandshakeTimeout
688 keepAlive = DefaultProxyKeepAlive
690 requestTimeout = DefaultRequestTimeout
691 connectTimeout = DefaultConnectTimeout
692 tlsTimeout = DefaultTLSHandshakeTimeout
693 keepAlive = DefaultKeepAlive
697 Timeout: requestTimeout,
698 // It's not safe to copy *http.DefaultTransport
699 // because it has a mutex (which might be locked)
700 // protecting a private map (which might not be nil).
701 // So we build our own, using the Go 1.12 default
702 // values, ignoring any changes the application has
703 // made to http.DefaultTransport.
704 Transport: &http.Transport{
705 DialContext: (&net.Dialer{
706 Timeout: connectTimeout,
707 KeepAlive: keepAlive,
711 IdleConnTimeout: 90 * time.Second,
712 TLSHandshakeTimeout: tlsTimeout,
713 ExpectContinueTimeout: 1 * time.Second,
714 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
717 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
721 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
723 func (kc *KeepClient) getRequestID() string {
724 if kc.RequestID != "" {
727 return reqIDGen.Next()
730 type Locator struct {
732 Size int // -1 if data size is not known
733 Hints []string // Including the size hint, if any
736 func (loc *Locator) String() string {
738 if len(loc.Hints) > 0 {
739 s = s + "+" + strings.Join(loc.Hints, "+")
744 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
746 func MakeLocator(path string) (*Locator, error) {
747 sm := locatorMatcher.FindStringSubmatch(path)
749 return nil, InvalidLocatorError
751 loc := Locator{Hash: sm[1], Size: -1}
753 loc.Hints = strings.Split(sm[3], "+")
755 loc.Hints = []string{}
757 if len(loc.Hints) > 0 {
758 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {