Merge branch '8784-dir-listings'
[arvados.git] / sdk / go / keepclient / keepclient.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
6 package keepclient
7
8 import (
9         "bytes"
10         "crypto/md5"
11         "errors"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "net"
16         "net/http"
17         "regexp"
18         "strconv"
19         "strings"
20         "sync"
21         "time"
22
23         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
24         "git.curoverse.com/arvados.git/sdk/go/streamer"
25 )
26
27 // A Keep "block" is 64MB.
28 const BLOCKSIZE = 64 * 1024 * 1024
29
30 var (
31         DefaultRequestTimeout      = 20 * time.Second
32         DefaultConnectTimeout      = 2 * time.Second
33         DefaultTLSHandshakeTimeout = 4 * time.Second
34         DefaultKeepAlive           = 180 * time.Second
35
36         DefaultProxyRequestTimeout      = 300 * time.Second
37         DefaultProxyConnectTimeout      = 30 * time.Second
38         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
39         DefaultProxyKeepAlive           = 120 * time.Second
40 )
41
42 // Error interface with an error and boolean indicating whether the error is temporary
43 type Error interface {
44         error
45         Temporary() bool
46 }
47
48 // multipleResponseError is of type Error
49 type multipleResponseError struct {
50         error
51         isTemp bool
52 }
53
54 func (e *multipleResponseError) Temporary() bool {
55         return e.isTemp
56 }
57
58 // BlockNotFound is a multipleResponseError where isTemp is false
59 var BlockNotFound = &ErrNotFound{multipleResponseError{
60         error:  errors.New("Block not found"),
61         isTemp: false,
62 }}
63
64 // ErrNotFound is a multipleResponseError where isTemp can be true or false
65 type ErrNotFound struct {
66         multipleResponseError
67 }
68
69 type InsufficientReplicasError error
70
71 type OversizeBlockError error
72
73 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
74 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
75 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
76 var InvalidLocatorError = errors.New("Invalid locator")
77
78 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
79 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
80
81 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
82 var ErrIncompleteIndex = errors.New("Got incomplete index")
83
84 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
85 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
86
87 type HTTPClient interface {
88         Do(*http.Request) (*http.Response, error)
89 }
90
91 // Information about Arvados and Keep servers.
92 type KeepClient struct {
93         Arvados            *arvadosclient.ArvadosClient
94         Want_replicas      int
95         localRoots         map[string]string
96         writableLocalRoots map[string]string
97         gatewayRoots       map[string]string
98         lock               sync.RWMutex
99         HTTPClient         HTTPClient
100         Retries            int
101         BlockCache         *BlockCache
102
103         // set to 1 if all writable services are of disk type, otherwise 0
104         replicasPerService int
105
106         // Any non-disk typed services found in the list of keepservers?
107         foundNonDiskSvc bool
108
109         // Disable automatic discovery of keep services
110         disableDiscovery bool
111 }
112
113 // MakeKeepClient creates a new KeepClient, calls
114 // DiscoverKeepServices(), and returns when the client is ready to
115 // use.
116 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
117         kc := New(arv)
118         return kc, kc.discoverServices()
119 }
120
121 // New creates a new KeepClient. Service discovery will occur on the
122 // next read/write operation.
123 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
124         defaultReplicationLevel := 2
125         value, err := arv.Discovery("defaultCollectionReplication")
126         if err == nil {
127                 v, ok := value.(float64)
128                 if ok && v > 0 {
129                         defaultReplicationLevel = int(v)
130                 }
131         }
132         return &KeepClient{
133                 Arvados:       arv,
134                 Want_replicas: defaultReplicationLevel,
135                 Retries:       2,
136         }
137 }
138
139 // Put a block given the block hash, a reader, and the number of bytes
140 // to read from the reader (which must be between 0 and BLOCKSIZE).
141 //
142 // Returns the locator for the written block, the number of replicas
143 // written, and an error.
144 //
145 // Returns an InsufficientReplicasError if 0 <= replicas <
146 // kc.Wants_replicas.
147 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
148         // Buffer for reads from 'r'
149         var bufsize int
150         if dataBytes > 0 {
151                 if dataBytes > BLOCKSIZE {
152                         return "", 0, ErrOversizeBlock
153                 }
154                 bufsize = int(dataBytes)
155         } else {
156                 bufsize = BLOCKSIZE
157         }
158
159         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
160         defer t.Close()
161
162         return kc.putReplicas(hash, t, dataBytes)
163 }
164
165 // PutHB writes a block to Keep. The hash of the bytes is given in
166 // hash, and the data is given in buf.
167 //
168 // Return values are the same as for PutHR.
169 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
170         t := streamer.AsyncStreamFromSlice(buf)
171         defer t.Close()
172         return kc.putReplicas(hash, t, int64(len(buf)))
173 }
174
175 // PutB writes a block to Keep. It computes the hash itself.
176 //
177 // Return values are the same as for PutHR.
178 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
179         hash := fmt.Sprintf("%x", md5.Sum(buffer))
180         return kc.PutHB(hash, buffer)
181 }
182
183 // PutR writes a block to Keep. It first reads all data from r into a buffer
184 // in order to compute the hash.
185 //
186 // Return values are the same as for PutHR.
187 //
188 // If the block hash and data size are known, PutHR is more efficient.
189 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
190         if buffer, err := ioutil.ReadAll(r); err != nil {
191                 return "", 0, err
192         } else {
193                 return kc.PutB(buffer)
194         }
195 }
196
197 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
198         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
199                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
200         }
201
202         var errs []string
203
204         tries_remaining := 1 + kc.Retries
205
206         serversToTry := kc.getSortedRoots(locator)
207
208         numServers := len(serversToTry)
209         count404 := 0
210
211         var retryList []string
212
213         for tries_remaining > 0 {
214                 tries_remaining -= 1
215                 retryList = nil
216
217                 for _, host := range serversToTry {
218                         url := host + "/" + locator
219
220                         req, err := http.NewRequest(method, url, nil)
221                         if err != nil {
222                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
223                                 continue
224                         }
225                         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
226                         resp, err := kc.httpClient().Do(req)
227                         if err != nil {
228                                 // Probably a network error, may be transient,
229                                 // can try again.
230                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
231                                 retryList = append(retryList, host)
232                         } else if resp.StatusCode != http.StatusOK {
233                                 var respbody []byte
234                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
235                                 resp.Body.Close()
236                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
237                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
238
239                                 if resp.StatusCode == 408 ||
240                                         resp.StatusCode == 429 ||
241                                         resp.StatusCode >= 500 {
242                                         // Timeout, too many requests, or other
243                                         // server side failure, transient
244                                         // error, can try again.
245                                         retryList = append(retryList, host)
246                                 } else if resp.StatusCode == 404 {
247                                         count404++
248                                 }
249                         } else {
250                                 // Success.
251                                 if method == "GET" {
252                                         return HashCheckingReader{
253                                                 Reader: resp.Body,
254                                                 Hash:   md5.New(),
255                                                 Check:  locator[0:32],
256                                         }, resp.ContentLength, url, nil
257                                 } else {
258                                         resp.Body.Close()
259                                         return nil, resp.ContentLength, url, nil
260                                 }
261                         }
262
263                 }
264                 serversToTry = retryList
265         }
266         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
267
268         var err error
269         if count404 == numServers {
270                 err = BlockNotFound
271         } else {
272                 err = &ErrNotFound{multipleResponseError{
273                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
274                         isTemp: len(serversToTry) > 0,
275                 }}
276         }
277         return nil, 0, "", err
278 }
279
280 // Get() retrieves a block, given a locator. Returns a reader, the
281 // expected data length, the URL the block is being fetched from, and
282 // an error.
283 //
284 // If the block checksum does not match, the final Read() on the
285 // reader returned by this method will return a BadChecksum error
286 // instead of EOF.
287 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
288         return kc.getOrHead("GET", locator)
289 }
290
291 // Ask() verifies that a block with the given hash is available and
292 // readable, according to at least one Keep service. Unlike Get, it
293 // does not retrieve the data or verify that the data content matches
294 // the hash specified by the locator.
295 //
296 // Returns the data size (content length) reported by the Keep service
297 // and the URI reporting the data size.
298 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
299         _, size, url, err := kc.getOrHead("HEAD", locator)
300         return size, url, err
301 }
302
303 // GetIndex retrieves a list of blocks stored on the given server whose hashes
304 // begin with the given prefix. The returned reader will return an error (other
305 // than EOF) if the complete index cannot be retrieved.
306 //
307 // This is meant to be used only by system components and admin tools.
308 // It will return an error unless the client is using a "data manager token"
309 // recognized by the Keep services.
310 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
311         url := kc.LocalRoots()[keepServiceUUID]
312         if url == "" {
313                 return nil, ErrNoSuchKeepServer
314         }
315
316         url += "/index"
317         if prefix != "" {
318                 url += "/" + prefix
319         }
320
321         req, err := http.NewRequest("GET", url, nil)
322         if err != nil {
323                 return nil, err
324         }
325
326         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
327         resp, err := kc.httpClient().Do(req)
328         if err != nil {
329                 return nil, err
330         }
331
332         defer resp.Body.Close()
333
334         if resp.StatusCode != http.StatusOK {
335                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
336         }
337
338         var respBody []byte
339         respBody, err = ioutil.ReadAll(resp.Body)
340         if err != nil {
341                 return nil, err
342         }
343
344         // Got index; verify that it is complete
345         // The response should be "\n" if no locators matched the prefix
346         // Else, it should be a list of locators followed by a blank line
347         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
348                 return nil, ErrIncompleteIndex
349         }
350
351         // Got complete index; strip the trailing newline and send
352         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
353 }
354
355 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
356 // services: uuid -> baseURI.
357 func (kc *KeepClient) LocalRoots() map[string]string {
358         kc.discoverServices()
359         kc.lock.RLock()
360         defer kc.lock.RUnlock()
361         return kc.localRoots
362 }
363
364 // GatewayRoots() returns the map of Keep remote gateway services:
365 // uuid -> baseURI.
366 func (kc *KeepClient) GatewayRoots() map[string]string {
367         kc.discoverServices()
368         kc.lock.RLock()
369         defer kc.lock.RUnlock()
370         return kc.gatewayRoots
371 }
372
373 // WritableLocalRoots() returns the map of writable local Keep services:
374 // uuid -> baseURI.
375 func (kc *KeepClient) WritableLocalRoots() map[string]string {
376         kc.discoverServices()
377         kc.lock.RLock()
378         defer kc.lock.RUnlock()
379         return kc.writableLocalRoots
380 }
381
382 // SetServiceRoots disables service discovery and updates the
383 // localRoots and gatewayRoots maps, without disrupting operations
384 // that are already in progress.
385 //
386 // The supplied maps must not be modified after calling
387 // SetServiceRoots.
388 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
389         kc.disableDiscovery = true
390         kc.setServiceRoots(locals, writables, gateways)
391 }
392
393 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
394         kc.lock.Lock()
395         defer kc.lock.Unlock()
396         kc.localRoots = locals
397         kc.writableLocalRoots = writables
398         kc.gatewayRoots = gateways
399 }
400
401 // getSortedRoots returns a list of base URIs of Keep services, in the
402 // order they should be attempted in order to retrieve content for the
403 // given locator.
404 func (kc *KeepClient) getSortedRoots(locator string) []string {
405         var found []string
406         for _, hint := range strings.Split(locator, "+") {
407                 if len(hint) < 7 || hint[0:2] != "K@" {
408                         // Not a service hint.
409                         continue
410                 }
411                 if len(hint) == 7 {
412                         // +K@abcde means fetch from proxy at
413                         // keep.abcde.arvadosapi.com
414                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
415                 } else if len(hint) == 29 {
416                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
417                         // from gateway with given uuid
418                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
419                                 found = append(found, gwURI)
420                         }
421                         // else this hint is no use to us; carry on.
422                 }
423         }
424         // After trying all usable service hints, fall back to local roots.
425         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
426         return found
427 }
428
429 func (kc *KeepClient) cache() *BlockCache {
430         if kc.BlockCache != nil {
431                 return kc.BlockCache
432         } else {
433                 return DefaultBlockCache
434         }
435 }
436
437 var (
438         // There are four global http.Client objects for the four
439         // possible permutations of TLS behavior (verify/skip-verify)
440         // and timeout settings (proxy/non-proxy).
441         defaultClient = map[bool]map[bool]HTTPClient{
442                 // defaultClient[false] is used for verified TLS reqs
443                 false: {},
444                 // defaultClient[true] is used for unverified
445                 // (insecure) TLS reqs
446                 true: {},
447         }
448         defaultClientMtx sync.Mutex
449 )
450
451 // httpClient returns the HTTPClient field if it's not nil, otherwise
452 // whichever of the four global http.Client objects is suitable for
453 // the current environment (i.e., TLS verification on/off, keep
454 // services are/aren't proxies).
455 func (kc *KeepClient) httpClient() HTTPClient {
456         if kc.HTTPClient != nil {
457                 return kc.HTTPClient
458         }
459         defaultClientMtx.Lock()
460         defer defaultClientMtx.Unlock()
461         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
462                 return c
463         }
464
465         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
466         if kc.foundNonDiskSvc {
467                 // Use longer timeouts when connecting to a proxy,
468                 // because this usually means the intervening network
469                 // is slower.
470                 requestTimeout = DefaultProxyRequestTimeout
471                 connectTimeout = DefaultProxyConnectTimeout
472                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
473                 keepAlive = DefaultProxyKeepAlive
474         } else {
475                 requestTimeout = DefaultRequestTimeout
476                 connectTimeout = DefaultConnectTimeout
477                 tlsTimeout = DefaultTLSHandshakeTimeout
478                 keepAlive = DefaultKeepAlive
479         }
480
481         transport, ok := http.DefaultTransport.(*http.Transport)
482         if ok {
483                 copy := *transport
484                 transport = &copy
485         } else {
486                 // Evidently the application has replaced
487                 // http.DefaultTransport with a different type, so we
488                 // need to build our own from scratch using the Go 1.8
489                 // defaults.
490                 transport = &http.Transport{
491                         MaxIdleConns:          100,
492                         IdleConnTimeout:       90 * time.Second,
493                         ExpectContinueTimeout: time.Second,
494                 }
495         }
496         transport.DialContext = (&net.Dialer{
497                 Timeout:   connectTimeout,
498                 KeepAlive: keepAlive,
499                 DualStack: true,
500         }).DialContext
501         transport.TLSHandshakeTimeout = tlsTimeout
502         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
503         c := &http.Client{
504                 Timeout:   requestTimeout,
505                 Transport: transport,
506         }
507         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
508         return c
509 }
510
511 type Locator struct {
512         Hash  string
513         Size  int      // -1 if data size is not known
514         Hints []string // Including the size hint, if any
515 }
516
517 func (loc *Locator) String() string {
518         s := loc.Hash
519         if len(loc.Hints) > 0 {
520                 s = s + "+" + strings.Join(loc.Hints, "+")
521         }
522         return s
523 }
524
525 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
526
527 func MakeLocator(path string) (*Locator, error) {
528         sm := locatorMatcher.FindStringSubmatch(path)
529         if sm == nil {
530                 return nil, InvalidLocatorError
531         }
532         loc := Locator{Hash: sm[1], Size: -1}
533         if sm[2] != "" {
534                 loc.Hints = strings.Split(sm[3], "+")
535         } else {
536                 loc.Hints = []string{}
537         }
538         if len(loc.Hints) > 0 {
539                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
540                         loc.Size = size
541                 }
542         }
543         return &loc, nil
544 }