Merge branch '14262-remote-container' refs #14262
[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.curoverse.com/arvados.git/sdk/go/arvadosclient"
24         "git.curoverse.com/arvados.git/sdk/go/asyncbuf"
25         "git.curoverse.com/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         if buffer, err := ioutil.ReadAll(r); err != nil {
195                 return "", 0, err
196         } else {
197                 return kc.PutB(buffer)
198         }
199 }
200
201 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
202         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
203                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", 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                         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
241                         req.Header.Add("X-Request-Id", reqid)
242                         resp, err := kc.httpClient().Do(req)
243                         if err != nil {
244                                 // Probably a network error, may be transient,
245                                 // can try again.
246                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
247                                 retryList = append(retryList, host)
248                                 continue
249                         }
250                         if resp.StatusCode != http.StatusOK {
251                                 var respbody []byte
252                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
253                                 resp.Body.Close()
254                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
255                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
256
257                                 if resp.StatusCode == 408 ||
258                                         resp.StatusCode == 429 ||
259                                         resp.StatusCode >= 500 {
260                                         // Timeout, too many requests, or other
261                                         // server side failure, transient
262                                         // error, can try again.
263                                         retryList = append(retryList, host)
264                                 } else if resp.StatusCode == 404 {
265                                         count404++
266                                 }
267                                 continue
268                         }
269                         if expectLength < 0 {
270                                 if resp.ContentLength < 0 {
271                                         resp.Body.Close()
272                                         return nil, 0, "", fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
273                                 }
274                                 expectLength = resp.ContentLength
275                         } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
276                                 resp.Body.Close()
277                                 return nil, 0, "", fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
278                         }
279                         // Success
280                         if method == "GET" {
281                                 return HashCheckingReader{
282                                         Reader: resp.Body,
283                                         Hash:   md5.New(),
284                                         Check:  locator[0:32],
285                                 }, expectLength, url, nil
286                         } else {
287                                 resp.Body.Close()
288                                 return nil, expectLength, url, nil
289                         }
290                 }
291                 serversToTry = retryList
292         }
293         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
294
295         var err error
296         if count404 == numServers {
297                 err = BlockNotFound
298         } else {
299                 err = &ErrNotFound{multipleResponseError{
300                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
301                         isTemp: len(serversToTry) > 0,
302                 }}
303         }
304         return nil, 0, "", err
305 }
306
307 // Get() retrieves a block, given a locator. Returns a reader, the
308 // expected data length, the URL the block is being fetched from, and
309 // an error.
310 //
311 // If the block checksum does not match, the final Read() on the
312 // reader returned by this method will return a BadChecksum error
313 // instead of EOF.
314 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
315         return kc.getOrHead("GET", locator)
316 }
317
318 // ReadAt() retrieves a portion of block from the cache if it's
319 // present, otherwise from the network.
320 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
321         return kc.cache().ReadAt(kc, locator, p, off)
322 }
323
324 // Ask() verifies that a block with the given hash is available and
325 // readable, according to at least one Keep service. Unlike Get, it
326 // does not retrieve the data or verify that the data content matches
327 // the hash specified by the locator.
328 //
329 // Returns the data size (content length) reported by the Keep service
330 // and the URI reporting the data size.
331 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
332         _, size, url, err := kc.getOrHead("HEAD", locator)
333         return size, url, err
334 }
335
336 // GetIndex retrieves a list of blocks stored on the given server whose hashes
337 // begin with the given prefix. The returned reader will return an error (other
338 // than EOF) if the complete index cannot be retrieved.
339 //
340 // This is meant to be used only by system components and admin tools.
341 // It will return an error unless the client is using a "data manager token"
342 // recognized by the Keep services.
343 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
344         url := kc.LocalRoots()[keepServiceUUID]
345         if url == "" {
346                 return nil, ErrNoSuchKeepServer
347         }
348
349         url += "/index"
350         if prefix != "" {
351                 url += "/" + prefix
352         }
353
354         req, err := http.NewRequest("GET", url, nil)
355         if err != nil {
356                 return nil, err
357         }
358
359         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
360         req.Header.Set("X-Request-Id", kc.getRequestID())
361         resp, err := kc.httpClient().Do(req)
362         if err != nil {
363                 return nil, err
364         }
365
366         defer resp.Body.Close()
367
368         if resp.StatusCode != http.StatusOK {
369                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
370         }
371
372         var respBody []byte
373         respBody, err = ioutil.ReadAll(resp.Body)
374         if err != nil {
375                 return nil, err
376         }
377
378         // Got index; verify that it is complete
379         // The response should be "\n" if no locators matched the prefix
380         // Else, it should be a list of locators followed by a blank line
381         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
382                 return nil, ErrIncompleteIndex
383         }
384
385         // Got complete index; strip the trailing newline and send
386         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
387 }
388
389 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
390 // services: uuid -> baseURI.
391 func (kc *KeepClient) LocalRoots() map[string]string {
392         kc.discoverServices()
393         kc.lock.RLock()
394         defer kc.lock.RUnlock()
395         return kc.localRoots
396 }
397
398 // GatewayRoots() returns the map of Keep remote gateway services:
399 // uuid -> baseURI.
400 func (kc *KeepClient) GatewayRoots() map[string]string {
401         kc.discoverServices()
402         kc.lock.RLock()
403         defer kc.lock.RUnlock()
404         return kc.gatewayRoots
405 }
406
407 // WritableLocalRoots() returns the map of writable local Keep services:
408 // uuid -> baseURI.
409 func (kc *KeepClient) WritableLocalRoots() map[string]string {
410         kc.discoverServices()
411         kc.lock.RLock()
412         defer kc.lock.RUnlock()
413         return kc.writableLocalRoots
414 }
415
416 // SetServiceRoots disables service discovery and updates the
417 // localRoots and gatewayRoots maps, without disrupting operations
418 // that are already in progress.
419 //
420 // The supplied maps must not be modified after calling
421 // SetServiceRoots.
422 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
423         kc.disableDiscovery = true
424         kc.setServiceRoots(locals, writables, gateways)
425 }
426
427 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
428         kc.lock.Lock()
429         defer kc.lock.Unlock()
430         kc.localRoots = locals
431         kc.writableLocalRoots = writables
432         kc.gatewayRoots = gateways
433 }
434
435 // getSortedRoots returns a list of base URIs of Keep services, in the
436 // order they should be attempted in order to retrieve content for the
437 // given locator.
438 func (kc *KeepClient) getSortedRoots(locator string) []string {
439         var found []string
440         for _, hint := range strings.Split(locator, "+") {
441                 if len(hint) < 7 || hint[0:2] != "K@" {
442                         // Not a service hint.
443                         continue
444                 }
445                 if len(hint) == 7 {
446                         // +K@abcde means fetch from proxy at
447                         // keep.abcde.arvadosapi.com
448                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
449                 } else if len(hint) == 29 {
450                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
451                         // from gateway with given uuid
452                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
453                                 found = append(found, gwURI)
454                         }
455                         // else this hint is no use to us; carry on.
456                 }
457         }
458         // After trying all usable service hints, fall back to local roots.
459         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
460         return found
461 }
462
463 func (kc *KeepClient) cache() *BlockCache {
464         if kc.BlockCache != nil {
465                 return kc.BlockCache
466         } else {
467                 return DefaultBlockCache
468         }
469 }
470
471 func (kc *KeepClient) ClearBlockCache() {
472         kc.cache().Clear()
473 }
474
475 var (
476         // There are four global http.Client objects for the four
477         // possible permutations of TLS behavior (verify/skip-verify)
478         // and timeout settings (proxy/non-proxy).
479         defaultClient = map[bool]map[bool]HTTPClient{
480                 // defaultClient[false] is used for verified TLS reqs
481                 false: {},
482                 // defaultClient[true] is used for unverified
483                 // (insecure) TLS reqs
484                 true: {},
485         }
486         defaultClientMtx sync.Mutex
487 )
488
489 // httpClient returns the HTTPClient field if it's not nil, otherwise
490 // whichever of the four global http.Client objects is suitable for
491 // the current environment (i.e., TLS verification on/off, keep
492 // services are/aren't proxies).
493 func (kc *KeepClient) httpClient() HTTPClient {
494         if kc.HTTPClient != nil {
495                 return kc.HTTPClient
496         }
497         defaultClientMtx.Lock()
498         defer defaultClientMtx.Unlock()
499         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
500                 return c
501         }
502
503         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
504         if kc.foundNonDiskSvc {
505                 // Use longer timeouts when connecting to a proxy,
506                 // because this usually means the intervening network
507                 // is slower.
508                 requestTimeout = DefaultProxyRequestTimeout
509                 connectTimeout = DefaultProxyConnectTimeout
510                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
511                 keepAlive = DefaultProxyKeepAlive
512         } else {
513                 requestTimeout = DefaultRequestTimeout
514                 connectTimeout = DefaultConnectTimeout
515                 tlsTimeout = DefaultTLSHandshakeTimeout
516                 keepAlive = DefaultKeepAlive
517         }
518
519         transport, ok := http.DefaultTransport.(*http.Transport)
520         if ok {
521                 copy := *transport
522                 transport = &copy
523         } else {
524                 // Evidently the application has replaced
525                 // http.DefaultTransport with a different type, so we
526                 // need to build our own from scratch using the Go 1.8
527                 // defaults.
528                 transport = &http.Transport{
529                         MaxIdleConns:          100,
530                         IdleConnTimeout:       90 * time.Second,
531                         ExpectContinueTimeout: time.Second,
532                 }
533         }
534         transport.DialContext = (&net.Dialer{
535                 Timeout:   connectTimeout,
536                 KeepAlive: keepAlive,
537                 DualStack: true,
538         }).DialContext
539         transport.TLSHandshakeTimeout = tlsTimeout
540         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
541         c := &http.Client{
542                 Timeout:   requestTimeout,
543                 Transport: transport,
544         }
545         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
546         return c
547 }
548
549 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
550
551 func (kc *KeepClient) getRequestID() string {
552         if kc.RequestID != "" {
553                 return kc.RequestID
554         } else {
555                 return reqIDGen.Next()
556         }
557 }
558
559 type Locator struct {
560         Hash  string
561         Size  int      // -1 if data size is not known
562         Hints []string // Including the size hint, if any
563 }
564
565 func (loc *Locator) String() string {
566         s := loc.Hash
567         if len(loc.Hints) > 0 {
568                 s = s + "+" + strings.Join(loc.Hints, "+")
569         }
570         return s
571 }
572
573 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
574
575 func MakeLocator(path string) (*Locator, error) {
576         sm := locatorMatcher.FindStringSubmatch(path)
577         if sm == nil {
578                 return nil, InvalidLocatorError
579         }
580         loc := Locator{Hash: sm[1], Size: -1}
581         if sm[2] != "" {
582                 loc.Hints = strings.Split(sm[3], "+")
583         } else {
584                 loc.Hints = []string{}
585         }
586         if len(loc.Hints) > 0 {
587                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
588                         loc.Size = size
589                 }
590         }
591         return &loc, nil
592 }