Merge branch 'main' into 21386-project-loading-view
[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         "net"
19         "net/http"
20         "os"
21         "path/filepath"
22         "regexp"
23         "strconv"
24         "strings"
25         "sync"
26         "time"
27
28         "git.arvados.org/arvados.git/sdk/go/arvados"
29         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
30         "git.arvados.org/arvados.git/sdk/go/httpserver"
31 )
32
33 // BLOCKSIZE defines the length of a Keep "block", which is 64MB.
34 const BLOCKSIZE = 64 * 1024 * 1024
35
36 var (
37         DefaultRequestTimeout      = 20 * time.Second
38         DefaultConnectTimeout      = 2 * time.Second
39         DefaultTLSHandshakeTimeout = 4 * time.Second
40         DefaultKeepAlive           = 180 * time.Second
41
42         DefaultProxyRequestTimeout      = 300 * time.Second
43         DefaultProxyConnectTimeout      = 30 * time.Second
44         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
45         DefaultProxyKeepAlive           = 120 * time.Second
46
47         DefaultRetryDelay = 2 * time.Second // see KeepClient.RetryDelay
48         MinimumRetryDelay = time.Millisecond
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 maximum delay for automatic retry. If zero,
124         // DefaultRetryDelay is used.  The delay after attempt N
125         // (0-based) will be a random duration between
126         // MinimumRetryDelay and RetryDelay * 2^N, not to exceed a cap
127         // of RetryDelay * 10.
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         delay := delayCalculator{InitialMaxDelay: kc.RetryDelay}
288         triesRemaining := 1 + kc.Retries
289
290         serversToTry := kc.getSortedRoots(locator)
291
292         numServers := len(serversToTry)
293         count404 := 0
294
295         var retryList []string
296
297         for triesRemaining > 0 {
298                 triesRemaining--
299                 retryList = nil
300
301                 for _, host := range serversToTry {
302                         url := host + "/" + locator
303
304                         req, err := http.NewRequest(method, url, nil)
305                         if err != nil {
306                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
307                                 continue
308                         }
309                         for k, v := range header {
310                                 req.Header[k] = append([]string(nil), v...)
311                         }
312                         if req.Header.Get("Authorization") == "" {
313                                 req.Header.Set("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
314                         }
315                         if req.Header.Get("X-Request-Id") == "" {
316                                 req.Header.Set("X-Request-Id", reqid)
317                         }
318                         resp, err := kc.httpClient().Do(req)
319                         if err != nil {
320                                 // Probably a network error, may be transient,
321                                 // can try again.
322                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
323                                 retryList = append(retryList, host)
324                                 continue
325                         }
326                         if resp.StatusCode != http.StatusOK {
327                                 var respbody []byte
328                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
329                                 resp.Body.Close()
330                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
331                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
332
333                                 if resp.StatusCode == 408 ||
334                                         resp.StatusCode == 429 ||
335                                         resp.StatusCode >= 500 {
336                                         // Timeout, too many requests, or other
337                                         // server side failure, transient
338                                         // error, can try again.
339                                         retryList = append(retryList, host)
340                                 } else if resp.StatusCode == 404 {
341                                         count404++
342                                 }
343                                 continue
344                         }
345                         if expectLength < 0 {
346                                 if resp.ContentLength < 0 {
347                                         resp.Body.Close()
348                                         return nil, 0, "", nil, fmt.Errorf("error reading %q: no size hint, no Content-Length header in response", locator)
349                                 }
350                                 expectLength = resp.ContentLength
351                         } else if resp.ContentLength >= 0 && expectLength != resp.ContentLength {
352                                 resp.Body.Close()
353                                 return nil, 0, "", nil, fmt.Errorf("error reading %q: size hint %d != Content-Length %d", locator, expectLength, resp.ContentLength)
354                         }
355                         // Success
356                         if method == "GET" {
357                                 return HashCheckingReader{
358                                         Reader: resp.Body,
359                                         Hash:   md5.New(),
360                                         Check:  locator[0:32],
361                                 }, expectLength, url, resp.Header, nil
362                         }
363                         resp.Body.Close()
364                         return nil, expectLength, url, resp.Header, nil
365                 }
366                 serversToTry = retryList
367                 if len(serversToTry) > 0 && triesRemaining > 0 {
368                         time.Sleep(delay.Next())
369                 }
370         }
371         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
372
373         var err error
374         if count404 == numServers {
375                 err = BlockNotFound
376         } else {
377                 err = &ErrNotFound{multipleResponseError{
378                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
379                         isTemp: len(serversToTry) > 0,
380                 }}
381         }
382         return nil, 0, "", nil, err
383 }
384
385 // attempt to create dir/subdir/ and its parents, up to but not
386 // including dir itself, using mode 0700.
387 func makedirs(dir, subdir string) {
388         for _, part := range strings.Split(subdir, string(os.PathSeparator)) {
389                 dir = filepath.Join(dir, part)
390                 os.Mkdir(dir, 0700)
391         }
392 }
393
394 // upstreamGateway creates/returns the KeepGateway stack used to read
395 // and write data: a disk-backed cache on top of an http backend.
396 func (kc *KeepClient) upstreamGateway() arvados.KeepGateway {
397         kc.lock.Lock()
398         defer kc.lock.Unlock()
399         if kc.gatewayStack != nil {
400                 return kc.gatewayStack
401         }
402         var cachedir string
403         if os.Geteuid() == 0 {
404                 cachedir = rootCacheDir
405                 makedirs("/", cachedir)
406         } else {
407                 home := "/" + os.Getenv("HOME")
408                 makedirs(home, userCacheDir)
409                 cachedir = filepath.Join(home, userCacheDir)
410         }
411         backend := &keepViaHTTP{kc}
412         if kc.DiskCacheSize == DiskCacheDisabled {
413                 kc.gatewayStack = backend
414         } else {
415                 kc.gatewayStack = &arvados.DiskCache{
416                         Dir:         cachedir,
417                         MaxSize:     kc.DiskCacheSize,
418                         KeepGateway: backend,
419                 }
420         }
421         return kc.gatewayStack
422 }
423
424 // LocalLocator returns a locator equivalent to the one supplied, but
425 // with a valid signature from the local cluster. If the given locator
426 // already has a local signature, it is returned unchanged.
427 func (kc *KeepClient) LocalLocator(locator string) (string, error) {
428         return kc.upstreamGateway().LocalLocator(locator)
429 }
430
431 // Get retrieves the specified block from the local cache or a backend
432 // server. Returns a reader, the expected data length (or -1 if not
433 // known), and an error.
434 //
435 // The third return value (formerly a source URL in previous versions)
436 // is an empty string.
437 //
438 // If the block checksum does not match, the final Read() on the
439 // reader returned by this method will return a BadChecksum error
440 // instead of EOF.
441 //
442 // New code should use BlockRead and/or ReadAt instead of Get.
443 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
444         loc, err := MakeLocator(locator)
445         if err != nil {
446                 return nil, 0, "", err
447         }
448         pr, pw := io.Pipe()
449         go func() {
450                 n, err := kc.BlockRead(context.Background(), arvados.BlockReadOptions{
451                         Locator: locator,
452                         WriteTo: pw,
453                 })
454                 if err != nil {
455                         pw.CloseWithError(err)
456                 } else if loc.Size >= 0 && n != loc.Size {
457                         pw.CloseWithError(fmt.Errorf("expected block size %d but read %d bytes", loc.Size, n))
458                 } else {
459                         pw.Close()
460                 }
461         }()
462         // Wait for the first byte to arrive, so that, if there's an
463         // error before we receive any data, we can return the error
464         // directly, instead of indirectly via a reader that returns
465         // an error.
466         bufr := bufio.NewReader(pr)
467         _, err = bufr.Peek(1)
468         if err != nil && err != io.EOF {
469                 pr.CloseWithError(err)
470                 return nil, 0, "", err
471         }
472         if err == io.EOF && (loc.Size == 0 || loc.Hash == "d41d8cd98f00b204e9800998ecf8427e") {
473                 // In the special case of the zero-length block, EOF
474                 // error from Peek() is normal.
475                 return pr, 0, "", nil
476         }
477         return struct {
478                 io.Reader
479                 io.Closer
480         }{
481                 Reader: bufr,
482                 Closer: pr,
483         }, int64(loc.Size), "", err
484 }
485
486 // BlockRead retrieves a block from the cache if it's present, otherwise
487 // from the network.
488 func (kc *KeepClient) BlockRead(ctx context.Context, opts arvados.BlockReadOptions) (int, error) {
489         return kc.upstreamGateway().BlockRead(ctx, opts)
490 }
491
492 // ReadAt retrieves a portion of block from the cache if it's
493 // present, otherwise from the network.
494 func (kc *KeepClient) ReadAt(locator string, p []byte, off int) (int, error) {
495         return kc.upstreamGateway().ReadAt(locator, p, off)
496 }
497
498 // BlockWrite writes a full block to upstream servers and saves a copy
499 // in the local cache.
500 func (kc *KeepClient) BlockWrite(ctx context.Context, req arvados.BlockWriteOptions) (arvados.BlockWriteResponse, error) {
501         return kc.upstreamGateway().BlockWrite(ctx, req)
502 }
503
504 // Ask verifies that a block with the given hash is available and
505 // readable, according to at least one Keep service. Unlike Get, it
506 // does not retrieve the data or verify that the data content matches
507 // the hash specified by the locator.
508 //
509 // Returns the data size (content length) reported by the Keep service
510 // and the URI reporting the data size.
511 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
512         _, size, url, _, err := kc.getOrHead("HEAD", locator, nil)
513         return size, url, err
514 }
515
516 // GetIndex retrieves a list of blocks stored on the given server whose hashes
517 // begin with the given prefix. The returned reader will return an error (other
518 // than EOF) if the complete index cannot be retrieved.
519 //
520 // This is meant to be used only by system components and admin tools.
521 // It will return an error unless the client is using a "data manager token"
522 // recognized by the Keep services.
523 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
524         url := kc.LocalRoots()[keepServiceUUID]
525         if url == "" {
526                 return nil, ErrNoSuchKeepServer
527         }
528
529         url += "/index"
530         if prefix != "" {
531                 url += "/" + prefix
532         }
533
534         req, err := http.NewRequest("GET", url, nil)
535         if err != nil {
536                 return nil, err
537         }
538
539         req.Header.Add("Authorization", "OAuth2 "+kc.Arvados.ApiToken)
540         req.Header.Set("X-Request-Id", kc.getRequestID())
541         resp, err := kc.httpClient().Do(req)
542         if err != nil {
543                 return nil, err
544         }
545
546         defer resp.Body.Close()
547
548         if resp.StatusCode != http.StatusOK {
549                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
550         }
551
552         var respBody []byte
553         respBody, err = ioutil.ReadAll(resp.Body)
554         if err != nil {
555                 return nil, err
556         }
557
558         // Got index; verify that it is complete
559         // The response should be "\n" if no locators matched the prefix
560         // Else, it should be a list of locators followed by a blank line
561         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
562                 return nil, ErrIncompleteIndex
563         }
564
565         // Got complete index; strip the trailing newline and send
566         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
567 }
568
569 // LocalRoots returns the map of local (i.e., disk and proxy) Keep
570 // services: uuid -> baseURI.
571 func (kc *KeepClient) LocalRoots() map[string]string {
572         kc.discoverServices()
573         kc.lock.RLock()
574         defer kc.lock.RUnlock()
575         return kc.localRoots
576 }
577
578 // GatewayRoots returns the map of Keep remote gateway services:
579 // uuid -> baseURI.
580 func (kc *KeepClient) GatewayRoots() map[string]string {
581         kc.discoverServices()
582         kc.lock.RLock()
583         defer kc.lock.RUnlock()
584         return kc.gatewayRoots
585 }
586
587 // WritableLocalRoots returns the map of writable local Keep services:
588 // uuid -> baseURI.
589 func (kc *KeepClient) WritableLocalRoots() map[string]string {
590         kc.discoverServices()
591         kc.lock.RLock()
592         defer kc.lock.RUnlock()
593         return kc.writableLocalRoots
594 }
595
596 // SetServiceRoots disables service discovery and updates the
597 // localRoots and gatewayRoots maps, without disrupting operations
598 // that are already in progress.
599 //
600 // The supplied maps must not be modified after calling
601 // SetServiceRoots.
602 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
603         kc.disableDiscovery = true
604         kc.setServiceRoots(locals, writables, gateways)
605 }
606
607 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
608         kc.lock.Lock()
609         defer kc.lock.Unlock()
610         kc.localRoots = locals
611         kc.writableLocalRoots = writables
612         kc.gatewayRoots = gateways
613 }
614
615 // getSortedRoots returns a list of base URIs of Keep services, in the
616 // order they should be attempted in order to retrieve content for the
617 // given locator.
618 func (kc *KeepClient) getSortedRoots(locator string) []string {
619         var found []string
620         for _, hint := range strings.Split(locator, "+") {
621                 if len(hint) < 7 || hint[0:2] != "K@" {
622                         // Not a service hint.
623                         continue
624                 }
625                 if len(hint) == 7 {
626                         // +K@abcde means fetch from proxy at
627                         // keep.abcde.arvadosapi.com
628                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
629                 } else if len(hint) == 29 {
630                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
631                         // from gateway with given uuid
632                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
633                                 found = append(found, gwURI)
634                         }
635                         // else this hint is no use to us; carry on.
636                 }
637         }
638         // After trying all usable service hints, fall back to local roots.
639         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
640         return found
641 }
642
643 func (kc *KeepClient) SetStorageClasses(sc []string) {
644         // make a copy so the caller can't mess with it.
645         kc.StorageClasses = append([]string{}, sc...)
646 }
647
648 var (
649         // There are four global http.Client objects for the four
650         // possible permutations of TLS behavior (verify/skip-verify)
651         // and timeout settings (proxy/non-proxy).
652         defaultClient = map[bool]map[bool]HTTPClient{
653                 // defaultClient[false] is used for verified TLS reqs
654                 false: {},
655                 // defaultClient[true] is used for unverified
656                 // (insecure) TLS reqs
657                 true: {},
658         }
659         defaultClientMtx sync.Mutex
660 )
661
662 // httpClient returns the HTTPClient field if it's not nil, otherwise
663 // whichever of the four global http.Client objects is suitable for
664 // the current environment (i.e., TLS verification on/off, keep
665 // services are/aren't proxies).
666 func (kc *KeepClient) httpClient() HTTPClient {
667         if kc.HTTPClient != nil {
668                 return kc.HTTPClient
669         }
670         defaultClientMtx.Lock()
671         defer defaultClientMtx.Unlock()
672         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
673                 return c
674         }
675
676         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
677         if kc.foundNonDiskSvc {
678                 // Use longer timeouts when connecting to a proxy,
679                 // because this usually means the intervening network
680                 // is slower.
681                 requestTimeout = DefaultProxyRequestTimeout
682                 connectTimeout = DefaultProxyConnectTimeout
683                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
684                 keepAlive = DefaultProxyKeepAlive
685         } else {
686                 requestTimeout = DefaultRequestTimeout
687                 connectTimeout = DefaultConnectTimeout
688                 tlsTimeout = DefaultTLSHandshakeTimeout
689                 keepAlive = DefaultKeepAlive
690         }
691
692         c := &http.Client{
693                 Timeout: requestTimeout,
694                 // It's not safe to copy *http.DefaultTransport
695                 // because it has a mutex (which might be locked)
696                 // protecting a private map (which might not be nil).
697                 // So we build our own, using the Go 1.12 default
698                 // values, ignoring any changes the application has
699                 // made to http.DefaultTransport.
700                 Transport: &http.Transport{
701                         DialContext: (&net.Dialer{
702                                 Timeout:   connectTimeout,
703                                 KeepAlive: keepAlive,
704                                 DualStack: true,
705                         }).DialContext,
706                         MaxIdleConns:          100,
707                         IdleConnTimeout:       90 * time.Second,
708                         TLSHandshakeTimeout:   tlsTimeout,
709                         ExpectContinueTimeout: 1 * time.Second,
710                         TLSClientConfig:       arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure),
711                 },
712         }
713         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
714         return c
715 }
716
717 var reqIDGen = httpserver.IDGenerator{Prefix: "req-"}
718
719 func (kc *KeepClient) getRequestID() string {
720         if kc.RequestID != "" {
721                 return kc.RequestID
722         }
723         return reqIDGen.Next()
724 }
725
726 type Locator struct {
727         Hash  string
728         Size  int      // -1 if data size is not known
729         Hints []string // Including the size hint, if any
730 }
731
732 func (loc *Locator) String() string {
733         s := loc.Hash
734         if len(loc.Hints) > 0 {
735                 s = s + "+" + strings.Join(loc.Hints, "+")
736         }
737         return s
738 }
739
740 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
741
742 func MakeLocator(path string) (*Locator, error) {
743         sm := locatorMatcher.FindStringSubmatch(path)
744         if sm == nil {
745                 return nil, InvalidLocatorError
746         }
747         loc := Locator{Hash: sm[1], Size: -1}
748         if sm[2] != "" {
749                 loc.Hints = strings.Split(sm[3], "+")
750         } else {
751                 loc.Hints = []string{}
752         }
753         if len(loc.Hints) > 0 {
754                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
755                         loc.Size = size
756                 }
757         }
758         return &loc, nil
759 }