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 rootCacheDir = "/var/cache/arvados/keep"
48 userCacheDir = ".cache/arvados/keep" // relative to HOME
51 // Error interface with an error and boolean indicating whether the error is temporary
52 type Error interface {
57 // multipleResponseError is of type Error
58 type multipleResponseError struct {
63 func (e *multipleResponseError) Temporary() bool {
67 // BlockNotFound is a multipleResponseError where isTemp is false
68 var BlockNotFound = &ErrNotFound{multipleResponseError{
69 error: errors.New("Block not found"),
73 // ErrNotFound is a multipleResponseError where isTemp can be true or false
74 type ErrNotFound struct {
78 type InsufficientReplicasError struct{ error }
80 type OversizeBlockError struct{ error }
82 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
83 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
84 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
85 var InvalidLocatorError = errors.New("Invalid locator")
87 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
88 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
90 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
91 var ErrIncompleteIndex = errors.New("Got incomplete index")
94 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
95 XKeepReplicasStored = "X-Keep-Replicas-Stored"
96 XKeepStorageClasses = "X-Keep-Storage-Classes"
97 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
100 type HTTPClient interface {
101 Do(*http.Request) (*http.Response, error)
104 const DiskCacheDisabled = arvados.ByteSizeOrPercent(1)
106 // KeepClient holds information about Arvados and Keep servers.
107 type KeepClient struct {
108 Arvados *arvadosclient.ArvadosClient
110 localRoots map[string]string
111 writableLocalRoots map[string]string
112 gatewayRoots map[string]string
114 HTTPClient HTTPClient
117 StorageClasses []string
118 DefaultStorageClasses []string // Set by cluster's exported config
119 DiskCacheSize arvados.ByteSizeOrPercent // See also DiskCacheDisabled
121 // set to 1 if all writable services are of disk type, otherwise 0
122 replicasPerService int
124 // Any non-disk typed services found in the list of keepservers?
127 // Disable automatic discovery of keep services
128 disableDiscovery bool
130 gatewayStack arvados.KeepGateway
133 func (kc *KeepClient) Clone() *KeepClient {
135 defer kc.lock.Unlock()
138 Want_replicas: kc.Want_replicas,
139 localRoots: kc.localRoots,
140 writableLocalRoots: kc.writableLocalRoots,
141 gatewayRoots: kc.gatewayRoots,
142 HTTPClient: kc.HTTPClient,
144 RequestID: kc.RequestID,
145 StorageClasses: kc.StorageClasses,
146 DefaultStorageClasses: kc.DefaultStorageClasses,
147 DiskCacheSize: kc.DiskCacheSize,
148 replicasPerService: kc.replicasPerService,
149 foundNonDiskSvc: kc.foundNonDiskSvc,
150 disableDiscovery: kc.disableDiscovery,
154 func (kc *KeepClient) loadDefaultClasses() error {
155 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
159 classes := scData.(map[string]interface{})
160 for scName := range classes {
161 scConf, _ := classes[scName].(map[string]interface{})
162 isDefault, ok := scConf["Default"].(bool)
164 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
170 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
171 // DiscoverKeepServices(), and returns when the client is ready to
173 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
175 return kc, kc.discoverServices()
178 // New creates a new KeepClient. Service discovery will occur on the
179 // next read/write operation.
180 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
181 defaultReplicationLevel := 2
182 value, err := arv.Discovery("defaultCollectionReplication")
184 v, ok := value.(float64)
186 defaultReplicationLevel = int(v)
191 Want_replicas: defaultReplicationLevel,
194 err = kc.loadDefaultClasses()
196 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
201 // PutHR puts a block given the block hash, a reader, and the number of bytes
202 // to read from the reader (which must be between 0 and BLOCKSIZE).
204 // Returns the locator for the written block, the number of replicas
205 // written, and an error.
207 // Returns an InsufficientReplicasError if 0 <= replicas <
208 // kc.Wants_replicas.
209 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
210 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
213 DataSize: int(dataBytes),
215 return resp.Locator, resp.Replicas, err
218 // PutHB writes a block to Keep. The hash of the bytes is given in
219 // hash, and the data is given in buf.
221 // Return values are the same as for PutHR.
222 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
223 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
227 return resp.Locator, resp.Replicas, err
230 // PutB writes a block to Keep. It computes the hash itself.
232 // Return values are the same as for PutHR.
233 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
234 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
237 return resp.Locator, resp.Replicas, err
240 // PutR writes a block to Keep. It first reads all data from r into a buffer
241 // in order to compute the hash.
243 // Return values are the same as for PutHR.
245 // If the block hash and data size are known, PutHR is more efficient.
246 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
247 buffer, err := ioutil.ReadAll(r)
251 return kc.PutB(buffer)
254 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
255 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
256 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
259 reqid := kc.getRequestID()
261 var expectLength int64
262 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
264 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
272 triesRemaining := 1 + kc.Retries
274 serversToTry := kc.getSortedRoots(locator)
276 numServers := len(serversToTry)
279 var retryList []string
281 for triesRemaining > 0 {
285 for _, host := range serversToTry {
286 url := host + "/" + locator
288 req, err := http.NewRequest(method, url, nil)
290 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
293 for k, v := range header {
294 req.Header[k] = append([]string(nil), v...)
296 if req.Header.Get("Authorization") == "" {
297 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
299 if req.Header.Get("X-Request-Id") == "" {
300 req.Header.Set("X-Request-Id", reqid)
302 resp, err := kc.httpClient().Do(req)
304 // Probably a network error, may be transient,
306 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
307 retryList = append(retryList, host)
310 if resp.StatusCode != http.StatusOK {
312 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
314 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
315 url, resp.StatusCode, bytes.TrimSpace(respbody)))
317 if resp.StatusCode == 408 ||
318 resp.StatusCode == 429 ||
319 resp.StatusCode >= 500 {
320 // Timeout, too many requests, or other
321 // server side failure, transient
322 // error, can try again.
323 retryList = append(retryList, host)
324 } else if resp.StatusCode == 404 {
329 if expectLength < 0 {
330 if resp.ContentLength < 0 {
332 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
334 expectLength = resp.ContentLength
335 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
337 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
341 return HashCheckingReader{
344 Check: locator[0:32],
345 }, expectLength, url, resp.Header, nil
348 return nil, expectLength, url, resp.Header, nil
350 serversToTry = retryList
352 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
355 if count404 == numServers {
358 err = &ErrNotFound{multipleResponseError{
359 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
360 isTemp: len(serversToTry) > 0,
363 return nil, 0, "", nil, err
366 // attempt to create dir/subdir/ and its parents, up to but not
367 // including dir itself, using mode 0700.
368 func makedirs(dir, subdir string) {
369 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
370 dir = filepath.Join(dir, part)
375 // upstreamGateway creates/returns the KeepGateway stack used to read
376 // and write data: a disk-backed cache on top of an http backend.
377 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
379 defer kc.lock.Unlock()
380 if kc.gatewayStack != nil {
381 return kc.gatewayStack
384 if os.Geteuid() == 0 {
385 cachedir = rootCacheDir
386 makedirs("/", cachedir)
388 home := "/" + os.Getenv("HOME")
389 makedirs(home, userCacheDir)
390 cachedir = filepath.Join(home, userCacheDir)
392 backend := &keepViaHTTP{kc}
393 if kc.DiskCacheSize == DiskCacheDisabled {
394 kc.gatewayStack = backend
396 kc.gatewayStack = &arvados.DiskCache{
398 MaxSize: kc.DiskCacheSize,
399 KeepGateway: backend,
402 return kc.gatewayStack
405 // LocalLocator returns a locator equivalent to the one supplied, but
406 // with a valid signature from the local cluster. If the given locator
407 // already has a local signature, it is returned unchanged.
408 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
409 return kc.upstreamGateway().LocalLocator(locator)
412 // Get retrieves the specified block from the local cache or a backend
413 // server. Returns a reader, the expected data length (or -1 if not
414 // known), and an error.
416 // The third return value (formerly a source URL in previous versions)
417 // is an empty string.
419 // If the block checksum does not match, the final Read() on the
420 // reader returned by this method will return a BadChecksum error
423 // New code should use BlockRead and/or ReadAt instead of Get.
424 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
425 loc, err := MakeLocator(locator)
427 return nil, 0, "", err
431 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
436 pw.CloseWithError(err)
437 } else if loc.Size >= 0 && n != loc.Size {
438 pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
443 // Wait for the first byte to arrive, so that, if there's an
444 // error before we receive any data, we can return the error
445 // directly, instead of indirectly via a reader that returns
447 bufr := bufio.NewReader(pr)
448 _, err = bufr.Peek(1)
449 if err != nil && err != io.EOF {
450 pr.CloseWithError(err)
451 return nil, 0, "", err
453 if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
454 // In the special case of the zero-length block, EOF
455 // error from Peek() is normal.
456 return pr, 0, "", nil
464 }, int64(loc.Size), "", err
467 // BlockRead retrieves a block from the cache if it's present, otherwise
469 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
470 return kc.upstreamGateway().BlockRead(ctx, opts)
473 // ReadAt retrieves a portion of block from the cache if it's
474 // present, otherwise from the network.
475 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
476 return kc.upstreamGateway().ReadAt(locator, p, off)
479 // BlockWrite writes a full block to upstream servers and saves a copy
480 // in the local cache.
481 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
482 return kc.upstreamGateway().BlockWrite(ctx, req)
485 // Ask verifies that a block with the given hash is available and
486 // readable, according to at least one Keep service. Unlike Get, it
487 // does not retrieve the data or verify that the data content matches
488 // the hash specified by the locator.
490 // Returns the data size (content length) reported by the Keep service
491 // and the URI reporting the data size.
492 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
493 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
494 return size, url, err
497 // GetIndex retrieves a list of blocks stored on the given server whose hashes
498 // begin with the given prefix. The returned reader will return an error (other
499 // than EOF) if the complete index cannot be retrieved.
501 // This is meant to be used only by system components and admin tools.
502 // It will return an error unless the client is using a "data manager token"
503 // recognized by the Keep services.
504 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
505 url := kc.LocalRoots()[keepServiceUUID]
507 return nil, ErrNoSuchKeepServer
515 req, err := http.NewRequest("GET", url, nil)
520 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
521 req.Header.Set("X-Request-Id", kc.getRequestID())
522 resp, err := kc.httpClient().Do(req)
527 defer resp.Body.Close()
529 if resp.StatusCode != http.StatusOK {
530 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
534 respBody, err = ioutil.ReadAll(resp.Body)
539 // Got index; verify that it is complete
540 // The response should be "\n" if no locators matched the prefix
541 // Else, it should be a list of locators followed by a blank line
542 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
543 return nil, ErrIncompleteIndex
546 // Got complete index; strip the trailing newline and send
547 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
550 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
551 // services: uuid -> baseURI.
552 func (kc *KeepClient) LocalRoots() map[string]string {
553 kc.discoverServices()
555 defer kc.lock.RUnlock()
559 // GatewayRoots returns the map of Keep remote gateway services:
561 func (kc *KeepClient) GatewayRoots() map[string]string {
562 kc.discoverServices()
564 defer kc.lock.RUnlock()
565 return kc.gatewayRoots
568 // WritableLocalRoots returns the map of writable local Keep services:
570 func (kc *KeepClient) WritableLocalRoots() map[string]string {
571 kc.discoverServices()
573 defer kc.lock.RUnlock()
574 return kc.writableLocalRoots
577 // SetServiceRoots disables service discovery and updates the
578 // localRoots and gatewayRoots maps, without disrupting operations
579 // that are already in progress.
581 // The supplied maps must not be modified after calling
583 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
584 kc.disableDiscovery = true
585 kc.setServiceRoots(locals, writables, gateways)
588 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
590 defer kc.lock.Unlock()
591 kc.localRoots = locals
592 kc.writableLocalRoots = writables
593 kc.gatewayRoots = gateways
596 // getSortedRoots returns a list of base URIs of Keep services, in the
597 // order they should be attempted in order to retrieve content for the
599 func (kc *KeepClient) getSortedRoots(locator string) []string {
601 for _, hint := range strings.Split(locator, "+") {
602 if len(hint) < 7 || hint[0:2] != "K@" {
603 // Not a service hint.
607 // +K@abcde means fetch from proxy at
608 // keep.abcde.arvadosapi.com
609 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
610 } else if len(hint) == 29 {
611 // +K@abcde-abcde-abcdeabcdeabcde means fetch
612 // from gateway with given uuid
613 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
614 found = append(found, gwURI)
616 // else this hint is no use to us; carry on.
619 // After trying all usable service hints, fall back to local roots.
620 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
624 func (kc *KeepClient) SetStorageClasses(sc []string) {
625 // make a copy so the caller can't mess with it.
626 kc.StorageClasses = append([]string{}, sc...)
630 // There are four global http.Client objects for the four
631 // possible permutations of TLS behavior (verify/skip-verify)
632 // and timeout settings (proxy/non-proxy).
633 defaultClient = map[bool]map[bool]HTTPClient{
634 // defaultClient[false] is used for verified TLS reqs
636 // defaultClient[true] is used for unverified
637 // (insecure) TLS reqs
640 defaultClientMtx sync.Mutex
643 // httpClient returns the HTTPClient field if it's not nil, otherwise
644 // whichever of the four global http.Client objects is suitable for
645 // the current environment (i.e., TLS verification on/off, keep
646 // services are/aren't proxies).
647 func (kc *KeepClient) httpClient() HTTPClient {
648 if kc.HTTPClient != nil {
651 defaultClientMtx.Lock()
652 defer defaultClientMtx.Unlock()
653 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
657 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
658 if kc.foundNonDiskSvc {
659 // Use longer timeouts when connecting to a proxy,
660 // because this usually means the intervening network
662 requestTimeout = DefaultProxyRequestTimeout
663 connectTimeout = DefaultProxyConnectTimeout
664 tlsTimeout = DefaultProxyTLSHandshakeTimeout
665 keepAlive = DefaultProxyKeepAlive
667 requestTimeout = DefaultRequestTimeout
668 connectTimeout = DefaultConnectTimeout
669 tlsTimeout = DefaultTLSHandshakeTimeout
670 keepAlive = DefaultKeepAlive
674 Timeout: requestTimeout,
675 // It's not safe to copy *http.DefaultTransport
676 // because it has a mutex (which might be locked)
677 // protecting a private map (which might not be nil).
678 // So we build our own, using the Go 1.12 default
679 // values, ignoring any changes the application has
680 // made to http.DefaultTransport.
681 Transport: &http.Transport{
682 DialContext: (&net.Dialer{
683 Timeout: connectTimeout,
684 KeepAlive: keepAlive,
688 IdleConnTimeout: 90 * time.Second,
689 TLSHandshakeTimeout: tlsTimeout,
690 ExpectContinueTimeout: 1 * time.Second,
691 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
694 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
698 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
700 func (kc *KeepClient) getRequestID() string {
701 if kc.RequestID != "" {
704 return reqIDGen.Next()
707 type Locator struct {
709 Size int // -1 if data size is not known
710 Hints []string // Including the size hint, if any
713 func (loc *Locator) String() string {
715 if len(loc.Hints) > 0 {
716 s = s + "+" + strings.Join(loc.Hints, "+")
721 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
723 func MakeLocator(path string) (*Locator, error) {
724 sm := locatorMatcher.FindStringSubmatch(path)
726 return nil, InvalidLocatorError
728 loc := Locator{Hash: sm[1], Size: -1}
730 loc.Hints = strings.Split(sm[3], "+")
732 loc.Hints = []string{}
734 if len(loc.Hints) > 0 {
735 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {