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