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