16992: Merge branch 'master' into 16992-disable-pg-pager
[arvados.git] / sdk / go / keepclient / keepclient.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
6 package keepclient
7
8 import (
9         "bytes"
10         "crypto/md5"
11         "errors"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "net"
16         "net/http"
17         "regexp"
18         "strconv"
19         "strings"
20         "sync"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
24         "git.arvados.org/arvados.git/sdk/go/asyncbuf"
25         "git.arvados.org/arvados.git/sdk/go/httpserver"
26 )
27
28 // A Keep "block" is 64MB.
29 const BLOCKSIZE = 64 * 1024 * 1024
30
31 var (
32         DefaultRequestTimeout      = 20 * time.Second
33         DefaultConnectTimeout      = 2 * time.Second
34         DefaultTLSHandshakeTimeout = 4 * time.Second
35         DefaultKeepAlive           = 180 * time.Second
36
37         DefaultProxyRequestTimeout      = 300 * time.Second
38         DefaultProxyConnectTimeout      = 30 * time.Second
39         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
40         DefaultProxyKeepAlive           = 120 * time.Second
41 )
42
43 // Error interface with an error and boolean indicating whether the error is temporary
44 type Error interface {
45         error
46         Temporary() bool
47 }
48
49 // multipleResponseError is of type Error
50 type multipleResponseError struct {
51         error
52         isTemp bool
53 }
54
55 func (e *multipleResponseError) Temporary() bool {
56         return e.isTemp
57 }
58
59 // BlockNotFound is a multipleResponseError where isTemp is false
60 var BlockNotFound = &ErrNotFound{multipleResponseError{
61         error:  errors.New("Block not found"),
62         isTemp: false,
63 }}
64
65 // ErrNotFound is a multipleResponseError where isTemp can be true or false
66 type ErrNotFound struct {
67         multipleResponseError
68 }
69
70 type InsufficientReplicasError error
71
72 type OversizeBlockError error
73
74 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
75 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
76 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
77 var InvalidLocatorError = errors.New("Invalid locator")
78
79 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
80 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
81
82 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
83 var ErrIncompleteIndex = errors.New("Got incomplete index")
84
85 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
86 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
87
88 type HTTPClient interface {
89         Do(*http.Request) (*http.Response, error)
90 }
91
92 // Information about Arvados and Keep servers.
93 type KeepClient struct {
94         Arvados            *arvadosclient.ArvadosClient
95         Want_replicas      int
96         localRoots         map[string]string
97         writableLocalRoots map[string]string
98         gatewayRoots       map[string]string
99         lock               sync.RWMutex
100         HTTPClient         HTTPClient
101         Retries            int
102         BlockCache         *BlockCache
103         RequestID          string
104         StorageClasses     []string
105
106         // set to 1 if all writable services are of disk type, otherwise 0
107         replicasPerService int
108
109         // Any non-disk typed services found in the list of keepservers?
110         foundNonDiskSvc bool
111
112         // Disable automatic discovery of keep services
113         disableDiscovery bool
114 }
115
116 // MakeKeepClient creates a new KeepClient, calls
117 // DiscoverKeepServices(), and returns when the client is ready to
118 // use.
119 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
120         kc := New(arv)
121         return kc, kc.discoverServices()
122 }
123
124 // New creates a new KeepClient. Service discovery will occur on the
125 // next read/write operation.
126 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
127         defaultReplicationLevel := 2
128         value, err := arv.Discovery("defaultCollectionReplication")
129         if err == nil {
130                 v, ok := value.(float64)
131                 if ok && v > 0 {
132                         defaultReplicationLevel = int(v)
133                 }
134         }
135         return &KeepClient{
136                 Arvados:       arv,
137                 Want_replicas: defaultReplicationLevel,
138                 Retries:       2,
139         }
140 }
141
142 // Put a block given the block hash, a reader, and the number of bytes
143 // to read from the reader (which must be between 0 and BLOCKSIZE).
144 //
145 // Returns the locator for the written block, the number of replicas
146 // written, and an error.
147 //
148 // Returns an InsufficientReplicasError if 0 <= replicas <
149 // kc.Wants_replicas.
150 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
151         // Buffer for reads from 'r'
152         var bufsize int
153         if dataBytes > 0 {
154                 if dataBytes > BLOCKSIZE {
155                         return "", 0, ErrOversizeBlock
156                 }
157                 bufsize = int(dataBytes)
158         } else {
159                 bufsize = BLOCKSIZE
160         }
161
162         buf := asyncbuf.NewBuffer(make([]byte, 0, bufsize))
163         go func() {
164                 _, err := io.Copy(buf, HashCheckingReader{r, md5.New(), hash})
165                 buf.CloseWithError(err)
166         }()
167         return kc.putReplicas(hash, buf.NewReader, dataBytes)
168 }
169
170 // PutHB writes a block to Keep. The hash of the bytes is given in
171 // hash, and the data is given in buf.
172 //
173 // Return values are the same as for PutHR.
174 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
175         newReader := func() io.Reader { return bytes.NewBuffer(buf) }
176         return kc.putReplicas(hash, newReader, int64(len(buf)))
177 }
178
179 // PutB writes a block to Keep. It computes the hash itself.
180 //
181 // Return values are the same as for PutHR.
182 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
183         hash := fmt.Sprintf("%x", md5.Sum(buffer))
184         return kc.PutHB(hash, buffer)
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         tries_remaining := 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 tries_remaining > 0 {
229                 tries_remaining -= 1
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 var (
504         // There are four global http.Client objects for the four
505         // possible permutations of TLS behavior (verify/skip-verify)
506         // and timeout settings (proxy/non-proxy).
507         defaultClient = map[bool]map[bool]HTTPClient{
508                 // defaultClient[false] is used for verified TLS reqs
509                 false: {},
510                 // defaultClient[true] is used for unverified
511                 // (insecure) TLS reqs
512                 true: {},
513         }
514         defaultClientMtx sync.Mutex
515 )
516
517 // httpClient returns the HTTPClient field if it's not nil, otherwise
518 // whichever of the four global http.Client objects is suitable for
519 // the current environment (i.e., TLS verification on/off, keep
520 // services are/aren't proxies).
521 func (kc *KeepClient) httpClient() HTTPClient {
522         if kc.HTTPClient != nil {
523                 return kc.HTTPClient
524         }
525         defaultClientMtx.Lock()
526         defer defaultClientMtx.Unlock()
527         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
528                 return c
529         }
530
531         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
532         if kc.foundNonDiskSvc {
533                 // Use longer timeouts when connecting to a proxy,
534                 // because this usually means the intervening network
535                 // is slower.
536                 requestTimeout = DefaultProxyRequestTimeout
537                 connectTimeout = DefaultProxyConnectTimeout
538                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
539                 keepAlive = DefaultProxyKeepAlive
540         } else {
541                 requestTimeout = DefaultRequestTimeout
542                 connectTimeout = DefaultConnectTimeout
543                 tlsTimeout = DefaultTLSHandshakeTimeout
544                 keepAlive = DefaultKeepAlive
545         }
546
547         c := &http.Client{
548                 Timeout: requestTimeout,
549                 // It's not safe to copy *http.DefaultTransport
550                 // because it has a mutex (which might be locked)
551                 // protecting a private map (which might not be nil).
552                 // So we build our own, using the Go 1.12 default
553                 // values, ignoring any changes the application has
554                 // made to http.DefaultTransport.
555                 Transport: &http.Transport{
556                         DialContext: (&net.Dialer{
557                                 Timeout:   connectTimeout,
558                                 KeepAlive: keepAlive,
559                                 DualStack: true,
560                         }).DialContext,
561                         MaxIdleConns:          100,
562                         IdleConnTimeout:       90 * time.Second,
563                         TLSHandshakeTimeout:   tlsTimeout,
564                         ExpectContinueTimeout: 1 * time.Second,
565                         TLSClientConfig:       arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
566                 },
567         }
568         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
569         return c
570 }
571
572 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
573
574 func (kc *KeepClient) getRequestID() string {
575         if kc.RequestID != "" {
576                 return kc.RequestID
577         }
578         return reqIDGen.Next()
579 }
580
581 type Locator struct {
582         Hash  string
583         Size  int      // -1 if data size is not known
584         Hints []string // Including the size hint, if any
585 }
586
587 func (loc *Locator) String() string {
588         s := loc.Hash
589         if len(loc.Hints) > 0 {
590                 s = s + "+" + strings.Join(loc.Hints, "+")
591         }
592         return s
593 }
594
595 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
596
597 func MakeLocator(path string) (*Locator, error) {
598         sm := locatorMatcher.FindStringSubmatch(path)
599         if sm == nil {
600                 return nil, InvalidLocatorError
601         }
602         loc := Locator{Hash: sm[1], Size: -1}
603         if sm[2] != "" {
604                 loc.Hints = strings.Split(sm[3], "+")
605         } else {
606                 loc.Hints = []string{}
607         }
608         if len(loc.Hints) > 0 {
609                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
610                         loc.Size = size
611                 }
612         }
613         return &loc, nil
614 }