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"
22 // A Keep "block" is 64MB.
23 const BLOCKSIZE = 64 * 1024 * 1024
25 var BlockNotFound = errors.New("Block not found")
26 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
27 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
28 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
29 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
30 var InvalidLocatorError = errors.New("Invalid locator")
32 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
33 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
35 // Information about Arvados and Keep servers.
36 type KeepClient struct {
37 Arvados *arvadosclient.ArvadosClient
40 localRoots *map[string]string
41 gatewayRoots *map[string]string
46 // Create a new KeepClient. This will contact the API server to discover Keep
48 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
49 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
50 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
55 Client: &http.Client{Transport: &http.Transport{
56 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
58 return kc, kc.DiscoverKeepServers()
61 // Put a block given the block hash, a reader, and the number of bytes
62 // to read from the reader (which must be between 0 and BLOCKSIZE).
64 // Returns the locator for the written block, the number of replicas
65 // written, and an error.
67 // Returns an InsufficientReplicas error if 0 <= replicas <
69 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
70 // Buffer for reads from 'r'
73 if dataBytes > BLOCKSIZE {
74 return "", 0, OversizeBlockError
76 bufsize = int(dataBytes)
81 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
84 return kc.putReplicas(hash, t, dataBytes)
87 // PutHB writes a block to Keep. The hash of the bytes is given in
88 // hash, and the data is given in buf.
90 // Return values are the same as for PutHR.
91 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
92 t := streamer.AsyncStreamFromSlice(buf)
94 return kc.putReplicas(hash, t, int64(len(buf)))
97 // PutB writes a block to Keep. It computes the hash itself.
99 // Return values are the same as for PutHR.
100 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
101 hash := fmt.Sprintf("%x", md5.Sum(buffer))
102 return kc.PutHB(hash, buffer)
105 // PutR writes a block to Keep. It first reads all data from r into a buffer
106 // in order to compute the hash.
108 // Return values are the same as for PutHR.
110 // If the block hash and data size are known, PutHR is more efficient.
111 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
112 if buffer, err := ioutil.ReadAll(r); err != nil {
115 return kc.PutB(buffer)
119 // Get() retrieves a block, given a locator. Returns a reader, the
120 // expected data length, the URL the block is being fetched from, and
123 // If the block checksum does not match, the final Read() on the
124 // reader returned by this method will return a BadChecksum error
126 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
128 for _, host := range kc.getSortedRoots(locator) {
129 url := host + "/" + locator
130 req, err := http.NewRequest("GET", url, nil)
134 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
135 resp, err := kc.Client.Do(req)
136 if err != nil || resp.StatusCode != http.StatusOK {
139 if resp.Body != nil {
140 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
142 errs = append(errs, fmt.Sprintf("%s: %d %s",
143 url, resp.StatusCode, strings.TrimSpace(string(respbody))))
145 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
149 return HashCheckingReader{
152 Check: locator[0:32],
153 }, resp.ContentLength, url, nil
155 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
156 return nil, 0, "", BlockNotFound
159 // Ask() verifies that a block with the given hash is available and
160 // readable, according to at least one Keep service. Unlike Get, it
161 // does not retrieve the data or verify that the data content matches
162 // the hash specified by the locator.
164 // Returns the data size (content length) reported by the Keep service
165 // and the URI reporting the data size.
166 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
167 for _, host := range kc.getSortedRoots(locator) {
168 url := host + "/" + locator
169 req, err := http.NewRequest("HEAD", url, nil)
173 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
174 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
175 return resp.ContentLength, url, nil
178 return 0, "", BlockNotFound
181 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
182 // services: uuid -> baseURI.
183 func (kc *KeepClient) LocalRoots() map[string]string {
185 defer kc.lock.RUnlock()
186 return *kc.localRoots
189 // GatewayRoots() returns the map of Keep remote gateway services:
191 func (kc *KeepClient) GatewayRoots() map[string]string {
193 defer kc.lock.RUnlock()
194 return *kc.gatewayRoots
197 // SetServiceRoots updates the localRoots and gatewayRoots maps,
198 // without risk of disrupting operations that are already in progress.
200 // The KeepClient makes its own copy of the supplied maps, so the
201 // caller can reuse/modify them after SetServiceRoots returns, but
202 // they should not be modified by any other goroutine while
203 // SetServiceRoots is running.
204 func (kc *KeepClient) SetServiceRoots(newLocals, newGateways map[string]string) {
205 locals := make(map[string]string)
206 for uuid, root := range newLocals {
209 gateways := make(map[string]string)
210 for uuid, root := range newGateways {
211 gateways[uuid] = root
214 defer kc.lock.Unlock()
215 kc.localRoots = &locals
216 kc.gatewayRoots = &gateways
219 // getSortedRoots returns a list of base URIs of Keep services, in the
220 // order they should be attempted in order to retrieve content for the
222 func (kc *KeepClient) getSortedRoots(locator string) []string {
224 for _, hint := range strings.Split(locator, "+") {
225 if len(hint) < 7 || hint[0:2] != "K@" {
226 // Not a service hint.
230 // +K@abcde means fetch from proxy at
231 // keep.abcde.arvadosapi.com
232 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
233 } else if len(hint) == 29 {
234 // +K@abcde-abcde-abcdeabcdeabcde means fetch
235 // from gateway with given uuid
236 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
237 found = append(found, gwURI)
239 // else this hint is no use to us; carry on.
242 // After trying all usable service hints, fall back to local roots.
243 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
247 type Locator struct {
249 Size int // -1 if data size is not known
250 Hints []string // Including the size hint, if any
253 func (loc *Locator) String() string {
255 if len(loc.Hints) > 0 {
256 s = s + "+" + strings.Join(loc.Hints, "+")
261 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
263 func MakeLocator(path string) (*Locator, error) {
264 sm := locatorMatcher.FindStringSubmatch(path)
266 return nil, InvalidLocatorError
268 loc := Locator{Hash: sm[1], Size: -1}
270 loc.Hints = strings.Split(sm[3], "+")
272 loc.Hints = []string{}
274 if len(loc.Hints) > 0 {
275 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {