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"
22 // A Keep "block" is 64MB.
23 const BLOCKSIZE = 64 * 1024 * 1024
25 // Error interface with an error and boolean indicating whether the error is temporary
26 type Error interface {
31 // multipleResponseError is of type Error
32 type multipleResponseError struct {
37 func (e *multipleResponseError) Temporary() bool {
41 // BlockNotFound is a multipleResponseError where isTemp is false
42 var BlockNotFound = &ErrNotFound{multipleResponseError{
43 error: errors.New("Block not found"),
47 // ErrNotFound is a multipleResponseError where isTemp can be true or false
48 type ErrNotFound struct {
52 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
53 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
54 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
55 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
56 var InvalidLocatorError = errors.New("Invalid locator")
58 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
59 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
61 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
62 var ErrIncompleteIndex = errors.New("Got incomplete index")
64 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
65 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
67 // Information about Arvados and Keep servers.
68 type KeepClient struct {
69 Arvados *arvadosclient.ArvadosClient
72 localRoots *map[string]string
73 writableLocalRoots *map[string]string
74 gatewayRoots *map[string]string
79 // set to 1 if all writable services are of disk type, otherwise 0
80 replicasPerService int
83 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
84 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
86 return kc, kc.DiscoverKeepServers()
89 // New func creates a new KeepClient struct.
90 // This func does not discover keep servers. It is the caller's responsibility.
91 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
92 defaultReplicationLevel := 2
93 value, err := arv.Discovery("defaultCollectionReplication")
95 v, ok := value.(float64)
97 defaultReplicationLevel = int(v)
103 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) {
174 tries_remaining := 1 + kc.Retries
175 serversToTry := kc.getSortedRoots(locator)
176 var retryList []string
178 for tries_remaining > 0 {
182 for _, host := range serversToTry {
183 url := host + "/" + locator
185 req, err := http.NewRequest(method, url, nil)
187 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
190 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
191 resp, err := kc.Client.Do(req)
193 // Probably a network error, may be transient,
195 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
196 retryList = append(retryList, host)
197 } else if resp.StatusCode != http.StatusOK {
199 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
201 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
202 url, resp.StatusCode, bytes.TrimSpace(respbody)))
204 if resp.StatusCode == 408 ||
205 resp.StatusCode == 429 ||
206 resp.StatusCode >= 500 {
207 // Timeout, too many requests, or other
208 // server side failure, transient
209 // error, can try again.
210 retryList = append(retryList, host)
211 } else if resp.StatusCode == 404 {
217 return HashCheckingReader{
220 Check: locator[0:32],
221 }, resp.ContentLength, url, nil
224 return nil, resp.ContentLength, url, nil
229 serversToTry = retryList
231 log.Printf("DEBUG: %s %s failed: %v", method, locator, errs)
234 if count404 == len(kc.getSortedRoots(locator)) {
237 err = &ErrNotFound{multipleResponseError{
238 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
239 isTemp: len(serversToTry) > 0,
242 return nil, 0, "", err
245 // Get() retrieves a block, given a locator. Returns a reader, the
246 // expected data length, the URL the block is being fetched from, and
249 // If the block checksum does not match, the final Read() on the
250 // reader returned by this method will return a BadChecksum error
252 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
253 return kc.getOrHead("GET", locator)
256 // Ask() verifies that a block with the given hash is available and
257 // readable, according to at least one Keep service. Unlike Get, it
258 // does not retrieve the data or verify that the data content matches
259 // the hash specified by the locator.
261 // Returns the data size (content length) reported by the Keep service
262 // and the URI reporting the data size.
263 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
264 _, size, url, err := kc.getOrHead("HEAD", locator)
265 return size, url, err
268 // GetIndex retrieves a list of blocks stored on the given server whose hashes
269 // begin with the given prefix. The returned reader will return an error (other
270 // than EOF) if the complete index cannot be retrieved.
272 // This is meant to be used only by system components and admin tools.
273 // It will return an error unless the client is using a "data manager token"
274 // recognized by the Keep services.
275 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
276 url := kc.LocalRoots()[keepServiceUUID]
278 return nil, ErrNoSuchKeepServer
286 req, err := http.NewRequest("GET", url, nil)
291 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
292 resp, err := kc.Client.Do(req)
297 defer resp.Body.Close()
299 if resp.StatusCode != http.StatusOK {
300 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
304 respBody, err = ioutil.ReadAll(resp.Body)
309 // Got index; verify that it is complete
310 // The response should be "\n" if no locators matched the prefix
311 // Else, it should be a list of locators followed by a blank line
312 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
313 return nil, ErrIncompleteIndex
316 // Got complete index; strip the trailing newline and send
317 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
320 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
321 // services: uuid -> baseURI.
322 func (kc *KeepClient) LocalRoots() map[string]string {
324 defer kc.lock.RUnlock()
325 return *kc.localRoots
328 // GatewayRoots() returns the map of Keep remote gateway services:
330 func (kc *KeepClient) GatewayRoots() map[string]string {
332 defer kc.lock.RUnlock()
333 return *kc.gatewayRoots
336 // WritableLocalRoots() returns the map of writable local Keep services:
338 func (kc *KeepClient) WritableLocalRoots() map[string]string {
340 defer kc.lock.RUnlock()
341 return *kc.writableLocalRoots
344 // SetServiceRoots updates the localRoots and gatewayRoots maps,
345 // without risk of disrupting operations that are already in progress.
347 // The KeepClient makes its own copy of the supplied maps, so the
348 // caller can reuse/modify them after SetServiceRoots returns, but
349 // they should not be modified by any other goroutine while
350 // SetServiceRoots is running.
351 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
352 locals := make(map[string]string)
353 for uuid, root := range newLocals {
357 writables := make(map[string]string)
358 for uuid, root := range newWritableLocals {
359 writables[uuid] = root
362 gateways := make(map[string]string)
363 for uuid, root := range newGateways {
364 gateways[uuid] = root
368 defer kc.lock.Unlock()
369 kc.localRoots = &locals
370 kc.writableLocalRoots = &writables
371 kc.gatewayRoots = &gateways
374 // getSortedRoots returns a list of base URIs of Keep services, in the
375 // order they should be attempted in order to retrieve content for the
377 func (kc *KeepClient) getSortedRoots(locator string) []string {
379 for _, hint := range strings.Split(locator, "+") {
380 if len(hint) < 7 || hint[0:2] != "K@" {
381 // Not a service hint.
385 // +K@abcde means fetch from proxy at
386 // keep.abcde.arvadosapi.com
387 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
388 } else if len(hint) == 29 {
389 // +K@abcde-abcde-abcdeabcdeabcde means fetch
390 // from gateway with given uuid
391 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
392 found = append(found, gwURI)
394 // else this hint is no use to us; carry on.
397 // After trying all usable service hints, fall back to local roots.
398 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
402 type Locator struct {
404 Size int // -1 if data size is not known
405 Hints []string // Including the size hint, if any
408 func (loc *Locator) String() string {
410 if len(loc.Hints) > 0 {
411 s = s + "+" + strings.Join(loc.Hints, "+")
416 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
418 func MakeLocator(path string) (*Locator, error) {
419 sm := locatorMatcher.FindStringSubmatch(path)
421 return nil, InvalidLocatorError
423 loc := Locator{Hash: sm[1], Size: -1}
425 loc.Hints = strings.Split(sm[3], "+")
427 loc.Hints = []string{}
429 if len(loc.Hints) > 0 {
430 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {