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