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