1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
9 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10 "git.curoverse.com/arvados.git/sdk/go/streamer"
20 // A Keep "block" is 64MB.
21 const BLOCKSIZE = 64 * 1024 * 1024
23 // Error interface with an error and boolean indicating whether the error is temporary
24 type Error interface {
29 // multipleResponseError is of type Error
30 type multipleResponseError struct {
35 func (e *multipleResponseError) Temporary() bool {
39 // BlockNotFound is a multipleResponseError where isTemp is false
40 var BlockNotFound = &ErrNotFound{multipleResponseError{
41 error: errors.New("Block not found"),
45 // ErrNotFound is a multipleResponseError where isTemp can be true or false
46 type ErrNotFound struct {
50 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
51 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
52 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
53 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
54 var InvalidLocatorError = errors.New("Invalid locator")
56 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
57 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
59 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
60 var ErrIncompleteIndex = errors.New("Got incomplete index")
62 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
63 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
65 // Information about Arvados and Keep servers.
66 type KeepClient struct {
67 Arvados *arvadosclient.ArvadosClient
69 localRoots *map[string]string
70 writableLocalRoots *map[string]string
71 gatewayRoots *map[string]string
76 // set to 1 if all writable services are of disk type, otherwise 0
77 replicasPerService int
79 // Any non-disk typed services found in the list of keepservers?
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,
104 Client: &http.Client{Transport: &http.Transport{
105 TLSClientConfig: arvadosclient.MakeTLSConfig(arv.ApiInsecure)}},
111 // Put a block given the block hash, a reader, and the number of bytes
112 // to read from the reader (which must be between 0 and BLOCKSIZE).
114 // Returns the locator for the written block, the number of replicas
115 // written, and an error.
117 // Returns an InsufficientReplicas error if 0 <= replicas <
118 // kc.Wants_replicas.
119 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
120 // Buffer for reads from 'r'
123 if dataBytes > BLOCKSIZE {
124 return "", 0, OversizeBlockError
126 bufsize = int(dataBytes)
131 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
134 return kc.putReplicas(hash, t, dataBytes)
137 // PutHB writes a block to Keep. The hash of the bytes is given in
138 // hash, and the data is given in buf.
140 // Return values are the same as for PutHR.
141 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
142 t := streamer.AsyncStreamFromSlice(buf)
144 return kc.putReplicas(hash, t, int64(len(buf)))
147 // PutB writes a block to Keep. It computes the hash itself.
149 // Return values are the same as for PutHR.
150 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
151 hash := fmt.Sprintf("%x", md5.Sum(buffer))
152 return kc.PutHB(hash, buffer)
155 // PutR writes a block to Keep. It first reads all data from r into a buffer
156 // in order to compute the hash.
158 // Return values are the same as for PutHR.
160 // If the block hash and data size are known, PutHR is more efficient.
161 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
162 if buffer, err := ioutil.ReadAll(r); err != nil {
165 return kc.PutB(buffer)
169 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
172 tries_remaining := 1 + kc.Retries
174 serversToTry := kc.getSortedRoots(locator)
176 numServers := len(serversToTry)
179 var retryList []string
181 for tries_remaining > 0 {
185 for _, host := range serversToTry {
186 url := host + "/" + locator
188 req, err := http.NewRequest(method, url, nil)
190 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
193 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
194 resp, err := kc.Client.Do(req)
196 // Probably a network error, may be transient,
198 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
199 retryList = append(retryList, host)
200 } else if resp.StatusCode != http.StatusOK {
202 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
204 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
205 url, resp.StatusCode, bytes.TrimSpace(respbody)))
207 if resp.StatusCode == 408 ||
208 resp.StatusCode == 429 ||
209 resp.StatusCode >= 500 {
210 // Timeout, too many requests, or other
211 // server side failure, transient
212 // error, can try again.
213 retryList = append(retryList, host)
214 } else if resp.StatusCode == 404 {
220 return HashCheckingReader{
223 Check: locator[0:32],
224 }, resp.ContentLength, url, nil
227 return nil, resp.ContentLength, url, nil
232 serversToTry = retryList
234 DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
237 if count404 == numServers {
240 err = &ErrNotFound{multipleResponseError{
241 error: fmt.Errorf("%s %s failed: %v", method, locator, errs),
242 isTemp: len(serversToTry) > 0,
245 return nil, 0, "", err
248 // Get() retrieves a block, given a locator. Returns a reader, the
249 // expected data length, the URL the block is being fetched from, and
252 // If the block checksum does not match, the final Read() on the
253 // reader returned by this method will return a BadChecksum error
255 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
256 return kc.getOrHead("GET", locator)
259 // Ask() verifies that a block with the given hash is available and
260 // readable, according to at least one Keep service. Unlike Get, it
261 // does not retrieve the data or verify that the data content matches
262 // the hash specified by the locator.
264 // Returns the data size (content length) reported by the Keep service
265 // and the URI reporting the data size.
266 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
267 _, size, url, err := kc.getOrHead("HEAD", locator)
268 return size, url, err
271 // GetIndex retrieves a list of blocks stored on the given server whose hashes
272 // begin with the given prefix. The returned reader will return an error (other
273 // than EOF) if the complete index cannot be retrieved.
275 // This is meant to be used only by system components and admin tools.
276 // It will return an error unless the client is using a "data manager token"
277 // recognized by the Keep services.
278 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
279 url := kc.LocalRoots()[keepServiceUUID]
281 return nil, ErrNoSuchKeepServer
289 req, err := http.NewRequest("GET", url, nil)
294 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
295 resp, err := kc.Client.Do(req)
300 defer resp.Body.Close()
302 if resp.StatusCode != http.StatusOK {
303 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
307 respBody, err = ioutil.ReadAll(resp.Body)
312 // Got index; verify that it is complete
313 // The response should be "\n" if no locators matched the prefix
314 // Else, it should be a list of locators followed by a blank line
315 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
316 return nil, ErrIncompleteIndex
319 // Got complete index; strip the trailing newline and send
320 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
323 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
324 // services: uuid -> baseURI.
325 func (kc *KeepClient) LocalRoots() map[string]string {
327 defer kc.lock.RUnlock()
328 return *kc.localRoots
331 // GatewayRoots() returns the map of Keep remote gateway services:
333 func (kc *KeepClient) GatewayRoots() map[string]string {
335 defer kc.lock.RUnlock()
336 return *kc.gatewayRoots
339 // WritableLocalRoots() returns the map of writable local Keep services:
341 func (kc *KeepClient) WritableLocalRoots() map[string]string {
343 defer kc.lock.RUnlock()
344 return *kc.writableLocalRoots
347 // SetServiceRoots updates the localRoots and gatewayRoots maps,
348 // without risk of disrupting operations that are already in progress.
350 // The KeepClient makes its own copy of the supplied maps, so the
351 // caller can reuse/modify them after SetServiceRoots returns, but
352 // they should not be modified by any other goroutine while
353 // SetServiceRoots is running.
354 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals, newGateways map[string]string) {
355 locals := make(map[string]string)
356 for uuid, root := range newLocals {
360 writables := make(map[string]string)
361 for uuid, root := range newWritableLocals {
362 writables[uuid] = root
365 gateways := make(map[string]string)
366 for uuid, root := range newGateways {
367 gateways[uuid] = root
371 defer kc.lock.Unlock()
372 kc.localRoots = &locals
373 kc.writableLocalRoots = &writables
374 kc.gatewayRoots = &gateways
377 // getSortedRoots returns a list of base URIs of Keep services, in the
378 // order they should be attempted in order to retrieve content for the
380 func (kc *KeepClient) getSortedRoots(locator string) []string {
382 for _, hint := range strings.Split(locator, "+") {
383 if len(hint) < 7 || hint[0:2] != "K@" {
384 // Not a service hint.
388 // +K@abcde means fetch from proxy at
389 // keep.abcde.arvadosapi.com
390 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
391 } else if len(hint) == 29 {
392 // +K@abcde-abcde-abcdeabcdeabcde means fetch
393 // from gateway with given uuid
394 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
395 found = append(found, gwURI)
397 // else this hint is no use to us; carry on.
400 // After trying all usable service hints, fall back to local roots.
401 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
405 type Locator struct {
407 Size int // -1 if data size is not known
408 Hints []string // Including the size hint, if any
411 func (loc *Locator) String() string {
413 if len(loc.Hints) > 0 {
414 s = s + "+" + strings.Join(loc.Hints, "+")
419 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
421 func MakeLocator(path string) (*Locator, error) {
422 sm := locatorMatcher.FindStringSubmatch(path)
424 return nil, InvalidLocatorError
426 loc := Locator{Hash: sm[1], Size: -1}
428 loc.Hints = strings.Split(sm[3], "+")
430 loc.Hints = []string{}
432 if len(loc.Hints) > 0 {
433 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {