17755: Merge branch 'main' into 17755-add-singularity-to-compute-image
[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
112         // set to 1 if all writable services are of disk type, otherwise 0
113         replicasPerService int
114
115         // Any non-disk typed services found in the list of keepservers?
116         foundNonDiskSvc bool
117
118         // Disable automatic discovery of keep services
119         disableDiscovery bool
120 }
121
122 // MakeKeepClient creates a new KeepClient, calls
123 // DiscoverKeepServices(), and returns when the client is ready to
124 // use.
125 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
126         kc := New(arv)
127         return kc, kc.discoverServices()
128 }
129
130 // New creates a new KeepClient. Service discovery will occur on the
131 // next read/write operation.
132 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
133         defaultReplicationLevel := 2
134         value, err := arv.Discovery("defaultCollectionReplication")
135         if err == nil {
136                 v, ok := value.(float64)
137                 if ok && v > 0 {
138                         defaultReplicationLevel = int(v)
139                 }
140         }
141         return &KeepClient{
142                 Arvados:       arv,
143                 Want_replicas: defaultReplicationLevel,
144                 Retries:       2,
145         }
146 }
147
148 // PutHR puts a block given the block hash, a reader, and the number of bytes
149 // to read from the reader (which must be between 0 and BLOCKSIZE).
150 //
151 // Returns the locator for the written block, the number of replicas
152 // written, and an error.
153 //
154 // Returns an InsufficientReplicasError if 0 <= replicas <
155 // kc.Wants_replicas.
156 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
157         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
158                 Hash:     hash,
159                 Reader:   r,
160                 DataSize: int(dataBytes),
161         })
162         return resp.Locator, resp.Replicas, err
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         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
171                 Hash: hash,
172                 Data: buf,
173         })
174         return resp.Locator, resp.Replicas, err
175 }
176
177 // PutB writes a block to Keep. It computes the hash itself.
178 //
179 // Return values are the same as for PutHR.
180 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
181         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
182                 Data: buffer,
183         })
184         return resp.Locator, resp.Replicas, err
185 }
186
187 // PutR writes a block to Keep. It first reads all data from r into a buffer
188 // in order to compute the hash.
189 //
190 // Return values are the same as for PutHR.
191 //
192 // If the block hash and data size are known, PutHR is more efficient.
193 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
194         buffer, err := ioutil.ReadAll(r)
195         if err != nil {
196                 return "", 0, err
197         }
198         return kc.PutB(buffer)
199 }
200
201 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
202         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
203                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
204         }
205
206         reqid := kc.getRequestID()
207
208         var expectLength int64
209         if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
210                 expectLength = -1
211         } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
212                 expectLength = -1
213         } else {
214                 expectLength = n
215         }
216
217         var errs []string
218
219         triesRemaining := 1 + kc.Retries
220
221         serversToTry := kc.getSortedRoots(locator)
222
223         numServers := len(serversToTry)
224         count404 := 0
225
226         var retryList []string
227
228         for triesRemaining > 0 {
229                 triesRemaining--
230                 retryList = nil
231
232                 for _, host := range serversToTry {
233                         url := host + "/" + locator
234
235                         req, err := http.NewRequest(method, url, nil)
236                         if err != nil {
237                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
238                                 continue
239                         }
240                         for k, v := range header {
241                                 req.Header[k] = append([]string(nil), v...)
242                         }
243                         if req.Header.Get("Authorization") == "" {
244                                 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
245                         }
246                         if req.Header.Get("X-Request-Id") == "" {
247                                 req.Header.Set("X-Request-Id", reqid)
248                         }
249                         resp, err := kc.httpClient().Do(req)
250                         if err != nil {
251                                 // Probably a network error, may be transient,
252                                 // can try again.
253                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
254                                 retryList = append(retryList, host)
255                                 continue
256                         }
257                         if resp.StatusCode != http.StatusOK {
258                                 var respbody []byte
259                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
260                                 resp.Body.Close()
261                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
262                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
263
264                                 if resp.StatusCode == 408 ||
265                                         resp.StatusCode == 429 ||
266                                         resp.StatusCode >= 500 {
267                                         // Timeout, too many requests, or other
268                                         // server side failure, transient
269                                         // error, can try again.
270                                         retryList = append(retryList, host)
271                                 } else if resp.StatusCode == 404 {
272                                         count404++
273                                 }
274                                 continue
275                         }
276                         if expectLength < 0 {
277                                 if resp.ContentLength < 0 {
278                                         resp.Body.Close()
279                                         return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
280                                 }
281                                 expectLength = resp.ContentLength
282                         } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
283                                 resp.Body.Close()
284                                 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
285                         }
286                         // Success
287                         if method == "GET" {
288                                 return HashCheckingReader{
289                                         Reader: resp.Body,
290                                         Hash:   md5.New(),
291                                         Check:  locator[0:32],
292                                 }, expectLength, url, resp.Header, nil
293                         }
294                         resp.Body.Close()
295                         return nil, expectLength, url, resp.Header, nil
296                 }
297                 serversToTry = retryList
298         }
299         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
300
301         var err error
302         if count404 == numServers {
303                 err = BlockNotFound
304         } else {
305                 err = &ErrNotFound{multipleResponseError{
306                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
307                         isTemp: len(serversToTry) > 0,
308                 }}
309         }
310         return nil, 0, "", nil, err
311 }
312
313 // LocalLocator returns a locator equivalent to the one supplied, but
314 // with a valid signature from the local cluster. If the given locator
315 // already has a local signature, it is returned unchanged.
316 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
317         if !strings.Contains(locator, "+R") {
318                 // Either it has +A, or it's unsigned and we assume
319                 // it's a local locator on a site with signatures
320                 // disabled.
321                 return locator, nil
322         }
323         sighdr := fmt.Sprintf("local, time=%s", time.Now().UTC().Format(time.RFC3339))
324         _, _, url, hdr, err := kc.getOrHead("HEAD", locator, http.Header{"X-Keep-Signature": []string{sighdr}})
325         if err != nil {
326                 return "", err
327         }
328         loc := hdr.Get("X-Keep-Locator")
329         if loc == "" {
330                 return "", fmt.Errorf("missing X-Keep-Locator header in HEAD response from %s", url)
331         }
332         return loc, nil
333 }
334
335 // Get retrieves a block, given a locator. Returns a reader, the
336 // expected data length, the URL the block is being fetched from, and
337 // an error.
338 //
339 // If the block checksum does not match, the final Read() on the
340 // reader returned by this method will return a BadChecksum error
341 // instead of EOF.
342 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
343         rdr, size, url, _, err := kc.getOrHead("GET", locator, nil)
344         return rdr, size, url, err
345 }
346
347 // ReadAt retrieves a portion of block from the cache if it's
348 // present, otherwise from the network.
349 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
350         return kc.cache().ReadAt(kc, locator, p, off)
351 }
352
353 // Ask verifies that a block with the given hash is available and
354 // readable, according to at least one Keep service. Unlike Get, it
355 // does not retrieve the data or verify that the data content matches
356 // the hash specified by the locator.
357 //
358 // Returns the data size (content length) reported by the Keep service
359 // and the URI reporting the data size.
360 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
361         _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
362         return size, url, err
363 }
364
365 // GetIndex retrieves a list of blocks stored on the given server whose hashes
366 // begin with the given prefix. The returned reader will return an error (other
367 // than EOF) if the complete index cannot be retrieved.
368 //
369 // This is meant to be used only by system components and admin tools.
370 // It will return an error unless the client is using a "data manager token"
371 // recognized by the Keep services.
372 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
373         url := kc.LocalRoots()[keepServiceUUID]
374         if url == "" {
375                 return nil, ErrNoSuchKeepServer
376         }
377
378         url += "/index"
379         if prefix != "" {
380                 url += "/" + prefix
381         }
382
383         req, err := http.NewRequest("GET", url, nil)
384         if err != nil {
385                 return nil, err
386         }
387
388         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
389         req.Header.Set("X-Request-Id", kc.getRequestID())
390         resp, err := kc.httpClient().Do(req)
391         if err != nil {
392                 return nil, err
393         }
394
395         defer resp.Body.Close()
396
397         if resp.StatusCode != http.StatusOK {
398                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
399         }
400
401         var respBody []byte
402         respBody, err = ioutil.ReadAll(resp.Body)
403         if err != nil {
404                 return nil, err
405         }
406
407         // Got index; verify that it is complete
408         // The response should be "\n" if no locators matched the prefix
409         // Else, it should be a list of locators followed by a blank line
410         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
411                 return nil, ErrIncompleteIndex
412         }
413
414         // Got complete index; strip the trailing newline and send
415         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
416 }
417
418 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
419 // services: uuid -> baseURI.
420 func (kc *KeepClient) LocalRoots() map[string]string {
421         kc.discoverServices()
422         kc.lock.RLock()
423         defer kc.lock.RUnlock()
424         return kc.localRoots
425 }
426
427 // GatewayRoots returns the map of Keep remote gateway services:
428 // uuid -> baseURI.
429 func (kc *KeepClient) GatewayRoots() map[string]string {
430         kc.discoverServices()
431         kc.lock.RLock()
432         defer kc.lock.RUnlock()
433         return kc.gatewayRoots
434 }
435
436 // WritableLocalRoots returns the map of writable local Keep services:
437 // uuid -> baseURI.
438 func (kc *KeepClient) WritableLocalRoots() map[string]string {
439         kc.discoverServices()
440         kc.lock.RLock()
441         defer kc.lock.RUnlock()
442         return kc.writableLocalRoots
443 }
444
445 // SetServiceRoots disables service discovery and updates the
446 // localRoots and gatewayRoots maps, without disrupting operations
447 // that are already in progress.
448 //
449 // The supplied maps must not be modified after calling
450 // SetServiceRoots.
451 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
452         kc.disableDiscovery = true
453         kc.setServiceRoots(locals, writables, gateways)
454 }
455
456 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
457         kc.lock.Lock()
458         defer kc.lock.Unlock()
459         kc.localRoots = locals
460         kc.writableLocalRoots = writables
461         kc.gatewayRoots = gateways
462 }
463
464 // getSortedRoots returns a list of base URIs of Keep services, in the
465 // order they should be attempted in order to retrieve content for the
466 // given locator.
467 func (kc *KeepClient) getSortedRoots(locator string) []string {
468         var found []string
469         for _, hint := range strings.Split(locator, "+") {
470                 if len(hint) < 7 || hint[0:2] != "K@" {
471                         // Not a service hint.
472                         continue
473                 }
474                 if len(hint) == 7 {
475                         // +K@abcde means fetch from proxy at
476                         // keep.abcde.arvadosapi.com
477                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
478                 } else if len(hint) == 29 {
479                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
480                         // from gateway with given uuid
481                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
482                                 found = append(found, gwURI)
483                         }
484                         // else this hint is no use to us; carry on.
485                 }
486         }
487         // After trying all usable service hints, fall back to local roots.
488         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
489         return found
490 }
491
492 func (kc *KeepClient) cache() *BlockCache {
493         if kc.BlockCache != nil {
494                 return kc.BlockCache
495         }
496         return DefaultBlockCache
497 }
498
499 func (kc *KeepClient) ClearBlockCache() {
500         kc.cache().Clear()
501 }
502
503 func (kc *KeepClient) SetStorageClasses(sc []string) {
504         // make a copy so the caller can't mess with it.
505         kc.StorageClasses = append([]string{}, sc...)
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 }