1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
10 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11 "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 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
52 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
53 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
54 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
55 var InvalidLocatorError = errors.New("Invalid locator")
57 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
58 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
60 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
61 var ErrIncompleteIndex = errors.New("Got incomplete index")
63 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
64 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
66 // Information about Arvados and Keep servers.
67 type KeepClient struct {
68 Arvados *arvadosclient.ArvadosClient
70 localRoots *map[string]string
71 writableLocalRoots *map[string]string
72 gatewayRoots *map[string]string
77 // set to 1 if all writable services are of disk type, otherwise 0
78 replicasPerService int
80 // Any non-disk typed services found in the list of keepservers?
84 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
85 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
87 return kc, kc.DiscoverKeepServers()
90 // New func creates a new KeepClient struct.
91 // This func does not discover keep servers. It is the caller's responsibility.
92 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
93 defaultReplicationLevel := 2
94 value, err := arv.Discovery("defaultCollectionReplication")
96 v, ok := value.(float64)
98 defaultReplicationLevel = int(v)
104 Want_replicas: defaultReplicationLevel,
105 Client: &http.Client{Transport: &http.Transport{
106 TLSClientConfig: &tls.Config{InsecureSkipVerify: arv.ApiInsecure}}},
112 // Put a block given the block hash, a reader, and the number of bytes
113 // to read from the reader (which must be between 0 and BLOCKSIZE).
115 // Returns the locator for the written block, the number of replicas
116 // written, and an error.
118 // Returns an InsufficientReplicas error if 0 <= replicas <
119 // kc.Wants_replicas.
120 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
121 // Buffer for reads from 'r'
124 if dataBytes > BLOCKSIZE {
125 return "", 0, OversizeBlockError
127 bufsize = int(dataBytes)
132 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
135 return kc.putReplicas(hash, t, dataBytes)
138 // PutHB writes a block to Keep. The hash of the bytes is given in
139 // hash, and the data is given in buf.
141 // Return values are the same as for PutHR.
142 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
143 t := streamer.AsyncStreamFromSlice(buf)
145 return kc.putReplicas(hash, t, int64(len(buf)))
148 // PutB writes a block to Keep. It computes the hash itself.
150 // Return values are the same as for PutHR.
151 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
152 hash := fmt.Sprintf("%x", md5.Sum(buffer))
153 return kc.PutHB(hash, buffer)
156 // PutR writes a block to Keep. It first reads all data from r into a buffer
157 // in order to compute the hash.
159 // Return values are the same as for PutHR.
161 // If the block hash and data size are known, PutHR is more efficient.
162 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
163 if buffer, err := ioutil.ReadAll(r); err != nil {
166 return kc.PutB(buffer)
170 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
173 tries_remaining := 1 + kc.Retries
175 serversToTry := kc.getSortedRoots(locator)
177 numServers := len(serversToTry)
180 var retryList []string
182 for tries_remaining > 0 {
186 for _, host := range serversToTry {
187 url := host + "/" + locator
189 req, err := http.NewRequest(method, url, nil)
191 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
194 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
195 resp, err := kc.Client.Do(req)
197 // Probably a network error, may be transient,
199 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
200 retryList = append(retryList, host)
201 } else if resp.StatusCode != http.StatusOK {
203 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
205 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
206 url, resp.StatusCode, bytes.TrimSpace(respbody)))
208 if resp.StatusCode == 408 ||
209 resp.StatusCode == 429 ||
210 resp.StatusCode >= 500 {
211 // Timeout, too many requests, or other
212 // server side failure, transient
213 // error, can try again.
214 retryList = append(retryList, host)
215 } else if resp.StatusCode == 404 {
221 return HashCheckingReader{
224 Check: locator[0:32],
225 }, resp.ContentLength, url, nil
228 return nil, resp.ContentLength, url, nil
233 serversToTry = retryList
235 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
238 if count404 == numServers {
241 err = &ErrNotFound{multipleResponseError{
242 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
243 isTemp: len(serversToTry) > 0,
246 return nil, 0, "", err
249 // Get() retrieves a block, given a locator. Returns a reader, the
250 // expected data length, the URL the block is being fetched from, and
253 // If the block checksum does not match, the final Read() on the
254 // reader returned by this method will return a BadChecksum error
256 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
257 return kc.getOrHead("GET", locator)
260 // Ask() verifies that a block with the given hash is available and
261 // readable, according to at least one Keep service. Unlike Get, it
262 // does not retrieve the data or verify that the data content matches
263 // the hash specified by the locator.
265 // Returns the data size (content length) reported by the Keep service
266 // and the URI reporting the data size.
267 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
268 _, size, url, err := kc.getOrHead("HEAD", locator)
269 return size, url, err
272 // GetIndex retrieves a list of blocks stored on the given server whose hashes
273 // begin with the given prefix. The returned reader will return an error (other
274 // than EOF) if the complete index cannot be retrieved.
276 // This is meant to be used only by system components and admin tools.
277 // It will return an error unless the client is using a "data manager token"
278 // recognized by the Keep services.
279 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
280 url := kc.LocalRoots()[keepServiceUUID]
282 return nil, ErrNoSuchKeepServer
290 req, err := http.NewRequest("GET", url, nil)
295 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
296 resp, err := kc.Client.Do(req)
301 defer resp.Body.Close()
303 if resp.StatusCode != http.StatusOK {
304 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
308 respBody, err = ioutil.ReadAll(resp.Body)
313 // Got index; verify that it is complete
314 // The response should be "\n" if no locators matched the prefix
315 // Else, it should be a list of locators followed by a blank line
316 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
317 return nil, ErrIncompleteIndex
320 // Got complete index; strip the trailing newline and send
321 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
324 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
325 // services: uuid -> baseURI.
326 func (kc *KeepClient) LocalRoots() map[string]string {
328 defer kc.lock.RUnlock()
329 return *kc.localRoots
332 // GatewayRoots() returns the map of Keep remote gateway services:
334 func (kc *KeepClient) GatewayRoots() map[string]string {
336 defer kc.lock.RUnlock()
337 return *kc.gatewayRoots
340 // WritableLocalRoots() returns the map of writable local Keep services:
342 func (kc *KeepClient) WritableLocalRoots() map[string]string {
344 defer kc.lock.RUnlock()
345 return *kc.writableLocalRoots
348 // SetServiceRoots updates the localRoots and gatewayRoots maps,
349 // without risk of disrupting operations that are already in progress.
351 // The KeepClient makes its own copy of the supplied maps, so the
352 // caller can reuse/modify them after SetServiceRoots returns, but
353 // they should not be modified by any other goroutine while
354 // SetServiceRoots is running.
355 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
356 locals := make(map[string]string)
357 for uuid, root := range newLocals {
361 writables := make(map[string]string)
362 for uuid, root := range newWritableLocals {
363 writables[uuid] = root
366 gateways := make(map[string]string)
367 for uuid, root := range newGateways {
368 gateways[uuid] = root
372 defer kc.lock.Unlock()
373 kc.localRoots = &locals
374 kc.writableLocalRoots = &writables
375 kc.gatewayRoots = &gateways
378 // getSortedRoots returns a list of base URIs of Keep services, in the
379 // order they should be attempted in order to retrieve content for the
381 func (kc *KeepClient) getSortedRoots(locator string) []string {
383 for _, hint := range strings.Split(locator, "+") {
384 if len(hint) < 7 || hint[0:2] != "K@" {
385 // Not a service hint.
389 // +K@abcde means fetch from proxy at
390 // keep.abcde.arvadosapi.com
391 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
392 } else if len(hint) == 29 {
393 // +K@abcde-abcde-abcdeabcdeabcde means fetch
394 // from gateway with given uuid
395 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
396 found = append(found, gwURI)
398 // else this hint is no use to us; carry on.
401 // After trying all usable service hints, fall back to local roots.
402 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
406 type Locator struct {
408 Size int // -1 if data size is not known
409 Hints []string // Including the size hint, if any
412 func (loc *Locator) String() string {
414 if len(loc.Hints) > 0 {
415 s = s + "+" + strings.Join(loc.Hints, "+")
420 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
422 func MakeLocator(path string) (*Locator, error) {
423 sm := locatorMatcher.FindStringSubmatch(path)
425 return nil, InvalidLocatorError
427 loc := Locator{Hash: sm[1], Size: -1}
429 loc.Hints = strings.Split(sm[3], "+")
431 loc.Hints = []string{}
433 if len(loc.Hints) > 0 {
434 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {