21023: Add exponential-backoff delay between keepclient retries.
[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         "bufio"
11         "bytes"
12         "context"
13         "crypto/md5"
14         "errors"
15         "fmt"
16         "io"
17         "io/ioutil"
18         "math/rand"
19         "net"
20         "net/http"
21         "os"
22         "path/filepath"
23         "regexp"
24         "strconv"
25         "strings"
26         "sync"
27         "time"
28
29         "git.arvados.org/arvados.git/sdk/go/arvados"
30         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
31         "git.arvados.org/arvados.git/sdk/go/httpserver"
32 )
33
34 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
35 const BLOCKSIZE = 64 * 1024 * 1024
36
37 var (
38         DefaultRequestTimeout      = 20 * time.Second
39         DefaultConnectTimeout      = 2 * time.Second
40         DefaultTLSHandshakeTimeout = 4 * time.Second
41         DefaultKeepAlive           = 180 * time.Second
42
43         DefaultProxyRequestTimeout      = 300 * time.Second
44         DefaultProxyConnectTimeout      = 30 * time.Second
45         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
46         DefaultProxyKeepAlive           = 120 * time.Second
47
48         DefaultRetryDelay = 2 * time.Second // see KeepClient.RetryDelay
49
50         rootCacheDir = "/var/cache/arvados/keep"
51         userCacheDir = ".cache/arvados/keep" // relative to HOME
52 )
53
54 // Error interface with an error and boolean indicating whether the error is temporary
55 type Error interface {
56         error
57         Temporary() bool
58 }
59
60 // multipleResponseError is of type Error
61 type multipleResponseError struct {
62         error
63         isTemp bool
64 }
65
66 func (e *multipleResponseError) Temporary() bool {
67         return e.isTemp
68 }
69
70 // BlockNotFound is a multipleResponseError where isTemp is false
71 var BlockNotFound = &ErrNotFound{multipleResponseError{
72         error:  errors.New("Block not found"),
73         isTemp: false,
74 }}
75
76 // ErrNotFound is a multipleResponseError where isTemp can be true or false
77 type ErrNotFound struct {
78         multipleResponseError
79 }
80
81 type InsufficientReplicasError struct{ error }
82
83 type OversizeBlockError struct{ error }
84
85 var ErrOversizeBlock = OversizeBlockError{error: errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")")}
86 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
87 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
88 var InvalidLocatorError = errors.New("Invalid locator")
89
90 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
91 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
92
93 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
94 var ErrIncompleteIndex = errors.New("Got incomplete index")
95
96 const (
97         XKeepDesiredReplicas         = "X-Keep-Desired-Replicas"
98         XKeepReplicasStored          = "X-Keep-Replicas-Stored"
99         XKeepStorageClasses          = "X-Keep-Storage-Classes"
100         XKeepStorageClassesConfirmed = "X-Keep-Storage-Classes-Confirmed"
101 )
102
103 type HTTPClient interface {
104         Do(*http.Request) (*http.Response, error)
105 }
106
107 const DiskCacheDisabled = arvados.ByteSizeOrPercent(1)
108
109 // KeepClient holds information about Arvados and Keep servers.
110 type KeepClient struct {
111         Arvados            *arvadosclient.ArvadosClient
112         Want_replicas      int
113         localRoots         map[string]string
114         writableLocalRoots map[string]string
115         gatewayRoots       map[string]string
116         lock               sync.RWMutex
117         HTTPClient         HTTPClient
118
119         // Number of times to automatically retry a read/write
120         // operation after a transient failure.
121         Retries int
122
123         // Initial delay after first attempt, used when automatic
124         // retry is invoked. If zero, DefaultRetryDelay is used.
125         // Delays after subsequent attempts are increased by a random
126         // factor between 1.75x and 2x, up to a maximum of 10x the
127         // initial delay.
128         RetryDelay time.Duration
129
130         RequestID             string
131         StorageClasses        []string
132         DefaultStorageClasses []string                  // Set by cluster's exported config
133         DiskCacheSize         arvados.ByteSizeOrPercent // See also DiskCacheDisabled
134
135         // set to 1 if all writable services are of disk type, otherwise 0
136         replicasPerService int
137
138         // Any non-disk typed services found in the list of keepservers?
139         foundNonDiskSvc bool
140
141         // Disable automatic discovery of keep services
142         disableDiscovery bool
143
144         gatewayStack arvados.KeepGateway
145 }
146
147 func (kc *KeepClient) Clone() *KeepClient {
148         kc.lock.Lock()
149         defer kc.lock.Unlock()
150         return &KeepClient{
151                 Arvados:               kc.Arvados,
152                 Want_replicas:         kc.Want_replicas,
153                 localRoots:            kc.localRoots,
154                 writableLocalRoots:    kc.writableLocalRoots,
155                 gatewayRoots:          kc.gatewayRoots,
156                 HTTPClient:            kc.HTTPClient,
157                 Retries:               kc.Retries,
158                 RetryDelay:            kc.RetryDelay,
159                 RequestID:             kc.RequestID,
160                 StorageClasses:        kc.StorageClasses,
161                 DefaultStorageClasses: kc.DefaultStorageClasses,
162                 DiskCacheSize:         kc.DiskCacheSize,
163                 replicasPerService:    kc.replicasPerService,
164                 foundNonDiskSvc:       kc.foundNonDiskSvc,
165                 disableDiscovery:      kc.disableDiscovery,
166         }
167 }
168
169 func (kc *KeepClient) loadDefaultClasses() error {
170         scData, err := kc.Arvados.ClusterConfig("StorageClasses")
171         if err != nil {
172                 return err
173         }
174         classes := scData.(map[string]interface{})
175         for scName := range classes {
176                 scConf, _ := classes[scName].(map[string]interface{})
177                 isDefault, ok := scConf["Default"].(bool)
178                 if ok && isDefault {
179                         kc.DefaultStorageClasses = append(kc.DefaultStorageClasses, scName)
180                 }
181         }
182         return nil
183 }
184
185 // MakeKeepClient creates a new KeepClient, loads default storage classes, calls
186 // DiscoverKeepServices(), and returns when the client is ready to
187 // use.
188 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
189         kc := New(arv)
190         return kc, kc.discoverServices()
191 }
192
193 // New creates a new KeepClient. Service discovery will occur on the
194 // next read/write operation.
195 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
196         defaultReplicationLevel := 2
197         value, err := arv.Discovery("defaultCollectionReplication")
198         if err == nil {
199                 v, ok := value.(float64)
200                 if ok && v > 0 {
201                         defaultReplicationLevel = int(v)
202                 }
203         }
204         kc := &KeepClient{
205                 Arvados:       arv,
206                 Want_replicas: defaultReplicationLevel,
207                 Retries:       2,
208         }
209         err = kc.loadDefaultClasses()
210         if err != nil {
211                 DebugPrintf("DEBUG: Unable to load the default storage classes cluster config")
212         }
213         return kc
214 }
215
216 // PutHR puts a block given the block hash, a reader, and the number of bytes
217 // to read from the reader (which must be between 0 and BLOCKSIZE).
218 //
219 // Returns the locator for the written block, the number of replicas
220 // written, and an error.
221 //
222 // Returns an InsufficientReplicasError if 0 <= replicas <
223 // kc.Wants_replicas.
224 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
225         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
226                 Hash:     hash,
227                 Reader:   r,
228                 DataSize: int(dataBytes),
229         })
230         return resp.Locator, resp.Replicas, err
231 }
232
233 // PutHB writes a block to Keep. The hash of the bytes is given in
234 // hash, and the data is given in buf.
235 //
236 // Return values are the same as for PutHR.
237 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
238         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
239                 Hash: hash,
240                 Data: buf,
241         })
242         return resp.Locator, resp.Replicas, err
243 }
244
245 // PutB writes a block to Keep. It computes the hash itself.
246 //
247 // Return values are the same as for PutHR.
248 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
249         resp, err := kc.BlockWrite(context.Background(), arvados.BlockWriteOptions{
250                 Data: buffer,
251         })
252         return resp.Locator, resp.Replicas, err
253 }
254
255 // PutR writes a block to Keep. It first reads all data from r into a buffer
256 // in order to compute the hash.
257 //
258 // Return values are the same as for PutHR.
259 //
260 // If the block hash and data size are known, PutHR is more efficient.
261 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
262         buffer, err := ioutil.ReadAll(r)
263         if err != nil {
264                 return "", 0, err
265         }
266         return kc.PutB(buffer)
267 }
268
269 func (kc *KeepClient) getOrHead(method string, locator string, header http.Header) (io.ReadCloser, int64, string, http.Header, error) {
270         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
271                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil, nil
272         }
273
274         reqid := kc.getRequestID()
275
276         var expectLength int64
277         if parts := strings.SplitN(locator, "+", 3); len(parts) < 2 {
278                 expectLength = -1
279         } else if n, err := strconv.ParseInt(parts[1], 10, 64); err != nil {
280                 expectLength = -1
281         } else {
282                 expectLength = n
283         }
284
285         var errs []string
286
287         retryDelay := kc.RetryDelay
288         if retryDelay < 1 {
289                 retryDelay = DefaultRetryDelay
290         }
291         maxRetryDelay := retryDelay * 10
292         triesRemaining := 1 + kc.Retries
293
294         serversToTry := kc.getSortedRoots(locator)
295
296         numServers := len(serversToTry)
297         count404 := 0
298
299         var retryList []string
300
301         for triesRemaining > 0 {
302                 triesRemaining--
303                 retryList = nil
304
305                 for _, host := range serversToTry {
306                         url := host + "/" + locator
307
308                         req, err := http.NewRequest(method, url, nil)
309                         if err != nil {
310                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
311                                 continue
312                         }
313                         for k, v := range header {
314                                 req.Header[k] = append([]string(nil), v...)
315                         }
316                         if req.Header.Get("Authorization") == "" {
317                                 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
318                         }
319                         if req.Header.Get("X-Request-Id") == "" {
320                                 req.Header.Set("X-Request-Id", reqid)
321                         }
322                         resp, err := kc.httpClient().Do(req)
323                         if err != nil {
324                                 // Probably a network error, may be transient,
325                                 // can try again.
326                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
327                                 retryList = append(retryList, host)
328                                 continue
329                         }
330                         if resp.StatusCode != http.StatusOK {
331                                 var respbody []byte
332                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
333                                 resp.Body.Close()
334                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
335                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
336
337                                 if resp.StatusCode == 408 ||
338                                         resp.StatusCode == 429 ||
339                                         resp.StatusCode >= 500 {
340                                         // Timeout, too many requests, or other
341                                         // server side failure, transient
342                                         // error, can try again.
343                                         retryList = append(retryList, host)
344                                 } else if resp.StatusCode == 404 {
345                                         count404++
346                                 }
347                                 continue
348                         }
349                         if expectLength < 0 {
350                                 if resp.ContentLength < 0 {
351                                         resp.Body.Close()
352                                         return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
353                                 }
354                                 expectLength = resp.ContentLength
355                         } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
356                                 resp.Body.Close()
357                                 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
358                         }
359                         // Success
360                         if method == "GET" {
361                                 return HashCheckingReader{
362                                         Reader: resp.Body,
363                                         Hash:   md5.New(),
364                                         Check:  locator[0:32],
365                                 }, expectLength, url, resp.Header, nil
366                         }
367                         resp.Body.Close()
368                         return nil, expectLength, url, resp.Header, nil
369                 }
370                 serversToTry = retryList
371                 if len(serversToTry) > 0 && triesRemaining > 0 {
372                         time.Sleep(retryDelay)
373                         // Increase delay by a random factor between
374                         // 1.75x and 2x
375                         retryDelay = time.Duration((2 - rand.Float64()/4) * float64(retryDelay))
376                         if retryDelay > maxRetryDelay {
377                                 retryDelay = maxRetryDelay
378                         }
379                 }
380         }
381         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
382
383         var err error
384         if count404 == numServers {
385                 err = BlockNotFound
386         } else {
387                 err = &ErrNotFound{multipleResponseError{
388                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
389                         isTemp: len(serversToTry) > 0,
390                 }}
391         }
392         return nil, 0, "", nil, err
393 }
394
395 // attempt to create dir/subdir/ and its parents, up to but not
396 // including dir itself, using mode 0700.
397 func makedirs(dir, subdir string) {
398         for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
399                 dir = filepath.Join(dir, part)
400                 os.Mkdir(dir, 0700)
401         }
402 }
403
404 // upstreamGateway creates/returns the KeepGateway stack used to read
405 // and write data: a disk-backed cache on top of an http backend.
406 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
407         kc.lock.Lock()
408         defer kc.lock.Unlock()
409         if kc.gatewayStack != nil {
410                 return kc.gatewayStack
411         }
412         var cachedir string
413         if os.Geteuid() == 0 {
414                 cachedir = rootCacheDir
415                 makedirs("/", cachedir)
416         } else {
417                 home := "/" + os.Getenv("HOME")
418                 makedirs(home, userCacheDir)
419                 cachedir = filepath.Join(home, userCacheDir)
420         }
421         backend := &keepViaHTTP{kc}
422         if kc.DiskCacheSize == DiskCacheDisabled {
423                 kc.gatewayStack = backend
424         } else {
425                 kc.gatewayStack = &arvados.DiskCache{
426                         Dir:         cachedir,
427                         MaxSize:     kc.DiskCacheSize,
428                         KeepGateway: backend,
429                 }
430         }
431         return kc.gatewayStack
432 }
433
434 // LocalLocator returns a locator equivalent to the one supplied, but
435 // with a valid signature from the local cluster. If the given locator
436 // already has a local signature, it is returned unchanged.
437 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
438         return kc.upstreamGateway().LocalLocator(locator)
439 }
440
441 // Get retrieves the specified block from the local cache or a backend
442 // server. Returns a reader, the expected data length (or -1 if not
443 // known), and an error.
444 //
445 // The third return value (formerly a source URL in previous versions)
446 // is an empty string.
447 //
448 // If the block checksum does not match, the final Read() on the
449 // reader returned by this method will return a BadChecksum error
450 // instead of EOF.
451 //
452 // New code should use BlockRead and/or ReadAt instead of Get.
453 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
454         loc, err := MakeLocator(locator)
455         if err != nil {
456                 return nil, 0, "", err
457         }
458         pr, pw := io.Pipe()
459         go func() {
460                 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
461                         Locator: locator,
462                         WriteTo: pw,
463                 })
464                 if err != nil {
465                         pw.CloseWithError(err)
466                 } else if loc.Size >= 0 && n != loc.Size {
467                         pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
468                 } else {
469                         pw.Close()
470                 }
471         }()
472         // Wait for the first byte to arrive, so that, if there's an
473         // error before we receive any data, we can return the error
474         // directly, instead of indirectly via a reader that returns
475         // an error.
476         bufr := bufio.NewReader(pr)
477         _, err = bufr.Peek(1)
478         if err != nil && err != io.EOF {
479                 pr.CloseWithError(err)
480                 return nil, 0, "", err
481         }
482         if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
483                 // In the special case of the zero-length block, EOF
484                 // error from Peek() is normal.
485                 return pr, 0, "", nil
486         }
487         return struct {
488                 io.Reader
489                 io.Closer
490         }{
491                 Reader: bufr,
492                 Closer: pr,
493         }, int64(loc.Size), "", err
494 }
495
496 // BlockRead retrieves a block from the cache if it's present, otherwise
497 // from the network.
498 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
499         return kc.upstreamGateway().BlockRead(ctx, opts)
500 }
501
502 // ReadAt retrieves a portion of block from the cache if it's
503 // present, otherwise from the network.
504 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
505         return kc.upstreamGateway().ReadAt(locator, p, off)
506 }
507
508 // BlockWrite writes a full block to upstream servers and saves a copy
509 // in the local cache.
510 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
511         return kc.upstreamGateway().BlockWrite(ctx, req)
512 }
513
514 // Ask verifies that a block with the given hash is available and
515 // readable, according to at least one Keep service. Unlike Get, it
516 // does not retrieve the data or verify that the data content matches
517 // the hash specified by the locator.
518 //
519 // Returns the data size (content length) reported by the Keep service
520 // and the URI reporting the data size.
521 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
522         _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
523         return size, url, err
524 }
525
526 // GetIndex retrieves a list of blocks stored on the given server whose hashes
527 // begin with the given prefix. The returned reader will return an error (other
528 // than EOF) if the complete index cannot be retrieved.
529 //
530 // This is meant to be used only by system components and admin tools.
531 // It will return an error unless the client is using a "data manager token"
532 // recognized by the Keep services.
533 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
534         url := kc.LocalRoots()[keepServiceUUID]
535         if url == "" {
536                 return nil, ErrNoSuchKeepServer
537         }
538
539         url += "/index"
540         if prefix != "" {
541                 url += "/" + prefix
542         }
543
544         req, err := http.NewRequest("GET", url, nil)
545         if err != nil {
546                 return nil, err
547         }
548
549         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
550         req.Header.Set("X-Request-Id", kc.getRequestID())
551         resp, err := kc.httpClient().Do(req)
552         if err != nil {
553                 return nil, err
554         }
555
556         defer resp.Body.Close()
557
558         if resp.StatusCode != http.StatusOK {
559                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
560         }
561
562         var respBody []byte
563         respBody, err = ioutil.ReadAll(resp.Body)
564         if err != nil {
565                 return nil, err
566         }
567
568         // Got index; verify that it is complete
569         // The response should be "\n" if no locators matched the prefix
570         // Else, it should be a list of locators followed by a blank line
571         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
572                 return nil, ErrIncompleteIndex
573         }
574
575         // Got complete index; strip the trailing newline and send
576         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
577 }
578
579 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
580 // services: uuid -> baseURI.
581 func (kc *KeepClient) LocalRoots() map[string]string {
582         kc.discoverServices()
583         kc.lock.RLock()
584         defer kc.lock.RUnlock()
585         return kc.localRoots
586 }
587
588 // GatewayRoots returns the map of Keep remote gateway services:
589 // uuid -> baseURI.
590 func (kc *KeepClient) GatewayRoots() map[string]string {
591         kc.discoverServices()
592         kc.lock.RLock()
593         defer kc.lock.RUnlock()
594         return kc.gatewayRoots
595 }
596
597 // WritableLocalRoots returns the map of writable local Keep services:
598 // uuid -> baseURI.
599 func (kc *KeepClient) WritableLocalRoots() map[string]string {
600         kc.discoverServices()
601         kc.lock.RLock()
602         defer kc.lock.RUnlock()
603         return kc.writableLocalRoots
604 }
605
606 // SetServiceRoots disables service discovery and updates the
607 // localRoots and gatewayRoots maps, without disrupting operations
608 // that are already in progress.
609 //
610 // The supplied maps must not be modified after calling
611 // SetServiceRoots.
612 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
613         kc.disableDiscovery = true
614         kc.setServiceRoots(locals, writables, gateways)
615 }
616
617 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
618         kc.lock.Lock()
619         defer kc.lock.Unlock()
620         kc.localRoots = locals
621         kc.writableLocalRoots = writables
622         kc.gatewayRoots = gateways
623 }
624
625 // getSortedRoots returns a list of base URIs of Keep services, in the
626 // order they should be attempted in order to retrieve content for the
627 // given locator.
628 func (kc *KeepClient) getSortedRoots(locator string) []string {
629         var found []string
630         for _, hint := range strings.Split(locator, "+") {
631                 if len(hint) < 7 || hint[0:2] != "K@" {
632                         // Not a service hint.
633                         continue
634                 }
635                 if len(hint) == 7 {
636                         // +K@abcde means fetch from proxy at
637                         // keep.abcde.arvadosapi.com
638                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
639                 } else if len(hint) == 29 {
640                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
641                         // from gateway with given uuid
642                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
643                                 found = append(found, gwURI)
644                         }
645                         // else this hint is no use to us; carry on.
646                 }
647         }
648         // After trying all usable service hints, fall back to local roots.
649         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
650         return found
651 }
652
653 func (kc *KeepClient) SetStorageClasses(sc []string) {
654         // make a copy so the caller can't mess with it.
655         kc.StorageClasses = append([]string{}, sc...)
656 }
657
658 var (
659         // There are four global http.Client objects for the four
660         // possible permutations of TLS behavior (verify/skip-verify)
661         // and timeout settings (proxy/non-proxy).
662         defaultClient = map[bool]map[bool]HTTPClient{
663                 // defaultClient[false] is used for verified TLS reqs
664                 false: {},
665                 // defaultClient[true] is used for unverified
666                 // (insecure) TLS reqs
667                 true: {},
668         }
669         defaultClientMtx sync.Mutex
670 )
671
672 // httpClient returns the HTTPClient field if it's not nil, otherwise
673 // whichever of the four global http.Client objects is suitable for
674 // the current environment (i.e., TLS verification on/off, keep
675 // services are/aren't proxies).
676 func (kc *KeepClient) httpClient() HTTPClient {
677         if kc.HTTPClient != nil {
678                 return kc.HTTPClient
679         }
680         defaultClientMtx.Lock()
681         defer defaultClientMtx.Unlock()
682         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
683                 return c
684         }
685
686         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
687         if kc.foundNonDiskSvc {
688                 // Use longer timeouts when connecting to a proxy,
689                 // because this usually means the intervening network
690                 // is slower.
691                 requestTimeout = DefaultProxyRequestTimeout
692                 connectTimeout = DefaultProxyConnectTimeout
693                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
694                 keepAlive = DefaultProxyKeepAlive
695         } else {
696                 requestTimeout = DefaultRequestTimeout
697                 connectTimeout = DefaultConnectTimeout
698                 tlsTimeout = DefaultTLSHandshakeTimeout
699                 keepAlive = DefaultKeepAlive
700         }
701
702         c := &http.Client{
703                 Timeout: requestTimeout,
704                 // It's not safe to copy *http.DefaultTransport
705                 // because it has a mutex (which might be locked)
706                 // protecting a private map (which might not be nil).
707                 // So we build our own, using the Go 1.12 default
708                 // values, ignoring any changes the application has
709                 // made to http.DefaultTransport.
710                 Transport: &http.Transport{
711                         DialContext: (&net.Dialer{
712                                 Timeout:   connectTimeout,
713                                 KeepAlive: keepAlive,
714                                 DualStack: true,
715                         }).DialContext,
716                         MaxIdleConns:          100,
717                         IdleConnTimeout:       90 * time.Second,
718                         TLSHandshakeTimeout:   tlsTimeout,
719                         ExpectContinueTimeout: 1 * time.Second,
720                         TLSClientConfig:       arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
721                 },
722         }
723         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
724         return c
725 }
726
727 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
728
729 func (kc *KeepClient) getRequestID() string {
730         if kc.RequestID != "" {
731                 return kc.RequestID
732         }
733         return reqIDGen.Next()
734 }
735
736 type Locator struct {
737         Hash  string
738         Size  int      // -1 if data size is not known
739         Hints []string // Including the size hint, if any
740 }
741
742 func (loc *Locator) String() string {
743         s := loc.Hash
744         if len(loc.Hints) > 0 {
745                 s = s + "+" + strings.Join(loc.Hints, "+")
746         }
747         return s
748 }
749
750 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
751
752 func MakeLocator(path string) (*Locator, error) {
753         sm := locatorMatcher.FindStringSubmatch(path)
754         if sm == nil {
755                 return nil, InvalidLocatorError
756         }
757         loc := Locator{Hash: sm[1], Size: -1}
758         if sm[2] != "" {
759                 loc.Hints = strings.Split(sm[3], "+")
760         } else {
761                 loc.Hints = []string{}
762         }
763         if len(loc.Hints) > 0 {
764                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
765                         loc.Size = size
766                 }
767         }
768         return &loc, nil
769 }