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
71 localRoots *map[string]string
72 writableLocalRoots *map[string]string
73 gatewayRoots *map[string]string
78 // set to 1 if all writable services are of disk type, otherwise 0
79 replicasPerService int
81 // Any non-disk typed services found in the list of keepservers?
85 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
86 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
88 return kc, kc.DiscoverKeepServers()
91 // New func creates a new KeepClient struct.
92 // This func does not discover keep servers. It is the caller's responsibility.
93 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
94 defaultReplicationLevel := 2
95 value, err := arv.Discovery("defaultCollectionReplication")
97 v, ok := value.(float64)
99 defaultReplicationLevel = int(v)
105 Want_replicas: defaultReplicationLevel,
106 Client: &http.Client{Transport: &http.Transport{
107 TLSClientConfig: &tls.Config{InsecureSkipVerify: arv.ApiInsecure}}},
113 // Put a block given the block hash, a reader, and the number of bytes
114 // to read from the reader (which must be between 0 and BLOCKSIZE).
116 // Returns the locator for the written block, the number of replicas
117 // written, and an error.
119 // Returns an InsufficientReplicas error if 0 <= replicas <
120 // kc.Wants_replicas.
121 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
122 // Buffer for reads from 'r'
125 if dataBytes > BLOCKSIZE {
126 return "", 0, OversizeBlockError
128 bufsize = int(dataBytes)
133 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
136 return kc.putReplicas(hash, t, dataBytes)
139 // PutHB writes a block to Keep. The hash of the bytes is given in
140 // hash, and the data is given in buf.
142 // Return values are the same as for PutHR.
143 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
144 t := streamer.AsyncStreamFromSlice(buf)
146 return kc.putReplicas(hash, t, int64(len(buf)))
149 // PutB writes a block to Keep. It computes the hash itself.
151 // Return values are the same as for PutHR.
152 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
153 hash := fmt.Sprintf("%x", md5.Sum(buffer))
154 return kc.PutHB(hash, buffer)
157 // PutR writes a block to Keep. It first reads all data from r into a buffer
158 // in order to compute the hash.
160 // Return values are the same as for PutHR.
162 // If the block hash and data size are known, PutHR is more efficient.
163 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
164 if buffer, err := ioutil.ReadAll(r); err != nil {
167 return kc.PutB(buffer)
171 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
174 tries_remaining := 1 + kc.Retries
176 serversToTry := kc.getSortedRoots(locator)
178 numServers := len(serversToTry)
181 var retryList []string
183 for tries_remaining > 0 {
187 for _, host := range serversToTry {
188 url := host + "/" + locator
190 req, err := http.NewRequest(method, url, nil)
192 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
195 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
196 resp, err := kc.Client.Do(req)
198 // Probably a network error, may be transient,
200 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
201 retryList = append(retryList, host)
202 } else if resp.StatusCode != http.StatusOK {
204 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
206 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
207 url, resp.StatusCode, bytes.TrimSpace(respbody)))
209 if resp.StatusCode == 408 ||
210 resp.StatusCode == 429 ||
211 resp.StatusCode >= 500 {
212 // Timeout, too many requests, or other
213 // server side failure, transient
214 // error, can try again.
215 retryList = append(retryList, host)
216 } else if resp.StatusCode == 404 {
222 return HashCheckingReader{
225 Check: locator[0:32],
226 }, resp.ContentLength, url, nil
229 return nil, resp.ContentLength, url, nil
234 serversToTry = retryList
236 log.Printf("DEBUG: %s %s failed: %v", method, locator, errs)
239 if count404 == numServers {
242 err = &ErrNotFound{multipleResponseError{
243 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
244 isTemp: len(serversToTry) > 0,
247 return nil, 0, "", err
250 // Get() retrieves a block, given a locator. Returns a reader, the
251 // expected data length, the URL the block is being fetched from, and
254 // If the block checksum does not match, the final Read() on the
255 // reader returned by this method will return a BadChecksum error
257 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
258 return kc.getOrHead("GET", locator)
261 // Ask() verifies that a block with the given hash is available and
262 // readable, according to at least one Keep service. Unlike Get, it
263 // does not retrieve the data or verify that the data content matches
264 // the hash specified by the locator.
266 // Returns the data size (content length) reported by the Keep service
267 // and the URI reporting the data size.
268 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
269 _, size, url, err := kc.getOrHead("HEAD", locator)
270 return size, url, err
273 // GetIndex retrieves a list of blocks stored on the given server whose hashes
274 // begin with the given prefix. The returned reader will return an error (other
275 // than EOF) if the complete index cannot be retrieved.
277 // This is meant to be used only by system components and admin tools.
278 // It will return an error unless the client is using a "data manager token"
279 // recognized by the Keep services.
280 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
281 url := kc.LocalRoots()[keepServiceUUID]
283 return nil, ErrNoSuchKeepServer
291 req, err := http.NewRequest("GET", url, nil)
296 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
297 resp, err := kc.Client.Do(req)
302 defer resp.Body.Close()
304 if resp.StatusCode != http.StatusOK {
305 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
309 respBody, err = ioutil.ReadAll(resp.Body)
314 // Got index; verify that it is complete
315 // The response should be "\n" if no locators matched the prefix
316 // Else, it should be a list of locators followed by a blank line
317 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
318 return nil, ErrIncompleteIndex
321 // Got complete index; strip the trailing newline and send
322 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
325 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
326 // services: uuid -> baseURI.
327 func (kc *KeepClient) LocalRoots() map[string]string {
329 defer kc.lock.RUnlock()
330 return *kc.localRoots
333 // GatewayRoots() returns the map of Keep remote gateway services:
335 func (kc *KeepClient) GatewayRoots() map[string]string {
337 defer kc.lock.RUnlock()
338 return *kc.gatewayRoots
341 // WritableLocalRoots() returns the map of writable local Keep services:
343 func (kc *KeepClient) WritableLocalRoots() map[string]string {
345 defer kc.lock.RUnlock()
346 return *kc.writableLocalRoots
349 // SetServiceRoots updates the localRoots and gatewayRoots maps,
350 // without risk of disrupting operations that are already in progress.
352 // The KeepClient makes its own copy of the supplied maps, so the
353 // caller can reuse/modify them after SetServiceRoots returns, but
354 // they should not be modified by any other goroutine while
355 // SetServiceRoots is running.
356 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
357 locals := make(map[string]string)
358 for uuid, root := range newLocals {
362 writables := make(map[string]string)
363 for uuid, root := range newWritableLocals {
364 writables[uuid] = root
367 gateways := make(map[string]string)
368 for uuid, root := range newGateways {
369 gateways[uuid] = root
373 defer kc.lock.Unlock()
374 kc.localRoots = &locals
375 kc.writableLocalRoots = &writables
376 kc.gatewayRoots = &gateways
379 // getSortedRoots returns a list of base URIs of Keep services, in the
380 // order they should be attempted in order to retrieve content for the
382 func (kc *KeepClient) getSortedRoots(locator string) []string {
384 for _, hint := range strings.Split(locator, "+") {
385 if len(hint) < 7 || hint[0:2] != "K@" {
386 // Not a service hint.
390 // +K@abcde means fetch from proxy at
391 // keep.abcde.arvadosapi.com
392 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
393 } else if len(hint) == 29 {
394 // +K@abcde-abcde-abcdeabcdeabcde means fetch
395 // from gateway with given uuid
396 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
397 found = append(found, gwURI)
399 // else this hint is no use to us; carry on.
402 // After trying all usable service hints, fall back to local roots.
403 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
407 type Locator struct {
409 Size int // -1 if data size is not known
410 Hints []string // Including the size hint, if any
413 func (loc *Locator) String() string {
415 if len(loc.Hints) > 0 {
416 s = s + "+" + strings.Join(loc.Hints, "+")
421 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
423 func MakeLocator(path string) (*Locator, error) {
424 sm := locatorMatcher.FindStringSubmatch(path)
426 return nil, InvalidLocatorError
428 loc := Locator{Hash: sm[1], Size: -1}
430 loc.Hints = strings.Split(sm[3], "+")
432 loc.Hints = []string{}
434 if len(loc.Hints) > 0 {
435 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {