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