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
26 // Error interface with an error and boolean indicating whether the error is temporary
27 type Error interface {
32 // multipleResponseError is of type Error
33 type multipleResponseError struct {
38 func (e *multipleResponseError) Temporary() bool {
42 // BlockNotFound is a multipleResponseError where isTemp is false
43 var BlockNotFound = &ErrNotFound{multipleResponseError{
44 error: errors.New("Block not found"),
48 // ErrNotFound is a multipleResponseError where isTemp can be true or false
49 type ErrNotFound struct {
53 type InsufficientReplicasError error
55 type OversizeBlockError error
57 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
58 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
59 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
60 var InvalidLocatorError = errors.New("Invalid locator")
62 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
63 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
65 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
66 var ErrIncompleteIndex = errors.New("Got incomplete index")
68 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
69 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
71 type HTTPClient interface {
72 Do(*http.Request) (*http.Response, error)
75 // Information about Arvados and Keep servers.
76 type KeepClient struct {
77 Arvados *arvadosclient.ArvadosClient
79 localRoots *map[string]string
80 writableLocalRoots *map[string]string
81 gatewayRoots *map[string]string
85 BlockCache *BlockCache
87 // set to 1 if all writable services are of disk type, otherwise 0
88 replicasPerService int
90 // Any non-disk typed services found in the list of keepservers?
94 // MakeKeepClient creates a new KeepClient, calls
95 // DiscoverKeepServices(), and returns when the client is ready to
97 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
99 return kc, kc.DiscoverKeepServers()
102 // New creates a new KeepClient. The caller must call
103 // DiscoverKeepServers() before using the returned client to read or
105 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
106 defaultReplicationLevel := 2
107 value, err := arv.Discovery("defaultCollectionReplication")
109 v, ok := value.(float64)
111 defaultReplicationLevel = int(v)
116 Want_replicas: defaultReplicationLevel,
121 // Put a block given the block hash, a reader, and the number of bytes
122 // to read from the reader (which must be between 0 and BLOCKSIZE).
124 // Returns the locator for the written block, the number of replicas
125 // written, and an error.
127 // Returns an InsufficientReplicasError if 0 <= replicas <
128 // kc.Wants_replicas.
129 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
130 // Buffer for reads from 'r'
133 if dataBytes > BLOCKSIZE {
134 return "", 0, ErrOversizeBlock
136 bufsize = int(dataBytes)
141 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
144 return kc.putReplicas(hash, t, dataBytes)
147 // PutHB writes a block to Keep. The hash of the bytes is given in
148 // hash, and the data is given in buf.
150 // Return values are the same as for PutHR.
151 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
152 t := streamer.AsyncStreamFromSlice(buf)
154 return kc.putReplicas(hash, t, int64(len(buf)))
157 // PutB writes a block to Keep. It computes the hash itself.
159 // Return values are the same as for PutHR.
160 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
161 hash := fmt.Sprintf("%x", md5.Sum(buffer))
162 return kc.PutHB(hash, buffer)
165 // PutR writes a block to Keep. It first reads all data from r into a buffer
166 // in order to compute the hash.
168 // Return values are the same as for PutHR.
170 // If the block hash and data size are known, PutHR is more efficient.
171 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
172 if buffer, err := ioutil.ReadAll(r); err != nil {
175 return kc.PutB(buffer)
179 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
180 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
181 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
186 tries_remaining := 1 + kc.Retries
188 serversToTry := kc.getSortedRoots(locator)
190 numServers := len(serversToTry)
193 var retryList []string
195 for tries_remaining > 0 {
199 for _, host := range serversToTry {
200 url := host + "/" + locator
202 req, err := http.NewRequest(method, url, nil)
204 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
207 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
208 resp, err := kc.httpClient().Do(req)
210 // Probably a network error, may be transient,
212 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
213 retryList = append(retryList, host)
214 } else if resp.StatusCode != http.StatusOK {
216 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
218 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
219 url, resp.StatusCode, bytes.TrimSpace(respbody)))
221 if resp.StatusCode == 408 ||
222 resp.StatusCode == 429 ||
223 resp.StatusCode >= 500 {
224 // Timeout, too many requests, or other
225 // server side failure, transient
226 // error, can try again.
227 retryList = append(retryList, host)
228 } else if resp.StatusCode == 404 {
234 return HashCheckingReader{
237 Check: locator[0:32],
238 }, resp.ContentLength, url, nil
241 return nil, resp.ContentLength, url, nil
246 serversToTry = retryList
248 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
251 if count404 == numServers {
254 err = &ErrNotFound{multipleResponseError{
255 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
256 isTemp: len(serversToTry) > 0,
259 return nil, 0, "", err
262 // Get() retrieves a block, given a locator. Returns a reader, the
263 // expected data length, the URL the block is being fetched from, and
266 // If the block checksum does not match, the final Read() on the
267 // reader returned by this method will return a BadChecksum error
269 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
270 return kc.getOrHead("GET", locator)
273 // Ask() verifies that a block with the given hash is available and
274 // readable, according to at least one Keep service. Unlike Get, it
275 // does not retrieve the data or verify that the data content matches
276 // the hash specified by the locator.
278 // Returns the data size (content length) reported by the Keep service
279 // and the URI reporting the data size.
280 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
281 _, size, url, err := kc.getOrHead("HEAD", locator)
282 return size, url, err
285 // GetIndex retrieves a list of blocks stored on the given server whose hashes
286 // begin with the given prefix. The returned reader will return an error (other
287 // than EOF) if the complete index cannot be retrieved.
289 // This is meant to be used only by system components and admin tools.
290 // It will return an error unless the client is using a "data manager token"
291 // recognized by the Keep services.
292 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
293 url := kc.LocalRoots()[keepServiceUUID]
295 return nil, ErrNoSuchKeepServer
303 req, err := http.NewRequest("GET", url, nil)
308 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
309 resp, err := kc.httpClient().Do(req)
314 defer resp.Body.Close()
316 if resp.StatusCode != http.StatusOK {
317 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
321 respBody, err = ioutil.ReadAll(resp.Body)
326 // Got index; verify that it is complete
327 // The response should be "\n" if no locators matched the prefix
328 // Else, it should be a list of locators followed by a blank line
329 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
330 return nil, ErrIncompleteIndex
333 // Got complete index; strip the trailing newline and send
334 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
337 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
338 // services: uuid -> baseURI.
339 func (kc *KeepClient) LocalRoots() map[string]string {
341 defer kc.lock.RUnlock()
342 return *kc.localRoots
345 // GatewayRoots() returns the map of Keep remote gateway services:
347 func (kc *KeepClient) GatewayRoots() map[string]string {
349 defer kc.lock.RUnlock()
350 return *kc.gatewayRoots
353 // WritableLocalRoots() returns the map of writable local Keep services:
355 func (kc *KeepClient) WritableLocalRoots() map[string]string {
357 defer kc.lock.RUnlock()
358 return *kc.writableLocalRoots
361 // SetServiceRoots updates the localRoots and gatewayRoots maps,
362 // without risk of disrupting operations that are already in progress.
364 // The KeepClient makes its own copy of the supplied maps, so the
365 // caller can reuse/modify them after SetServiceRoots returns, but
366 // they should not be modified by any other goroutine while
367 // SetServiceRoots is running.
368 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals, newGateways map[string]string) {
369 locals := make(map[string]string)
370 for uuid, root := range newLocals {
374 writables := make(map[string]string)
375 for uuid, root := range newWritableLocals {
376 writables[uuid] = root
379 gateways := make(map[string]string)
380 for uuid, root := range newGateways {
381 gateways[uuid] = root
385 defer kc.lock.Unlock()
386 kc.localRoots = &locals
387 kc.writableLocalRoots = &writables
388 kc.gatewayRoots = &gateways
391 // getSortedRoots returns a list of base URIs of Keep services, in the
392 // order they should be attempted in order to retrieve content for the
394 func (kc *KeepClient) getSortedRoots(locator string) []string {
396 for _, hint := range strings.Split(locator, "+") {
397 if len(hint) < 7 || hint[0:2] != "K@" {
398 // Not a service hint.
402 // +K@abcde means fetch from proxy at
403 // keep.abcde.arvadosapi.com
404 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
405 } else if len(hint) == 29 {
406 // +K@abcde-abcde-abcdeabcdeabcde means fetch
407 // from gateway with given uuid
408 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
409 found = append(found, gwURI)
411 // else this hint is no use to us; carry on.
414 // After trying all usable service hints, fall back to local roots.
415 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
419 func (kc *KeepClient) cache() *BlockCache {
420 if kc.BlockCache != nil {
423 return DefaultBlockCache
428 // There are four global http.Client objects for the four
429 // possible permutations of TLS behavior (verify/skip-verify)
430 // and timeout settings (proxy/non-proxy).
431 defaultClient = map[bool]map[bool]HTTPClient{
432 // defaultClient[false] is used for verified TLS reqs
434 // defaultClient[true] is used for unverified
435 // (insecure) TLS reqs
438 defaultClientMtx sync.Mutex
441 // httpClient returns the HTTPClient field if it's not nil, otherwise
442 // whichever of the four global http.Client objects is suitable for
443 // the current environment (i.e., TLS verification on/off, keep
444 // services are/aren't proxies).
445 func (kc *KeepClient) httpClient() HTTPClient {
446 if kc.HTTPClient != nil {
449 defaultClientMtx.Lock()
450 defer defaultClientMtx.Unlock()
451 if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
455 var requestTimeout, connectTimeout, keepAliveInterval, tlsTimeout time.Duration
456 if kc.foundNonDiskSvc {
457 // Use longer timeouts when connecting to a proxy,
458 // because this usually means the intervening network
460 requestTimeout = 300 * time.Second
461 connectTimeout = 30 * time.Second
462 tlsTimeout = 10 * time.Second
463 keepAliveInterval = 120 * time.Second
465 requestTimeout = 20 * time.Second
466 connectTimeout = 2 * time.Second
467 tlsTimeout = 4 * time.Second
468 keepAliveInterval = 180 * time.Second
470 transport := &http.Transport{
472 Timeout: connectTimeout,
473 KeepAlive: keepAliveInterval,
475 TLSClientConfig: arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
476 TLSHandshakeTimeout: tlsTimeout,
479 for range time.NewTicker(10 * time.Minute).C {
480 transport.CloseIdleConnections()
484 Timeout: requestTimeout,
485 Transport: transport,
487 defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
491 type Locator struct {
493 Size int // -1 if data size is not known
494 Hints []string // Including the size hint, if any
497 func (loc *Locator) String() string {
499 if len(loc.Hints) > 0 {
500 s = s + "+" + strings.Join(loc.Hints, "+")
505 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
507 func MakeLocator(path string) (*Locator, error) {
508 sm := locatorMatcher.FindStringSubmatch(path)
510 return nil, InvalidLocatorError
512 loc := Locator{Hash: sm[1], Size: -1}
514 loc.Hints = strings.Split(sm[3], "+")
516 loc.Hints = []string{}
518 if len(loc.Hints) > 0 {
519 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {