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?
106 // MakeKeepClient creates a new KeepClient, calls
107 // DiscoverKeepServices(), and returns when the client is ready to
109 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
111 return kc, kc.DiscoverKeepServers()
114 // New creates a new KeepClient. The caller must call
115 // DiscoverKeepServers() before using the returned client to read or
117 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
118 defaultReplicationLevel := 2
119 value, err := arv.Discovery("defaultCollectionReplication")
121 v, ok := value.(float64)
123 defaultReplicationLevel = int(v)
128 Want_replicas: defaultReplicationLevel,
133 // Put a block given the block hash, a reader, and the number of bytes
134 // to read from the reader (which must be between 0 and BLOCKSIZE).
136 // Returns the locator for the written block, the number of replicas
137 // written, and an error.
139 // Returns an InsufficientReplicasError if 0 <= replicas <
140 // kc.Wants_replicas.
141 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
142 // Buffer for reads from 'r'
145 if dataBytes > BLOCKSIZE {
146 return "", 0, ErrOversizeBlock
148 bufsize = int(dataBytes)
153 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
156 return kc.putReplicas(hash, t, dataBytes)
159 // PutHB writes a block to Keep. The hash of the bytes is given in
160 // hash, and the data is given in buf.
162 // Return values are the same as for PutHR.
163 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
164 t := streamer.AsyncStreamFromSlice(buf)
166 return kc.putReplicas(hash, t, int64(len(buf)))
169 // PutB writes a block to Keep. It computes the hash itself.
171 // Return values are the same as for PutHR.
172 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
173 hash := fmt.Sprintf("%x", md5.Sum(buffer))
174 return kc.PutHB(hash, buffer)
177 // PutR writes a block to Keep. It first reads all data from r into a buffer
178 // in order to compute the hash.
180 // Return values are the same as for PutHR.
182 // If the block hash and data size are known, PutHR is more efficient.
183 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
184 if buffer, err := ioutil.ReadAll(r); err != nil {
187 return kc.PutB(buffer)
191 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
192 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
193 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
198 tries_remaining := 1 + kc.Retries
200 serversToTry := kc.getSortedRoots(locator)
202 numServers := len(serversToTry)
205 var retryList []string
207 for tries_remaining > 0 {
211 for _, host := range serversToTry {
212 url := host + "/" + locator
214 req, err := http.NewRequest(method, url, nil)
216 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
219 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
220 resp, err := kc.httpClient().Do(req)
222 // Probably a network error, may be transient,
224 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
225 retryList = append(retryList, host)
226 } else if resp.StatusCode != http.StatusOK {
228 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
230 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
231 url, resp.StatusCode, bytes.TrimSpace(respbody)))
233 if resp.StatusCode == 408 ||
234 resp.StatusCode == 429 ||
235 resp.StatusCode >= 500 {
236 // Timeout, too many requests, or other
237 // server side failure, transient
238 // error, can try again.
239 retryList = append(retryList, host)
240 } else if resp.StatusCode == 404 {
246 return HashCheckingReader{
249 Check: locator[0:32],
250 }, resp.ContentLength, url, nil
253 return nil, resp.ContentLength, url, nil
258 serversToTry = retryList
260 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
263 if count404 == numServers {
266 err = &ErrNotFound{multipleResponseError{
267 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
268 isTemp: len(serversToTry) > 0,
271 return nil, 0, "", err
274 // Get() retrieves a block, given a locator. Returns a reader, the
275 // expected data length, the URL the block is being fetched from, and
278 // If the block checksum does not match, the final Read() on the
279 // reader returned by this method will return a BadChecksum error
281 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
282 return kc.getOrHead("GET", locator)
285 // Ask() verifies that a block with the given hash is available and
286 // readable, according to at least one Keep service. Unlike Get, it
287 // does not retrieve the data or verify that the data content matches
288 // the hash specified by the locator.
290 // Returns the data size (content length) reported by the Keep service
291 // and the URI reporting the data size.
292 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
293 _, size, url, err := kc.getOrHead("HEAD", locator)
294 return size, url, err
297 // GetIndex retrieves a list of blocks stored on the given server whose hashes
298 // begin with the given prefix. The returned reader will return an error (other
299 // than EOF) if the complete index cannot be retrieved.
301 // This is meant to be used only by system components and admin tools.
302 // It will return an error unless the client is using a "data manager token"
303 // recognized by the Keep services.
304 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
305 url := kc.LocalRoots()[keepServiceUUID]
307 return nil, ErrNoSuchKeepServer
315 req, err := http.NewRequest("GET", url, nil)
320 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
321 resp, err := kc.httpClient().Do(req)
326 defer resp.Body.Close()
328 if resp.StatusCode != http.StatusOK {
329 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
333 respBody, err = ioutil.ReadAll(resp.Body)
338 // Got index; verify that it is complete
339 // The response should be "\n" if no locators matched the prefix
340 // Else, it should be a list of locators followed by a blank line
341 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
342 return nil, ErrIncompleteIndex
345 // Got complete index; strip the trailing newline and send
346 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
349 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
350 // services: uuid -> baseURI.
351 func (kc *KeepClient) LocalRoots() map[string]string {
353 defer kc.lock.RUnlock()
354 return *kc.localRoots
357 // GatewayRoots() returns the map of Keep remote gateway services:
359 func (kc *KeepClient) GatewayRoots() map[string]string {
361 defer kc.lock.RUnlock()
362 return *kc.gatewayRoots
365 // WritableLocalRoots() returns the map of writable local Keep services:
367 func (kc *KeepClient) WritableLocalRoots() map[string]string {
369 defer kc.lock.RUnlock()
370 return *kc.writableLocalRoots
373 // SetServiceRoots updates the localRoots and gatewayRoots maps,
374 // without risk of disrupting operations that are already in progress.
376 // The KeepClient makes its own copy of the supplied maps, so the
377 // caller can reuse/modify them after SetServiceRoots returns, but
378 // they should not be modified by any other goroutine while
379 // SetServiceRoots is running.
380 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals, newGateways map[string]string) {
381 locals := make(map[string]string)
382 for uuid, root := range newLocals {
386 writables := make(map[string]string)
387 for uuid, root := range newWritableLocals {
388 writables[uuid] = root
391 gateways := make(map[string]string)
392 for uuid, root := range newGateways {
393 gateways[uuid] = root
397 defer kc.lock.Unlock()
398 kc.localRoots = &locals
399 kc.writableLocalRoots = &writables
400 kc.gatewayRoots = &gateways
403 // getSortedRoots returns a list of base URIs of Keep services, in the
404 // order they should be attempted in order to retrieve content for the
406 func (kc *KeepClient) getSortedRoots(locator string) []string {
408 for _, hint := range strings.Split(locator, "+") {
409 if len(hint) < 7 || hint[0:2] != "K@" {
410 // Not a service hint.
414 // +K@abcde means fetch from proxy at
415 // keep.abcde.arvadosapi.com
416 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
417 } else if len(hint) == 29 {
418 // +K@abcde-abcde-abcdeabcdeabcde means fetch
419 // from gateway with given uuid
420 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
421 found = append(found, gwURI)
423 // else this hint is no use to us; carry on.
426 // After trying all usable service hints, fall back to local roots.
427 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
431 func (kc *KeepClient) cache() *BlockCache {
432 if kc.BlockCache != nil {
435 return DefaultBlockCache
440 // There are four global http.Client objects for the four
441 // possible permutations of TLS behavior (verify/skip-verify)
442 // and timeout settings (proxy/non-proxy).
443 defaultClient = map[bool]map[bool]HTTPClient{
444 // defaultClient[false] is used for verified TLS reqs
446 // defaultClient[true] is used for unverified
447 // (insecure) TLS reqs
450 defaultClientMtx sync.Mutex
453 // httpClient returns the HTTPClient field if it's not nil, otherwise
454 // whichever of the four global http.Client objects is suitable for
455 // the current environment (i.e., TLS verification on/off, keep
456 // services are/aren't proxies).
457 func (kc *KeepClient) httpClient() HTTPClient {
458 if kc.HTTPClient != nil {
461 defaultClientMtx.Lock()
462 defer defaultClientMtx.Unlock()
463 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
467 var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
468 if kc.foundNonDiskSvc {
469 // Use longer timeouts when connecting to a proxy,
470 // because this usually means the intervening network
472 requestTimeout = DefaultProxyRequestTimeout
473 connectTimeout = DefaultProxyConnectTimeout
474 tlsTimeout = DefaultProxyTLSHandshakeTimeout
475 keepAlive = DefaultProxyKeepAlive
477 requestTimeout = DefaultRequestTimeout
478 connectTimeout = DefaultConnectTimeout
479 tlsTimeout = DefaultTLSHandshakeTimeout
480 keepAlive = DefaultKeepAlive
483 transport, ok := http.DefaultTransport.(*http.Transport)
488 // Evidently the application has replaced
489 // http.DefaultTransport with a different type, so we
490 // need to build our own from scratch using the Go 1.8
492 transport = &http.Transport{
494 IdleConnTimeout: 90 * time.Second,
495 ExpectContinueTimeout: time.Second,
498 transport.DialContext = (&net.Dialer{
499 Timeout: connectTimeout,
500 KeepAlive: keepAlive,
503 transport.TLSHandshakeTimeout = tlsTimeout
504 transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
506 Timeout: requestTimeout,
507 Transport: transport,
509 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
513 type Locator struct {
515 Size int // -1 if data size is not known
516 Hints []string // Including the size hint, if any
519 func (loc *Locator) String() string {
521 if len(loc.Hints) > 0 {
522 s = s + "+" + strings.Join(loc.Hints, "+")
527 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
529 func MakeLocator(path string) (*Locator, error) {
530 sm := locatorMatcher.FindStringSubmatch(path)
532 return nil, InvalidLocatorError
534 loc := Locator{Hash: sm[1], Size: -1}
536 loc.Hints = strings.Split(sm[3], "+")
538 loc.Hints = []string{}
540 if len(loc.Hints) > 0 {
541 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {