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