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
113 BlockCache *BlockCache
115 StorageClasses []string
116 DefaultStorageClasses []string // Set by cluster's exported config
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) loadDefaultClasses() error {
131 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
135 classes := scData.(map[string]interface{})
136 for scName := range classes {
137 scConf, _ := classes[scName].(map[string]interface{})
138 isDefault, ok := scConf["Default"].(bool)
140 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
146 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
147 // DiscoverKeepServices(), and returns when the client is ready to
149 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
151 return kc, kc.discoverServices()
154 // New creates a new KeepClient. Service discovery will occur on the
155 // next read/write operation.
156 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
157 defaultReplicationLevel := 2
158 value, err := arv.Discovery("defaultCollectionReplication")
160 v, ok := value.(float64)
162 defaultReplicationLevel = int(v)
167 Want_replicas: defaultReplicationLevel,
170 err = kc.loadDefaultClasses()
172 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
177 // PutHR puts a block given the block hash, a reader, and the number of bytes
178 // to read from the reader (which must be between 0 and BLOCKSIZE).
180 // Returns the locator for the written block, the number of replicas
181 // written, and an error.
183 // Returns an InsufficientReplicasError if 0 <= replicas <
184 // kc.Wants_replicas.
185 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
186 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
189 DataSize: int(dataBytes),
191 return resp.Locator, resp.Replicas, err
194 // PutHB writes a block to Keep. The hash of the bytes is given in
195 // hash, and the data is given in buf.
197 // Return values are the same as for PutHR.
198 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
199 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
203 return resp.Locator, resp.Replicas, err
206 // PutB writes a block to Keep. It computes the hash itself.
208 // Return values are the same as for PutHR.
209 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
210 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
213 return resp.Locator, resp.Replicas, err
216 // PutR writes a block to Keep. It first reads all data from r into a buffer
217 // in order to compute the hash.
219 // Return values are the same as for PutHR.
221 // If the block hash and data size are known, PutHR is more efficient.
222 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
223 buffer, err := ioutil.ReadAll(r)
227 return kc.PutB(buffer)
230 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
231 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
232 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
235 reqid := kc.getRequestID()
237 var expectLength int64
238 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
240 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
248 triesRemaining := 1 + kc.Retries
250 serversToTry := kc.getSortedRoots(locator)
252 numServers := len(serversToTry)
255 var retryList []string
257 for triesRemaining > 0 {
261 for _, host := range serversToTry {
262 url := host + "/" + locator
264 req, err := http.NewRequest(method, url, nil)
266 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
269 for k, v := range header {
270 req.Header[k] = append([]string(nil), v...)
272 if req.Header.Get("Authorization") == "" {
273 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
275 if req.Header.Get("X-Request-Id") == "" {
276 req.Header.Set("X-Request-Id", reqid)
278 resp, err := kc.httpClient().Do(req)
280 // Probably a network error, may be transient,
282 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
283 retryList = append(retryList, host)
286 if resp.StatusCode != http.StatusOK {
288 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
290 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
291 url, resp.StatusCode, bytes.TrimSpace(respbody)))
293 if resp.StatusCode == 408 ||
294 resp.StatusCode == 429 ||
295 resp.StatusCode >= 500 {
296 // Timeout, too many requests, or other
297 // server side failure, transient
298 // error, can try again.
299 retryList = append(retryList, host)
300 } else if resp.StatusCode == 404 {
305 if expectLength < 0 {
306 if resp.ContentLength < 0 {
308 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
310 expectLength = resp.ContentLength
311 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
313 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
317 return HashCheckingReader{
320 Check: locator[0:32],
321 }, expectLength, url, resp.Header, nil
324 return nil, expectLength, url, resp.Header, nil
326 serversToTry = retryList
328 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
331 if count404 == numServers {
334 err = &ErrNotFound{multipleResponseError{
335 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
336 isTemp: len(serversToTry) > 0,
339 return nil, 0, "", nil, err
342 // attempt to create dir/subdir/ and its parents, up to but not
343 // including dir itself, using mode 0700.
344 func makedirs(dir, subdir string) {
345 for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
346 dir = filepath.Join(dir, part)
351 // upstreamGateway creates/returns the KeepGateway stack used to read
352 // and write data: a disk-backed cache on top of an http backend.
353 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
355 defer kc.lock.Unlock()
356 if kc.gatewayStack != nil {
357 return kc.gatewayStack
360 if os.Geteuid() == 0 {
361 cachedir = rootCacheDir
362 makedirs("/", cachedir)
364 home := "/" + os.Getenv("HOME")
365 makedirs(home, userCacheDir)
366 cachedir = filepath.Join(home, userCacheDir)
368 kc.gatewayStack = &arvados.DiskCache{
370 KeepGateway: &keepViaHTTP{kc},
372 return kc.gatewayStack
375 // LocalLocator returns a locator equivalent to the one supplied, but
376 // with a valid signature from the local cluster. If the given locator
377 // already has a local signature, it is returned unchanged.
378 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
379 return kc.upstreamGateway().LocalLocator(locator)
382 // Get retrieves a block, given a locator. Returns a reader, the
383 // expected data length, the URL the block is being fetched from, and
386 // If the block checksum does not match, the final Read() on the
387 // reader returned by this method will return a BadChecksum error
389 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
390 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
391 return rdr, size, url, err
394 // ReadAt retrieves a portion of block from the cache if it's
395 // present, otherwise from the network.
396 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
397 return kc.upstreamGateway().ReadAt(locator, p, off)
400 // BlockWrite writes a full block to upstream servers and saves a copy
401 // in the local cache.
402 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
403 return kc.upstreamGateway().BlockWrite(ctx, req)
406 // Ask verifies that a block with the given hash is available and
407 // readable, according to at least one Keep service. Unlike Get, it
408 // does not retrieve the data or verify that the data content matches
409 // the hash specified by the locator.
411 // Returns the data size (content length) reported by the Keep service
412 // and the URI reporting the data size.
413 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
414 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
415 return size, url, err
418 // GetIndex retrieves a list of blocks stored on the given server whose hashes
419 // begin with the given prefix. The returned reader will return an error (other
420 // than EOF) if the complete index cannot be retrieved.
422 // This is meant to be used only by system components and admin tools.
423 // It will return an error unless the client is using a "data manager token"
424 // recognized by the Keep services.
425 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
426 url := kc.LocalRoots()[keepServiceUUID]
428 return nil, ErrNoSuchKeepServer
436 req, err := http.NewRequest("GET", url, nil)
441 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
442 req.Header.Set("X-Request-Id", kc.getRequestID())
443 resp, err := kc.httpClient().Do(req)
448 defer resp.Body.Close()
450 if resp.StatusCode != http.StatusOK {
451 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
455 respBody, err = ioutil.ReadAll(resp.Body)
460 // Got index; verify that it is complete
461 // The response should be "\n" if no locators matched the prefix
462 // Else, it should be a list of locators followed by a blank line
463 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
464 return nil, ErrIncompleteIndex
467 // Got complete index; strip the trailing newline and send
468 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
471 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
472 // services: uuid -> baseURI.
473 func (kc *KeepClient) LocalRoots() map[string]string {
474 kc.discoverServices()
476 defer kc.lock.RUnlock()
480 // GatewayRoots returns the map of Keep remote gateway services:
482 func (kc *KeepClient) GatewayRoots() map[string]string {
483 kc.discoverServices()
485 defer kc.lock.RUnlock()
486 return kc.gatewayRoots
489 // WritableLocalRoots returns the map of writable local Keep services:
491 func (kc *KeepClient) WritableLocalRoots() map[string]string {
492 kc.discoverServices()
494 defer kc.lock.RUnlock()
495 return kc.writableLocalRoots
498 // SetServiceRoots disables service discovery and updates the
499 // localRoots and gatewayRoots maps, without disrupting operations
500 // that are already in progress.
502 // The supplied maps must not be modified after calling
504 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
505 kc.disableDiscovery = true
506 kc.setServiceRoots(locals, writables, gateways)
509 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
511 defer kc.lock.Unlock()
512 kc.localRoots = locals
513 kc.writableLocalRoots = writables
514 kc.gatewayRoots = gateways
517 // getSortedRoots returns a list of base URIs of Keep services, in the
518 // order they should be attempted in order to retrieve content for the
520 func (kc *KeepClient) getSortedRoots(locator string) []string {
522 for _, hint := range strings.Split(locator, "+") {
523 if len(hint) < 7 || hint[0:2] != "K@" {
524 // Not a service hint.
528 // +K@abcde means fetch from proxy at
529 // keep.abcde.arvadosapi.com
530 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
531 } else if len(hint) == 29 {
532 // +K@abcde-abcde-abcdeabcdeabcde means fetch
533 // from gateway with given uuid
534 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
535 found = append(found, gwURI)
537 // else this hint is no use to us; carry on.
540 // After trying all usable service hints, fall back to local roots.
541 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
545 func (kc *KeepClient) cache() *BlockCache {
546 if kc.BlockCache != nil {
549 return DefaultBlockCache
552 func (kc *KeepClient) ClearBlockCache() {
556 func (kc *KeepClient) SetStorageClasses(sc []string) {
557 // make a copy so the caller can't mess with it.
558 kc.StorageClasses = append([]string{}, sc...)
562 // There are four global http.Client objects for the four
563 // possible permutations of TLS behavior (verify/skip-verify)
564 // and timeout settings (proxy/non-proxy).
565 defaultClient = map[bool]map[bool]HTTPClient{
566 // defaultClient[false] is used for verified TLS reqs
568 // defaultClient[true] is used for unverified
569 // (insecure) TLS reqs
572 defaultClientMtx sync.Mutex
575 // httpClient returns the HTTPClient field if it's not nil, otherwise
576 // whichever of the four global http.Client objects is suitable for
577 // the current environment (i.e., TLS verification on/off, keep
578 // services are/aren't proxies).
579 func (kc *KeepClient) httpClient() HTTPClient {
580 if kc.HTTPClient != nil {
583 defaultClientMtx.Lock()
584 defer defaultClientMtx.Unlock()
585 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
589 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
590 if kc.foundNonDiskSvc {
591 // Use longer timeouts when connecting to a proxy,
592 // because this usually means the intervening network
594 requestTimeout = DefaultProxyRequestTimeout
595 connectTimeout = DefaultProxyConnectTimeout
596 tlsTimeout = DefaultProxyTLSHandshakeTimeout
597 keepAlive = DefaultProxyKeepAlive
599 requestTimeout = DefaultRequestTimeout
600 connectTimeout = DefaultConnectTimeout
601 tlsTimeout = DefaultTLSHandshakeTimeout
602 keepAlive = DefaultKeepAlive
606 Timeout: requestTimeout,
607 // It's not safe to copy *http.DefaultTransport
608 // because it has a mutex (which might be locked)
609 // protecting a private map (which might not be nil).
610 // So we build our own, using the Go 1.12 default
611 // values, ignoring any changes the application has
612 // made to http.DefaultTransport.
613 Transport: &http.Transport{
614 DialContext: (&net.Dialer{
615 Timeout: connectTimeout,
616 KeepAlive: keepAlive,
620 IdleConnTimeout: 90 * time.Second,
621 TLSHandshakeTimeout: tlsTimeout,
622 ExpectContinueTimeout: 1 * time.Second,
623 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
626 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
630 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
632 func (kc *KeepClient) getRequestID() string {
633 if kc.RequestID != "" {
636 return reqIDGen.Next()
639 type Locator struct {
641 Size int // -1 if data size is not known
642 Hints []string // Including the size hint, if any
645 func (loc *Locator) String() string {
647 if len(loc.Hints) > 0 {
648 s = s + "+" + strings.Join(loc.Hints, "+")
653 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
655 func MakeLocator(path string) (*Locator, error) {
656 sm := locatorMatcher.FindStringSubmatch(path)
658 return nil, InvalidLocatorError
660 loc := Locator{Hash: sm[1], Size: -1}
662 loc.Hints = strings.Split(sm[3], "+")
664 loc.Hints = []string{}
666 if len(loc.Hints) > 0 {
667 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {