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 writableLocalRoots *map[string]string
42 gatewayRoots *map[string]string
47 // Create a new KeepClient. This will contact the API server to discover Keep
49 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
50 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
51 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
56 Client: &http.Client{Transport: &http.Transport{
57 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
59 return kc, kc.DiscoverKeepServers()
62 // Put a block given the block hash, a reader, and the number of bytes
63 // to read from the reader (which must be between 0 and BLOCKSIZE).
65 // Returns the locator for the written block, the number of replicas
66 // written, and an error.
68 // Returns an InsufficientReplicas error if 0 <= replicas <
70 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
71 // Buffer for reads from 'r'
74 if dataBytes > BLOCKSIZE {
75 return "", 0, OversizeBlockError
77 bufsize = int(dataBytes)
82 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
85 return kc.putReplicas(hash, t, dataBytes)
88 // PutHB writes a block to Keep. The hash of the bytes is given in
89 // hash, and the data is given in buf.
91 // Return values are the same as for PutHR.
92 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
93 t := streamer.AsyncStreamFromSlice(buf)
95 return kc.putReplicas(hash, t, int64(len(buf)))
98 // PutB writes a block to Keep. It computes the hash itself.
100 // Return values are the same as for PutHR.
101 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
102 hash := fmt.Sprintf("%x", md5.Sum(buffer))
103 return kc.PutHB(hash, buffer)
106 // PutR writes a block to Keep. It first reads all data from r into a buffer
107 // in order to compute the hash.
109 // Return values are the same as for PutHR.
111 // If the block hash and data size are known, PutHR is more efficient.
112 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
113 if buffer, err := ioutil.ReadAll(r); err != nil {
116 return kc.PutB(buffer)
120 // Get() retrieves a block, given a locator. Returns a reader, the
121 // expected data length, the URL the block is being fetched from, and
124 // If the block checksum does not match, the final Read() on the
125 // reader returned by this method will return a BadChecksum error
127 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
129 for _, host := range kc.getSortedRoots(locator) {
130 url := host + "/" + locator
131 req, err := http.NewRequest("GET", url, nil)
135 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
136 resp, err := kc.Client.Do(req)
137 if err != nil || resp.StatusCode != http.StatusOK {
140 if resp.Body != nil {
141 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
143 errs = append(errs, fmt.Sprintf("%s: %d %s",
144 url, resp.StatusCode, strings.TrimSpace(string(respbody))))
146 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
150 return HashCheckingReader{
153 Check: locator[0:32],
154 }, resp.ContentLength, url, nil
156 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
157 return nil, 0, "", BlockNotFound
160 // Ask() verifies that a block with the given hash is available and
161 // readable, according to at least one Keep service. Unlike Get, it
162 // does not retrieve the data or verify that the data content matches
163 // the hash specified by the locator.
165 // Returns the data size (content length) reported by the Keep service
166 // and the URI reporting the data size.
167 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
168 for _, host := range kc.getSortedRoots(locator) {
169 url := host + "/" + locator
170 req, err := http.NewRequest("HEAD", url, nil)
174 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
175 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
176 return resp.ContentLength, url, nil
179 return 0, "", BlockNotFound
182 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
183 // services: uuid -> baseURI.
184 func (kc *KeepClient) LocalRoots() map[string]string {
186 defer kc.lock.RUnlock()
187 return *kc.localRoots
190 // GatewayRoots() returns the map of Keep remote gateway services:
192 func (kc *KeepClient) GatewayRoots() map[string]string {
194 defer kc.lock.RUnlock()
195 return *kc.gatewayRoots
198 // WritableLocalRoots() returns the map of writable local Keep services:
200 func (kc *KeepClient) WritableLocalRoots() map[string]string {
202 defer kc.lock.RUnlock()
203 return *kc.writableLocalRoots
206 // SetServiceRoots updates the localRoots and gatewayRoots maps,
207 // without risk of disrupting operations that are already in progress.
209 // The KeepClient makes its own copy of the supplied maps, so the
210 // caller can reuse/modify them after SetServiceRoots returns, but
211 // they should not be modified by any other goroutine while
212 // SetServiceRoots is running.
213 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
214 locals := make(map[string]string)
215 for uuid, root := range newLocals {
219 writables := make(map[string]string)
220 for uuid, root := range newWritableLocals {
221 writables[uuid] = root
224 gateways := make(map[string]string)
225 for uuid, root := range newGateways {
226 gateways[uuid] = root
230 defer kc.lock.Unlock()
231 kc.localRoots = &locals
232 kc.writableLocalRoots = &writables
233 kc.gatewayRoots = &gateways
236 // getSortedRoots returns a list of base URIs of Keep services, in the
237 // order they should be attempted in order to retrieve content for the
239 func (kc *KeepClient) getSortedRoots(locator string) []string {
241 for _, hint := range strings.Split(locator, "+") {
242 if len(hint) < 7 || hint[0:2] != "K@" {
243 // Not a service hint.
247 // +K@abcde means fetch from proxy at
248 // keep.abcde.arvadosapi.com
249 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
250 } else if len(hint) == 29 {
251 // +K@abcde-abcde-abcdeabcdeabcde means fetch
252 // from gateway with given uuid
253 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
254 found = append(found, gwURI)
256 // else this hint is no use to us; carry on.
259 // After trying all usable service hints, fall back to local roots.
260 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
264 type Locator struct {
266 Size int // -1 if data size is not known
267 Hints []string // Including the size hint, if any
270 func (loc *Locator) String() string {
272 if len(loc.Hints) > 0 {
273 s = s + "+" + strings.Join(loc.Hints, "+")
278 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
280 func MakeLocator(path string) (*Locator, error) {
281 sm := locatorMatcher.FindStringSubmatch(path)
283 return nil, InvalidLocatorError
285 loc := Locator{Hash: sm[1], Size: -1}
287 loc.Hints = strings.Split(sm[3], "+")
289 loc.Hints = []string{}
291 if len(loc.Hints) > 0 {
292 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {