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.
27 "git.arvados.org/arvados.git/sdk/go/arvados"
28 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
29 "git.arvados.org/arvados.git/sdk/go/httpserver"
32 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
33 const BLOCKSIZE = 64 * 1024 * 1024
36 DefaultRequestTimeout = 20 * time.Second
37 DefaultConnectTimeout = 2 * time.Second
38 DefaultTLSHandshakeTimeout = 4 * time.Second
39 DefaultKeepAlive = 180 * time.Second
41 DefaultProxyRequestTimeout = 300 * time.Second
42 DefaultProxyConnectTimeout = 30 * time.Second
43 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
44 DefaultProxyKeepAlive = 120 * time.Second
46 rootCacheDir = "/var/cache/arvados/keep"
47 userCacheDir = ".cache/arvados/keep" // relative to HOME
50 // Error interface with an error and boolean indicating whether the error is temporary
51 type Error interface {
56 // multipleResponseError is of type Error
57 type multipleResponseError struct {
62 func (e *multipleResponseError) Temporary() bool {
66 // BlockNotFound is a multipleResponseError where isTemp is false
67 var BlockNotFound = &ErrNotFound{multipleResponseError{
68 error: errors.New("Block not found"),
72 // ErrNotFound is a multipleResponseError where isTemp can be true or false
73 type ErrNotFound struct {
77 type InsufficientReplicasError struct{ error }
79 type OversizeBlockError struct{ error }
81 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
82 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
83 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
84 var InvalidLocatorError = errors.New("Invalid locator")
86 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
87 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
89 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
90 var ErrIncompleteIndex = errors.New("Got incomplete index")
93 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
94 XKeepReplicasStored = "X-Keep-Replicas-Stored"
95 XKeepStorageClasses = "X-Keep-Storage-Classes"
96 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
99 type HTTPClient interface {
100 Do(*http.Request) (*http.Response, error)
103 // KeepClient holds information about Arvados and Keep servers.
104 type KeepClient struct {
105 Arvados *arvadosclient.ArvadosClient
107 localRoots map[string]string
108 writableLocalRoots map[string]string
109 gatewayRoots map[string]string
111 HTTPClient HTTPClient
114 StorageClasses []string
115 DefaultStorageClasses []string // Set by cluster's exported config
116 DiskCacheSize arvados.ByteSizeOrPercent
118 // set to 1 if all writable services are of disk type, otherwise 0
119 replicasPerService int
121 // Any non-disk typed services found in the list of keepservers?
124 // Disable automatic discovery of keep services
125 disableDiscovery bool
127 gatewayStack arvados.KeepGateway
130 func (kc *KeepClient) Clone() *KeepClient {
132 defer kc.lock.Unlock()
135 Want_replicas: kc.Want_replicas,
136 localRoots: kc.localRoots,
137 writableLocalRoots: kc.writableLocalRoots,
138 gatewayRoots: kc.gatewayRoots,
139 HTTPClient: kc.HTTPClient,
141 RequestID: kc.RequestID,
142 StorageClasses: kc.StorageClasses,
143 DefaultStorageClasses: kc.DefaultStorageClasses,
144 replicasPerService: kc.replicasPerService,
145 foundNonDiskSvc: kc.foundNonDiskSvc,
146 disableDiscovery: kc.disableDiscovery,
150 func (kc *KeepClient) loadDefaultClasses() error {
151 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
155 classes := scData.(map[string]interface{})
156 for scName := range classes {
157 scConf, _ := classes[scName].(map[string]interface{})
158 isDefault, ok := scConf["Default"].(bool)
160 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
166 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
167 // DiscoverKeepServices(), and returns when the client is ready to
169 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
171 return kc, kc.discoverServices()
174 // New creates a new KeepClient. Service discovery will occur on the
175 // next read/write operation.
176 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
177 defaultReplicationLevel := 2
178 value, err := arv.Discovery("defaultCollectionReplication")
180 v, ok := value.(float64)
182 defaultReplicationLevel = int(v)
187 Want_replicas: defaultReplicationLevel,
190 err = kc.loadDefaultClasses()
192 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
197 // PutHR puts a block given the block hash, a reader, and the number of bytes
198 // to read from the reader (which must be between 0 and BLOCKSIZE).
200 // Returns the locator for the written block, the number of replicas
201 // written, and an error.
203 // Returns an InsufficientReplicasError if 0 <= replicas <
204 // kc.Wants_replicas.
205 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
206 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
209 DataSize: int(dataBytes),
211 return resp.Locator, resp.Replicas, err
214 // PutHB writes a block to Keep. The hash of the bytes is given in
215 // hash, and the data is given in buf.
217 // Return values are the same as for PutHR.
218 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
219 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
223 return resp.Locator, resp.Replicas, err
226 // PutB writes a block to Keep. It computes the hash itself.
228 // Return values are the same as for PutHR.
229 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
230 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
233 return resp.Locator, resp.Replicas, err
236 // PutR writes a block to Keep. It first reads all data from r into a buffer
237 // in order to compute the hash.
239 // Return values are the same as for PutHR.
241 // If the block hash and data size are known, PutHR is more efficient.
242 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
243 buffer, err := ioutil.ReadAll(r)
247 return kc.PutB(buffer)
250 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
251 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
252 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
255 reqid := kc.getRequestID()
257 var expectLength int64
258 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
260 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
268 triesRemaining := 1 + kc.Retries
270 serversToTry := kc.getSortedRoots(locator)
272 numServers := len(serversToTry)
275 var retryList []string
277 for triesRemaining > 0 {
281 for _, host := range serversToTry {
282 url := host + "/" + locator
284 req, err := http.NewRequest(method, url, nil)
286 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
289 for k, v := range header {
290 req.Header[k] = append([]string(nil), v...)
292 if req.Header.Get("Authorization") == "" {
293 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
295 if req.Header.Get("X-Request-Id") == "" {
296 req.Header.Set("X-Request-Id", reqid)
298 resp, err := kc.httpClient().Do(req)
300 // Probably a network error, may be transient,
302 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
303 retryList = append(retryList, host)
306 if resp.StatusCode != http.StatusOK {
308 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
310 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
311 url, resp.StatusCode, bytes.TrimSpace(respbody)))
313 if resp.StatusCode == 408 ||
314 resp.StatusCode == 429 ||
315 resp.StatusCode >= 500 {
316 // Timeout, too many requests, or other
317 // server side failure, transient
318 // error, can try again.
319 retryList = append(retryList, host)
320 } else if resp.StatusCode == 404 {
325 if expectLength < 0 {
326 if resp.ContentLength < 0 {
328 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
330 expectLength = resp.ContentLength
331 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
333 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
337 return HashCheckingReader{
340 Check: locator[0:32],
341 }, expectLength, url, resp.Header, nil
344 return nil, expectLength, url, resp.Header, nil
346 serversToTry = retryList
348 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
351 if count404 == numServers {
354 err = &ErrNotFound{multipleResponseError{
355 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
356 isTemp: len(serversToTry) > 0,
359 return nil, 0, "", nil, err
362 // attempt to create dir/subdir/ and its parents, up to but not
363 // including dir itself, using mode 0700.
364 func makedirs(dir, subdir string) {
365 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
366 dir = filepath.Join(dir, part)
371 // upstreamGateway creates/returns the KeepGateway stack used to read
372 // and write data: a disk-backed cache on top of an http backend.
373 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
375 defer kc.lock.Unlock()
376 if kc.gatewayStack != nil {
377 return kc.gatewayStack
380 if os.Geteuid() == 0 {
381 cachedir = rootCacheDir
382 makedirs("/", cachedir)
384 home := "/" + os.Getenv("HOME")
385 makedirs(home, userCacheDir)
386 cachedir = filepath.Join(home, userCacheDir)
388 kc.gatewayStack = &arvados.DiskCache{
390 MaxSize: kc.DiskCacheSize,
391 KeepGateway: &keepViaHTTP{kc},
393 return kc.gatewayStack
396 // LocalLocator returns a locator equivalent to the one supplied, but
397 // with a valid signature from the local cluster. If the given locator
398 // already has a local signature, it is returned unchanged.
399 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
400 return kc.upstreamGateway().LocalLocator(locator)
403 // Get retrieves a block, given a locator. Returns a reader, the
404 // expected data length, the URL the block is being fetched from, and
407 // If the block checksum does not match, the final Read() on the
408 // reader returned by this method will return a BadChecksum error
410 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
411 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
412 return rdr, size, url, err
415 // ReadAt retrieves a portion of block from the cache if it's
416 // present, otherwise from the network.
417 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
418 return kc.upstreamGateway().ReadAt(locator, p, off)
421 // BlockWrite writes a full block to upstream servers and saves a copy
422 // in the local cache.
423 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
424 return kc.upstreamGateway().BlockWrite(ctx, req)
427 // Ask verifies that a block with the given hash is available and
428 // readable, according to at least one Keep service. Unlike Get, it
429 // does not retrieve the data or verify that the data content matches
430 // the hash specified by the locator.
432 // Returns the data size (content length) reported by the Keep service
433 // and the URI reporting the data size.
434 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
435 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
436 return size, url, err
439 // GetIndex retrieves a list of blocks stored on the given server whose hashes
440 // begin with the given prefix. The returned reader will return an error (other
441 // than EOF) if the complete index cannot be retrieved.
443 // This is meant to be used only by system components and admin tools.
444 // It will return an error unless the client is using a "data manager token"
445 // recognized by the Keep services.
446 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
447 url := kc.LocalRoots()[keepServiceUUID]
449 return nil, ErrNoSuchKeepServer
457 req, err := http.NewRequest("GET", url, nil)
462 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
463 req.Header.Set("X-Request-Id", kc.getRequestID())
464 resp, err := kc.httpClient().Do(req)
469 defer resp.Body.Close()
471 if resp.StatusCode != http.StatusOK {
472 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
476 respBody, err = ioutil.ReadAll(resp.Body)
481 // Got index; verify that it is complete
482 // The response should be "\n" if no locators matched the prefix
483 // Else, it should be a list of locators followed by a blank line
484 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
485 return nil, ErrIncompleteIndex
488 // Got complete index; strip the trailing newline and send
489 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
492 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
493 // services: uuid -> baseURI.
494 func (kc *KeepClient) LocalRoots() map[string]string {
495 kc.discoverServices()
497 defer kc.lock.RUnlock()
501 // GatewayRoots returns the map of Keep remote gateway services:
503 func (kc *KeepClient) GatewayRoots() map[string]string {
504 kc.discoverServices()
506 defer kc.lock.RUnlock()
507 return kc.gatewayRoots
510 // WritableLocalRoots returns the map of writable local Keep services:
512 func (kc *KeepClient) WritableLocalRoots() map[string]string {
513 kc.discoverServices()
515 defer kc.lock.RUnlock()
516 return kc.writableLocalRoots
519 // SetServiceRoots disables service discovery and updates the
520 // localRoots and gatewayRoots maps, without disrupting operations
521 // that are already in progress.
523 // The supplied maps must not be modified after calling
525 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
526 kc.disableDiscovery = true
527 kc.setServiceRoots(locals, writables, gateways)
530 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
532 defer kc.lock.Unlock()
533 kc.localRoots = locals
534 kc.writableLocalRoots = writables
535 kc.gatewayRoots = gateways
538 // getSortedRoots returns a list of base URIs of Keep services, in the
539 // order they should be attempted in order to retrieve content for the
541 func (kc *KeepClient) getSortedRoots(locator string) []string {
543 for _, hint := range strings.Split(locator, "+") {
544 if len(hint) < 7 || hint[0:2] != "K@" {
545 // Not a service hint.
549 // +K@abcde means fetch from proxy at
550 // keep.abcde.arvadosapi.com
551 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
552 } else if len(hint) == 29 {
553 // +K@abcde-abcde-abcdeabcdeabcde means fetch
554 // from gateway with given uuid
555 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
556 found = append(found, gwURI)
558 // else this hint is no use to us; carry on.
561 // After trying all usable service hints, fall back to local roots.
562 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
566 func (kc *KeepClient) SetStorageClasses(sc []string) {
567 // make a copy so the caller can't mess with it.
568 kc.StorageClasses = append([]string{}, sc...)
572 // There are four global http.Client objects for the four
573 // possible permutations of TLS behavior (verify/skip-verify)
574 // and timeout settings (proxy/non-proxy).
575 defaultClient = map[bool]map[bool]HTTPClient{
576 // defaultClient[false] is used for verified TLS reqs
578 // defaultClient[true] is used for unverified
579 // (insecure) TLS reqs
582 defaultClientMtx sync.Mutex
585 // httpClient returns the HTTPClient field if it's not nil, otherwise
586 // whichever of the four global http.Client objects is suitable for
587 // the current environment (i.e., TLS verification on/off, keep
588 // services are/aren't proxies).
589 func (kc *KeepClient) httpClient() HTTPClient {
590 if kc.HTTPClient != nil {
593 defaultClientMtx.Lock()
594 defer defaultClientMtx.Unlock()
595 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
599 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
600 if kc.foundNonDiskSvc {
601 // Use longer timeouts when connecting to a proxy,
602 // because this usually means the intervening network
604 requestTimeout = DefaultProxyRequestTimeout
605 connectTimeout = DefaultProxyConnectTimeout
606 tlsTimeout = DefaultProxyTLSHandshakeTimeout
607 keepAlive = DefaultProxyKeepAlive
609 requestTimeout = DefaultRequestTimeout
610 connectTimeout = DefaultConnectTimeout
611 tlsTimeout = DefaultTLSHandshakeTimeout
612 keepAlive = DefaultKeepAlive
616 Timeout: requestTimeout,
617 // It's not safe to copy *http.DefaultTransport
618 // because it has a mutex (which might be locked)
619 // protecting a private map (which might not be nil).
620 // So we build our own, using the Go 1.12 default
621 // values, ignoring any changes the application has
622 // made to http.DefaultTransport.
623 Transport: &http.Transport{
624 DialContext: (&net.Dialer{
625 Timeout: connectTimeout,
626 KeepAlive: keepAlive,
630 IdleConnTimeout: 90 * time.Second,
631 TLSHandshakeTimeout: tlsTimeout,
632 ExpectContinueTimeout: 1 * time.Second,
633 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
636 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
640 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
642 func (kc *KeepClient) getRequestID() string {
643 if kc.RequestID != "" {
646 return reqIDGen.Next()
649 type Locator struct {
651 Size int // -1 if data size is not known
652 Hints []string // Including the size hint, if any
655 func (loc *Locator) String() string {
657 if len(loc.Hints) > 0 {
658 s = s + "+" + strings.Join(loc.Hints, "+")
663 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
665 func MakeLocator(path string) (*Locator, error) {
666 sm := locatorMatcher.FindStringSubmatch(path)
668 return nil, InvalidLocatorError
670 loc := Locator{Hash: sm[1], Size: -1}
672 loc.Hints = strings.Split(sm[3], "+")
674 loc.Hints = []string{}
676 if len(loc.Hints) > 0 {
677 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {