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