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
47 // Error interface with an error and boolean indicating whether the error is temporary
48 type Error interface {
53 // multipleResponseError is of type Error
54 type multipleResponseError struct {
59 func (e *multipleResponseError) Temporary() bool {
63 // BlockNotFound is a multipleResponseError where isTemp is false
64 var BlockNotFound = &ErrNotFound{multipleResponseError{
65 error: errors.New("Block not found"),
69 // ErrNotFound is a multipleResponseError where isTemp can be true or false
70 type ErrNotFound struct {
74 type InsufficientReplicasError struct{ error }
76 type OversizeBlockError struct{ error }
78 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
79 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
80 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
81 var InvalidLocatorError = errors.New("Invalid locator")
83 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
84 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
86 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
87 var ErrIncompleteIndex = errors.New("Got incomplete index")
90 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
91 XKeepReplicasStored = "X-Keep-Replicas-Stored"
92 XKeepStorageClasses = "X-Keep-Storage-Classes"
93 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
96 type HTTPClient interface {
97 Do(*http.Request) (*http.Response, error)
100 // KeepClient holds information about Arvados and Keep servers.
101 type KeepClient struct {
102 Arvados *arvadosclient.ArvadosClient
104 localRoots map[string]string
105 writableLocalRoots map[string]string
106 gatewayRoots map[string]string
108 HTTPClient HTTPClient
110 BlockCache *BlockCache
112 StorageClasses []string
113 DefaultStorageClasses []string // Set by cluster's exported config
115 // set to 1 if all writable services are of disk type, otherwise 0
116 replicasPerService int
118 // Any non-disk typed services found in the list of keepservers?
121 // Disable automatic discovery of keep services
122 disableDiscovery bool
124 gatewayStack arvados.KeepGateway
127 func (kc *KeepClient) loadDefaultClasses() error {
128 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
132 classes := scData.(map[string]interface{})
133 for scName := range classes {
134 scConf, _ := classes[scName].(map[string]interface{})
135 isDefault, ok := scConf["Default"].(bool)
137 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
143 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
144 // DiscoverKeepServices(), and returns when the client is ready to
146 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
148 return kc, kc.discoverServices()
151 // New creates a new KeepClient. Service discovery will occur on the
152 // next read/write operation.
153 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
154 defaultReplicationLevel := 2
155 value, err := arv.Discovery("defaultCollectionReplication")
157 v, ok := value.(float64)
159 defaultReplicationLevel = int(v)
164 Want_replicas: defaultReplicationLevel,
167 err = kc.loadDefaultClasses()
169 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
174 // PutHR puts a block given the block hash, a reader, and the number of bytes
175 // to read from the reader (which must be between 0 and BLOCKSIZE).
177 // Returns the locator for the written block, the number of replicas
178 // written, and an error.
180 // Returns an InsufficientReplicasError if 0 <= replicas <
181 // kc.Wants_replicas.
182 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
183 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
186 DataSize: int(dataBytes),
188 return resp.Locator, resp.Replicas, err
191 // PutHB writes a block to Keep. The hash of the bytes is given in
192 // hash, and the data is given in buf.
194 // Return values are the same as for PutHR.
195 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
196 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
200 return resp.Locator, resp.Replicas, err
203 // PutB writes a block to Keep. It computes the hash itself.
205 // Return values are the same as for PutHR.
206 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
207 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
210 return resp.Locator, resp.Replicas, err
213 // PutR writes a block to Keep. It first reads all data from r into a buffer
214 // in order to compute the hash.
216 // Return values are the same as for PutHR.
218 // If the block hash and data size are known, PutHR is more efficient.
219 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
220 buffer, err := ioutil.ReadAll(r)
224 return kc.PutB(buffer)
227 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
228 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
229 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
232 reqid := kc.getRequestID()
234 var expectLength int64
235 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
237 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
245 triesRemaining := 1 + kc.Retries
247 serversToTry := kc.getSortedRoots(locator)
249 numServers := len(serversToTry)
252 var retryList []string
254 for triesRemaining > 0 {
258 for _, host := range serversToTry {
259 url := host + "/" + locator
261 req, err := http.NewRequest(method, url, nil)
263 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
266 for k, v := range header {
267 req.Header[k] = append([]string(nil), v...)
269 if req.Header.Get("Authorization") == "" {
270 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
272 if req.Header.Get("X-Request-Id") == "" {
273 req.Header.Set("X-Request-Id", reqid)
275 resp, err := kc.httpClient().Do(req)
277 // Probably a network error, may be transient,
279 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
280 retryList = append(retryList, host)
283 if resp.StatusCode != http.StatusOK {
285 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
287 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
288 url, resp.StatusCode, bytes.TrimSpace(respbody)))
290 if resp.StatusCode == 408 ||
291 resp.StatusCode == 429 ||
292 resp.StatusCode >= 500 {
293 // Timeout, too many requests, or other
294 // server side failure, transient
295 // error, can try again.
296 retryList = append(retryList, host)
297 } else if resp.StatusCode == 404 {
302 if expectLength < 0 {
303 if resp.ContentLength < 0 {
305 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
307 expectLength = resp.ContentLength
308 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
310 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
314 return HashCheckingReader{
317 Check: locator[0:32],
318 }, expectLength, url, resp.Header, nil
321 return nil, expectLength, url, resp.Header, nil
323 serversToTry = retryList
325 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
328 if count404 == numServers {
331 err = &ErrNotFound{multipleResponseError{
332 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
333 isTemp: len(serversToTry) > 0,
336 return nil, 0, "", nil, err
339 // upstreamGateway creates/returns the KeepGateway stack used to read
340 // and write data: a memory cache, a disk-backed cache if available,
341 // and an http backend.
342 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
344 defer kc.lock.Unlock()
345 if kc.gatewayStack != nil {
346 return kc.gatewayStack
348 var stack arvados.KeepGateway = &keepViaHTTP{kc}
350 // Wrap with a disk cache, if cache dir is writable
351 home := os.Getenv("HOME")
352 if fi, err := os.Stat(home); home != "" && err == nil && fi.IsDir() {
355 for _, part := range []string{".cache", "arvados", "keep"} {
356 dir = filepath.Join(dir, part)
357 err = os.Mkdir(dir, 0700)
359 if err == nil || os.IsExist(err) {
360 os.Mkdir(filepath.Join(dir, "tmp"), 0700)
361 err = os.WriteFile(filepath.Join(dir, "tmp", "check.tmp"), nil, 0600)
363 stack = &arvados.DiskCache{
370 stack = &keepViaBlockCache{
374 kc.gatewayStack = stack
378 // LocalLocator returns a locator equivalent to the one supplied, but
379 // with a valid signature from the local cluster. If the given locator
380 // already has a local signature, it is returned unchanged.
381 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
382 if !strings.Contains(locator, "+R") {
383 // Either it has +A, or it's unsigned and we assume
384 // it's a local locator on a site with signatures
388 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
389 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
393 loc := hdr.Get("X-Keep-Locator")
395 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
400 // Get retrieves a block, given a locator. Returns a reader, the
401 // expected data length, the URL the block is being fetched from, and
404 // If the block checksum does not match, the final Read() on the
405 // reader returned by this method will return a BadChecksum error
407 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
408 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
409 return rdr, size, url, err
412 // ReadAt retrieves a portion of block from the cache if it's
413 // present, otherwise from the network.
414 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
415 return kc.upstreamGateway().ReadAt(locator, p, off)
418 // Ask verifies that a block with the given hash is available and
419 // readable, according to at least one Keep service. Unlike Get, it
420 // does not retrieve the data or verify that the data content matches
421 // the hash specified by the locator.
423 // Returns the data size (content length) reported by the Keep service
424 // and the URI reporting the data size.
425 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
426 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
427 return size, url, err
430 // GetIndex retrieves a list of blocks stored on the given server whose hashes
431 // begin with the given prefix. The returned reader will return an error (other
432 // than EOF) if the complete index cannot be retrieved.
434 // This is meant to be used only by system components and admin tools.
435 // It will return an error unless the client is using a "data manager token"
436 // recognized by the Keep services.
437 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
438 url := kc.LocalRoots()[keepServiceUUID]
440 return nil, ErrNoSuchKeepServer
448 req, err := http.NewRequest("GET", url, nil)
453 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
454 req.Header.Set("X-Request-Id", kc.getRequestID())
455 resp, err := kc.httpClient().Do(req)
460 defer resp.Body.Close()
462 if resp.StatusCode != http.StatusOK {
463 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
467 respBody, err = ioutil.ReadAll(resp.Body)
472 // Got index; verify that it is complete
473 // The response should be "\n" if no locators matched the prefix
474 // Else, it should be a list of locators followed by a blank line
475 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
476 return nil, ErrIncompleteIndex
479 // Got complete index; strip the trailing newline and send
480 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
483 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
484 // services: uuid -> baseURI.
485 func (kc *KeepClient) LocalRoots() map[string]string {
486 kc.discoverServices()
488 defer kc.lock.RUnlock()
492 // GatewayRoots returns the map of Keep remote gateway services:
494 func (kc *KeepClient) GatewayRoots() map[string]string {
495 kc.discoverServices()
497 defer kc.lock.RUnlock()
498 return kc.gatewayRoots
501 // WritableLocalRoots returns the map of writable local Keep services:
503 func (kc *KeepClient) WritableLocalRoots() map[string]string {
504 kc.discoverServices()
506 defer kc.lock.RUnlock()
507 return kc.writableLocalRoots
510 // SetServiceRoots disables service discovery and updates the
511 // localRoots and gatewayRoots maps, without disrupting operations
512 // that are already in progress.
514 // The supplied maps must not be modified after calling
516 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
517 kc.disableDiscovery = true
518 kc.setServiceRoots(locals, writables, gateways)
521 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
523 defer kc.lock.Unlock()
524 kc.localRoots = locals
525 kc.writableLocalRoots = writables
526 kc.gatewayRoots = gateways
529 // getSortedRoots returns a list of base URIs of Keep services, in the
530 // order they should be attempted in order to retrieve content for the
532 func (kc *KeepClient) getSortedRoots(locator string) []string {
534 for _, hint := range strings.Split(locator, "+") {
535 if len(hint) < 7 || hint[0:2] != "K@" {
536 // Not a service hint.
540 // +K@abcde means fetch from proxy at
541 // keep.abcde.arvadosapi.com
542 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
543 } else if len(hint) == 29 {
544 // +K@abcde-abcde-abcdeabcdeabcde means fetch
545 // from gateway with given uuid
546 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
547 found = append(found, gwURI)
549 // else this hint is no use to us; carry on.
552 // After trying all usable service hints, fall back to local roots.
553 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
557 func (kc *KeepClient) cache() *BlockCache {
558 if kc.BlockCache != nil {
561 return DefaultBlockCache
564 func (kc *KeepClient) ClearBlockCache() {
568 func (kc *KeepClient) SetStorageClasses(sc []string) {
569 // make a copy so the caller can't mess with it.
570 kc.StorageClasses = append([]string{}, sc...)
574 // There are four global http.Client objects for the four
575 // possible permutations of TLS behavior (verify/skip-verify)
576 // and timeout settings (proxy/non-proxy).
577 defaultClient = map[bool]map[bool]HTTPClient{
578 // defaultClient[false] is used for verified TLS reqs
580 // defaultClient[true] is used for unverified
581 // (insecure) TLS reqs
584 defaultClientMtx sync.Mutex
587 // httpClient returns the HTTPClient field if it's not nil, otherwise
588 // whichever of the four global http.Client objects is suitable for
589 // the current environment (i.e., TLS verification on/off, keep
590 // services are/aren't proxies).
591 func (kc *KeepClient) httpClient() HTTPClient {
592 if kc.HTTPClient != nil {
595 defaultClientMtx.Lock()
596 defer defaultClientMtx.Unlock()
597 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
601 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
602 if kc.foundNonDiskSvc {
603 // Use longer timeouts when connecting to a proxy,
604 // because this usually means the intervening network
606 requestTimeout = DefaultProxyRequestTimeout
607 connectTimeout = DefaultProxyConnectTimeout
608 tlsTimeout = DefaultProxyTLSHandshakeTimeout
609 keepAlive = DefaultProxyKeepAlive
611 requestTimeout = DefaultRequestTimeout
612 connectTimeout = DefaultConnectTimeout
613 tlsTimeout = DefaultTLSHandshakeTimeout
614 keepAlive = DefaultKeepAlive
618 Timeout: requestTimeout,
619 // It's not safe to copy *http.DefaultTransport
620 // because it has a mutex (which might be locked)
621 // protecting a private map (which might not be nil).
622 // So we build our own, using the Go 1.12 default
623 // values, ignoring any changes the application has
624 // made to http.DefaultTransport.
625 Transport: &http.Transport{
626 DialContext: (&net.Dialer{
627 Timeout: connectTimeout,
628 KeepAlive: keepAlive,
632 IdleConnTimeout: 90 * time.Second,
633 TLSHandshakeTimeout: tlsTimeout,
634 ExpectContinueTimeout: 1 * time.Second,
635 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
638 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
642 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
644 func (kc *KeepClient) getRequestID() string {
645 if kc.RequestID != "" {
648 return reqIDGen.Next()
651 type Locator struct {
653 Size int // -1 if data size is not known
654 Hints []string // Including the size hint, if any
657 func (loc *Locator) String() string {
659 if len(loc.Hints) > 0 {
660 s = s + "+" + strings.Join(loc.Hints, "+")
665 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
667 func MakeLocator(path string) (*Locator, error) {
668 sm := locatorMatcher.FindStringSubmatch(path)
670 return nil, InvalidLocatorError
672 loc := Locator{Hash: sm[1], Size: -1}
674 loc.Hints = strings.Split(sm[3], "+")
676 loc.Hints = []string{}
678 if len(loc.Hints) > 0 {
679 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {