1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
23 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24 "git.curoverse.com/arvados.git/sdk/go/asyncbuf"
25 "git.curoverse.com/arvados.git/sdk/go/httpserver"
28 // A Keep "block" is 64MB.
29 const BLOCKSIZE = 64 * 1024 * 1024
32 DefaultRequestTimeout = 20 * time.Second
33 DefaultConnectTimeout = 2 * time.Second
34 DefaultTLSHandshakeTimeout = 4 * time.Second
35 DefaultKeepAlive = 180 * time.Second
37 DefaultProxyRequestTimeout = 300 * time.Second
38 DefaultProxyConnectTimeout = 30 * time.Second
39 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
40 DefaultProxyKeepAlive = 120 * time.Second
43 // Error interface with an error and boolean indicating whether the error is temporary
44 type Error interface {
49 // multipleResponseError is of type Error
50 type multipleResponseError struct {
55 func (e *multipleResponseError) Temporary() bool {
59 // BlockNotFound is a multipleResponseError where isTemp is false
60 var BlockNotFound = &ErrNotFound{multipleResponseError{
61 error: errors.New("Block not found"),
65 // ErrNotFound is a multipleResponseError where isTemp can be true or false
66 type ErrNotFound struct {
70 type InsufficientReplicasError error
72 type OversizeBlockError error
74 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
75 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
76 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
77 var InvalidLocatorError = errors.New("Invalid locator")
79 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
80 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
82 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
83 var ErrIncompleteIndex = errors.New("Got incomplete index")
85 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
86 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
88 type HTTPClient interface {
89 Do(*http.Request) (*http.Response, error)
92 // Information about Arvados and Keep servers.
93 type KeepClient struct {
94 Arvados *arvadosclient.ArvadosClient
96 localRoots map[string]string
97 writableLocalRoots map[string]string
98 gatewayRoots map[string]string
100 HTTPClient HTTPClient
102 BlockCache *BlockCache
105 // set to 1 if all writable services are of disk type, otherwise 0
106 replicasPerService int
108 // Any non-disk typed services found in the list of keepservers?
111 // Disable automatic discovery of keep services
112 disableDiscovery bool
115 // MakeKeepClient creates a new KeepClient, calls
116 // DiscoverKeepServices(), and returns when the client is ready to
118 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
120 return kc, kc.discoverServices()
123 // New creates a new KeepClient. Service discovery will occur on the
124 // next read/write operation.
125 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
126 defaultReplicationLevel := 2
127 value, err := arv.Discovery("defaultCollectionReplication")
129 v, ok := value.(float64)
131 defaultReplicationLevel = int(v)
136 Want_replicas: defaultReplicationLevel,
141 // Put a block given the block hash, a reader, and the number of bytes
142 // to read from the reader (which must be between 0 and BLOCKSIZE).
144 // Returns the locator for the written block, the number of replicas
145 // written, and an error.
147 // Returns an InsufficientReplicasError if 0 <= replicas <
148 // kc.Wants_replicas.
149 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
150 // Buffer for reads from 'r'
153 if dataBytes > BLOCKSIZE {
154 return "", 0, ErrOversizeBlock
156 bufsize = int(dataBytes)
161 buf := asyncbuf.NewBuffer(make([]byte, 0, bufsize))
163 _, err := io.Copy(buf, HashCheckingReader{r, md5.New(), hash})
164 buf.CloseWithError(err)
166 return kc.putReplicas(hash, buf.NewReader, dataBytes)
169 // PutHB writes a block to Keep. The hash of the bytes is given in
170 // hash, and the data is given in buf.
172 // Return values are the same as for PutHR.
173 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
174 newReader := func() io.Reader { return bytes.NewBuffer(buf) }
175 return kc.putReplicas(hash, newReader, int64(len(buf)))
178 // PutB writes a block to Keep. It computes the hash itself.
180 // Return values are the same as for PutHR.
181 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
182 hash := fmt.Sprintf("%x", md5.Sum(buffer))
183 return kc.PutHB(hash, buffer)
186 // PutR writes a block to Keep. It first reads all data from r into a buffer
187 // in order to compute the hash.
189 // Return values are the same as for PutHR.
191 // If the block hash and data size are known, PutHR is more efficient.
192 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
193 if buffer, err := ioutil.ReadAll(r); err != nil {
196 return kc.PutB(buffer)
200 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
201 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
202 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
205 var expectLength int64
206 if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
208 } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
216 tries_remaining := 1 + kc.Retries
218 serversToTry := kc.getSortedRoots(locator)
220 numServers := len(serversToTry)
223 var retryList []string
225 for tries_remaining > 0 {
229 for _, host := range serversToTry {
230 url := host + "/" + locator
232 req, err := http.NewRequest(method, url, nil)
234 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
237 kc.setRequestHeaders(req)
238 resp, err := kc.httpClient().Do(req)
240 // Probably a network error, may be transient,
242 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
243 retryList = append(retryList, host)
246 if resp.StatusCode != http.StatusOK {
248 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
250 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
251 url, resp.StatusCode, bytes.TrimSpace(respbody)))
253 if resp.StatusCode == 408 ||
254 resp.StatusCode == 429 ||
255 resp.StatusCode >= 500 {
256 // Timeout, too many requests, or other
257 // server side failure, transient
258 // error, can try again.
259 retryList = append(retryList, host)
260 } else if resp.StatusCode == 404 {
265 if expectLength < 0 {
266 if resp.ContentLength < 0 {
268 return nil, 0, "", fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
270 expectLength = resp.ContentLength
271 } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
273 return nil, 0, "", fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
277 return HashCheckingReader{
280 Check: locator[0:32],
281 }, expectLength, url, nil
284 return nil, expectLength, url, nil
287 serversToTry = retryList
289 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
292 if count404 == numServers {
295 err = &ErrNotFound{multipleResponseError{
296 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
297 isTemp: len(serversToTry) > 0,
300 return nil, 0, "", err
303 // Get() retrieves a block, given a locator. Returns a reader, the
304 // expected data length, the URL the block is being fetched from, and
307 // If the block checksum does not match, the final Read() on the
308 // reader returned by this method will return a BadChecksum error
310 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
311 return kc.getOrHead("GET", locator)
314 // ReadAt() retrieves a portion of block from the cache if it's
315 // present, otherwise from the network.
316 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
317 return kc.cache().ReadAt(kc, locator, p, off)
320 // Ask() verifies that a block with the given hash is available and
321 // readable, according to at least one Keep service. Unlike Get, it
322 // does not retrieve the data or verify that the data content matches
323 // the hash specified by the locator.
325 // Returns the data size (content length) reported by the Keep service
326 // and the URI reporting the data size.
327 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
328 _, size, url, err := kc.getOrHead("HEAD", locator)
329 return size, url, err
332 // GetIndex retrieves a list of blocks stored on the given server whose hashes
333 // begin with the given prefix. The returned reader will return an error (other
334 // than EOF) if the complete index cannot be retrieved.
336 // This is meant to be used only by system components and admin tools.
337 // It will return an error unless the client is using a "data manager token"
338 // recognized by the Keep services.
339 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
340 url := kc.LocalRoots()[keepServiceUUID]
342 return nil, ErrNoSuchKeepServer
350 req, err := http.NewRequest("GET", url, nil)
355 kc.setRequestHeaders(req)
356 resp, err := kc.httpClient().Do(req)
361 defer resp.Body.Close()
363 if resp.StatusCode != http.StatusOK {
364 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
368 respBody, err = ioutil.ReadAll(resp.Body)
373 // Got index; verify that it is complete
374 // The response should be "\n" if no locators matched the prefix
375 // Else, it should be a list of locators followed by a blank line
376 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
377 return nil, ErrIncompleteIndex
380 // Got complete index; strip the trailing newline and send
381 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
384 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
385 // services: uuid -> baseURI.
386 func (kc *KeepClient) LocalRoots() map[string]string {
387 kc.discoverServices()
389 defer kc.lock.RUnlock()
393 // GatewayRoots() returns the map of Keep remote gateway services:
395 func (kc *KeepClient) GatewayRoots() map[string]string {
396 kc.discoverServices()
398 defer kc.lock.RUnlock()
399 return kc.gatewayRoots
402 // WritableLocalRoots() returns the map of writable local Keep services:
404 func (kc *KeepClient) WritableLocalRoots() map[string]string {
405 kc.discoverServices()
407 defer kc.lock.RUnlock()
408 return kc.writableLocalRoots
411 // SetServiceRoots disables service discovery and updates the
412 // localRoots and gatewayRoots maps, without disrupting operations
413 // that are already in progress.
415 // The supplied maps must not be modified after calling
417 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
418 kc.disableDiscovery = true
419 kc.setServiceRoots(locals, writables, gateways)
422 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
424 defer kc.lock.Unlock()
425 kc.localRoots = locals
426 kc.writableLocalRoots = writables
427 kc.gatewayRoots = gateways
430 // getSortedRoots returns a list of base URIs of Keep services, in the
431 // order they should be attempted in order to retrieve content for the
433 func (kc *KeepClient) getSortedRoots(locator string) []string {
435 for _, hint := range strings.Split(locator, "+") {
436 if len(hint) < 7 || hint[0:2] != "K@" {
437 // Not a service hint.
441 // +K@abcde means fetch from proxy at
442 // keep.abcde.arvadosapi.com
443 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
444 } else if len(hint) == 29 {
445 // +K@abcde-abcde-abcdeabcdeabcde means fetch
446 // from gateway with given uuid
447 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
448 found = append(found, gwURI)
450 // else this hint is no use to us; carry on.
453 // After trying all usable service hints, fall back to local roots.
454 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
458 func (kc *KeepClient) cache() *BlockCache {
459 if kc.BlockCache != nil {
462 return DefaultBlockCache
466 func (kc *KeepClient) ClearBlockCache() {
471 // There are four global http.Client objects for the four
472 // possible permutations of TLS behavior (verify/skip-verify)
473 // and timeout settings (proxy/non-proxy).
474 defaultClient = map[bool]map[bool]HTTPClient{
475 // defaultClient[false] is used for verified TLS reqs
477 // defaultClient[true] is used for unverified
478 // (insecure) TLS reqs
481 defaultClientMtx sync.Mutex
484 // httpClient returns the HTTPClient field if it's not nil, otherwise
485 // whichever of the four global http.Client objects is suitable for
486 // the current environment (i.e., TLS verification on/off, keep
487 // services are/aren't proxies).
488 func (kc *KeepClient) httpClient() HTTPClient {
489 if kc.HTTPClient != nil {
492 defaultClientMtx.Lock()
493 defer defaultClientMtx.Unlock()
494 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
498 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
499 if kc.foundNonDiskSvc {
500 // Use longer timeouts when connecting to a proxy,
501 // because this usually means the intervening network
503 requestTimeout = DefaultProxyRequestTimeout
504 connectTimeout = DefaultProxyConnectTimeout
505 tlsTimeout = DefaultProxyTLSHandshakeTimeout
506 keepAlive = DefaultProxyKeepAlive
508 requestTimeout = DefaultRequestTimeout
509 connectTimeout = DefaultConnectTimeout
510 tlsTimeout = DefaultTLSHandshakeTimeout
511 keepAlive = DefaultKeepAlive
514 transport, ok := http.DefaultTransport.(*http.Transport)
519 // Evidently the application has replaced
520 // http.DefaultTransport with a different type, so we
521 // need to build our own from scratch using the Go 1.8
523 transport = &http.Transport{
525 IdleConnTimeout: 90 * time.Second,
526 ExpectContinueTimeout: time.Second,
529 transport.DialContext = (&net.Dialer{
530 Timeout: connectTimeout,
531 KeepAlive: keepAlive,
534 transport.TLSHandshakeTimeout = tlsTimeout
535 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
537 Timeout: requestTimeout,
538 Transport: transport,
540 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
544 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
546 func (kc *KeepClient) setRequestHeaders(req *http.Request) {
547 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
548 if kc.RequestID != "" {
549 req.Header.Set("X-Request-Id", kc.RequestID)
551 req.Header.Set("X-Request-Id", reqIDGen.Next())
555 type Locator struct {
557 Size int // -1 if data size is not known
558 Hints []string // Including the size hint, if any
561 func (loc *Locator) String() string {
563 if len(loc.Hints) > 0 {
564 s = s + "+" + strings.Join(loc.Hints, "+")
569 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
571 func MakeLocator(path string) (*Locator, error) {
572 sm := locatorMatcher.FindStringSubmatch(path)
574 return nil, InvalidLocatorError
576 loc := Locator{Hash: sm[1], Size: -1}
578 loc.Hints = strings.Split(sm[3], "+")
580 loc.Hints = []string{}
582 if len(loc.Hints) > 0 {
583 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {