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"
23 // A Keep "block" is 64MB.
24 const BLOCKSIZE = 64 * 1024 * 1024
26 var BlockNotFound = errors.New("Block not found")
27 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
28 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
29 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
30 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
31 var InvalidLocatorError = errors.New("Invalid locator")
33 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
34 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
36 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
37 var ErrIncompleteIndex = errors.New("Got incomplete index")
39 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
40 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
42 // Information about Arvados and Keep servers.
43 type KeepClient struct {
44 Arvados *arvadosclient.ArvadosClient
47 localRoots *map[string]string
48 writableLocalRoots *map[string]string
49 gatewayRoots *map[string]string
53 // set to 1 if all writable services are of disk type, otherwise 0
54 replicasPerService int
57 // Create a new KeepClient. This will contact the API server to discover Keep
59 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
60 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
61 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
66 Client: &http.Client{Transport: &http.Transport{
67 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
69 return kc, kc.DiscoverKeepServers()
72 // Put a block given the block hash, a reader, and the number of bytes
73 // to read from the reader (which must be between 0 and BLOCKSIZE).
75 // Returns the locator for the written block, the number of replicas
76 // written, and an error.
78 // Returns an InsufficientReplicas error if 0 <= replicas <
80 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
81 // Buffer for reads from 'r'
84 if dataBytes > BLOCKSIZE {
85 return "", 0, OversizeBlockError
87 bufsize = int(dataBytes)
92 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
95 return kc.putReplicas(hash, t, dataBytes)
98 // PutHB writes a block to Keep. The hash of the bytes is given in
99 // hash, and the data is given in buf.
101 // Return values are the same as for PutHR.
102 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
103 t := streamer.AsyncStreamFromSlice(buf)
105 return kc.putReplicas(hash, t, int64(len(buf)))
108 // PutB writes a block to Keep. It computes the hash itself.
110 // Return values are the same as for PutHR.
111 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
112 hash := fmt.Sprintf("%x", md5.Sum(buffer))
113 return kc.PutHB(hash, buffer)
116 // PutR writes a block to Keep. It first reads all data from r into a buffer
117 // in order to compute the hash.
119 // Return values are the same as for PutHR.
121 // If the block hash and data size are known, PutHR is more efficient.
122 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
123 if buffer, err := ioutil.ReadAll(r); err != nil {
126 return kc.PutB(buffer)
130 // Get() retrieves a block, given a locator. Returns a reader, the
131 // expected data length, the URL the block is being fetched from, and
134 // If the block checksum does not match, the final Read() on the
135 // reader returned by this method will return a BadChecksum error
137 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
139 for _, host := range kc.getSortedRoots(locator) {
140 url := host + "/" + locator
141 req, err := http.NewRequest("GET", url, nil)
145 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
146 resp, err := kc.Client.Do(req)
147 if err != nil || resp.StatusCode != http.StatusOK {
150 if resp.Body != nil {
151 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
153 errs = append(errs, fmt.Sprintf("%s: %d %s",
154 url, resp.StatusCode, strings.TrimSpace(string(respbody))))
156 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
160 return HashCheckingReader{
163 Check: locator[0:32],
164 }, resp.ContentLength, url, nil
166 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
167 return nil, 0, "", BlockNotFound
170 // Ask() verifies that a block with the given hash is available and
171 // readable, according to at least one Keep service. Unlike Get, it
172 // does not retrieve the data or verify that the data content matches
173 // the hash specified by the locator.
175 // Returns the data size (content length) reported by the Keep service
176 // and the URI reporting the data size.
177 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
178 for _, host := range kc.getSortedRoots(locator) {
179 url := host + "/" + locator
180 req, err := http.NewRequest("HEAD", url, nil)
184 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
185 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
186 return resp.ContentLength, url, nil
189 return 0, "", BlockNotFound
192 // GetIndex retrieves a list of blocks stored on the given server whose hashes
193 // begin with the given prefix. The returned reader will return an error (other
194 // than EOF) if the complete index cannot be retrieved.
196 // This is meant to be used only by system components and admin tools.
197 // It will return an error unless the client is using a "data manager token"
198 // recognized by the Keep services.
199 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
200 url := kc.LocalRoots()[keepServiceUUID]
202 return nil, ErrNoSuchKeepServer
210 req, err := http.NewRequest("GET", url, nil)
215 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
216 resp, err := kc.Client.Do(req)
221 defer resp.Body.Close()
223 if resp.StatusCode != http.StatusOK {
224 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
228 respBody, err = ioutil.ReadAll(resp.Body)
233 // Got index; verify that it is complete
234 // The response should be "\n" if no locators matched the prefix
235 // Else, it should be a list of locators followed by a blank line
236 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
237 return nil, ErrIncompleteIndex
240 // Got complete index; strip the trailing newline and send
241 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
244 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
245 // services: uuid -> baseURI.
246 func (kc *KeepClient) LocalRoots() map[string]string {
248 defer kc.lock.RUnlock()
249 return *kc.localRoots
252 // GatewayRoots() returns the map of Keep remote gateway services:
254 func (kc *KeepClient) GatewayRoots() map[string]string {
256 defer kc.lock.RUnlock()
257 return *kc.gatewayRoots
260 // WritableLocalRoots() returns the map of writable local Keep services:
262 func (kc *KeepClient) WritableLocalRoots() map[string]string {
264 defer kc.lock.RUnlock()
265 return *kc.writableLocalRoots
268 // SetServiceRoots updates the localRoots and gatewayRoots maps,
269 // without risk of disrupting operations that are already in progress.
271 // The KeepClient makes its own copy of the supplied maps, so the
272 // caller can reuse/modify them after SetServiceRoots returns, but
273 // they should not be modified by any other goroutine while
274 // SetServiceRoots is running.
275 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
276 locals := make(map[string]string)
277 for uuid, root := range newLocals {
281 writables := make(map[string]string)
282 for uuid, root := range newWritableLocals {
283 writables[uuid] = root
286 gateways := make(map[string]string)
287 for uuid, root := range newGateways {
288 gateways[uuid] = root
292 defer kc.lock.Unlock()
293 kc.localRoots = &locals
294 kc.writableLocalRoots = &writables
295 kc.gatewayRoots = &gateways
298 // getSortedRoots returns a list of base URIs of Keep services, in the
299 // order they should be attempted in order to retrieve content for the
301 func (kc *KeepClient) getSortedRoots(locator string) []string {
303 for _, hint := range strings.Split(locator, "+") {
304 if len(hint) < 7 || hint[0:2] != "K@" {
305 // Not a service hint.
309 // +K@abcde means fetch from proxy at
310 // keep.abcde.arvadosapi.com
311 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
312 } else if len(hint) == 29 {
313 // +K@abcde-abcde-abcdeabcdeabcde means fetch
314 // from gateway with given uuid
315 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
316 found = append(found, gwURI)
318 // else this hint is no use to us; carry on.
321 // After trying all usable service hints, fall back to local roots.
322 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
326 type Locator struct {
328 Size int // -1 if data size is not known
329 Hints []string // Including the size hint, if any
332 func (loc *Locator) String() string {
334 if len(loc.Hints) > 0 {
335 s = s + "+" + strings.Join(loc.Hints, "+")
340 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
342 func MakeLocator(path string) (*Locator, error) {
343 sm := locatorMatcher.FindStringSubmatch(path)
345 return nil, InvalidLocatorError
347 loc := Locator{Hash: sm[1], Size: -1}
349 loc.Hints = strings.Split(sm[3], "+")
351 loc.Hints = []string{}
353 if len(loc.Hints) > 0 {
354 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {