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
104 StorageClasses []string
106 // set to 1 if all writable services are of disk type, otherwise 0
107 replicasPerService int
109 // Any non-disk typed services found in the list of keepservers?
112 // Disable automatic discovery of keep services
113 disableDiscovery bool
116 // MakeKeepClient creates a new KeepClient, calls
117 // DiscoverKeepServices(), and returns when the client is ready to
119 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
121 return kc, kc.discoverServices()
124 // New creates a new KeepClient. Service discovery will occur on the
125 // next read/write operation.
126 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
127 defaultReplicationLevel := 2
128 value, err := arv.Discovery("defaultCollectionReplication")
130 v, ok := value.(float64)
132 defaultReplicationLevel = int(v)
137 Want_replicas: defaultReplicationLevel,
142 // Put a block given the block hash, a reader, and the number of bytes
143 // to read from the reader (which must be between 0 and BLOCKSIZE).
145 // Returns the locator for the written block, the number of replicas
146 // written, and an error.
148 // Returns an InsufficientReplicasError if 0 <= replicas <
149 // kc.Wants_replicas.
150 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
151 // Buffer for reads from 'r'
154 if dataBytes > BLOCKSIZE {
155 return "", 0, ErrOversizeBlock
157 bufsize = int(dataBytes)
162 buf := asyncbuf.NewBuffer(make([]byte, 0, bufsize))
164 _, err := io.Copy(buf, HashCheckingReader{r, md5.New(), hash})
165 buf.CloseWithError(err)
167 return kc.putReplicas(hash, buf.NewReader, dataBytes)
170 // PutHB writes a block to Keep. The hash of the bytes is given in
171 // hash, and the data is given in buf.
173 // Return values are the same as for PutHR.
174 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
175 newReader := func() io.Reader { return bytes.NewBuffer(buf) }
176 return kc.putReplicas(hash, newReader, int64(len(buf)))
179 // PutB writes a block to Keep. It computes the hash itself.
181 // Return values are the same as for PutHR.
182 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
183 hash := fmt.Sprintf("%x", md5.Sum(buffer))
184 return kc.PutHB(hash, buffer)
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 if buffer, err := ioutil.ReadAll(r); err != nil {
197 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 tries_remaining := 1 + kc.Retries
221 serversToTry := kc.getSortedRoots(locator)
223 numServers := len(serversToTry)
226 var retryList []string
228 for tries_remaining > 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
298 serversToTry = retryList
300 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
303 if count404 == numServers {
306 err = &ErrNotFound{multipleResponseError{
307 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
308 isTemp: len(serversToTry) > 0,
311 return nil, 0, "", nil, err
314 // LocalLocator returns a locator equivalent to the one supplied, but
315 // with a valid signature from the local cluster. If the given locator
316 // already has a local signature, it is returned unchanged.
317 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
318 if !strings.Contains(locator, "+R") {
319 // Either it has +A, or it's unsigned and we assume
320 // it's a local locator on a site with signatures
324 sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
325 _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
329 loc := hdr.Get("X-Keep-Locator")
331 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
336 // Get() retrieves a block, given a locator. Returns a reader, the
337 // expected data length, the URL the block is being fetched from, and
340 // If the block checksum does not match, the final Read() on the
341 // reader returned by this method will return a BadChecksum error
343 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
344 rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
345 return rdr, size, url, err
348 // ReadAt() retrieves a portion of block from the cache if it's
349 // present, otherwise from the network.
350 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
351 return kc.cache().ReadAt(kc, locator, p, off)
354 // Ask() verifies that a block with the given hash is available and
355 // readable, according to at least one Keep service. Unlike Get, it
356 // does not retrieve the data or verify that the data content matches
357 // the hash specified by the locator.
359 // Returns the data size (content length) reported by the Keep service
360 // and the URI reporting the data size.
361 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
362 _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
363 return size, url, err
366 // GetIndex retrieves a list of blocks stored on the given server whose hashes
367 // begin with the given prefix. The returned reader will return an error (other
368 // than EOF) if the complete index cannot be retrieved.
370 // This is meant to be used only by system components and admin tools.
371 // It will return an error unless the client is using a "data manager token"
372 // recognized by the Keep services.
373 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
374 url := kc.LocalRoots()[keepServiceUUID]
376 return nil, ErrNoSuchKeepServer
384 req, err := http.NewRequest("GET", url, nil)
389 req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
390 req.Header.Set("X-Request-Id", kc.getRequestID())
391 resp, err := kc.httpClient().Do(req)
396 defer resp.Body.Close()
398 if resp.StatusCode != http.StatusOK {
399 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
403 respBody, err = ioutil.ReadAll(resp.Body)
408 // Got index; verify that it is complete
409 // The response should be "\n" if no locators matched the prefix
410 // Else, it should be a list of locators followed by a blank line
411 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
412 return nil, ErrIncompleteIndex
415 // Got complete index; strip the trailing newline and send
416 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
419 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
420 // services: uuid -> baseURI.
421 func (kc *KeepClient) LocalRoots() map[string]string {
422 kc.discoverServices()
424 defer kc.lock.RUnlock()
428 // GatewayRoots() returns the map of Keep remote gateway services:
430 func (kc *KeepClient) GatewayRoots() map[string]string {
431 kc.discoverServices()
433 defer kc.lock.RUnlock()
434 return kc.gatewayRoots
437 // WritableLocalRoots() returns the map of writable local Keep services:
439 func (kc *KeepClient) WritableLocalRoots() map[string]string {
440 kc.discoverServices()
442 defer kc.lock.RUnlock()
443 return kc.writableLocalRoots
446 // SetServiceRoots disables service discovery and updates the
447 // localRoots and gatewayRoots maps, without disrupting operations
448 // that are already in progress.
450 // The supplied maps must not be modified after calling
452 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
453 kc.disableDiscovery = true
454 kc.setServiceRoots(locals, writables, gateways)
457 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
459 defer kc.lock.Unlock()
460 kc.localRoots = locals
461 kc.writableLocalRoots = writables
462 kc.gatewayRoots = gateways
465 // getSortedRoots returns a list of base URIs of Keep services, in the
466 // order they should be attempted in order to retrieve content for the
468 func (kc *KeepClient) getSortedRoots(locator string) []string {
470 for _, hint := range strings.Split(locator, "+") {
471 if len(hint) < 7 || hint[0:2] != "K@" {
472 // Not a service hint.
476 // +K@abcde means fetch from proxy at
477 // keep.abcde.arvadosapi.com
478 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
479 } else if len(hint) == 29 {
480 // +K@abcde-abcde-abcdeabcdeabcde means fetch
481 // from gateway with given uuid
482 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
483 found = append(found, gwURI)
485 // else this hint is no use to us; carry on.
488 // After trying all usable service hints, fall back to local roots.
489 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
493 func (kc *KeepClient) cache() *BlockCache {
494 if kc.BlockCache != nil {
497 return DefaultBlockCache
501 func (kc *KeepClient) ClearBlockCache() {
506 // There are four global http.Client objects for the four
507 // possible permutations of TLS behavior (verify/skip-verify)
508 // and timeout settings (proxy/non-proxy).
509 defaultClient = map[bool]map[bool]HTTPClient{
510 // defaultClient[false] is used for verified TLS reqs
512 // defaultClient[true] is used for unverified
513 // (insecure) TLS reqs
516 defaultClientMtx sync.Mutex
519 // httpClient returns the HTTPClient field if it's not nil, otherwise
520 // whichever of the four global http.Client objects is suitable for
521 // the current environment (i.e., TLS verification on/off, keep
522 // services are/aren't proxies).
523 func (kc *KeepClient) httpClient() HTTPClient {
524 if kc.HTTPClient != nil {
527 defaultClientMtx.Lock()
528 defer defaultClientMtx.Unlock()
529 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
533 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
534 if kc.foundNonDiskSvc {
535 // Use longer timeouts when connecting to a proxy,
536 // because this usually means the intervening network
538 requestTimeout = DefaultProxyRequestTimeout
539 connectTimeout = DefaultProxyConnectTimeout
540 tlsTimeout = DefaultProxyTLSHandshakeTimeout
541 keepAlive = DefaultProxyKeepAlive
543 requestTimeout = DefaultRequestTimeout
544 connectTimeout = DefaultConnectTimeout
545 tlsTimeout = DefaultTLSHandshakeTimeout
546 keepAlive = DefaultKeepAlive
550 Timeout: requestTimeout,
551 // It's not safe to copy *http.DefaultTransport
552 // because it has a mutex (which might be locked)
553 // protecting a private map (which might not be nil).
554 // So we build our own, using the Go 1.10 default
555 // values, ignoring any changes the application has
556 // made to http.DefaultTransport.
557 Transport: &http.Transport{
558 DialContext: (&net.Dialer{
559 Timeout: connectTimeout,
560 KeepAlive: keepAlive,
564 IdleConnTimeout: 90 * time.Second,
565 TLSHandshakeTimeout: tlsTimeout,
566 ExpectContinueTimeout: time.Second,
567 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
570 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
574 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
576 func (kc *KeepClient) getRequestID() string {
577 if kc.RequestID != "" {
580 return reqIDGen.Next()
584 type Locator struct {
586 Size int // -1 if data size is not known
587 Hints []string // Including the size hint, if any
590 func (loc *Locator) String() string {
592 if len(loc.Hints) > 0 {
593 s = s + "+" + strings.Join(loc.Hints, "+")
598 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
600 func MakeLocator(path string) (*Locator, error) {
601 sm := locatorMatcher.FindStringSubmatch(path)
603 return nil, InvalidLocatorError
605 loc := Locator{Hash: sm[1], Size: -1}
607 loc.Hints = strings.Split(sm[3], "+")
609 loc.Hints = []string{}
611 if len(loc.Hints) > 0 {
612 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {