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 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
58 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
59 kc := initKeepClient(arv)
60 return kc, kc.DiscoverKeepServers()
63 // MakeKeepClientFromJSON creates a new KeepClient using the given json to load keep servers.
64 func MakeKeepClientFromJSON(arv *arvadosclient.ArvadosClient, svcJSON string) (*KeepClient, error) {
65 kc := initKeepClient(arv)
66 return kc, kc.DiscoverKeepServersFromJSON(svcJSON)
69 // Make a new KeepClient struct.
70 func initKeepClient(arv *arvadosclient.ArvadosClient) *KeepClient {
71 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
72 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
77 Client: &http.Client{Transport: &http.Transport{
78 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
83 // Put a block given the block hash, a reader, and the number of bytes
84 // to read from the reader (which must be between 0 and BLOCKSIZE).
86 // Returns the locator for the written block, the number of replicas
87 // written, and an error.
89 // Returns an InsufficientReplicas error if 0 <= replicas <
91 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
92 // Buffer for reads from 'r'
95 if dataBytes > BLOCKSIZE {
96 return "", 0, OversizeBlockError
98 bufsize = int(dataBytes)
103 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
106 return kc.putReplicas(hash, t, dataBytes)
109 // PutHB writes a block to Keep. The hash of the bytes is given in
110 // hash, and the data is given in buf.
112 // Return values are the same as for PutHR.
113 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
114 t := streamer.AsyncStreamFromSlice(buf)
116 return kc.putReplicas(hash, t, int64(len(buf)))
119 // PutB writes a block to Keep. It computes the hash itself.
121 // Return values are the same as for PutHR.
122 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
123 hash := fmt.Sprintf("%x", md5.Sum(buffer))
124 return kc.PutHB(hash, buffer)
127 // PutR writes a block to Keep. It first reads all data from r into a buffer
128 // in order to compute the hash.
130 // Return values are the same as for PutHR.
132 // If the block hash and data size are known, PutHR is more efficient.
133 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
134 if buffer, err := ioutil.ReadAll(r); err != nil {
137 return kc.PutB(buffer)
141 // Get() retrieves a block, given a locator. Returns a reader, the
142 // expected data length, the URL the block is being fetched from, and
145 // If the block checksum does not match, the final Read() on the
146 // reader returned by this method will return a BadChecksum error
148 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
150 for _, host := range kc.getSortedRoots(locator) {
151 url := host + "/" + locator
152 req, err := http.NewRequest("GET", url, nil)
156 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
157 resp, err := kc.Client.Do(req)
158 if err != nil || resp.StatusCode != http.StatusOK {
161 if resp.Body != nil {
162 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
164 errs = append(errs, fmt.Sprintf("%s: %d %s",
165 url, resp.StatusCode, strings.TrimSpace(string(respbody))))
167 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
171 return HashCheckingReader{
174 Check: locator[0:32],
175 }, resp.ContentLength, url, nil
177 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
178 return nil, 0, "", BlockNotFound
181 // Ask() verifies that a block with the given hash is available and
182 // readable, according to at least one Keep service. Unlike Get, it
183 // does not retrieve the data or verify that the data content matches
184 // the hash specified by the locator.
186 // Returns the data size (content length) reported by the Keep service
187 // and the URI reporting the data size.
188 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
189 for _, host := range kc.getSortedRoots(locator) {
190 url := host + "/" + locator
191 req, err := http.NewRequest("HEAD", url, nil)
195 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
196 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
197 return resp.ContentLength, url, nil
200 return 0, "", BlockNotFound
203 // GetIndex retrieves a list of blocks stored on the given server whose hashes
204 // begin with the given prefix. The returned reader will return an error (other
205 // than EOF) if the complete index cannot be retrieved.
207 // This is meant to be used only by system components and admin tools.
208 // It will return an error unless the client is using a "data manager token"
209 // recognized by the Keep services.
210 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
211 url := kc.LocalRoots()[keepServiceUUID]
213 return nil, ErrNoSuchKeepServer
221 req, err := http.NewRequest("GET", url, nil)
226 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
227 resp, err := kc.Client.Do(req)
232 defer resp.Body.Close()
234 if resp.StatusCode != http.StatusOK {
235 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
239 respBody, err = ioutil.ReadAll(resp.Body)
244 // Got index; verify that it is complete
245 // The response should be "\n" if no locators matched the prefix
246 // Else, it should be a list of locators followed by a blank line
247 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
248 return nil, ErrIncompleteIndex
251 // Got complete index; strip the trailing newline and send
252 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
255 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
256 // services: uuid -> baseURI.
257 func (kc *KeepClient) LocalRoots() map[string]string {
259 defer kc.lock.RUnlock()
260 return *kc.localRoots
263 // GatewayRoots() returns the map of Keep remote gateway services:
265 func (kc *KeepClient) GatewayRoots() map[string]string {
267 defer kc.lock.RUnlock()
268 return *kc.gatewayRoots
271 // WritableLocalRoots() returns the map of writable local Keep services:
273 func (kc *KeepClient) WritableLocalRoots() map[string]string {
275 defer kc.lock.RUnlock()
276 return *kc.writableLocalRoots
279 // SetServiceRoots updates the localRoots and gatewayRoots maps,
280 // without risk of disrupting operations that are already in progress.
282 // The KeepClient makes its own copy of the supplied maps, so the
283 // caller can reuse/modify them after SetServiceRoots returns, but
284 // they should not be modified by any other goroutine while
285 // SetServiceRoots is running.
286 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
287 locals := make(map[string]string)
288 for uuid, root := range newLocals {
292 writables := make(map[string]string)
293 for uuid, root := range newWritableLocals {
294 writables[uuid] = root
297 gateways := make(map[string]string)
298 for uuid, root := range newGateways {
299 gateways[uuid] = root
303 defer kc.lock.Unlock()
304 kc.localRoots = &locals
305 kc.writableLocalRoots = &writables
306 kc.gatewayRoots = &gateways
309 // getSortedRoots returns a list of base URIs of Keep services, in the
310 // order they should be attempted in order to retrieve content for the
312 func (kc *KeepClient) getSortedRoots(locator string) []string {
314 for _, hint := range strings.Split(locator, "+") {
315 if len(hint) < 7 || hint[0:2] != "K@" {
316 // Not a service hint.
320 // +K@abcde means fetch from proxy at
321 // keep.abcde.arvadosapi.com
322 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
323 } else if len(hint) == 29 {
324 // +K@abcde-abcde-abcdeabcdeabcde means fetch
325 // from gateway with given uuid
326 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
327 found = append(found, gwURI)
329 // else this hint is no use to us; carry on.
332 // After trying all usable service hints, fall back to local roots.
333 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
337 type Locator struct {
339 Size int // -1 if data size is not known
340 Hints []string // Including the size hint, if any
343 func (loc *Locator) String() string {
345 if len(loc.Hints) > 0 {
346 s = s + "+" + strings.Join(loc.Hints, "+")
351 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
353 func MakeLocator(path string) (*Locator, error) {
354 sm := locatorMatcher.FindStringSubmatch(path)
356 return nil, InvalidLocatorError
358 loc := Locator{Hash: sm[1], Size: -1}
360 loc.Hints = strings.Split(sm[3], "+")
362 loc.Hints = []string{}
364 if len(loc.Hints) > 0 {
365 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {