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.
24 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
25 "git.arvados.org/arvados.git/sdk/go/asyncbuf"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
29 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
30 const BLOCKSIZE = 64 * 1024 * 1024
33 DefaultRequestTimeout = 20 * time.Second
34 DefaultConnectTimeout = 2 * time.Second
35 DefaultTLSHandshakeTimeout = 4 * time.Second
36 DefaultKeepAlive = 180 * time.Second
38 DefaultProxyRequestTimeout = 300 * time.Second
39 DefaultProxyConnectTimeout = 30 * time.Second
40 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
41 DefaultProxyKeepAlive = 120 * time.Second
44 // Error interface with an error and boolean indicating whether the error is temporary
45 type Error interface {
50 // multipleResponseError is of type Error
51 type multipleResponseError struct {
56 func (e *multipleResponseError) Temporary() bool {
60 // BlockNotFound is a multipleResponseError where isTemp is false
61 var BlockNotFound = &ErrNotFound{multipleResponseError{
62 error: errors.New("Block not found"),
66 // ErrNotFound is a multipleResponseError where isTemp can be true or false
67 type ErrNotFound struct {
71 type InsufficientReplicasError error
73 type OversizeBlockError error
75 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
76 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
77 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
78 var InvalidLocatorError = errors.New("Invalid locator")
80 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
81 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
83 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
84 var ErrIncompleteIndex = errors.New("Got incomplete index")
87 XKeepDesiredReplicas = "X-Keep-Desired-Replicas"
88 XKeepReplicasStored = "X-Keep-Replicas-Stored"
89 XKeepStorageClasses = "X-Keep-Storage-Classes"
90 XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
93 type HTTPClient interface {
94 Do(*http.Request) (*http.Response, error)
97 // KeepClient holds information about Arvados and Keep servers.
98 type KeepClient struct {
99 Arvados *arvadosclient.ArvadosClient
101 localRoots map[string]string
102 writableLocalRoots map[string]string
103 gatewayRoots map[string]string
105 HTTPClient HTTPClient
107 BlockCache *BlockCache
109 StorageClasses []string
111 // set to 1 if all writable services are of disk type, otherwise 0
112 replicasPerService int
114 // Any non-disk typed services found in the list of keepservers?
117 // Disable automatic discovery of keep services
118 disableDiscovery bool
121 // MakeKeepClient creates a new KeepClient, calls
122 // DiscoverKeepServices(), and returns when the client is ready to
124 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
126 return kc, kc.discoverServices()
129 // New creates a new KeepClient. Service discovery will occur on the
130 // next read/write operation.
131 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
132 defaultReplicationLevel := 2
133 value, err := arv.Discovery("defaultCollectionReplication")
135 v, ok := value.(float64)
137 defaultReplicationLevel = int(v)
142 Want_replicas: defaultReplicationLevel,
147 // PutHR puts a block given the block hash, a reader, and the number of bytes
148 // to read from the reader (which must be between 0 and BLOCKSIZE).
150 // Returns the locator for the written block, the number of replicas
151 // written, and an error.
153 // Returns an InsufficientReplicasError if 0 <= replicas <
154 // kc.Wants_replicas.
155 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
156 // Buffer for reads from 'r'
159 if dataBytes > BLOCKSIZE {
160 return "", 0, ErrOversizeBlock
162 bufsize = int(dataBytes)
167 buf := asyncbuf.NewBuffer(make([]byte, 0, bufsize))
169 _, err := io.Copy(buf, HashCheckingReader{r, md5.New(), hash})
170 buf.CloseWithError(err)
172 return kc.putReplicas(hash, buf.NewReader, dataBytes)
175 // PutHB writes a block to Keep. The hash of the bytes is given in
176 // hash, and the data is given in buf.
178 // Return values are the same as for PutHR.
179 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
180 newReader := func() io.Reader { return bytes.NewBuffer(buf) }
181 return kc.putReplicas(hash, newReader, int64(len(buf)))
184 // PutB writes a block to Keep. It computes the hash itself.
186 // Return values are the same as for PutHR.
187 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
188 hash := fmt.Sprintf("%x", md5.Sum(buffer))
189 return kc.PutHB(hash, buffer)
192 // PutR writes a block to Keep. It first reads all data from r into a buffer
193 // in order to compute the hash.
195 // Return values are the same as for PutHR.
197 // If the block hash and data size are known, PutHR is more efficient.
198 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
199 buffer, err := ioutil.ReadAll(r)
203 return kc.PutB(buffer)
206 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
207 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
208 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
211 reqid := kc.getRequestID()
213 var expectLength int64
214 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
216 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
224 triesRemaining := 1 + kc.Retries
226 serversToTry := kc.getSortedRoots(locator)
228 numServers := len(serversToTry)
231 var retryList []string
233 for triesRemaining > 0 {
237 for _, host := range serversToTry {
238 url := host + "/" + locator
240 req, err := http.NewRequest(method, url, nil)
242 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
245 for k, v := range header {
246 req.Header[k] = append([]string(nil), v...)
248 if req.Header.Get("Authorization") == "" {
249 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
251 if req.Header.Get("X-Request-Id") == "" {
252 req.Header.Set("X-Request-Id", reqid)
254 resp, err := kc.httpClient().Do(req)
256 // Probably a network error, may be transient,
258 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
259 retryList = append(retryList, host)
262 if resp.StatusCode != http.StatusOK {
264 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
266 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
267 url, resp.StatusCode, bytes.TrimSpace(respbody)))
269 if resp.StatusCode == 408 ||
270 resp.StatusCode == 429 ||
271 resp.StatusCode >= 500 {
272 // Timeout, too many requests, or other
273 // server side failure, transient
274 // error, can try again.
275 retryList = append(retryList, host)
276 } else if resp.StatusCode == 404 {
281 if expectLength < 0 {
282 if resp.ContentLength < 0 {
284 return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
286 expectLength = resp.ContentLength
287 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
289 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
293 return HashCheckingReader{
296 Check: locator[0:32],
297 }, expectLength, url, resp.Header, nil
300 return nil, expectLength, url, resp.Header, nil
302 serversToTry = retryList
304 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
307 if count404 == numServers {
310 err = &ErrNotFound{multipleResponseError{
311 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
312 isTemp: len(serversToTry) > 0,
315 return nil, 0, "", nil, err
318 // LocalLocator returns a locator equivalent to the one supplied, but
319 // with a valid signature from the local cluster. If the given locator
320 // already has a local signature, it is returned unchanged.
321 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
322 if !strings.Contains(locator, "+R") {
323 // Either it has +A, or it's unsigned and we assume
324 // it's a local locator on a site with signatures
328 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
329 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
333 loc := hdr.Get("X-Keep-Locator")
335 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
340 // Get retrieves a block, given a locator. Returns a reader, the
341 // expected data length, the URL the block is being fetched from, and
344 // If the block checksum does not match, the final Read() on the
345 // reader returned by this method will return a BadChecksum error
347 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
348 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
349 return rdr, size, url, err
352 // ReadAt retrieves a portion of block from the cache if it's
353 // present, otherwise from the network.
354 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
355 return kc.cache().ReadAt(kc, locator, p, off)
358 // Ask verifies that a block with the given hash is available and
359 // readable, according to at least one Keep service. Unlike Get, it
360 // does not retrieve the data or verify that the data content matches
361 // the hash specified by the locator.
363 // Returns the data size (content length) reported by the Keep service
364 // and the URI reporting the data size.
365 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
366 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
367 return size, url, err
370 // GetIndex retrieves a list of blocks stored on the given server whose hashes
371 // begin with the given prefix. The returned reader will return an error (other
372 // than EOF) if the complete index cannot be retrieved.
374 // This is meant to be used only by system components and admin tools.
375 // It will return an error unless the client is using a "data manager token"
376 // recognized by the Keep services.
377 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
378 url := kc.LocalRoots()[keepServiceUUID]
380 return nil, ErrNoSuchKeepServer
388 req, err := http.NewRequest("GET", url, nil)
393 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
394 req.Header.Set("X-Request-Id", kc.getRequestID())
395 resp, err := kc.httpClient().Do(req)
400 defer resp.Body.Close()
402 if resp.StatusCode != http.StatusOK {
403 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
407 respBody, err = ioutil.ReadAll(resp.Body)
412 // Got index; verify that it is complete
413 // The response should be "\n" if no locators matched the prefix
414 // Else, it should be a list of locators followed by a blank line
415 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
416 return nil, ErrIncompleteIndex
419 // Got complete index; strip the trailing newline and send
420 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
423 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
424 // services: uuid -> baseURI.
425 func (kc *KeepClient) LocalRoots() map[string]string {
426 kc.discoverServices()
428 defer kc.lock.RUnlock()
432 // GatewayRoots returns the map of Keep remote gateway services:
434 func (kc *KeepClient) GatewayRoots() map[string]string {
435 kc.discoverServices()
437 defer kc.lock.RUnlock()
438 return kc.gatewayRoots
441 // WritableLocalRoots returns the map of writable local Keep services:
443 func (kc *KeepClient) WritableLocalRoots() map[string]string {
444 kc.discoverServices()
446 defer kc.lock.RUnlock()
447 return kc.writableLocalRoots
450 // SetServiceRoots disables service discovery and updates the
451 // localRoots and gatewayRoots maps, without disrupting operations
452 // that are already in progress.
454 // The supplied maps must not be modified after calling
456 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
457 kc.disableDiscovery = true
458 kc.setServiceRoots(locals, writables, gateways)
461 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
463 defer kc.lock.Unlock()
464 kc.localRoots = locals
465 kc.writableLocalRoots = writables
466 kc.gatewayRoots = gateways
469 // getSortedRoots returns a list of base URIs of Keep services, in the
470 // order they should be attempted in order to retrieve content for the
472 func (kc *KeepClient) getSortedRoots(locator string) []string {
474 for _, hint := range strings.Split(locator, "+") {
475 if len(hint) < 7 || hint[0:2] != "K@" {
476 // Not a service hint.
480 // +K@abcde means fetch from proxy at
481 // keep.abcde.arvadosapi.com
482 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
483 } else if len(hint) == 29 {
484 // +K@abcde-abcde-abcdeabcdeabcde means fetch
485 // from gateway with given uuid
486 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
487 found = append(found, gwURI)
489 // else this hint is no use to us; carry on.
492 // After trying all usable service hints, fall back to local roots.
493 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
497 func (kc *KeepClient) cache() *BlockCache {
498 if kc.BlockCache != nil {
501 return DefaultBlockCache
504 func (kc *KeepClient) ClearBlockCache() {
508 func (kc *KeepClient) SetStorageClasses(sc []string) {
509 // make a copy so the caller can't mess with it.
510 kc.StorageClasses = append([]string{}, sc...)
514 // There are four global http.Client objects for the four
515 // possible permutations of TLS behavior (verify/skip-verify)
516 // and timeout settings (proxy/non-proxy).
517 defaultClient = map[bool]map[bool]HTTPClient{
518 // defaultClient[false] is used for verified TLS reqs
520 // defaultClient[true] is used for unverified
521 // (insecure) TLS reqs
524 defaultClientMtx sync.Mutex
527 // httpClient returns the HTTPClient field if it's not nil, otherwise
528 // whichever of the four global http.Client objects is suitable for
529 // the current environment (i.e., TLS verification on/off, keep
530 // services are/aren't proxies).
531 func (kc *KeepClient) httpClient() HTTPClient {
532 if kc.HTTPClient != nil {
535 defaultClientMtx.Lock()
536 defer defaultClientMtx.Unlock()
537 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
541 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
542 if kc.foundNonDiskSvc {
543 // Use longer timeouts when connecting to a proxy,
544 // because this usually means the intervening network
546 requestTimeout = DefaultProxyRequestTimeout
547 connectTimeout = DefaultProxyConnectTimeout
548 tlsTimeout = DefaultProxyTLSHandshakeTimeout
549 keepAlive = DefaultProxyKeepAlive
551 requestTimeout = DefaultRequestTimeout
552 connectTimeout = DefaultConnectTimeout
553 tlsTimeout = DefaultTLSHandshakeTimeout
554 keepAlive = DefaultKeepAlive
558 Timeout: requestTimeout,
559 // It's not safe to copy *http.DefaultTransport
560 // because it has a mutex (which might be locked)
561 // protecting a private map (which might not be nil).
562 // So we build our own, using the Go 1.12 default
563 // values, ignoring any changes the application has
564 // made to http.DefaultTransport.
565 Transport: &http.Transport{
566 DialContext: (&net.Dialer{
567 Timeout: connectTimeout,
568 KeepAlive: keepAlive,
572 IdleConnTimeout: 90 * time.Second,
573 TLSHandshakeTimeout: tlsTimeout,
574 ExpectContinueTimeout: 1 * time.Second,
575 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
578 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
582 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
584 func (kc *KeepClient) getRequestID() string {
585 if kc.RequestID != "" {
588 return reqIDGen.Next()
591 type Locator struct {
593 Size int // -1 if data size is not known
594 Hints []string // Including the size hint, if any
597 func (loc *Locator) String() string {
599 if len(loc.Hints) > 0 {
600 s = s + "+" + strings.Join(loc.Hints, "+")
605 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
607 func MakeLocator(path string) (*Locator, error) {
608 sm := locatorMatcher.FindStringSubmatch(path)
610 return nil, InvalidLocatorError
612 loc := Locator{Hash: sm[1], Size: -1}
614 loc.Hints = strings.Split(sm[3], "+")
616 loc.Hints = []string{}
618 if len(loc.Hints) > 0 {
619 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {