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