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