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.
25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
27 "git.arvados.org/arvados.git/sdk/go/httpserver"
30 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
31 const BLOCKSIZE = 64 * 1024 * 1024
34 DefaultRequestTimeout = 20 * time.Second
35 DefaultConnectTimeout = 2 * time.Second
36 DefaultTLSHandshakeTimeout = 4 * time.Second
37 DefaultKeepAlive = 180 * time.Second
39 DefaultProxyRequestTimeout = 300 * time.Second
40 DefaultProxyConnectTimeout = 30 * time.Second
41 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
42 DefaultProxyKeepAlive = 120 * time.Second
45 // Error interface with an error and boolean indicating whether the error is temporary
46 type Error interface {
51 // multipleResponseError is of type Error
52 type multipleResponseError struct {
57 func (e *multipleResponseError) Temporary() bool {
61 // BlockNotFound is a multipleResponseError where isTemp is false
62 var BlockNotFound = &ErrNotFound{multipleResponseError{
63 error: errors.New("Block not found"),
67 // ErrNotFound is a multipleResponseError where isTemp can be true or false
68 type ErrNotFound struct {
72 type InsufficientReplicasError struct{ error }
74 type OversizeBlockError struct{ error }
76 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
77 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
78 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
79 var InvalidLocatorError = errors.New("Invalid locator")
81 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
82 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
84 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
85 var ErrIncompleteIndex = errors.New("Got incomplete index")
88 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
89 XKeepReplicasStored = "X-Keep-Replicas-Stored"
90 XKeepStorageClasses = "X-Keep-Storage-Classes"
91 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
94 type HTTPClient interface {
95 Do(*http.Request) (*http.Response, error)
98 // KeepClient holds information about Arvados and Keep servers.
99 type KeepClient struct {
100 Arvados *arvadosclient.ArvadosClient
102 localRoots map[string]string
103 writableLocalRoots map[string]string
104 gatewayRoots map[string]string
106 HTTPClient HTTPClient
108 BlockCache *BlockCache
110 StorageClasses []string
111 DefaultStorageClasses []string // Set by cluster's exported config
113 // set to 1 if all writable services are of disk type, otherwise 0
114 replicasPerService int
116 // Any non-disk typed services found in the list of keepservers?
119 // Disable automatic discovery of keep services
120 disableDiscovery bool
123 func (kc *KeepClient) loadDefaultClasses() error {
124 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
128 classes := scData.(map[string]interface{})
129 for scName := range classes {
130 scConf, _ := classes[scName].(map[string]interface{})
131 isDefault, ok := scConf["Default"].(bool)
133 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
139 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
140 // DiscoverKeepServices(), and returns when the client is ready to
142 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
144 return kc, kc.discoverServices()
147 // New creates a new KeepClient. Service discovery will occur on the
148 // next read/write operation.
149 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
150 defaultReplicationLevel := 2
151 value, err := arv.Discovery("defaultCollectionReplication")
153 v, ok := value.(float64)
155 defaultReplicationLevel = int(v)
160 Want_replicas: defaultReplicationLevel,
163 err = kc.loadDefaultClasses()
165 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
170 // PutHR puts a block given the block hash, a reader, and the number of bytes
171 // to read from the reader (which must be between 0 and BLOCKSIZE).
173 // Returns the locator for the written block, the number of replicas
174 // written, and an error.
176 // Returns an InsufficientReplicasError if 0 <= replicas <
177 // kc.Wants_replicas.
178 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
179 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
182 DataSize: int(dataBytes),
184 return resp.Locator, resp.Replicas, err
187 // PutHB writes a block to Keep. The hash of the bytes is given in
188 // hash, and the data is given in buf.
190 // Return values are the same as for PutHR.
191 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
192 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
196 return resp.Locator, resp.Replicas, err
199 // PutB writes a block to Keep. It computes the hash itself.
201 // Return values are the same as for PutHR.
202 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
203 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
206 return resp.Locator, resp.Replicas, err
209 // PutR writes a block to Keep. It first reads all data from r into a buffer
210 // in order to compute the hash.
212 // Return values are the same as for PutHR.
214 // If the block hash and data size are known, PutHR is more efficient.
215 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
216 buffer, err := ioutil.ReadAll(r)
220 return kc.PutB(buffer)
223 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
224 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
225 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
228 reqid := kc.getRequestID()
230 var expectLength int64
231 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
233 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
241 triesRemaining := 1 + kc.Retries
243 serversToTry := kc.getSortedRoots(locator)
245 numServers := len(serversToTry)
248 var retryList []string
250 for triesRemaining > 0 {
254 for _, host := range serversToTry {
255 url := host + "/" + locator
257 req, err := http.NewRequest(method, url, nil)
259 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
262 for k, v := range header {
263 req.Header[k] = append([]string(nil), v...)
265 if req.Header.Get("Authorization") == "" {
266 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
268 if req.Header.Get("X-Request-Id") == "" {
269 req.Header.Set("X-Request-Id", reqid)
271 resp, err := kc.httpClient().Do(req)
273 // Probably a network error, may be transient,
275 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
276 retryList = append(retryList, host)
279 if resp.StatusCode != http.StatusOK {
281 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
283 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
284 url, resp.StatusCode, bytes.TrimSpace(respbody)))
286 if resp.StatusCode == 408 ||
287 resp.StatusCode == 429 ||
288 resp.StatusCode >= 500 {
289 // Timeout, too many requests, or other
290 // server side failure, transient
291 // error, can try again.
292 retryList = append(retryList, host)
293 } else if resp.StatusCode == 404 {
298 if expectLength < 0 {
299 if resp.ContentLength < 0 {
301 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
303 expectLength = resp.ContentLength
304 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
306 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
310 return HashCheckingReader{
313 Check: locator[0:32],
314 }, expectLength, url, resp.Header, nil
317 return nil, expectLength, url, resp.Header, nil
319 serversToTry = retryList
321 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
324 if count404 == numServers {
327 err = &ErrNotFound{multipleResponseError{
328 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
329 isTemp: len(serversToTry) > 0,
332 return nil, 0, "", nil, err
335 // LocalLocator returns a locator equivalent to the one supplied, but
336 // with a valid signature from the local cluster. If the given locator
337 // already has a local signature, it is returned unchanged.
338 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
339 if !strings.Contains(locator, "+R") {
340 // Either it has +A, or it's unsigned and we assume
341 // it's a local locator on a site with signatures
345 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
346 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
350 loc := hdr.Get("X-Keep-Locator")
352 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
357 // Get retrieves a block, given a locator. Returns a reader, the
358 // expected data length, the URL the block is being fetched from, and
361 // If the block checksum does not match, the final Read() on the
362 // reader returned by this method will return a BadChecksum error
364 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
365 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
366 return rdr, size, url, err
369 // ReadAt retrieves a portion of block from the cache if it's
370 // present, otherwise from the network.
371 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
372 return kc.cache().ReadAt(kc, locator, p, off)
375 // Ask verifies that a block with the given hash is available and
376 // readable, according to at least one Keep service. Unlike Get, it
377 // does not retrieve the data or verify that the data content matches
378 // the hash specified by the locator.
380 // Returns the data size (content length) reported by the Keep service
381 // and the URI reporting the data size.
382 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
383 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
384 return size, url, err
387 // GetIndex retrieves a list of blocks stored on the given server whose hashes
388 // begin with the given prefix. The returned reader will return an error (other
389 // than EOF) if the complete index cannot be retrieved.
391 // This is meant to be used only by system components and admin tools.
392 // It will return an error unless the client is using a "data manager token"
393 // recognized by the Keep services.
394 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
395 url := kc.LocalRoots()[keepServiceUUID]
397 return nil, ErrNoSuchKeepServer
405 req, err := http.NewRequest("GET", url, nil)
410 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
411 req.Header.Set("X-Request-Id", kc.getRequestID())
412 resp, err := kc.httpClient().Do(req)
417 defer resp.Body.Close()
419 if resp.StatusCode != http.StatusOK {
420 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
424 respBody, err = ioutil.ReadAll(resp.Body)
429 // Got index; verify that it is complete
430 // The response should be "\n" if no locators matched the prefix
431 // Else, it should be a list of locators followed by a blank line
432 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
433 return nil, ErrIncompleteIndex
436 // Got complete index; strip the trailing newline and send
437 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
440 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
441 // services: uuid -> baseURI.
442 func (kc *KeepClient) LocalRoots() map[string]string {
443 kc.discoverServices()
445 defer kc.lock.RUnlock()
449 // GatewayRoots returns the map of Keep remote gateway services:
451 func (kc *KeepClient) GatewayRoots() map[string]string {
452 kc.discoverServices()
454 defer kc.lock.RUnlock()
455 return kc.gatewayRoots
458 // WritableLocalRoots returns the map of writable local Keep services:
460 func (kc *KeepClient) WritableLocalRoots() map[string]string {
461 kc.discoverServices()
463 defer kc.lock.RUnlock()
464 return kc.writableLocalRoots
467 // SetServiceRoots disables service discovery and updates the
468 // localRoots and gatewayRoots maps, without disrupting operations
469 // that are already in progress.
471 // The supplied maps must not be modified after calling
473 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
474 kc.disableDiscovery = true
475 kc.setServiceRoots(locals, writables, gateways)
478 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
480 defer kc.lock.Unlock()
481 kc.localRoots = locals
482 kc.writableLocalRoots = writables
483 kc.gatewayRoots = gateways
486 // getSortedRoots returns a list of base URIs of Keep services, in the
487 // order they should be attempted in order to retrieve content for the
489 func (kc *KeepClient) getSortedRoots(locator string) []string {
491 for _, hint := range strings.Split(locator, "+") {
492 if len(hint) < 7 || hint[0:2] != "K@" {
493 // Not a service hint.
497 // +K@abcde means fetch from proxy at
498 // keep.abcde.arvadosapi.com
499 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
500 } else if len(hint) == 29 {
501 // +K@abcde-abcde-abcdeabcdeabcde means fetch
502 // from gateway with given uuid
503 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
504 found = append(found, gwURI)
506 // else this hint is no use to us; carry on.
509 // After trying all usable service hints, fall back to local roots.
510 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
514 func (kc *KeepClient) cache() *BlockCache {
515 if kc.BlockCache != nil {
518 return DefaultBlockCache
521 func (kc *KeepClient) ClearBlockCache() {
525 func (kc *KeepClient) SetStorageClasses(sc []string) {
526 // make a copy so the caller can't mess with it.
527 kc.StorageClasses = append([]string{}, sc...)
531 // There are four global http.Client objects for the four
532 // possible permutations of TLS behavior (verify/skip-verify)
533 // and timeout settings (proxy/non-proxy).
534 defaultClient = map[bool]map[bool]HTTPClient{
535 // defaultClient[false] is used for verified TLS reqs
537 // defaultClient[true] is used for unverified
538 // (insecure) TLS reqs
541 defaultClientMtx sync.Mutex
544 // httpClient returns the HTTPClient field if it's not nil, otherwise
545 // whichever of the four global http.Client objects is suitable for
546 // the current environment (i.e., TLS verification on/off, keep
547 // services are/aren't proxies).
548 func (kc *KeepClient) httpClient() HTTPClient {
549 if kc.HTTPClient != nil {
552 defaultClientMtx.Lock()
553 defer defaultClientMtx.Unlock()
554 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
558 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
559 if kc.foundNonDiskSvc {
560 // Use longer timeouts when connecting to a proxy,
561 // because this usually means the intervening network
563 requestTimeout = DefaultProxyRequestTimeout
564 connectTimeout = DefaultProxyConnectTimeout
565 tlsTimeout = DefaultProxyTLSHandshakeTimeout
566 keepAlive = DefaultProxyKeepAlive
568 requestTimeout = DefaultRequestTimeout
569 connectTimeout = DefaultConnectTimeout
570 tlsTimeout = DefaultTLSHandshakeTimeout
571 keepAlive = DefaultKeepAlive
575 Timeout: requestTimeout,
576 // It's not safe to copy *http.DefaultTransport
577 // because it has a mutex (which might be locked)
578 // protecting a private map (which might not be nil).
579 // So we build our own, using the Go 1.12 default
580 // values, ignoring any changes the application has
581 // made to http.DefaultTransport.
582 Transport: &http.Transport{
583 DialContext: (&net.Dialer{
584 Timeout: connectTimeout,
585 KeepAlive: keepAlive,
589 IdleConnTimeout: 90 * time.Second,
590 TLSHandshakeTimeout: tlsTimeout,
591 ExpectContinueTimeout: 1 * time.Second,
592 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
595 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
599 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
601 func (kc *KeepClient) getRequestID() string {
602 if kc.RequestID != "" {
605 return reqIDGen.Next()
608 type Locator struct {
610 Size int // -1 if data size is not known
611 Hints []string // Including the size hint, if any
614 func (loc *Locator) String() string {
616 if len(loc.Hints) > 0 {
617 s = s + "+" + strings.Join(loc.Hints, "+")
622 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
624 func MakeLocator(path string) (*Locator, error) {
625 sm := locatorMatcher.FindStringSubmatch(path)
627 return nil, InvalidLocatorError
629 loc := Locator{Hash: sm[1], Size: -1}
631 loc.Hints = strings.Split(sm[3], "+")
633 loc.Hints = []string{}
635 if len(loc.Hints) > 0 {
636 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {