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
112 // set to 1 if all writable services are of disk type, otherwise 0
113 replicasPerService int
115 // Any non-disk typed services found in the list of keepservers?
118 // Disable automatic discovery of keep services
119 disableDiscovery bool
122 // MakeKeepClient creates a new KeepClient, calls
123 // DiscoverKeepServices(), and returns when the client is ready to
125 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
127 return kc, kc.discoverServices()
130 // New creates a new KeepClient. Service discovery will occur on the
131 // next read/write operation.
132 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
133 defaultReplicationLevel := 2
134 value, err := arv.Discovery("defaultCollectionReplication")
136 v, ok := value.(float64)
138 defaultReplicationLevel = int(v)
143 Want_replicas: defaultReplicationLevel,
148 // PutHR puts a block given the block hash, a reader, and the number of bytes
149 // to read from the reader (which must be between 0 and BLOCKSIZE).
151 // Returns the locator for the written block, the number of replicas
152 // written, and an error.
154 // Returns an InsufficientReplicasError if 0 <= replicas <
155 // kc.Wants_replicas.
156 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
157 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
160 DataSize: int(dataBytes),
162 return resp.Locator, resp.Replicas, err
165 // PutHB writes a block to Keep. The hash of the bytes is given in
166 // hash, and the data is given in buf.
168 // Return values are the same as for PutHR.
169 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
170 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
174 return resp.Locator, resp.Replicas, err
177 // PutB writes a block to Keep. It computes the hash itself.
179 // Return values are the same as for PutHR.
180 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
181 resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
184 return resp.Locator, resp.Replicas, err
187 // PutR writes a block to Keep. It first reads all data from r into a buffer
188 // in order to compute the hash.
190 // Return values are the same as for PutHR.
192 // If the block hash and data size are known, PutHR is more efficient.
193 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
194 buffer, err := ioutil.ReadAll(r)
198 return kc.PutB(buffer)
201 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
202 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
203 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
206 reqid := kc.getRequestID()
208 var expectLength int64
209 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
211 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
219 triesRemaining := 1 + kc.Retries
221 serversToTry := kc.getSortedRoots(locator)
223 numServers := len(serversToTry)
226 var retryList []string
228 for triesRemaining > 0 {
232 for _, host := range serversToTry {
233 url := host + "/" + locator
235 req, err := http.NewRequest(method, url, nil)
237 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
240 for k, v := range header {
241 req.Header[k] = append([]string(nil), v...)
243 if req.Header.Get("Authorization") == "" {
244 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
246 if req.Header.Get("X-Request-Id") == "" {
247 req.Header.Set("X-Request-Id", reqid)
249 resp, err := kc.httpClient().Do(req)
251 // Probably a network error, may be transient,
253 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
254 retryList = append(retryList, host)
257 if resp.StatusCode != http.StatusOK {
259 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
261 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
262 url, resp.StatusCode, bytes.TrimSpace(respbody)))
264 if resp.StatusCode == 408 ||
265 resp.StatusCode == 429 ||
266 resp.StatusCode >= 500 {
267 // Timeout, too many requests, or other
268 // server side failure, transient
269 // error, can try again.
270 retryList = append(retryList, host)
271 } else if resp.StatusCode == 404 {
276 if expectLength < 0 {
277 if resp.ContentLength < 0 {
279 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
281 expectLength = resp.ContentLength
282 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
284 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
288 return HashCheckingReader{
291 Check: locator[0:32],
292 }, expectLength, url, resp.Header, nil
295 return nil, expectLength, url, resp.Header, nil
297 serversToTry = retryList
299 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
302 if count404 == numServers {
305 err = &ErrNotFound{multipleResponseError{
306 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
307 isTemp: len(serversToTry) > 0,
310 return nil, 0, "", nil, err
313 // LocalLocator returns a locator equivalent to the one supplied, but
314 // with a valid signature from the local cluster. If the given locator
315 // already has a local signature, it is returned unchanged.
316 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
317 if !strings.Contains(locator, "+R") {
318 // Either it has +A, or it's unsigned and we assume
319 // it's a local locator on a site with signatures
323 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
324 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
328 loc := hdr.Get("X-Keep-Locator")
330 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
335 // Get retrieves a block, given a locator. Returns a reader, the
336 // expected data length, the URL the block is being fetched from, and
339 // If the block checksum does not match, the final Read() on the
340 // reader returned by this method will return a BadChecksum error
342 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
343 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
344 return rdr, size, url, err
347 // ReadAt retrieves a portion of block from the cache if it's
348 // present, otherwise from the network.
349 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
350 return kc.cache().ReadAt(kc, locator, p, off)
353 // Ask verifies that a block with the given hash is available and
354 // readable, according to at least one Keep service. Unlike Get, it
355 // does not retrieve the data or verify that the data content matches
356 // the hash specified by the locator.
358 // Returns the data size (content length) reported by the Keep service
359 // and the URI reporting the data size.
360 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
361 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
362 return size, url, err
365 // GetIndex retrieves a list of blocks stored on the given server whose hashes
366 // begin with the given prefix. The returned reader will return an error (other
367 // than EOF) if the complete index cannot be retrieved.
369 // This is meant to be used only by system components and admin tools.
370 // It will return an error unless the client is using a "data manager token"
371 // recognized by the Keep services.
372 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
373 url := kc.LocalRoots()[keepServiceUUID]
375 return nil, ErrNoSuchKeepServer
383 req, err := http.NewRequest("GET", url, nil)
388 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
389 req.Header.Set("X-Request-Id", kc.getRequestID())
390 resp, err := kc.httpClient().Do(req)
395 defer resp.Body.Close()
397 if resp.StatusCode != http.StatusOK {
398 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
402 respBody, err = ioutil.ReadAll(resp.Body)
407 // Got index; verify that it is complete
408 // The response should be "\n" if no locators matched the prefix
409 // Else, it should be a list of locators followed by a blank line
410 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
411 return nil, ErrIncompleteIndex
414 // Got complete index; strip the trailing newline and send
415 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
418 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
419 // services: uuid -> baseURI.
420 func (kc *KeepClient) LocalRoots() map[string]string {
421 kc.discoverServices()
423 defer kc.lock.RUnlock()
427 // GatewayRoots returns the map of Keep remote gateway services:
429 func (kc *KeepClient) GatewayRoots() map[string]string {
430 kc.discoverServices()
432 defer kc.lock.RUnlock()
433 return kc.gatewayRoots
436 // WritableLocalRoots returns the map of writable local Keep services:
438 func (kc *KeepClient) WritableLocalRoots() map[string]string {
439 kc.discoverServices()
441 defer kc.lock.RUnlock()
442 return kc.writableLocalRoots
445 // SetServiceRoots disables service discovery and updates the
446 // localRoots and gatewayRoots maps, without disrupting operations
447 // that are already in progress.
449 // The supplied maps must not be modified after calling
451 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
452 kc.disableDiscovery = true
453 kc.setServiceRoots(locals, writables, gateways)
456 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
458 defer kc.lock.Unlock()
459 kc.localRoots = locals
460 kc.writableLocalRoots = writables
461 kc.gatewayRoots = gateways
464 // getSortedRoots returns a list of base URIs of Keep services, in the
465 // order they should be attempted in order to retrieve content for the
467 func (kc *KeepClient) getSortedRoots(locator string) []string {
469 for _, hint := range strings.Split(locator, "+") {
470 if len(hint) < 7 || hint[0:2] != "K@" {
471 // Not a service hint.
475 // +K@abcde means fetch from proxy at
476 // keep.abcde.arvadosapi.com
477 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
478 } else if len(hint) == 29 {
479 // +K@abcde-abcde-abcdeabcdeabcde means fetch
480 // from gateway with given uuid
481 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
482 found = append(found, gwURI)
484 // else this hint is no use to us; carry on.
487 // After trying all usable service hints, fall back to local roots.
488 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
492 func (kc *KeepClient) cache() *BlockCache {
493 if kc.BlockCache != nil {
496 return DefaultBlockCache
499 func (kc *KeepClient) ClearBlockCache() {
503 func (kc *KeepClient) SetStorageClasses(sc []string) {
504 // make a copy so the caller can't mess with it.
505 kc.StorageClasses = append([]string{}, sc...)
509 // There are four global http.Client objects for the four
510 // possible permutations of TLS behavior (verify/skip-verify)
511 // and timeout settings (proxy/non-proxy).
512 defaultClient = map[bool]map[bool]HTTPClient{
513 // defaultClient[false] is used for verified TLS reqs
515 // defaultClient[true] is used for unverified
516 // (insecure) TLS reqs
519 defaultClientMtx sync.Mutex
522 // httpClient returns the HTTPClient field if it's not nil, otherwise
523 // whichever of the four global http.Client objects is suitable for
524 // the current environment (i.e., TLS verification on/off, keep
525 // services are/aren't proxies).
526 func (kc *KeepClient) httpClient() HTTPClient {
527 if kc.HTTPClient != nil {
530 defaultClientMtx.Lock()
531 defer defaultClientMtx.Unlock()
532 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
536 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
537 if kc.foundNonDiskSvc {
538 // Use longer timeouts when connecting to a proxy,
539 // because this usually means the intervening network
541 requestTimeout = DefaultProxyRequestTimeout
542 connectTimeout = DefaultProxyConnectTimeout
543 tlsTimeout = DefaultProxyTLSHandshakeTimeout
544 keepAlive = DefaultProxyKeepAlive
546 requestTimeout = DefaultRequestTimeout
547 connectTimeout = DefaultConnectTimeout
548 tlsTimeout = DefaultTLSHandshakeTimeout
549 keepAlive = DefaultKeepAlive
553 Timeout: requestTimeout,
554 // It's not safe to copy *http.DefaultTransport
555 // because it has a mutex (which might be locked)
556 // protecting a private map (which might not be nil).
557 // So we build our own, using the Go 1.12 default
558 // values, ignoring any changes the application has
559 // made to http.DefaultTransport.
560 Transport: &http.Transport{
561 DialContext: (&net.Dialer{
562 Timeout: connectTimeout,
563 KeepAlive: keepAlive,
567 IdleConnTimeout: 90 * time.Second,
568 TLSHandshakeTimeout: tlsTimeout,
569 ExpectContinueTimeout: 1 * time.Second,
570 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
573 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
577 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
579 func (kc *KeepClient) getRequestID() string {
580 if kc.RequestID != "" {
583 return reqIDGen.Next()
586 type Locator struct {
588 Size int // -1 if data size is not known
589 Hints []string // Including the size hint, if any
592 func (loc *Locator) String() string {
594 if len(loc.Hints) > 0 {
595 s = s + "+" + strings.Join(loc.Hints, "+")
600 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
602 func MakeLocator(path string) (*Locator, error) {
603 sm := locatorMatcher.FindStringSubmatch(path)
605 return nil, InvalidLocatorError
607 loc := Locator{Hash: sm[1], Size: -1}
609 loc.Hints = strings.Split(sm[3], "+")
611 loc.Hints = []string{}
613 if len(loc.Hints) > 0 {
614 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {