1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
17 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
18 "git.curoverse.com/arvados.git/sdk/go/streamer"
21 // A Keep "block" is 64MB.
22 const BLOCKSIZE = 64 * 1024 * 1024
24 // Error interface with an error and boolean indicating whether the error is temporary
25 type Error interface {
30 // multipleResponseError is of type Error
31 type multipleResponseError struct {
36 func (e *multipleResponseError) Temporary() bool {
40 // BlockNotFound is a multipleResponseError where isTemp is false
41 var BlockNotFound = &ErrNotFound{multipleResponseError{
42 error: errors.New("Block not found"),
46 // ErrNotFound is a multipleResponseError where isTemp can be true or false
47 type ErrNotFound struct {
51 type InsufficientReplicasError error
53 type OversizeBlockError error
55 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
56 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
57 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
58 var InvalidLocatorError = errors.New("Invalid locator")
60 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
61 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
63 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
64 var ErrIncompleteIndex = errors.New("Got incomplete index")
66 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
67 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
69 type HTTPClient interface {
70 Do(*http.Request) (*http.Response, error)
73 // Information about Arvados and Keep servers.
74 type KeepClient struct {
75 Arvados *arvadosclient.ArvadosClient
77 localRoots *map[string]string
78 writableLocalRoots *map[string]string
79 gatewayRoots *map[string]string
83 BlockCache *BlockCache
85 // set to 1 if all writable services are of disk type, otherwise 0
86 replicasPerService int
88 // Any non-disk typed services found in the list of keepservers?
92 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
93 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
95 return kc, kc.DiscoverKeepServers()
98 // New func creates a new KeepClient struct.
99 // This func does not discover keep servers. It is the caller's responsibility.
100 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
101 defaultReplicationLevel := 2
102 value, err := arv.Discovery("defaultCollectionReplication")
104 v, ok := value.(float64)
106 defaultReplicationLevel = int(v)
112 Want_replicas: defaultReplicationLevel,
113 Client: &http.Client{Transport: &http.Transport{
114 TLSClientConfig: arvadosclient.MakeTLSConfig(arv.ApiInsecure)}},
120 // Put a block given the block hash, a reader, and the number of bytes
121 // to read from the reader (which must be between 0 and BLOCKSIZE).
123 // Returns the locator for the written block, the number of replicas
124 // written, and an error.
126 // Returns an InsufficientReplicasError if 0 <= replicas <
127 // kc.Wants_replicas.
128 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
129 // Buffer for reads from 'r'
132 if dataBytes > BLOCKSIZE {
133 return "", 0, ErrOversizeBlock
135 bufsize = int(dataBytes)
140 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
143 return kc.putReplicas(hash, t, dataBytes)
146 // PutHB writes a block to Keep. The hash of the bytes is given in
147 // hash, and the data is given in buf.
149 // Return values are the same as for PutHR.
150 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
151 t := streamer.AsyncStreamFromSlice(buf)
153 return kc.putReplicas(hash, t, int64(len(buf)))
156 // PutB writes a block to Keep. It computes the hash itself.
158 // Return values are the same as for PutHR.
159 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
160 hash := fmt.Sprintf("%x", md5.Sum(buffer))
161 return kc.PutHB(hash, buffer)
164 // PutR writes a block to Keep. It first reads all data from r into a buffer
165 // in order to compute the hash.
167 // Return values are the same as for PutHR.
169 // If the block hash and data size are known, PutHR is more efficient.
170 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
171 if buffer, err := ioutil.ReadAll(r); err != nil {
174 return kc.PutB(buffer)
178 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
179 if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
180 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
185 tries_remaining := 1 + kc.Retries
187 serversToTry := kc.getSortedRoots(locator)
189 numServers := len(serversToTry)
192 var retryList []string
194 for tries_remaining > 0 {
198 for _, host := range serversToTry {
199 url := host + "/" + locator
201 req, err := http.NewRequest(method, url, nil)
203 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
206 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
207 resp, err := kc.Client.Do(req)
209 // Probably a network error, may be transient,
211 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
212 retryList = append(retryList, host)
213 } else if resp.StatusCode != http.StatusOK {
215 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
217 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
218 url, resp.StatusCode, bytes.TrimSpace(respbody)))
220 if resp.StatusCode == 408 ||
221 resp.StatusCode == 429 ||
222 resp.StatusCode >= 500 {
223 // Timeout, too many requests, or other
224 // server side failure, transient
225 // error, can try again.
226 retryList = append(retryList, host)
227 } else if resp.StatusCode == 404 {
233 return HashCheckingReader{
236 Check: locator[0:32],
237 }, resp.ContentLength, url, nil
240 return nil, resp.ContentLength, url, nil
245 serversToTry = retryList
247 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
250 if count404 == numServers {
253 err = &ErrNotFound{multipleResponseError{
254 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
255 isTemp: len(serversToTry) > 0,
258 return nil, 0, "", err
261 // Get() retrieves a block, given a locator. Returns a reader, the
262 // expected data length, the URL the block is being fetched from, and
265 // If the block checksum does not match, the final Read() on the
266 // reader returned by this method will return a BadChecksum error
268 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
269 return kc.getOrHead("GET", locator)
272 // Ask() verifies that a block with the given hash is available and
273 // readable, according to at least one Keep service. Unlike Get, it
274 // does not retrieve the data or verify that the data content matches
275 // the hash specified by the locator.
277 // Returns the data size (content length) reported by the Keep service
278 // and the URI reporting the data size.
279 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
280 _, size, url, err := kc.getOrHead("HEAD", locator)
281 return size, url, err
284 // GetIndex retrieves a list of blocks stored on the given server whose hashes
285 // begin with the given prefix. The returned reader will return an error (other
286 // than EOF) if the complete index cannot be retrieved.
288 // This is meant to be used only by system components and admin tools.
289 // It will return an error unless the client is using a "data manager token"
290 // recognized by the Keep services.
291 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
292 url := kc.LocalRoots()[keepServiceUUID]
294 return nil, ErrNoSuchKeepServer
302 req, err := http.NewRequest("GET", url, nil)
307 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
308 resp, err := kc.Client.Do(req)
313 defer resp.Body.Close()
315 if resp.StatusCode != http.StatusOK {
316 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
320 respBody, err = ioutil.ReadAll(resp.Body)
325 // Got index; verify that it is complete
326 // The response should be "\n" if no locators matched the prefix
327 // Else, it should be a list of locators followed by a blank line
328 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
329 return nil, ErrIncompleteIndex
332 // Got complete index; strip the trailing newline and send
333 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
336 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
337 // services: uuid -> baseURI.
338 func (kc *KeepClient) LocalRoots() map[string]string {
340 defer kc.lock.RUnlock()
341 return *kc.localRoots
344 // GatewayRoots() returns the map of Keep remote gateway services:
346 func (kc *KeepClient) GatewayRoots() map[string]string {
348 defer kc.lock.RUnlock()
349 return *kc.gatewayRoots
352 // WritableLocalRoots() returns the map of writable local Keep services:
354 func (kc *KeepClient) WritableLocalRoots() map[string]string {
356 defer kc.lock.RUnlock()
357 return *kc.writableLocalRoots
360 // SetServiceRoots updates the localRoots and gatewayRoots maps,
361 // without risk of disrupting operations that are already in progress.
363 // The KeepClient makes its own copy of the supplied maps, so the
364 // caller can reuse/modify them after SetServiceRoots returns, but
365 // they should not be modified by any other goroutine while
366 // SetServiceRoots is running.
367 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals, newGateways map[string]string) {
368 locals := make(map[string]string)
369 for uuid, root := range newLocals {
373 writables := make(map[string]string)
374 for uuid, root := range newWritableLocals {
375 writables[uuid] = root
378 gateways := make(map[string]string)
379 for uuid, root := range newGateways {
380 gateways[uuid] = root
384 defer kc.lock.Unlock()
385 kc.localRoots = &locals
386 kc.writableLocalRoots = &writables
387 kc.gatewayRoots = &gateways
390 // getSortedRoots returns a list of base URIs of Keep services, in the
391 // order they should be attempted in order to retrieve content for the
393 func (kc *KeepClient) getSortedRoots(locator string) []string {
395 for _, hint := range strings.Split(locator, "+") {
396 if len(hint) < 7 || hint[0:2] != "K@" {
397 // Not a service hint.
401 // +K@abcde means fetch from proxy at
402 // keep.abcde.arvadosapi.com
403 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
404 } else if len(hint) == 29 {
405 // +K@abcde-abcde-abcdeabcdeabcde means fetch
406 // from gateway with given uuid
407 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
408 found = append(found, gwURI)
410 // else this hint is no use to us; carry on.
413 // After trying all usable service hints, fall back to local roots.
414 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
418 func (kc *KeepClient) cache() *BlockCache {
419 if kc.BlockCache != nil {
422 return DefaultBlockCache
426 type Locator struct {
428 Size int // -1 if data size is not known
429 Hints []string // Including the size hint, if any
432 func (loc *Locator) String() string {
434 if len(loc.Hints) > 0 {
435 s = s + "+" + strings.Join(loc.Hints, "+")
440 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
442 func MakeLocator(path string) (*Locator, error) {
443 sm := locatorMatcher.FindStringSubmatch(path)
445 return nil, InvalidLocatorError
447 loc := Locator{Hash: sm[1], Size: -1}
449 loc.Hints = strings.Split(sm[3], "+")
451 loc.Hints = []string{}
453 if len(loc.Hints) > 0 {
454 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {