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) Clone() *KeepClient {
125 defer kc.lock.Unlock()
128 Want_replicas: kc.Want_replicas,
129 localRoots: kc.localRoots,
130 writableLocalRoots: kc.writableLocalRoots,
131 gatewayRoots: kc.gatewayRoots,
132 HTTPClient: kc.HTTPClient,
134 BlockCache: kc.BlockCache,
135 RequestID: kc.RequestID,
136 StorageClasses: kc.StorageClasses,
137 DefaultStorageClasses: kc.DefaultStorageClasses,
138 replicasPerService: kc.replicasPerService,
139 foundNonDiskSvc: kc.foundNonDiskSvc,
140 disableDiscovery: kc.disableDiscovery,
144 func (kc *KeepClient) loadDefaultClasses() error {
145 scData, err := kc.Arvados.ClusterConfig("StorageClasses")
149 classes := scData.(map[string]interface{})
150 for scName := range classes {
151 scConf, _ := classes[scName].(map[string]interface{})
152 isDefault, ok := scConf["Default"].(bool)
154 kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
160 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
161 // DiscoverKeepServices(), and returns when the client is ready to
163 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
165 return kc, kc.discoverServices()
168 // New creates a new KeepClient. Service discovery will occur on the
169 // next read/write operation.
170 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
171 defaultReplicationLevel := 2
172 value, err := arv.Discovery("defaultCollectionReplication")
174 v, ok := value.(float64)
176 defaultReplicationLevel = int(v)
181 Want_replicas: defaultReplicationLevel,
184 err = kc.loadDefaultClasses()
186 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
191 // PutHR puts a block given the block hash, a reader, and the number of bytes
192 // to read from the reader (which must be between 0 and BLOCKSIZE).
194 // Returns the locator for the written block, the number of replicas
195 // written, and an error.
197 // Returns an InsufficientReplicasError if 0 <= replicas <
198 // kc.Wants_replicas.
199 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
200 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
203 DataSize: int(dataBytes),
205 return resp.Locator, resp.Replicas, err
208 // PutHB writes a block to Keep. The hash of the bytes is given in
209 // hash, and the data is given in buf.
211 // Return values are the same as for PutHR.
212 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
213 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
217 return resp.Locator, resp.Replicas, err
220 // PutB writes a block to Keep. It computes the hash itself.
222 // Return values are the same as for PutHR.
223 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
224 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
227 return resp.Locator, resp.Replicas, err
230 // PutR writes a block to Keep. It first reads all data from r into a buffer
231 // in order to compute the hash.
233 // Return values are the same as for PutHR.
235 // If the block hash and data size are known, PutHR is more efficient.
236 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
237 buffer, err := ioutil.ReadAll(r)
241 return kc.PutB(buffer)
244 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
245 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
246 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
249 reqid := kc.getRequestID()
251 var expectLength int64
252 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
254 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
262 triesRemaining := 1 + kc.Retries
264 serversToTry := kc.getSortedRoots(locator)
266 numServers := len(serversToTry)
269 var retryList []string
271 for triesRemaining > 0 {
275 for _, host := range serversToTry {
276 url := host + "/" + locator
278 req, err := http.NewRequest(method, url, nil)
280 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
283 for k, v := range header {
284 req.Header[k] = append([]string(nil), v...)
286 if req.Header.Get("Authorization") == "" {
287 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
289 if req.Header.Get("X-Request-Id") == "" {
290 req.Header.Set("X-Request-Id", reqid)
292 resp, err := kc.httpClient().Do(req)
294 // Probably a network error, may be transient,
296 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
297 retryList = append(retryList, host)
300 if resp.StatusCode != http.StatusOK {
302 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
304 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
305 url, resp.StatusCode, bytes.TrimSpace(respbody)))
307 if resp.StatusCode == 408 ||
308 resp.StatusCode == 429 ||
309 resp.StatusCode >= 500 {
310 // Timeout, too many requests, or other
311 // server side failure, transient
312 // error, can try again.
313 retryList = append(retryList, host)
314 } else if resp.StatusCode == 404 {
319 if expectLength < 0 {
320 if resp.ContentLength < 0 {
322 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
324 expectLength = resp.ContentLength
325 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
327 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
331 return HashCheckingReader{
334 Check: locator[0:32],
335 }, expectLength, url, resp.Header, nil
338 return nil, expectLength, url, resp.Header, nil
340 serversToTry = retryList
342 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
345 if count404 == numServers {
348 err = &ErrNotFound{multipleResponseError{
349 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
350 isTemp: len(serversToTry) > 0,
353 return nil, 0, "", nil, err
356 // LocalLocator returns a locator equivalent to the one supplied, but
357 // with a valid signature from the local cluster. If the given locator
358 // already has a local signature, it is returned unchanged.
359 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
360 if !strings.Contains(locator, "+R") {
361 // Either it has +A, or it's unsigned and we assume
362 // it's a local locator on a site with signatures
366 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
367 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
371 loc := hdr.Get("X-Keep-Locator")
373 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
378 // Get retrieves a block, given a locator. Returns a reader, the
379 // expected data length, the URL the block is being fetched from, and
382 // If the block checksum does not match, the final Read() on the
383 // reader returned by this method will return a BadChecksum error
385 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
386 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
387 return rdr, size, url, err
390 // ReadAt retrieves a portion of block from the cache if it's
391 // present, otherwise from the network.
392 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
393 return kc.cache().ReadAt(kc, locator, p, off)
396 // Ask verifies that a block with the given hash is available and
397 // readable, according to at least one Keep service. Unlike Get, it
398 // does not retrieve the data or verify that the data content matches
399 // the hash specified by the locator.
401 // Returns the data size (content length) reported by the Keep service
402 // and the URI reporting the data size.
403 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
404 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
405 return size, url, err
408 // GetIndex retrieves a list of blocks stored on the given server whose hashes
409 // begin with the given prefix. The returned reader will return an error (other
410 // than EOF) if the complete index cannot be retrieved.
412 // This is meant to be used only by system components and admin tools.
413 // It will return an error unless the client is using a "data manager token"
414 // recognized by the Keep services.
415 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
416 url := kc.LocalRoots()[keepServiceUUID]
418 return nil, ErrNoSuchKeepServer
426 req, err := http.NewRequest("GET", url, nil)
431 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
432 req.Header.Set("X-Request-Id", kc.getRequestID())
433 resp, err := kc.httpClient().Do(req)
438 defer resp.Body.Close()
440 if resp.StatusCode != http.StatusOK {
441 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
445 respBody, err = ioutil.ReadAll(resp.Body)
450 // Got index; verify that it is complete
451 // The response should be "\n" if no locators matched the prefix
452 // Else, it should be a list of locators followed by a blank line
453 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
454 return nil, ErrIncompleteIndex
457 // Got complete index; strip the trailing newline and send
458 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
461 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
462 // services: uuid -> baseURI.
463 func (kc *KeepClient) LocalRoots() map[string]string {
464 kc.discoverServices()
466 defer kc.lock.RUnlock()
470 // GatewayRoots returns the map of Keep remote gateway services:
472 func (kc *KeepClient) GatewayRoots() map[string]string {
473 kc.discoverServices()
475 defer kc.lock.RUnlock()
476 return kc.gatewayRoots
479 // WritableLocalRoots returns the map of writable local Keep services:
481 func (kc *KeepClient) WritableLocalRoots() map[string]string {
482 kc.discoverServices()
484 defer kc.lock.RUnlock()
485 return kc.writableLocalRoots
488 // SetServiceRoots disables service discovery and updates the
489 // localRoots and gatewayRoots maps, without disrupting operations
490 // that are already in progress.
492 // The supplied maps must not be modified after calling
494 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
495 kc.disableDiscovery = true
496 kc.setServiceRoots(locals, writables, gateways)
499 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
501 defer kc.lock.Unlock()
502 kc.localRoots = locals
503 kc.writableLocalRoots = writables
504 kc.gatewayRoots = gateways
507 // getSortedRoots returns a list of base URIs of Keep services, in the
508 // order they should be attempted in order to retrieve content for the
510 func (kc *KeepClient) getSortedRoots(locator string) []string {
512 for _, hint := range strings.Split(locator, "+") {
513 if len(hint) < 7 || hint[0:2] != "K@" {
514 // Not a service hint.
518 // +K@abcde means fetch from proxy at
519 // keep.abcde.arvadosapi.com
520 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
521 } else if len(hint) == 29 {
522 // +K@abcde-abcde-abcdeabcdeabcde means fetch
523 // from gateway with given uuid
524 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
525 found = append(found, gwURI)
527 // else this hint is no use to us; carry on.
530 // After trying all usable service hints, fall back to local roots.
531 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
535 func (kc *KeepClient) cache() *BlockCache {
536 if kc.BlockCache != nil {
539 return DefaultBlockCache
542 func (kc *KeepClient) ClearBlockCache() {
546 func (kc *KeepClient) SetStorageClasses(sc []string) {
547 // make a copy so the caller can't mess with it.
548 kc.StorageClasses = append([]string{}, sc...)
552 // There are four global http.Client objects for the four
553 // possible permutations of TLS behavior (verify/skip-verify)
554 // and timeout settings (proxy/non-proxy).
555 defaultClient = map[bool]map[bool]HTTPClient{
556 // defaultClient[false] is used for verified TLS reqs
558 // defaultClient[true] is used for unverified
559 // (insecure) TLS reqs
562 defaultClientMtx sync.Mutex
565 // httpClient returns the HTTPClient field if it's not nil, otherwise
566 // whichever of the four global http.Client objects is suitable for
567 // the current environment (i.e., TLS verification on/off, keep
568 // services are/aren't proxies).
569 func (kc *KeepClient) httpClient() HTTPClient {
570 if kc.HTTPClient != nil {
573 defaultClientMtx.Lock()
574 defer defaultClientMtx.Unlock()
575 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
579 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
580 if kc.foundNonDiskSvc {
581 // Use longer timeouts when connecting to a proxy,
582 // because this usually means the intervening network
584 requestTimeout = DefaultProxyRequestTimeout
585 connectTimeout = DefaultProxyConnectTimeout
586 tlsTimeout = DefaultProxyTLSHandshakeTimeout
587 keepAlive = DefaultProxyKeepAlive
589 requestTimeout = DefaultRequestTimeout
590 connectTimeout = DefaultConnectTimeout
591 tlsTimeout = DefaultTLSHandshakeTimeout
592 keepAlive = DefaultKeepAlive
596 Timeout: requestTimeout,
597 // It's not safe to copy *http.DefaultTransport
598 // because it has a mutex (which might be locked)
599 // protecting a private map (which might not be nil).
600 // So we build our own, using the Go 1.12 default
601 // values, ignoring any changes the application has
602 // made to http.DefaultTransport.
603 Transport: &http.Transport{
604 DialContext: (&net.Dialer{
605 Timeout: connectTimeout,
606 KeepAlive: keepAlive,
610 IdleConnTimeout: 90 * time.Second,
611 TLSHandshakeTimeout: tlsTimeout,
612 ExpectContinueTimeout: 1 * time.Second,
613 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
616 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
620 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
622 func (kc *KeepClient) getRequestID() string {
623 if kc.RequestID != "" {
626 return reqIDGen.Next()
629 type Locator struct {
631 Size int // -1 if data size is not known
632 Hints []string // Including the size hint, if any
635 func (loc *Locator) String() string {
637 if len(loc.Hints) > 0 {
638 s = s + "+" + strings.Join(loc.Hints, "+")
643 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
645 func MakeLocator(path string) (*Locator, error) {
646 sm := locatorMatcher.FindStringSubmatch(path)
648 return nil, InvalidLocatorError
650 loc := Locator{Hash: sm[1], Size: -1}
652 loc.Hints = strings.Split(sm[3], "+")
654 loc.Hints = []string{}
656 if len(loc.Hints) > 0 {
657 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {