5824: Merge branch 'master' into 5824-keep-web
[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         "regexp"
17         "strconv"
18         "strings"
19         "sync"
20 )
21
22 // A Keep "block" is 64MB.
23 const BLOCKSIZE = 64 * 1024 * 1024
24
25 // Error interface with an error and boolean indicating whether the error is temporary
26 type Error interface {
27         error
28         Temporary() bool
29 }
30
31 // multipleResponseError is of type Error
32 type multipleResponseError struct {
33         error
34         isTemp bool
35 }
36
37 func (e *multipleResponseError) Temporary() bool {
38         return e.isTemp
39 }
40
41 // BlockNotFound is a multipleResponseError where isTemp is false
42 var BlockNotFound = &ErrNotFound{multipleResponseError{
43         error:  errors.New("Block not found"),
44         isTemp: false,
45 }}
46
47 // ErrNotFound is a multipleResponseError where isTemp can be true or false
48 type ErrNotFound struct {
49         multipleResponseError
50 }
51
52 var InsufficientReplicasError = errors.New("Could not write sufficient replicas")
53 var OversizeBlockError = errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")
54 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
55 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
56 var InvalidLocatorError = errors.New("Invalid locator")
57
58 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
59 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
60
61 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
62 var ErrIncompleteIndex = errors.New("Got incomplete index")
63
64 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
65 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
66
67 // Information about Arvados and Keep servers.
68 type KeepClient struct {
69         Arvados            *arvadosclient.ArvadosClient
70         Want_replicas      int
71         Using_proxy        bool
72         localRoots         *map[string]string
73         writableLocalRoots *map[string]string
74         gatewayRoots       *map[string]string
75         lock               sync.RWMutex
76         Client             *http.Client
77         Retries            int
78
79         // set to 1 if all writable services are of disk type, otherwise 0
80         replicasPerService int
81 }
82
83 // MakeKeepClient creates a new KeepClient by contacting the API server to discover Keep servers.
84 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
85         kc := New(arv)
86         return kc, kc.DiscoverKeepServers()
87 }
88
89 // New func creates a new KeepClient struct.
90 // This func does not discover keep servers. It is the caller's responsibility.
91 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
92         defaultReplicationLevel := 2
93         value, err := arv.Discovery("defaultCollectionReplication")
94         if err == nil {
95                 v, ok := value.(float64)
96                 if ok && v > 0 {
97                         defaultReplicationLevel = int(v)
98                 }
99         }
100
101         kc := &KeepClient{
102                 Arvados:       arv,
103                 Want_replicas: defaultReplicationLevel,
104                 Using_proxy:   false,
105                 Client: &http.Client{Transport: &http.Transport{
106                         TLSClientConfig: &tls.Config{InsecureSkipVerify: arv.ApiInsecure}}},
107                 Retries: 2,
108         }
109         return kc
110 }
111
112 // Put a block given the block hash, a reader, and the number of bytes
113 // to read from the reader (which must be between 0 and BLOCKSIZE).
114 //
115 // Returns the locator for the written block, the number of replicas
116 // written, and an error.
117 //
118 // Returns an InsufficientReplicas error if 0 <= replicas <
119 // kc.Wants_replicas.
120 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
121         // Buffer for reads from 'r'
122         var bufsize int
123         if dataBytes > 0 {
124                 if dataBytes > BLOCKSIZE {
125                         return "", 0, OversizeBlockError
126                 }
127                 bufsize = int(dataBytes)
128         } else {
129                 bufsize = BLOCKSIZE
130         }
131
132         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
133         defer t.Close()
134
135         return kc.putReplicas(hash, t, dataBytes)
136 }
137
138 // PutHB writes a block to Keep. The hash of the bytes is given in
139 // hash, and the data is given in buf.
140 //
141 // Return values are the same as for PutHR.
142 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
143         t := streamer.AsyncStreamFromSlice(buf)
144         defer t.Close()
145         return kc.putReplicas(hash, t, int64(len(buf)))
146 }
147
148 // PutB writes a block to Keep. It computes the hash itself.
149 //
150 // Return values are the same as for PutHR.
151 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
152         hash := fmt.Sprintf("%x", md5.Sum(buffer))
153         return kc.PutHB(hash, buffer)
154 }
155
156 // PutR writes a block to Keep. It first reads all data from r into a buffer
157 // in order to compute the hash.
158 //
159 // Return values are the same as for PutHR.
160 //
161 // If the block hash and data size are known, PutHR is more efficient.
162 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
163         if buffer, err := ioutil.ReadAll(r); err != nil {
164                 return "", 0, err
165         } else {
166                 return kc.PutB(buffer)
167         }
168 }
169
170 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
171         var errs []string
172
173         tries_remaining := 1 + kc.Retries
174
175         serversToTry := kc.getSortedRoots(locator)
176
177         numServers := len(serversToTry)
178         count404 := 0
179
180         var retryList []string
181
182         for tries_remaining > 0 {
183                 tries_remaining -= 1
184                 retryList = nil
185
186                 for _, host := range serversToTry {
187                         url := host + "/" + locator
188
189                         req, err := http.NewRequest(method, url, nil)
190                         if err != nil {
191                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
192                                 continue
193                         }
194                         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
195                         resp, err := kc.Client.Do(req)
196                         if err != nil {
197                                 // Probably a network error, may be transient,
198                                 // can try again.
199                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
200                                 retryList = append(retryList, host)
201                         } else if resp.StatusCode != http.StatusOK {
202                                 var respbody []byte
203                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
204                                 resp.Body.Close()
205                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
206                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
207
208                                 if resp.StatusCode == 408 ||
209                                         resp.StatusCode == 429 ||
210                                         resp.StatusCode >= 500 {
211                                         // Timeout, too many requests, or other
212                                         // server side failure, transient
213                                         // error, can try again.
214                                         retryList = append(retryList, host)
215                                 } else if resp.StatusCode == 404 {
216                                         count404++
217                                 }
218                         } else {
219                                 // Success.
220                                 if method == "GET" {
221                                         return HashCheckingReader{
222                                                 Reader: resp.Body,
223                                                 Hash:   md5.New(),
224                                                 Check:  locator[0:32],
225                                         }, resp.ContentLength, url, nil
226                                 } else {
227                                         resp.Body.Close()
228                                         return nil, resp.ContentLength, url, nil
229                                 }
230                         }
231
232                 }
233                 serversToTry = retryList
234         }
235         log.Printf("DEBUG: %s %s failed: %v", method, locator, errs)
236
237         var err error
238         if count404 == numServers {
239                 err = BlockNotFound
240         } else {
241                 err = &ErrNotFound{multipleResponseError{
242                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
243                         isTemp: len(serversToTry) > 0,
244                 }}
245         }
246         return nil, 0, "", err
247 }
248
249 // Get() retrieves a block, given a locator. Returns a reader, the
250 // expected data length, the URL the block is being fetched from, and
251 // an error.
252 //
253 // If the block checksum does not match, the final Read() on the
254 // reader returned by this method will return a BadChecksum error
255 // instead of EOF.
256 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
257         return kc.getOrHead("GET", locator)
258 }
259
260 // Ask() verifies that a block with the given hash is available and
261 // readable, according to at least one Keep service. Unlike Get, it
262 // does not retrieve the data or verify that the data content matches
263 // the hash specified by the locator.
264 //
265 // Returns the data size (content length) reported by the Keep service
266 // and the URI reporting the data size.
267 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
268         _, size, url, err := kc.getOrHead("HEAD", locator)
269         return size, url, err
270 }
271
272 // GetIndex retrieves a list of blocks stored on the given server whose hashes
273 // begin with the given prefix. The returned reader will return an error (other
274 // than EOF) if the complete index cannot be retrieved.
275 //
276 // This is meant to be used only by system components and admin tools.
277 // It will return an error unless the client is using a "data manager token"
278 // recognized by the Keep services.
279 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
280         url := kc.LocalRoots()[keepServiceUUID]
281         if url == "" {
282                 return nil, ErrNoSuchKeepServer
283         }
284
285         url += "/index"
286         if prefix != "" {
287                 url += "/" + prefix
288         }
289
290         req, err := http.NewRequest("GET", url, nil)
291         if err != nil {
292                 return nil, err
293         }
294
295         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
296         resp, err := kc.Client.Do(req)
297         if err != nil {
298                 return nil, err
299         }
300
301         defer resp.Body.Close()
302
303         if resp.StatusCode != http.StatusOK {
304                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
305         }
306
307         var respBody []byte
308         respBody, err = ioutil.ReadAll(resp.Body)
309         if err != nil {
310                 return nil, err
311         }
312
313         // Got index; verify that it is complete
314         // The response should be "\n" if no locators matched the prefix
315         // Else, it should be a list of locators followed by a blank line
316         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
317                 return nil, ErrIncompleteIndex
318         }
319
320         // Got complete index; strip the trailing newline and send
321         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
322 }
323
324 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
325 // services: uuid -> baseURI.
326 func (kc *KeepClient) LocalRoots() map[string]string {
327         kc.lock.RLock()
328         defer kc.lock.RUnlock()
329         return *kc.localRoots
330 }
331
332 // GatewayRoots() returns the map of Keep remote gateway services:
333 // uuid -> baseURI.
334 func (kc *KeepClient) GatewayRoots() map[string]string {
335         kc.lock.RLock()
336         defer kc.lock.RUnlock()
337         return *kc.gatewayRoots
338 }
339
340 // WritableLocalRoots() returns the map of writable local Keep services:
341 // uuid -> baseURI.
342 func (kc *KeepClient) WritableLocalRoots() map[string]string {
343         kc.lock.RLock()
344         defer kc.lock.RUnlock()
345         return *kc.writableLocalRoots
346 }
347
348 // SetServiceRoots updates the localRoots and gatewayRoots maps,
349 // without risk of disrupting operations that are already in progress.
350 //
351 // The KeepClient makes its own copy of the supplied maps, so the
352 // caller can reuse/modify them after SetServiceRoots returns, but
353 // they should not be modified by any other goroutine while
354 // SetServiceRoots is running.
355 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
356         locals := make(map[string]string)
357         for uuid, root := range newLocals {
358                 locals[uuid] = root
359         }
360
361         writables := make(map[string]string)
362         for uuid, root := range newWritableLocals {
363                 writables[uuid] = root
364         }
365
366         gateways := make(map[string]string)
367         for uuid, root := range newGateways {
368                 gateways[uuid] = root
369         }
370
371         kc.lock.Lock()
372         defer kc.lock.Unlock()
373         kc.localRoots = &locals
374         kc.writableLocalRoots = &writables
375         kc.gatewayRoots = &gateways
376 }
377
378 // getSortedRoots returns a list of base URIs of Keep services, in the
379 // order they should be attempted in order to retrieve content for the
380 // given locator.
381 func (kc *KeepClient) getSortedRoots(locator string) []string {
382         var found []string
383         for _, hint := range strings.Split(locator, "+") {
384                 if len(hint) < 7 || hint[0:2] != "K@" {
385                         // Not a service hint.
386                         continue
387                 }
388                 if len(hint) == 7 {
389                         // +K@abcde means fetch from proxy at
390                         // keep.abcde.arvadosapi.com
391                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
392                 } else if len(hint) == 29 {
393                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
394                         // from gateway with given uuid
395                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
396                                 found = append(found, gwURI)
397                         }
398                         // else this hint is no use to us; carry on.
399                 }
400         }
401         // After trying all usable service hints, fall back to local roots.
402         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
403         return found
404 }
405
406 type Locator struct {
407         Hash  string
408         Size  int      // -1 if data size is not known
409         Hints []string // Including the size hint, if any
410 }
411
412 func (loc *Locator) String() string {
413         s := loc.Hash
414         if len(loc.Hints) > 0 {
415                 s = s + "+" + strings.Join(loc.Hints, "+")
416         }
417         return s
418 }
419
420 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
421
422 func MakeLocator(path string) (*Locator, error) {
423         sm := locatorMatcher.FindStringSubmatch(path)
424         if sm == nil {
425                 return nil, InvalidLocatorError
426         }
427         loc := Locator{Hash: sm[1], Size: -1}
428         if sm[2] != "" {
429                 loc.Hints = strings.Split(sm[3], "+")
430         } else {
431                 loc.Hints = []string{}
432         }
433         if len(loc.Hints) > 0 {
434                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
435                         loc.Size = size
436                 }
437         }
438         return &loc, nil
439 }