1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
19 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
20 "git.curoverse.com/arvados.git/sdk/go/streamer"
23 // A Keep "block" is 64MB.
24 const BLOCKSIZE = 64 * 1024 * 1024
27 DefaultRequestTimeout = 20 * time.Second
28 DefaultConnectTimeout = 2 * time.Second
29 DefaultTLSHandshakeTimeout = 4 * time.Second
30 DefaultKeepAlive = 180 * time.Second
32 DefaultProxyRequestTimeout = 300 * time.Second
33 DefaultProxyConnectTimeout = 30 * time.Second
34 DefaultProxyTLSHandshakeTimeout = 10 * time.Second
35 DefaultProxyKeepAlive = 120 * time.Second
38 // Error interface with an error and boolean indicating whether the error is temporary
39 type Error interface {
44 // multipleResponseError is of type Error
45 type multipleResponseError struct {
50 func (e *multipleResponseError) Temporary() bool {
54 // BlockNotFound is a multipleResponseError where isTemp is false
55 var BlockNotFound = &ErrNotFound{multipleResponseError{
56 error: errors.New("Block not found"),
60 // ErrNotFound is a multipleResponseError where isTemp can be true or false
61 type ErrNotFound struct {
65 type InsufficientReplicasError error
67 type OversizeBlockError error
69 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
70 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
71 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
72 var InvalidLocatorError = errors.New("Invalid locator")
74 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
75 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
77 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
78 var ErrIncompleteIndex = errors.New("Got incomplete index")
80 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
81 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
83 type HTTPClient interface {
84 Do(*http.Request) (*http.Response, error)
87 // Information about Arvados and Keep servers.
88 type KeepClient struct {
89 Arvados *arvadosclient.ArvadosClient
91 localRoots map[string]string
92 writableLocalRoots map[string]string
93 gatewayRoots map[string]string
97 BlockCache *BlockCache
99 // set to 1 if all writable services are of disk type, otherwise 0
100 replicasPerService int
102 // Any non-disk typed services found in the list of keepservers?
105 // Disable automatic discovery of keep services
106 disableDiscovery bool
109 // MakeKeepClient creates a new KeepClient, calls
110 // DiscoverKeepServices(), and returns when the client is ready to
112 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
114 return kc, kc.discoverServices()
117 // New creates a new KeepClient. Service discovery will occur on the
118 // next read/write operation.
119 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
120 defaultReplicationLevel := 2
121 value, err := arv.Discovery("defaultCollectionReplication")
123 v, ok := value.(float64)
125 defaultReplicationLevel = int(v)
130 Want_replicas: defaultReplicationLevel,
135 // Put a block given the block hash, a reader, and the number of bytes
136 // to read from the reader (which must be between 0 and BLOCKSIZE).
138 // Returns the locator for the written block, the number of replicas
139 // written, and an error.
141 // Returns an InsufficientReplicasError if 0 <= replicas <
142 // kc.Wants_replicas.
143 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
144 // Buffer for reads from 'r'
147 if dataBytes > BLOCKSIZE {
148 return "", 0, ErrOversizeBlock
150 bufsize = int(dataBytes)
155 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
158 return kc.putReplicas(hash, t, dataBytes)
161 // PutHB writes a block to Keep. The hash of the bytes is given in
162 // hash, and the data is given in buf.
164 // Return values are the same as for PutHR.
165 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
166 t := streamer.AsyncStreamFromSlice(buf)
168 return kc.putReplicas(hash, t, int64(len(buf)))
171 // PutB writes a block to Keep. It computes the hash itself.
173 // Return values are the same as for PutHR.
174 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
175 hash := fmt.Sprintf("%x", md5.Sum(buffer))
176 return kc.PutHB(hash, buffer)
179 // PutR writes a block to Keep. It first reads all data from r into a buffer
180 // in order to compute the hash.
182 // Return values are the same as for PutHR.
184 // If the block hash and data size are known, PutHR is more efficient.
185 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
186 if buffer, err := ioutil.ReadAll(r); err != nil {
189 return kc.PutB(buffer)
193 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
194 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
195 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
200 tries_remaining := 1 + kc.Retries
202 serversToTry := kc.getSortedRoots(locator)
204 numServers := len(serversToTry)
207 var retryList []string
209 for tries_remaining > 0 {
213 for _, host := range serversToTry {
214 url := host + "/" + locator
216 req, err := http.NewRequest(method, url, nil)
218 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
221 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
222 resp, err := kc.httpClient().Do(req)
224 // Probably a network error, may be transient,
226 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
227 retryList = append(retryList, host)
228 } else if resp.StatusCode != http.StatusOK {
230 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
232 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
233 url, resp.StatusCode, bytes.TrimSpace(respbody)))
235 if resp.StatusCode == 408 ||
236 resp.StatusCode == 429 ||
237 resp.StatusCode >= 500 {
238 // Timeout, too many requests, or other
239 // server side failure, transient
240 // error, can try again.
241 retryList = append(retryList, host)
242 } else if resp.StatusCode == 404 {
248 return HashCheckingReader{
251 Check: locator[0:32],
252 }, resp.ContentLength, url, nil
255 return nil, resp.ContentLength, url, nil
260 serversToTry = retryList
262 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
265 if count404 == numServers {
268 err = &ErrNotFound{multipleResponseError{
269 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
270 isTemp: len(serversToTry) > 0,
273 return nil, 0, "", err
276 // Get() retrieves a block, given a locator. Returns a reader, the
277 // expected data length, the URL the block is being fetched from, and
280 // If the block checksum does not match, the final Read() on the
281 // reader returned by this method will return a BadChecksum error
283 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
284 return kc.getOrHead("GET", locator)
287 // Ask() verifies that a block with the given hash is available and
288 // readable, according to at least one Keep service. Unlike Get, it
289 // does not retrieve the data or verify that the data content matches
290 // the hash specified by the locator.
292 // Returns the data size (content length) reported by the Keep service
293 // and the URI reporting the data size.
294 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
295 _, size, url, err := kc.getOrHead("HEAD", locator)
296 return size, url, err
299 // GetIndex retrieves a list of blocks stored on the given server whose hashes
300 // begin with the given prefix. The returned reader will return an error (other
301 // than EOF) if the complete index cannot be retrieved.
303 // This is meant to be used only by system components and admin tools.
304 // It will return an error unless the client is using a "data manager token"
305 // recognized by the Keep services.
306 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
307 url := kc.LocalRoots()[keepServiceUUID]
309 return nil, ErrNoSuchKeepServer
317 req, err := http.NewRequest("GET", url, nil)
322 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
323 resp, err := kc.httpClient().Do(req)
328 defer resp.Body.Close()
330 if resp.StatusCode != http.StatusOK {
331 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
335 respBody, err = ioutil.ReadAll(resp.Body)
340 // Got index; verify that it is complete
341 // The response should be "\n" if no locators matched the prefix
342 // Else, it should be a list of locators followed by a blank line
343 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
344 return nil, ErrIncompleteIndex
347 // Got complete index; strip the trailing newline and send
348 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
351 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
352 // services: uuid -> baseURI.
353 func (kc *KeepClient) LocalRoots() map[string]string {
354 kc.discoverServices()
356 defer kc.lock.RUnlock()
360 // GatewayRoots() returns the map of Keep remote gateway services:
362 func (kc *KeepClient) GatewayRoots() map[string]string {
363 kc.discoverServices()
365 defer kc.lock.RUnlock()
366 return kc.gatewayRoots
369 // WritableLocalRoots() returns the map of writable local Keep services:
371 func (kc *KeepClient) WritableLocalRoots() map[string]string {
372 kc.discoverServices()
374 defer kc.lock.RUnlock()
375 return kc.writableLocalRoots
378 // SetServiceRoots disables service discovery and updates the
379 // localRoots and gatewayRoots maps, without disrupting operations
380 // that are already in progress.
382 // The supplied maps must not be modified after calling
384 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
385 kc.disableDiscovery = true
386 kc.setServiceRoots(locals, writables, gateways)
389 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
391 defer kc.lock.Unlock()
392 kc.localRoots = locals
393 kc.writableLocalRoots = writables
394 kc.gatewayRoots = gateways
397 // getSortedRoots returns a list of base URIs of Keep services, in the
398 // order they should be attempted in order to retrieve content for the
400 func (kc *KeepClient) getSortedRoots(locator string) []string {
402 for _, hint := range strings.Split(locator, "+") {
403 if len(hint) < 7 || hint[0:2] != "K@" {
404 // Not a service hint.
408 // +K@abcde means fetch from proxy at
409 // keep.abcde.arvadosapi.com
410 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
411 } else if len(hint) == 29 {
412 // +K@abcde-abcde-abcdeabcdeabcde means fetch
413 // from gateway with given uuid
414 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
415 found = append(found, gwURI)
417 // else this hint is no use to us; carry on.
420 // After trying all usable service hints, fall back to local roots.
421 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
425 func (kc *KeepClient) cache() *BlockCache {
426 if kc.BlockCache != nil {
429 return DefaultBlockCache
434 // There are four global http.Client objects for the four
435 // possible permutations of TLS behavior (verify/skip-verify)
436 // and timeout settings (proxy/non-proxy).
437 defaultClient = map[bool]map[bool]HTTPClient{
438 // defaultClient[false] is used for verified TLS reqs
440 // defaultClient[true] is used for unverified
441 // (insecure) TLS reqs
444 defaultClientMtx sync.Mutex
447 // httpClient returns the HTTPClient field if it's not nil, otherwise
448 // whichever of the four global http.Client objects is suitable for
449 // the current environment (i.e., TLS verification on/off, keep
450 // services are/aren't proxies).
451 func (kc *KeepClient) httpClient() HTTPClient {
452 if kc.HTTPClient != nil {
455 defaultClientMtx.Lock()
456 defer defaultClientMtx.Unlock()
457 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
461 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
462 if kc.foundNonDiskSvc {
463 // Use longer timeouts when connecting to a proxy,
464 // because this usually means the intervening network
466 requestTimeout = DefaultProxyRequestTimeout
467 connectTimeout = DefaultProxyConnectTimeout
468 tlsTimeout = DefaultProxyTLSHandshakeTimeout
469 keepAlive = DefaultProxyKeepAlive
471 requestTimeout = DefaultRequestTimeout
472 connectTimeout = DefaultConnectTimeout
473 tlsTimeout = DefaultTLSHandshakeTimeout
474 keepAlive = DefaultKeepAlive
477 transport, ok := http.DefaultTransport.(*http.Transport)
482 // Evidently the application has replaced
483 // http.DefaultTransport with a different type, so we
484 // need to build our own from scratch using the Go 1.8
486 transport = &http.Transport{
488 IdleConnTimeout: 90 * time.Second,
489 ExpectContinueTimeout: time.Second,
492 transport.DialContext = (&net.Dialer{
493 Timeout: connectTimeout,
494 KeepAlive: keepAlive,
497 transport.TLSHandshakeTimeout = tlsTimeout
498 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
500 Timeout: requestTimeout,
501 Transport: transport,
503 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
507 type Locator struct {
509 Size int // -1 if data size is not known
510 Hints []string // Including the size hint, if any
513 func (loc *Locator) String() string {
515 if len(loc.Hints) > 0 {
516 s = s + "+" + strings.Join(loc.Hints, "+")
521 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
523 func MakeLocator(path string) (*Locator, error) {
524 sm := locatorMatcher.FindStringSubmatch(path)
526 return nil, InvalidLocatorError
528 loc := Locator{Hash: sm[1], Size: -1}
530 loc.Hints = strings.Split(sm[3], "+")
532 loc.Hints = []string{}
534 if len(loc.Hints) > 0 {
535 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {