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