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)
143 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
146 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
147 resp, err := kc.Client.Do(req)
149 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
151 } else if resp.StatusCode != http.StatusOK {
152 respbody, _ := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
154 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
155 url, resp.StatusCode, bytes.TrimSpace(respbody)))
158 return HashCheckingReader{
161 Check: locator[0:32],
162 }, resp.ContentLength, url, nil
164 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
165 return nil, 0, "", BlockNotFound
168 // Ask() verifies that a block with the given hash is available and
169 // readable, according to at least one Keep service. Unlike Get, it
170 // does not retrieve the data or verify that the data content matches
171 // the hash specified by the locator.
173 // Returns the data size (content length) reported by the Keep service
174 // and the URI reporting the data size.
175 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
176 for _, host := range kc.getSortedRoots(locator) {
177 url := host + "/" + locator
178 req, err := http.NewRequest("HEAD", url, nil)
182 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
183 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
184 return resp.ContentLength, url, nil
187 return 0, "", BlockNotFound
190 // GetIndex retrieves a list of blocks stored on the given server whose hashes
191 // begin with the given prefix. The returned reader will return an error (other
192 // than EOF) if the complete index cannot be retrieved.
194 // This is meant to be used only by system components and admin tools.
195 // It will return an error unless the client is using a "data manager token"
196 // recognized by the Keep services.
197 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
198 url := kc.LocalRoots()[keepServiceUUID]
200 return nil, ErrNoSuchKeepServer
208 req, err := http.NewRequest("GET", url, nil)
213 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
214 resp, err := kc.Client.Do(req)
219 defer resp.Body.Close()
221 if resp.StatusCode != http.StatusOK {
222 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
226 respBody, err = ioutil.ReadAll(resp.Body)
231 // Got index; verify that it is complete
232 // The response should be "\n" if no locators matched the prefix
233 // Else, it should be a list of locators followed by a blank line
234 if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
235 return nil, ErrIncompleteIndex
238 // Got complete index; strip the trailing newline and send
239 return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
242 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
243 // services: uuid -> baseURI.
244 func (kc *KeepClient) LocalRoots() map[string]string {
246 defer kc.lock.RUnlock()
247 return *kc.localRoots
250 // GatewayRoots() returns the map of Keep remote gateway services:
252 func (kc *KeepClient) GatewayRoots() map[string]string {
254 defer kc.lock.RUnlock()
255 return *kc.gatewayRoots
258 // WritableLocalRoots() returns the map of writable local Keep services:
260 func (kc *KeepClient) WritableLocalRoots() map[string]string {
262 defer kc.lock.RUnlock()
263 return *kc.writableLocalRoots
266 // SetServiceRoots updates the localRoots and gatewayRoots maps,
267 // without risk of disrupting operations that are already in progress.
269 // The KeepClient makes its own copy of the supplied maps, so the
270 // caller can reuse/modify them after SetServiceRoots returns, but
271 // they should not be modified by any other goroutine while
272 // SetServiceRoots is running.
273 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
274 locals := make(map[string]string)
275 for uuid, root := range newLocals {
279 writables := make(map[string]string)
280 for uuid, root := range newWritableLocals {
281 writables[uuid] = root
284 gateways := make(map[string]string)
285 for uuid, root := range newGateways {
286 gateways[uuid] = root
290 defer kc.lock.Unlock()
291 kc.localRoots = &locals
292 kc.writableLocalRoots = &writables
293 kc.gatewayRoots = &gateways
296 // getSortedRoots returns a list of base URIs of Keep services, in the
297 // order they should be attempted in order to retrieve content for the
299 func (kc *KeepClient) getSortedRoots(locator string) []string {
301 for _, hint := range strings.Split(locator, "+") {
302 if len(hint) < 7 || hint[0:2] != "K@" {
303 // Not a service hint.
307 // +K@abcde means fetch from proxy at
308 // keep.abcde.arvadosapi.com
309 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
310 } else if len(hint) == 29 {
311 // +K@abcde-abcde-abcdeabcdeabcde means fetch
312 // from gateway with given uuid
313 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
314 found = append(found, gwURI)
316 // else this hint is no use to us; carry on.
319 // After trying all usable service hints, fall back to local roots.
320 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
324 type Locator struct {
326 Size int // -1 if data size is not known
327 Hints []string // Including the size hint, if any
330 func (loc *Locator) String() string {
332 if len(loc.Hints) > 0 {
333 s = s + "+" + strings.Join(loc.Hints, "+")
338 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
340 func MakeLocator(path string) (*Locator, error) {
341 sm := locatorMatcher.FindStringSubmatch(path)
343 return nil, InvalidLocatorError
345 loc := Locator{Hash: sm[1], Size: -1}
347 loc.Hints = strings.Split(sm[3], "+")
349 loc.Hints = []string{}
351 if len(loc.Hints) > 0 {
352 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {