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"
27 // A Keep "block" is 64MB.
28 const BLOCKSIZE = 64 * 1024 * 1024
31 DefaultRequestTimeout = 20 * time.Second
32 DefaultConnectTimeout = 2 * time.Second
33 DefaultTLSHandshakeTimeout = 4 * time.Second
34 DefaultKeepAlive = 180 * time.Second
36 DefaultProxyRequestTimeout = 300 * time.Second
37 DefaultProxyConnectTimeout = 30 * time.Second
38 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
39 DefaultProxyKeepAlive = 120 * time.Second
42 // Error interface with an error and boolean indicating whether the error is temporary
43 type Error interface {
48 // multipleResponseError is of type Error
49 type multipleResponseError struct {
54 func (e *multipleResponseError) Temporary() bool {
58 // BlockNotFound is a multipleResponseError where isTemp is false
59 var BlockNotFound = &ErrNotFound{multipleResponseError{
60 error: errors.New("Block not found"),
64 // ErrNotFound is a multipleResponseError where isTemp can be true or false
65 type ErrNotFound struct {
69 type InsufficientReplicasError error
71 type OversizeBlockError error
73 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
74 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
75 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
76 var InvalidLocatorError = errors.New("Invalid locator")
78 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
79 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
81 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
82 var ErrIncompleteIndex = errors.New("Got incomplete index")
84 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
85 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
87 type HTTPClient interface {
88 Do(*http.Request) (*http.Response, error)
91 // Information about Arvados and Keep servers.
92 type KeepClient struct {
93 Arvados *arvadosclient.ArvadosClient
95 localRoots map[string]string
96 writableLocalRoots map[string]string
97 gatewayRoots map[string]string
101 BlockCache *BlockCache
103 // set to 1 if all writable services are of disk type, otherwise 0
104 replicasPerService int
106 // Any non-disk typed services found in the list of keepservers?
109 // Disable automatic discovery of keep services
110 disableDiscovery bool
113 // MakeKeepClient creates a new KeepClient, calls
114 // DiscoverKeepServices(), and returns when the client is ready to
116 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
118 return kc, kc.discoverServices()
121 // New creates a new KeepClient. Service discovery will occur on the
122 // next read/write operation.
123 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
124 defaultReplicationLevel := 2
125 value, err := arv.Discovery("defaultCollectionReplication")
127 v, ok := value.(float64)
129 defaultReplicationLevel = int(v)
134 Want_replicas: defaultReplicationLevel,
139 // Put a block given the block hash, a reader, and the number of bytes
140 // to read from the reader (which must be between 0 and BLOCKSIZE).
142 // Returns the locator for the written block, the number of replicas
143 // written, and an error.
145 // Returns an InsufficientReplicasError if 0 <= replicas <
146 // kc.Wants_replicas.
147 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
148 // Buffer for reads from 'r'
151 if dataBytes > BLOCKSIZE {
152 return "", 0, ErrOversizeBlock
154 bufsize = int(dataBytes)
159 buf := asyncbuf.NewBuffer(make([]byte, 0, bufsize))
161 _, err := io.Copy(buf, HashCheckingReader{r, md5.New(), hash})
162 buf.CloseWithError(err)
164 return kc.putReplicas(hash, buf.NewReader, dataBytes)
167 // PutHB writes a block to Keep. The hash of the bytes is given in
168 // hash, and the data is given in buf.
170 // Return values are the same as for PutHR.
171 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
172 newReader := func() io.Reader { return bytes.NewBuffer(buf) }
173 return kc.putReplicas(hash, newReader, int64(len(buf)))
176 // PutB writes a block to Keep. It computes the hash itself.
178 // Return values are the same as for PutHR.
179 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
180 hash := fmt.Sprintf("%x", md5.Sum(buffer))
181 return kc.PutHB(hash, buffer)
184 // PutR writes a block to Keep. It first reads all data from r into a buffer
185 // in order to compute the hash.
187 // Return values are the same as for PutHR.
189 // If the block hash and data size are known, PutHR is more efficient.
190 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
191 if buffer, err := ioutil.ReadAll(r); err != nil {
194 return kc.PutB(buffer)
198 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
199 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
200 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
205 tries_remaining := 1 + kc.Retries
207 serversToTry := kc.getSortedRoots(locator)
209 numServers := len(serversToTry)
212 var retryList []string
214 for tries_remaining > 0 {
218 for _, host := range serversToTry {
219 url := host + "/" + locator
221 req, err := http.NewRequest(method, url, nil)
223 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
226 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
227 resp, err := kc.httpClient().Do(req)
229 // Probably a network error, may be transient,
231 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
232 retryList = append(retryList, host)
233 } else if resp.StatusCode != http.StatusOK {
235 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
237 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
238 url, resp.StatusCode, bytes.TrimSpace(respbody)))
240 if resp.StatusCode == 408 ||
241 resp.StatusCode == 429 ||
242 resp.StatusCode >= 500 {
243 // Timeout, too many requests, or other
244 // server side failure, transient
245 // error, can try again.
246 retryList = append(retryList, host)
247 } else if resp.StatusCode == 404 {
250 } else if resp.ContentLength < 0 {
251 // Missing Content-Length
253 return nil, 0, "", fmt.Errorf("Missing Content-Length of block")
257 return HashCheckingReader{
260 Check: locator[0:32],
261 }, resp.ContentLength, url, nil
264 return nil, resp.ContentLength, url, nil
269 serversToTry = retryList
271 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
274 if count404 == numServers {
277 err = &ErrNotFound{multipleResponseError{
278 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
279 isTemp: len(serversToTry) > 0,
282 return nil, 0, "", err
285 // Get() retrieves a block, given a locator. Returns a reader, the
286 // expected data length, the URL the block is being fetched from, and
289 // If the block checksum does not match, the final Read() on the
290 // reader returned by this method will return a BadChecksum error
292 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
293 return kc.getOrHead("GET", locator)
296 // ReadAt() retrieves a portion of block from the cache if it's
297 // present, otherwise from the network.
298 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
299 return kc.cache().ReadAt(kc, locator, p, off)
302 // Ask() verifies that a block with the given hash is available and
303 // readable, according to at least one Keep service. Unlike Get, it
304 // does not retrieve the data or verify that the data content matches
305 // the hash specified by the locator.
307 // Returns the data size (content length) reported by the Keep service
308 // and the URI reporting the data size.
309 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
310 _, size, url, err := kc.getOrHead("HEAD", locator)
311 return size, url, err
314 // GetIndex retrieves a list of blocks stored on the given server whose hashes
315 // begin with the given prefix. The returned reader will return an error (other
316 // than EOF) if the complete index cannot be retrieved.
318 // This is meant to be used only by system components and admin tools.
319 // It will return an error unless the client is using a "data manager token"
320 // recognized by the Keep services.
321 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
322 url := kc.LocalRoots()[keepServiceUUID]
324 return nil, ErrNoSuchKeepServer
332 req, err := http.NewRequest("GET", url, nil)
337 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
338 resp, err := kc.httpClient().Do(req)
343 defer resp.Body.Close()
345 if resp.StatusCode != http.StatusOK {
346 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
350 respBody, err = ioutil.ReadAll(resp.Body)
355 // Got index; verify that it is complete
356 // The response should be "\n" if no locators matched the prefix
357 // Else, it should be a list of locators followed by a blank line
358 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
359 return nil, ErrIncompleteIndex
362 // Got complete index; strip the trailing newline and send
363 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
366 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
367 // services: uuid -> baseURI.
368 func (kc *KeepClient) LocalRoots() map[string]string {
369 kc.discoverServices()
371 defer kc.lock.RUnlock()
375 // GatewayRoots() returns the map of Keep remote gateway services:
377 func (kc *KeepClient) GatewayRoots() map[string]string {
378 kc.discoverServices()
380 defer kc.lock.RUnlock()
381 return kc.gatewayRoots
384 // WritableLocalRoots() returns the map of writable local Keep services:
386 func (kc *KeepClient) WritableLocalRoots() map[string]string {
387 kc.discoverServices()
389 defer kc.lock.RUnlock()
390 return kc.writableLocalRoots
393 // SetServiceRoots disables service discovery and updates the
394 // localRoots and gatewayRoots maps, without disrupting operations
395 // that are already in progress.
397 // The supplied maps must not be modified after calling
399 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
400 kc.disableDiscovery = true
401 kc.setServiceRoots(locals, writables, gateways)
404 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
406 defer kc.lock.Unlock()
407 kc.localRoots = locals
408 kc.writableLocalRoots = writables
409 kc.gatewayRoots = gateways
412 // getSortedRoots returns a list of base URIs of Keep services, in the
413 // order they should be attempted in order to retrieve content for the
415 func (kc *KeepClient) getSortedRoots(locator string) []string {
417 for _, hint := range strings.Split(locator, "+") {
418 if len(hint) < 7 || hint[0:2] != "K@" {
419 // Not a service hint.
423 // +K@abcde means fetch from proxy at
424 // keep.abcde.arvadosapi.com
425 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
426 } else if len(hint) == 29 {
427 // +K@abcde-abcde-abcdeabcdeabcde means fetch
428 // from gateway with given uuid
429 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
430 found = append(found, gwURI)
432 // else this hint is no use to us; carry on.
435 // After trying all usable service hints, fall back to local roots.
436 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
440 func (kc *KeepClient) cache() *BlockCache {
441 if kc.BlockCache != nil {
444 return DefaultBlockCache
448 func (kc *KeepClient) ClearBlockCache() {
453 // There are four global http.Client objects for the four
454 // possible permutations of TLS behavior (verify/skip-verify)
455 // and timeout settings (proxy/non-proxy).
456 defaultClient = map[bool]map[bool]HTTPClient{
457 // defaultClient[false] is used for verified TLS reqs
459 // defaultClient[true] is used for unverified
460 // (insecure) TLS reqs
463 defaultClientMtx sync.Mutex
466 // httpClient returns the HTTPClient field if it's not nil, otherwise
467 // whichever of the four global http.Client objects is suitable for
468 // the current environment (i.e., TLS verification on/off, keep
469 // services are/aren't proxies).
470 func (kc *KeepClient) httpClient() HTTPClient {
471 if kc.HTTPClient != nil {
474 defaultClientMtx.Lock()
475 defer defaultClientMtx.Unlock()
476 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
480 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
481 if kc.foundNonDiskSvc {
482 // Use longer timeouts when connecting to a proxy,
483 // because this usually means the intervening network
485 requestTimeout = DefaultProxyRequestTimeout
486 connectTimeout = DefaultProxyConnectTimeout
487 tlsTimeout = DefaultProxyTLSHandshakeTimeout
488 keepAlive = DefaultProxyKeepAlive
490 requestTimeout = DefaultRequestTimeout
491 connectTimeout = DefaultConnectTimeout
492 tlsTimeout = DefaultTLSHandshakeTimeout
493 keepAlive = DefaultKeepAlive
496 transport, ok := http.DefaultTransport.(*http.Transport)
501 // Evidently the application has replaced
502 // http.DefaultTransport with a different type, so we
503 // need to build our own from scratch using the Go 1.8
505 transport = &http.Transport{
507 IdleConnTimeout: 90 * time.Second,
508 ExpectContinueTimeout: time.Second,
511 transport.DialContext = (&net.Dialer{
512 Timeout: connectTimeout,
513 KeepAlive: keepAlive,
516 transport.TLSHandshakeTimeout = tlsTimeout
517 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
519 Timeout: requestTimeout,
520 Transport: transport,
522 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
526 type Locator struct {
528 Size int // -1 if data size is not known
529 Hints []string // Including the size hint, if any
532 func (loc *Locator) String() string {
534 if len(loc.Hints) > 0 {
535 s = s + "+" + strings.Join(loc.Hints, "+")
540 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
542 func MakeLocator(path string) (*Locator, error) {
543 sm := locatorMatcher.FindStringSubmatch(path)
545 return nil, InvalidLocatorError
547 loc := Locator{Hash: sm[1], Size: -1}
549 loc.Hints = strings.Split(sm[3], "+")
551 loc.Hints = []string{}
553 if len(loc.Hints) > 0 {
554 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {