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
46 // set to 1 if all writable services are of disk type, otherwise 0
47 replicasPerService int
50 // Create a new KeepClient. This will contact the API server to discover Keep
52 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
53 var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
54 insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
59 Client: &http.Client{Transport: &http.Transport{
60 TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
62 return kc, kc.DiscoverKeepServers()
65 // Put a block given the block hash, a reader, and the number of bytes
66 // to read from the reader (which must be between 0 and BLOCKSIZE).
68 // Returns the locator for the written block, the number of replicas
69 // written, and an error.
71 // Returns an InsufficientReplicas error if 0 <= replicas <
73 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
74 // Buffer for reads from 'r'
77 if dataBytes > BLOCKSIZE {
78 return "", 0, OversizeBlockError
80 bufsize = int(dataBytes)
85 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
88 return kc.putReplicas(hash, t, dataBytes)
91 // PutHB writes a block to Keep. The hash of the bytes is given in
92 // hash, and the data is given in buf.
94 // Return values are the same as for PutHR.
95 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
96 t := streamer.AsyncStreamFromSlice(buf)
98 return kc.putReplicas(hash, t, int64(len(buf)))
101 // PutB writes a block to Keep. It computes the hash itself.
103 // Return values are the same as for PutHR.
104 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
105 hash := fmt.Sprintf("%x", md5.Sum(buffer))
106 return kc.PutHB(hash, buffer)
109 // PutR writes a block to Keep. It first reads all data from r into a buffer
110 // in order to compute the hash.
112 // Return values are the same as for PutHR.
114 // If the block hash and data size are known, PutHR is more efficient.
115 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
116 if buffer, err := ioutil.ReadAll(r); err != nil {
119 return kc.PutB(buffer)
123 // Get() retrieves a block, given a locator. Returns a reader, the
124 // expected data length, the URL the block is being fetched from, and
127 // If the block checksum does not match, the final Read() on the
128 // reader returned by this method will return a BadChecksum error
130 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
132 for _, host := range kc.getSortedRoots(locator) {
133 url := host + "/" + locator
134 req, err := http.NewRequest("GET", url, nil)
138 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
139 resp, err := kc.Client.Do(req)
140 if err != nil || resp.StatusCode != http.StatusOK {
143 if resp.Body != nil {
144 respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
146 errs = append(errs, fmt.Sprintf("%s: %d %s",
147 url, resp.StatusCode, strings.TrimSpace(string(respbody))))
149 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
153 return HashCheckingReader{
156 Check: locator[0:32],
157 }, resp.ContentLength, url, nil
159 log.Printf("DEBUG: GET %s failed: %v", locator, errs)
160 return nil, 0, "", BlockNotFound
163 // Ask() verifies that a block with the given hash is available and
164 // readable, according to at least one Keep service. Unlike Get, it
165 // does not retrieve the data or verify that the data content matches
166 // the hash specified by the locator.
168 // Returns the data size (content length) reported by the Keep service
169 // and the URI reporting the data size.
170 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
171 for _, host := range kc.getSortedRoots(locator) {
172 url := host + "/" + locator
173 req, err := http.NewRequest("HEAD", url, nil)
177 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
178 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
179 return resp.ContentLength, url, nil
182 return 0, "", BlockNotFound
185 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
186 // services: uuid -> baseURI.
187 func (kc *KeepClient) LocalRoots() map[string]string {
189 defer kc.lock.RUnlock()
190 return *kc.localRoots
193 // GatewayRoots() returns the map of Keep remote gateway services:
195 func (kc *KeepClient) GatewayRoots() map[string]string {
197 defer kc.lock.RUnlock()
198 return *kc.gatewayRoots
201 // WritableLocalRoots() returns the map of writable local Keep services:
203 func (kc *KeepClient) WritableLocalRoots() map[string]string {
205 defer kc.lock.RUnlock()
206 return *kc.writableLocalRoots
209 // SetServiceRoots updates the localRoots and gatewayRoots maps,
210 // without risk of disrupting operations that are already in progress.
212 // The KeepClient makes its own copy of the supplied maps, so the
213 // caller can reuse/modify them after SetServiceRoots returns, but
214 // they should not be modified by any other goroutine while
215 // SetServiceRoots is running.
216 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
217 locals := make(map[string]string)
218 for uuid, root := range newLocals {
222 writables := make(map[string]string)
223 for uuid, root := range newWritableLocals {
224 writables[uuid] = root
227 gateways := make(map[string]string)
228 for uuid, root := range newGateways {
229 gateways[uuid] = root
233 defer kc.lock.Unlock()
234 kc.localRoots = &locals
235 kc.writableLocalRoots = &writables
236 kc.gatewayRoots = &gateways
239 // getSortedRoots returns a list of base URIs of Keep services, in the
240 // order they should be attempted in order to retrieve content for the
242 func (kc *KeepClient) getSortedRoots(locator string) []string {
244 for _, hint := range strings.Split(locator, "+") {
245 if len(hint) < 7 || hint[0:2] != "K@" {
246 // Not a service hint.
250 // +K@abcde means fetch from proxy at
251 // keep.abcde.arvadosapi.com
252 found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
253 } else if len(hint) == 29 {
254 // +K@abcde-abcde-abcdeabcdeabcde means fetch
255 // from gateway with given uuid
256 if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
257 found = append(found, gwURI)
259 // else this hint is no use to us; carry on.
262 // After trying all usable service hints, fall back to local roots.
263 found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
267 type Locator struct {
269 Size int // -1 if data size is not known
270 Hints []string // Including the size hint, if any
273 func (loc *Locator) String() string {
275 if len(loc.Hints) > 0 {
276 s = s + "+" + strings.Join(loc.Hints, "+")
281 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
283 func MakeLocator(path string) (*Locator, error) {
284 sm := locatorMatcher.FindStringSubmatch(path)
286 return nil, InvalidLocatorError
288 loc := Locator{Hash: sm[1], Size: -1}
290 loc.Hints = strings.Split(sm[3], "+")
292 loc.Hints = []string{}
294 if len(loc.Hints) > 0 {
295 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {