Merge branch '7491-keepclient-bugs' refs #7491
[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         "bytes"
6         "crypto/md5"
7         "crypto/tls"
8         "errors"
9         "fmt"
10         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
11         "git.curoverse.com/arvados.git/sdk/go/streamer"
12         "io"
13         "io/ioutil"
14         "log"
15         "net/http"
16         "os"
17         "regexp"
18         "strconv"
19         "strings"
20         "sync"
21 )
22
23 // A Keep "block" is 64MB.
24 const BLOCKSIZE = 64 * 1024 * 1024
25
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")
32
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")
35
36 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
37 var ErrIncompleteIndex = errors.New("Got incomplete index")
38
39 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
40 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
41
42 // Information about Arvados and Keep servers.
43 type KeepClient struct {
44         Arvados            *arvadosclient.ArvadosClient
45         Want_replicas      int
46         Using_proxy        bool
47         localRoots         *map[string]string
48         writableLocalRoots *map[string]string
49         gatewayRoots       *map[string]string
50         lock               sync.RWMutex
51         Client             *http.Client
52
53         // set to 1 if all writable services are of disk type, otherwise 0
54         replicasPerService int
55 }
56
57 // Create a new KeepClient.  This will contact the API server to discover Keep
58 // servers.
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"))
62         kc := &KeepClient{
63                 Arvados:       arv,
64                 Want_replicas: 2,
65                 Using_proxy:   false,
66                 Client: &http.Client{Transport: &http.Transport{
67                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
68         }
69         return kc, kc.DiscoverKeepServers()
70 }
71
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).
74 //
75 // Returns the locator for the written block, the number of replicas
76 // written, and an error.
77 //
78 // Returns an InsufficientReplicas error if 0 <= replicas <
79 // kc.Wants_replicas.
80 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
81         // Buffer for reads from 'r'
82         var bufsize int
83         if dataBytes > 0 {
84                 if dataBytes > BLOCKSIZE {
85                         return "", 0, OversizeBlockError
86                 }
87                 bufsize = int(dataBytes)
88         } else {
89                 bufsize = BLOCKSIZE
90         }
91
92         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
93         defer t.Close()
94
95         return kc.putReplicas(hash, t, dataBytes)
96 }
97
98 // PutHB writes a block to Keep. The hash of the bytes is given in
99 // hash, and the data is given in buf.
100 //
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)
104         defer t.Close()
105         return kc.putReplicas(hash, t, int64(len(buf)))
106 }
107
108 // PutB writes a block to Keep. It computes the hash itself.
109 //
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)
114 }
115
116 // PutR writes a block to Keep. It first reads all data from r into a buffer
117 // in order to compute the hash.
118 //
119 // Return values are the same as for PutHR.
120 //
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 {
124                 return "", 0, err
125         } else {
126                 return kc.PutB(buffer)
127         }
128 }
129
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
132 // an error.
133 //
134 // If the block checksum does not match, the final Read() on the
135 // reader returned by this method will return a BadChecksum error
136 // instead of EOF.
137 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
138         var errs []string
139         for _, host := range kc.getSortedRoots(locator) {
140                 url := host + "/" + locator
141                 req, err := http.NewRequest("GET", url, nil)
142                 if err != nil {
143                         errs = append(errs, fmt.Sprintf("%s: %v", url, err))
144                         continue
145                 }
146                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
147                 resp, err := kc.Client.Do(req)
148                 if err != nil {
149                         errs = append(errs, fmt.Sprintf("%s: %v", url, err))
150                         continue
151                 } else if resp.StatusCode != http.StatusOK {
152                         respbody, _ := ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
153                         resp.Body.Close()
154                         errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
155                                 url, resp.StatusCode, bytes.TrimSpace(respbody)))
156                         continue
157                 }
158                 return HashCheckingReader{
159                         Reader: resp.Body,
160                         Hash:   md5.New(),
161                         Check:  locator[0:32],
162                 }, resp.ContentLength, url, nil
163         }
164         log.Printf("DEBUG: GET %s failed: %v", locator, errs)
165         return nil, 0, "", BlockNotFound
166 }
167
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.
172 //
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)
179                 if err != nil {
180                         continue
181                 }
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
185                 }
186         }
187         return 0, "", BlockNotFound
188 }
189
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.
193 //
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]
199         if url == "" {
200                 return nil, ErrNoSuchKeepServer
201         }
202
203         url += "/index"
204         if prefix != "" {
205                 url += "/" + prefix
206         }
207
208         req, err := http.NewRequest("GET", url, nil)
209         if err != nil {
210                 return nil, err
211         }
212
213         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
214         resp, err := kc.Client.Do(req)
215         if err != nil {
216                 return nil, err
217         }
218
219         defer resp.Body.Close()
220
221         if resp.StatusCode != http.StatusOK {
222                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
223         }
224
225         var respBody []byte
226         respBody, err = ioutil.ReadAll(resp.Body)
227         if err != nil {
228                 return nil, err
229         }
230
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
236         }
237
238         // Got complete index; strip the trailing newline and send
239         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
240 }
241
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 {
245         kc.lock.RLock()
246         defer kc.lock.RUnlock()
247         return *kc.localRoots
248 }
249
250 // GatewayRoots() returns the map of Keep remote gateway services:
251 // uuid -> baseURI.
252 func (kc *KeepClient) GatewayRoots() map[string]string {
253         kc.lock.RLock()
254         defer kc.lock.RUnlock()
255         return *kc.gatewayRoots
256 }
257
258 // WritableLocalRoots() returns the map of writable local Keep services:
259 // uuid -> baseURI.
260 func (kc *KeepClient) WritableLocalRoots() map[string]string {
261         kc.lock.RLock()
262         defer kc.lock.RUnlock()
263         return *kc.writableLocalRoots
264 }
265
266 // SetServiceRoots updates the localRoots and gatewayRoots maps,
267 // without risk of disrupting operations that are already in progress.
268 //
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 {
276                 locals[uuid] = root
277         }
278
279         writables := make(map[string]string)
280         for uuid, root := range newWritableLocals {
281                 writables[uuid] = root
282         }
283
284         gateways := make(map[string]string)
285         for uuid, root := range newGateways {
286                 gateways[uuid] = root
287         }
288
289         kc.lock.Lock()
290         defer kc.lock.Unlock()
291         kc.localRoots = &locals
292         kc.writableLocalRoots = &writables
293         kc.gatewayRoots = &gateways
294 }
295
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
298 // given locator.
299 func (kc *KeepClient) getSortedRoots(locator string) []string {
300         var found []string
301         for _, hint := range strings.Split(locator, "+") {
302                 if len(hint) < 7 || hint[0:2] != "K@" {
303                         // Not a service hint.
304                         continue
305                 }
306                 if len(hint) == 7 {
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)
315                         }
316                         // else this hint is no use to us; carry on.
317                 }
318         }
319         // After trying all usable service hints, fall back to local roots.
320         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
321         return found
322 }
323
324 type Locator struct {
325         Hash  string
326         Size  int      // -1 if data size is not known
327         Hints []string // Including the size hint, if any
328 }
329
330 func (loc *Locator) String() string {
331         s := loc.Hash
332         if len(loc.Hints) > 0 {
333                 s = s + "+" + strings.Join(loc.Hints, "+")
334         }
335         return s
336 }
337
338 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
339
340 func MakeLocator(path string) (*Locator, error) {
341         sm := locatorMatcher.FindStringSubmatch(path)
342         if sm == nil {
343                 return nil, InvalidLocatorError
344         }
345         loc := Locator{Hash: sm[1], Size: -1}
346         if sm[2] != "" {
347                 loc.Hints = strings.Split(sm[3], "+")
348         } else {
349                 loc.Hints = []string{}
350         }
351         if len(loc.Hints) > 0 {
352                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
353                         loc.Size = size
354                 }
355         }
356         return &loc, nil
357 }