Merge branch '3198-inode-cache' into 3198-writable-fuse, fix tests.
[arvados.git] / sdk / go / keepclient / keepclient.go
1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
2 package keepclient
3
4 import (
5         "crypto/md5"
6         "crypto/tls"
7         "errors"
8         "fmt"
9         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10         "git.curoverse.com/arvados.git/sdk/go/streamer"
11         "io"
12         "io/ioutil"
13         "log"
14         "net/http"
15         "os"
16         "regexp"
17         "strconv"
18         "strings"
19         "sync"
20 )
21
22 // A Keep "block" is 64MB.
23 const BLOCKSIZE = 64 * 1024 * 1024
24
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")
31
32 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
33 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
34
35 // Information about Arvados and Keep servers.
36 type KeepClient struct {
37         Arvados       *arvadosclient.ArvadosClient
38         Want_replicas int
39         Using_proxy   bool
40         localRoots    *map[string]string
41         gatewayRoots  *map[string]string
42         lock          sync.RWMutex
43         Client        *http.Client
44 }
45
46 // Create a new KeepClient.  This will contact the API server to discover Keep
47 // servers.
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"))
51         kc := &KeepClient{
52                 Arvados:       arv,
53                 Want_replicas: 2,
54                 Using_proxy:   false,
55                 Client: &http.Client{Transport: &http.Transport{
56                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
57         }
58         return kc, kc.DiscoverKeepServers()
59 }
60
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).
63 //
64 // Returns the locator for the written block, the number of replicas
65 // written, and an error.
66 //
67 // Returns an InsufficientReplicas error if 0 <= replicas <
68 // kc.Wants_replicas.
69 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
70         // Buffer for reads from 'r'
71         var bufsize int
72         if dataBytes > 0 {
73                 if dataBytes > BLOCKSIZE {
74                         return "", 0, OversizeBlockError
75                 }
76                 bufsize = int(dataBytes)
77         } else {
78                 bufsize = BLOCKSIZE
79         }
80
81         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
82         defer t.Close()
83
84         return kc.putReplicas(hash, t, dataBytes)
85 }
86
87 // PutHB writes a block to Keep. The hash of the bytes is given in
88 // hash, and the data is given in buf.
89 //
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)
93         defer t.Close()
94         return kc.putReplicas(hash, t, int64(len(buf)))
95 }
96
97 // PutB writes a block to Keep. It computes the hash itself.
98 //
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)
103 }
104
105 // PutR writes a block to Keep. It first reads all data from r into a buffer
106 // in order to compute the hash.
107 //
108 // Return values are the same as for PutHR.
109 //
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 {
113                 return "", 0, err
114         } else {
115                 return kc.PutB(buffer)
116         }
117 }
118
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
121 // an error.
122 //
123 // If the block checksum does not match, the final Read() on the
124 // reader returned by this method will return a BadChecksum error
125 // instead of EOF.
126 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
127         var errs []string
128         for _, host := range kc.getSortedRoots(locator) {
129                 url := host + "/" + locator
130                 req, err := http.NewRequest("GET", url, nil)
131                 if err != nil {
132                         continue
133                 }
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 {
137                         if resp != nil {
138                                 var respbody []byte
139                                 if resp.Body != nil {
140                                         respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
141                                 }
142                                 errs = append(errs, fmt.Sprintf("%s: %d %s",
143                                         url, resp.StatusCode, strings.TrimSpace(string(respbody))))
144                         } else {
145                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
146                         }
147                         continue
148                 }
149                 return HashCheckingReader{
150                         Reader: resp.Body,
151                         Hash:   md5.New(),
152                         Check:  locator[0:32],
153                 }, resp.ContentLength, url, nil
154         }
155         log.Printf("DEBUG: GET %s failed: %v", locator, errs)
156         return nil, 0, "", BlockNotFound
157 }
158
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.
163 //
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)
170                 if err != nil {
171                         continue
172                 }
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
176                 }
177         }
178         return 0, "", BlockNotFound
179 }
180
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 {
184         kc.lock.RLock()
185         defer kc.lock.RUnlock()
186         return *kc.localRoots
187 }
188
189 // GatewayRoots() returns the map of Keep remote gateway services:
190 // uuid -> baseURI.
191 func (kc *KeepClient) GatewayRoots() map[string]string {
192         kc.lock.RLock()
193         defer kc.lock.RUnlock()
194         return *kc.gatewayRoots
195 }
196
197 // SetServiceRoots updates the localRoots and gatewayRoots maps,
198 // without risk of disrupting operations that are already in progress.
199 //
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 {
207                 locals[uuid] = root
208         }
209         gateways := make(map[string]string)
210         for uuid, root := range newGateways {
211                 gateways[uuid] = root
212         }
213         kc.lock.Lock()
214         defer kc.lock.Unlock()
215         kc.localRoots = &locals
216         kc.gatewayRoots = &gateways
217 }
218
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
221 // given locator.
222 func (kc *KeepClient) getSortedRoots(locator string) []string {
223         var found []string
224         for _, hint := range strings.Split(locator, "+") {
225                 if len(hint) < 7 || hint[0:2] != "K@" {
226                         // Not a service hint.
227                         continue
228                 }
229                 if len(hint) == 7 {
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)
238                         }
239                         // else this hint is no use to us; carry on.
240                 }
241         }
242         // After trying all usable service hints, fall back to local roots.
243         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
244         return found
245 }
246
247 type Locator struct {
248         Hash  string
249         Size  int      // -1 if data size is not known
250         Hints []string // Including the size hint, if any
251 }
252
253 func (loc *Locator) String() string {
254         s := loc.Hash
255         if len(loc.Hints) > 0 {
256                 s = s + "+" + strings.Join(loc.Hints, "+")
257         }
258         return s
259 }
260
261 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
262
263 func MakeLocator(path string) (*Locator, error) {
264         sm := locatorMatcher.FindStringSubmatch(path)
265         if sm == nil {
266                 return nil, InvalidLocatorError
267         }
268         loc := Locator{Hash: sm[1], Size: -1}
269         if sm[2] != "" {
270                 loc.Hints = strings.Split(sm[3], "+")
271         } else {
272                 loc.Hints = []string{}
273         }
274         if len(loc.Hints) > 0 {
275                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
276                         loc.Size = size
277                 }
278         }
279         return &loc, nil
280 }