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 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 maximum delay for automatic retry. If zero,
124 // DefaultRetryDelay is used. The delay after attempt N
125 // (0-based) will be a random duration between
126 // MinimumRetryDelay and RetryDelay * 2^N, not to exceed a cap
127 // of RetryDelay * 10.
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 delay := delayCalculator{InitialMaxDelay: kc.RetryDelay}
288 triesRemaining := 1 + kc.Retries
290 serversToTry := kc.getSortedRoots(locator)
292 numServers := len(serversToTry)
295 var retryList []string
297 for triesRemaining > 0 {
301 for _, host := range serversToTry {
302 url := host + "/" + locator
304 req, err := http.NewRequest(method, url, nil)
306 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
309 for k, v := range header {
310 req.Header[k] = append([]string(nil), v...)
312 if req.Header.Get("Authorization") == "" {
313 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
315 if req.Header.Get("X-Request-Id") == "" {
316 req.Header.Set("X-Request-Id", reqid)
318 resp, err := kc.httpClient().Do(req)
320 // Probably a network error, may be transient,
322 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
323 retryList = append(retryList, host)
326 if resp.StatusCode != http.StatusOK {
328 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
330 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
331 url, resp.StatusCode, bytes.TrimSpace(respbody)))
333 if resp.StatusCode == 408 ||
334 resp.StatusCode == 429 ||
335 resp.StatusCode >= 500 {
336 // Timeout, too many requests, or other
337 // server side failure, transient
338 // error, can try again.
339 retryList = append(retryList, host)
340 } else if resp.StatusCode == 404 {
345 if expectLength < 0 {
346 if resp.ContentLength < 0 {
348 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
350 expectLength = resp.ContentLength
351 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
353 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
357 return HashCheckingReader{
360 Check: locator[0:32],
361 }, expectLength, url, resp.Header, nil
364 return nil, expectLength, url, resp.Header, nil
366 serversToTry = retryList
367 if len(serversToTry) > 0 && triesRemaining > 0 {
368 time.Sleep(delay.Next())
371 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
374 if count404 == numServers {
377 err = &ErrNotFound{multipleResponseError{
378 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
379 isTemp: len(serversToTry) > 0,
382 return nil, 0, "", nil, err
385 // attempt to create dir/subdir/ and its parents, up to but not
386 // including dir itself, using mode 0700.
387 func makedirs(dir, subdir string) {
388 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
389 dir = filepath.Join(dir, part)
394 // upstreamGateway creates/returns the KeepGateway stack used to read
395 // and write data: a disk-backed cache on top of an http backend.
396 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
398 defer kc.lock.Unlock()
399 if kc.gatewayStack != nil {
400 return kc.gatewayStack
403 if os.Geteuid() == 0 {
404 cachedir = rootCacheDir
405 makedirs("/", cachedir)
407 home := "/" + os.Getenv("HOME")
408 makedirs(home, userCacheDir)
409 cachedir = filepath.Join(home, userCacheDir)
411 backend := &keepViaHTTP{kc}
412 if kc.DiskCacheSize == DiskCacheDisabled {
413 kc.gatewayStack = backend
415 kc.gatewayStack = &arvados.DiskCache{
417 MaxSize: kc.DiskCacheSize,
418 KeepGateway: backend,
421 return kc.gatewayStack
424 // LocalLocator returns a locator equivalent to the one supplied, but
425 // with a valid signature from the local cluster. If the given locator
426 // already has a local signature, it is returned unchanged.
427 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
428 return kc.upstreamGateway().LocalLocator(locator)
431 // Get retrieves the specified block from the local cache or a backend
432 // server. Returns a reader, the expected data length (or -1 if not
433 // known), and an error.
435 // The third return value (formerly a source URL in previous versions)
436 // is an empty string.
438 // If the block checksum does not match, the final Read() on the
439 // reader returned by this method will return a BadChecksum error
442 // New code should use BlockRead and/or ReadAt instead of Get.
443 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
444 loc, err := MakeLocator(locator)
446 return nil, 0, "", err
450 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
455 pw.CloseWithError(err)
456 } else if loc.Size >= 0 && n != loc.Size {
457 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
462 // Wait for the first byte to arrive, so that, if there's an
463 // error before we receive any data, we can return the error
464 // directly, instead of indirectly via a reader that returns
466 bufr := bufio.NewReader(pr)
467 _, err = bufr.Peek(1)
468 if err != nil && err != io.EOF {
469 pr.CloseWithError(err)
470 return nil, 0, "", err
472 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
473 // In the special case of the zero-length block, EOF
474 // error from Peek() is normal.
475 return pr, 0, "", nil
483 }, int64(loc.Size), "", err
486 // BlockRead retrieves a block from the cache if it's present, otherwise
488 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
489 return kc.upstreamGateway().BlockRead(ctx, opts)
492 // ReadAt retrieves a portion of block from the cache if it's
493 // present, otherwise from the network.
494 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
495 return kc.upstreamGateway().ReadAt(locator, p, off)
498 // BlockWrite writes a full block to upstream servers and saves a copy
499 // in the local cache.
500 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
501 return kc.upstreamGateway().BlockWrite(ctx, req)
504 // Ask verifies that a block with the given hash is available and
505 // readable, according to at least one Keep service. Unlike Get, it
506 // does not retrieve the data or verify that the data content matches
507 // the hash specified by the locator.
509 // Returns the data size (content length) reported by the Keep service
510 // and the URI reporting the data size.
511 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
512 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
513 return size, url, err
516 // GetIndex retrieves a list of blocks stored on the given server whose hashes
517 // begin with the given prefix. The returned reader will return an error (other
518 // than EOF) if the complete index cannot be retrieved.
520 // This is meant to be used only by system components and admin tools.
521 // It will return an error unless the client is using a "data manager token"
522 // recognized by the Keep services.
523 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
524 url := kc.LocalRoots()[keepServiceUUID]
526 return nil, ErrNoSuchKeepServer
534 req, err := http.NewRequest("GET", url, nil)
539 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
540 req.Header.Set("X-Request-Id", kc.getRequestID())
541 resp, err := kc.httpClient().Do(req)
546 defer resp.Body.Close()
548 if resp.StatusCode != http.StatusOK {
549 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
553 respBody, err = ioutil.ReadAll(resp.Body)
558 // Got index; verify that it is complete
559 // The response should be "\n" if no locators matched the prefix
560 // Else, it should be a list of locators followed by a blank line
561 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
562 return nil, ErrIncompleteIndex
565 // Got complete index; strip the trailing newline and send
566 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
569 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
570 // services: uuid -> baseURI.
571 func (kc *KeepClient) LocalRoots() map[string]string {
572 kc.discoverServices()
574 defer kc.lock.RUnlock()
578 // GatewayRoots returns the map of Keep remote gateway services:
580 func (kc *KeepClient) GatewayRoots() map[string]string {
581 kc.discoverServices()
583 defer kc.lock.RUnlock()
584 return kc.gatewayRoots
587 // WritableLocalRoots returns the map of writable local Keep services:
589 func (kc *KeepClient) WritableLocalRoots() map[string]string {
590 kc.discoverServices()
592 defer kc.lock.RUnlock()
593 return kc.writableLocalRoots
596 // SetServiceRoots disables service discovery and updates the
597 // localRoots and gatewayRoots maps, without disrupting operations
598 // that are already in progress.
600 // The supplied maps must not be modified after calling
602 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
603 kc.disableDiscovery = true
604 kc.setServiceRoots(locals, writables, gateways)
607 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
609 defer kc.lock.Unlock()
610 kc.localRoots = locals
611 kc.writableLocalRoots = writables
612 kc.gatewayRoots = gateways
615 // getSortedRoots returns a list of base URIs of Keep services, in the
616 // order they should be attempted in order to retrieve content for the
618 func (kc *KeepClient) getSortedRoots(locator string) []string {
620 for _, hint := range strings.Split(locator, "+") {
621 if len(hint) < 7 || hint[0:2] != "K@" {
622 // Not a service hint.
626 // +K@abcde means fetch from proxy at
627 // keep.abcde.arvadosapi.com
628 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
629 } else if len(hint) == 29 {
630 // +K@abcde-abcde-abcdeabcdeabcde means fetch
631 // from gateway with given uuid
632 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
633 found = append(found, gwURI)
635 // else this hint is no use to us; carry on.
638 // After trying all usable service hints, fall back to local roots.
639 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
643 func (kc *KeepClient) SetStorageClasses(sc []string) {
644 // make a copy so the caller can't mess with it.
645 kc.StorageClasses = append([]string{}, sc...)
649 // There are four global http.Client objects for the four
650 // possible permutations of TLS behavior (verify/skip-verify)
651 // and timeout settings (proxy/non-proxy).
652 defaultClient = map[bool]map[bool]HTTPClient{
653 // defaultClient[false] is used for verified TLS reqs
655 // defaultClient[true] is used for unverified
656 // (insecure) TLS reqs
659 defaultClientMtx sync.Mutex
662 // httpClient returns the HTTPClient field if it's not nil, otherwise
663 // whichever of the four global http.Client objects is suitable for
664 // the current environment (i.e., TLS verification on/off, keep
665 // services are/aren't proxies).
666 func (kc *KeepClient) httpClient() HTTPClient {
667 if kc.HTTPClient != nil {
670 defaultClientMtx.Lock()
671 defer defaultClientMtx.Unlock()
672 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
676 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
677 if kc.foundNonDiskSvc {
678 // Use longer timeouts when connecting to a proxy,
679 // because this usually means the intervening network
681 requestTimeout = DefaultProxyRequestTimeout
682 connectTimeout = DefaultProxyConnectTimeout
683 tlsTimeout = DefaultProxyTLSHandshakeTimeout
684 keepAlive = DefaultProxyKeepAlive
686 requestTimeout = DefaultRequestTimeout
687 connectTimeout = DefaultConnectTimeout
688 tlsTimeout = DefaultTLSHandshakeTimeout
689 keepAlive = DefaultKeepAlive
693 Timeout: requestTimeout,
694 // It's not safe to copy *http.DefaultTransport
695 // because it has a mutex (which might be locked)
696 // protecting a private map (which might not be nil).
697 // So we build our own, using the Go 1.12 default
698 // values, ignoring any changes the application has
699 // made to http.DefaultTransport.
700 Transport: &http.Transport{
701 DialContext: (&net.Dialer{
702 Timeout: connectTimeout,
703 KeepAlive: keepAlive,
707 IdleConnTimeout: 90 * time.Second,
708 TLSHandshakeTimeout: tlsTimeout,
709 ExpectContinueTimeout: 1 * time.Second,
710 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
713 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
717 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
719 func (kc *KeepClient) getRequestID() string {
720 if kc.RequestID != "" {
723 return reqIDGen.Next()
726 type Locator struct {
728 Size int // -1 if data size is not known
729 Hints []string // Including the size hint, if any
732 func (loc *Locator) String() string {
734 if len(loc.Hints) > 0 {
735 s = s + "+" + strings.Join(loc.Hints, "+")
740 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
742 func MakeLocator(path string) (*Locator, error) {
743 sm := locatorMatcher.FindStringSubmatch(path)
745 return nil, InvalidLocatorError
747 loc := Locator{Hash: sm[1], Size: -1}
749 loc.Hints = strings.Split(sm[3], "+")
751 loc.Hints = []string{}
753 if len(loc.Hints) > 0 {
754 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {