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 err := kc.loadDefaultClasses()
146 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
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,
169 // PutHR puts a block given the block hash, a reader, and the number of bytes
170 // to read from the reader (which must be between 0 and BLOCKSIZE).
172 // Returns the locator for the written block, the number of replicas
173 // written, and an error.
175 // Returns an InsufficientReplicasError if 0 <= replicas <
176 // kc.Wants_replicas.
177 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
178 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
181 DataSize: int(dataBytes),
183 return resp.Locator, resp.Replicas, err
186 // PutHB writes a block to Keep. The hash of the bytes is given in
187 // hash, and the data is given in buf.
189 // Return values are the same as for PutHR.
190 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
191 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
195 return resp.Locator, resp.Replicas, err
198 // PutB writes a block to Keep. It computes the hash itself.
200 // Return values are the same as for PutHR.
201 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
202 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
205 return resp.Locator, resp.Replicas, err
208 // PutR writes a block to Keep. It first reads all data from r into a buffer
209 // in order to compute the hash.
211 // Return values are the same as for PutHR.
213 // If the block hash and data size are known, PutHR is more efficient.
214 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
215 buffer, err := ioutil.ReadAll(r)
219 return kc.PutB(buffer)
222 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
223 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
224 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
227 reqid := kc.getRequestID()
229 var expectLength int64
230 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
232 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
240 triesRemaining := 1 + kc.Retries
242 serversToTry := kc.getSortedRoots(locator)
244 numServers := len(serversToTry)
247 var retryList []string
249 for triesRemaining > 0 {
253 for _, host := range serversToTry {
254 url := host + "/" + locator
256 req, err := http.NewRequest(method, url, nil)
258 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
261 for k, v := range header {
262 req.Header[k] = append([]string(nil), v...)
264 if req.Header.Get("Authorization") == "" {
265 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
267 if req.Header.Get("X-Request-Id") == "" {
268 req.Header.Set("X-Request-Id", reqid)
270 resp, err := kc.httpClient().Do(req)
272 // Probably a network error, may be transient,
274 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
275 retryList = append(retryList, host)
278 if resp.StatusCode != http.StatusOK {
280 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
282 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
283 url, resp.StatusCode, bytes.TrimSpace(respbody)))
285 if resp.StatusCode == 408 ||
286 resp.StatusCode == 429 ||
287 resp.StatusCode >= 500 {
288 // Timeout, too many requests, or other
289 // server side failure, transient
290 // error, can try again.
291 retryList = append(retryList, host)
292 } else if resp.StatusCode == 404 {
297 if expectLength < 0 {
298 if resp.ContentLength < 0 {
300 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
302 expectLength = resp.ContentLength
303 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
305 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
309 return HashCheckingReader{
312 Check: locator[0:32],
313 }, expectLength, url, resp.Header, nil
316 return nil, expectLength, url, resp.Header, nil
318 serversToTry = retryList
320 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
323 if count404 == numServers {
326 err = &ErrNotFound{multipleResponseError{
327 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
328 isTemp: len(serversToTry) > 0,
331 return nil, 0, "", nil, err
334 // LocalLocator returns a locator equivalent to the one supplied, but
335 // with a valid signature from the local cluster. If the given locator
336 // already has a local signature, it is returned unchanged.
337 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
338 if !strings.Contains(locator, "+R") {
339 // Either it has +A, or it's unsigned and we assume
340 // it's a local locator on a site with signatures
344 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
345 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
349 loc := hdr.Get("X-Keep-Locator")
351 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
356 // Get retrieves a block, given a locator. Returns a reader, the
357 // expected data length, the URL the block is being fetched from, and
360 // If the block checksum does not match, the final Read() on the
361 // reader returned by this method will return a BadChecksum error
363 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
364 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
365 return rdr, size, url, err
368 // ReadAt retrieves a portion of block from the cache if it's
369 // present, otherwise from the network.
370 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
371 return kc.cache().ReadAt(kc, locator, p, off)
374 // Ask verifies that a block with the given hash is available and
375 // readable, according to at least one Keep service. Unlike Get, it
376 // does not retrieve the data or verify that the data content matches
377 // the hash specified by the locator.
379 // Returns the data size (content length) reported by the Keep service
380 // and the URI reporting the data size.
381 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
382 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
383 return size, url, err
386 // GetIndex retrieves a list of blocks stored on the given server whose hashes
387 // begin with the given prefix. The returned reader will return an error (other
388 // than EOF) if the complete index cannot be retrieved.
390 // This is meant to be used only by system components and admin tools.
391 // It will return an error unless the client is using a "data manager token"
392 // recognized by the Keep services.
393 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
394 url := kc.LocalRoots()[keepServiceUUID]
396 return nil, ErrNoSuchKeepServer
404 req, err := http.NewRequest("GET", url, nil)
409 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
410 req.Header.Set("X-Request-Id", kc.getRequestID())
411 resp, err := kc.httpClient().Do(req)
416 defer resp.Body.Close()
418 if resp.StatusCode != http.StatusOK {
419 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
423 respBody, err = ioutil.ReadAll(resp.Body)
428 // Got index; verify that it is complete
429 // The response should be "\n" if no locators matched the prefix
430 // Else, it should be a list of locators followed by a blank line
431 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
432 return nil, ErrIncompleteIndex
435 // Got complete index; strip the trailing newline and send
436 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
439 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
440 // services: uuid -> baseURI.
441 func (kc *KeepClient) LocalRoots() map[string]string {
442 kc.discoverServices()
444 defer kc.lock.RUnlock()
448 // GatewayRoots returns the map of Keep remote gateway services:
450 func (kc *KeepClient) GatewayRoots() map[string]string {
451 kc.discoverServices()
453 defer kc.lock.RUnlock()
454 return kc.gatewayRoots
457 // WritableLocalRoots returns the map of writable local Keep services:
459 func (kc *KeepClient) WritableLocalRoots() map[string]string {
460 kc.discoverServices()
462 defer kc.lock.RUnlock()
463 return kc.writableLocalRoots
466 // SetServiceRoots disables service discovery and updates the
467 // localRoots and gatewayRoots maps, without disrupting operations
468 // that are already in progress.
470 // The supplied maps must not be modified after calling
472 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
473 kc.disableDiscovery = true
474 kc.setServiceRoots(locals, writables, gateways)
477 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
479 defer kc.lock.Unlock()
480 kc.localRoots = locals
481 kc.writableLocalRoots = writables
482 kc.gatewayRoots = gateways
485 // getSortedRoots returns a list of base URIs of Keep services, in the
486 // order they should be attempted in order to retrieve content for the
488 func (kc *KeepClient) getSortedRoots(locator string) []string {
490 for _, hint := range strings.Split(locator, "+") {
491 if len(hint) < 7 || hint[0:2] != "K@" {
492 // Not a service hint.
496 // +K@abcde means fetch from proxy at
497 // keep.abcde.arvadosapi.com
498 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
499 } else if len(hint) == 29 {
500 // +K@abcde-abcde-abcdeabcdeabcde means fetch
501 // from gateway with given uuid
502 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
503 found = append(found, gwURI)
505 // else this hint is no use to us; carry on.
508 // After trying all usable service hints, fall back to local roots.
509 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
513 func (kc *KeepClient) cache() *BlockCache {
514 if kc.BlockCache != nil {
517 return DefaultBlockCache
520 func (kc *KeepClient) ClearBlockCache() {
524 func (kc *KeepClient) SetStorageClasses(sc []string) {
525 // make a copy so the caller can't mess with it.
526 kc.StorageClasses = append([]string{}, sc...)
530 // There are four global http.Client objects for the four
531 // possible permutations of TLS behavior (verify/skip-verify)
532 // and timeout settings (proxy/non-proxy).
533 defaultClient = map[bool]map[bool]HTTPClient{
534 // defaultClient[false] is used for verified TLS reqs
536 // defaultClient[true] is used for unverified
537 // (insecure) TLS reqs
540 defaultClientMtx sync.Mutex
543 // httpClient returns the HTTPClient field if it's not nil, otherwise
544 // whichever of the four global http.Client objects is suitable for
545 // the current environment (i.e., TLS verification on/off, keep
546 // services are/aren't proxies).
547 func (kc *KeepClient) httpClient() HTTPClient {
548 if kc.HTTPClient != nil {
551 defaultClientMtx.Lock()
552 defer defaultClientMtx.Unlock()
553 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
557 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
558 if kc.foundNonDiskSvc {
559 // Use longer timeouts when connecting to a proxy,
560 // because this usually means the intervening network
562 requestTimeout = DefaultProxyRequestTimeout
563 connectTimeout = DefaultProxyConnectTimeout
564 tlsTimeout = DefaultProxyTLSHandshakeTimeout
565 keepAlive = DefaultProxyKeepAlive
567 requestTimeout = DefaultRequestTimeout
568 connectTimeout = DefaultConnectTimeout
569 tlsTimeout = DefaultTLSHandshakeTimeout
570 keepAlive = DefaultKeepAlive
574 Timeout: requestTimeout,
575 // It's not safe to copy *http.DefaultTransport
576 // because it has a mutex (which might be locked)
577 // protecting a private map (which might not be nil).
578 // So we build our own, using the Go 1.12 default
579 // values, ignoring any changes the application has
580 // made to http.DefaultTransport.
581 Transport: &http.Transport{
582 DialContext: (&net.Dialer{
583 Timeout: connectTimeout,
584 KeepAlive: keepAlive,
588 IdleConnTimeout: 90 * time.Second,
589 TLSHandshakeTimeout: tlsTimeout,
590 ExpectContinueTimeout: 1 * time.Second,
591 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
594 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
598 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
600 func (kc *KeepClient) getRequestID() string {
601 if kc.RequestID != "" {
604 return reqIDGen.Next()
607 type Locator struct {
609 Size int // -1 if data size is not known
610 Hints []string // Including the size hint, if any
613 func (loc *Locator) String() string {
615 if len(loc.Hints) > 0 {
616 s = s + "+" + strings.Join(loc.Hints, "+")
621 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
623 func MakeLocator(path string) (*Locator, error) {
624 sm := locatorMatcher.FindStringSubmatch(path)
626 return nil, InvalidLocatorError
628 loc := Locator{Hash: sm[1], Size: -1}
630 loc.Hints = strings.Split(sm[3], "+")
632 loc.Hints = []string{}
634 if len(loc.Hints) > 0 {
635 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {