8784: Fix test for latest firefox.
[arvados.git] / sdk / go / keepclient / keepclient.go
1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
2 package keepclient
3
4 import (
5         "bytes"
6         "crypto/md5"
7         "errors"
8         "fmt"
9         "io"
10         "io/ioutil"
11         "net"
12         "net/http"
13         "regexp"
14         "strconv"
15         "strings"
16         "sync"
17         "time"
18
19         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
20         "git.curoverse.com/arvados.git/sdk/go/streamer"
21 )
22
23 // A Keep "block" is 64MB.
24 const BLOCKSIZE = 64 * 1024 * 1024
25
26 var (
27         DefaultRequestTimeout      = 20 * time.Second
28         DefaultConnectTimeout      = 2 * time.Second
29         DefaultTLSHandshakeTimeout = 4 * time.Second
30         DefaultKeepAlive           = 180 * time.Second
31
32         DefaultProxyRequestTimeout      = 300 * time.Second
33         DefaultProxyConnectTimeout      = 30 * time.Second
34         DefaultProxyTLSHandshakeTimeout = 10 * time.Second
35         DefaultProxyKeepAlive           = 120 * time.Second
36 )
37
38 // Error interface with an error and boolean indicating whether the error is temporary
39 type Error interface {
40         error
41         Temporary() bool
42 }
43
44 // multipleResponseError is of type Error
45 type multipleResponseError struct {
46         error
47         isTemp bool
48 }
49
50 func (e *multipleResponseError) Temporary() bool {
51         return e.isTemp
52 }
53
54 // BlockNotFound is a multipleResponseError where isTemp is false
55 var BlockNotFound = &ErrNotFound{multipleResponseError{
56         error:  errors.New("Block not found"),
57         isTemp: false,
58 }}
59
60 // ErrNotFound is a multipleResponseError where isTemp can be true or false
61 type ErrNotFound struct {
62         multipleResponseError
63 }
64
65 type InsufficientReplicasError error
66
67 type OversizeBlockError error
68
69 var ErrOversizeBlock = OversizeBlockError(errors.New("Exceeded maximum block size (" + strconv.Itoa(BLOCKSIZE) + ")"))
70 var MissingArvadosApiHost = errors.New("Missing required environment variable ARVADOS_API_HOST")
71 var MissingArvadosApiToken = errors.New("Missing required environment variable ARVADOS_API_TOKEN")
72 var InvalidLocatorError = errors.New("Invalid locator")
73
74 // ErrNoSuchKeepServer is returned when GetIndex is invoked with a UUID with no matching keep server
75 var ErrNoSuchKeepServer = errors.New("No keep server matching the given UUID is found")
76
77 // ErrIncompleteIndex is returned when the Index response does not end with a new empty line
78 var ErrIncompleteIndex = errors.New("Got incomplete index")
79
80 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
81 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
82
83 type HTTPClient interface {
84         Do(*http.Request) (*http.Response, error)
85 }
86
87 // Information about Arvados and Keep servers.
88 type KeepClient struct {
89         Arvados            *arvadosclient.ArvadosClient
90         Want_replicas      int
91         localRoots         map[string]string
92         writableLocalRoots map[string]string
93         gatewayRoots       map[string]string
94         lock               sync.RWMutex
95         HTTPClient         HTTPClient
96         Retries            int
97         BlockCache         *BlockCache
98
99         // set to 1 if all writable services are of disk type, otherwise 0
100         replicasPerService int
101
102         // Any non-disk typed services found in the list of keepservers?
103         foundNonDiskSvc bool
104
105         // Disable automatic discovery of keep services
106         disableDiscovery bool
107 }
108
109 // MakeKeepClient creates a new KeepClient, calls
110 // DiscoverKeepServices(), and returns when the client is ready to
111 // use.
112 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
113         kc := New(arv)
114         return kc, kc.discoverServices()
115 }
116
117 // New creates a new KeepClient. Service discovery will occur on the
118 // next read/write operation.
119 func New(arv *arvadosclient.ArvadosClient) *KeepClient {
120         defaultReplicationLevel := 2
121         value, err := arv.Discovery("defaultCollectionReplication")
122         if err == nil {
123                 v, ok := value.(float64)
124                 if ok && v > 0 {
125                         defaultReplicationLevel = int(v)
126                 }
127         }
128         return &KeepClient{
129                 Arvados:       arv,
130                 Want_replicas: defaultReplicationLevel,
131                 Retries:       2,
132         }
133 }
134
135 // Put a block given the block hash, a reader, and the number of bytes
136 // to read from the reader (which must be between 0 and BLOCKSIZE).
137 //
138 // Returns the locator for the written block, the number of replicas
139 // written, and an error.
140 //
141 // Returns an InsufficientReplicasError if 0 <= replicas <
142 // kc.Wants_replicas.
143 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
144         // Buffer for reads from 'r'
145         var bufsize int
146         if dataBytes > 0 {
147                 if dataBytes > BLOCKSIZE {
148                         return "", 0, ErrOversizeBlock
149                 }
150                 bufsize = int(dataBytes)
151         } else {
152                 bufsize = BLOCKSIZE
153         }
154
155         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
156         defer t.Close()
157
158         return kc.putReplicas(hash, t, dataBytes)
159 }
160
161 // PutHB writes a block to Keep. The hash of the bytes is given in
162 // hash, and the data is given in buf.
163 //
164 // Return values are the same as for PutHR.
165 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
166         t := streamer.AsyncStreamFromSlice(buf)
167         defer t.Close()
168         return kc.putReplicas(hash, t, int64(len(buf)))
169 }
170
171 // PutB writes a block to Keep. It computes the hash itself.
172 //
173 // Return values are the same as for PutHR.
174 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
175         hash := fmt.Sprintf("%x", md5.Sum(buffer))
176         return kc.PutHB(hash, buffer)
177 }
178
179 // PutR writes a block to Keep. It first reads all data from r into a buffer
180 // in order to compute the hash.
181 //
182 // Return values are the same as for PutHR.
183 //
184 // If the block hash and data size are known, PutHR is more efficient.
185 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
186         if buffer, err := ioutil.ReadAll(r); err != nil {
187                 return "", 0, err
188         } else {
189                 return kc.PutB(buffer)
190         }
191 }
192
193 func (kc *KeepClient) getOrHead(method string, locator string) (io.ReadCloser, int64, string, error) {
194         if strings.HasPrefix(locator, "d41d8cd98f00b204e9800998ecf8427e+0") {
195                 return ioutil.NopCloser(bytes.NewReader(nil)), 0, "", nil
196         }
197
198         var errs []string
199
200         tries_remaining := 1 + kc.Retries
201
202         serversToTry := kc.getSortedRoots(locator)
203
204         numServers := len(serversToTry)
205         count404 := 0
206
207         var retryList []string
208
209         for tries_remaining > 0 {
210                 tries_remaining -= 1
211                 retryList = nil
212
213                 for _, host := range serversToTry {
214                         url := host + "/" + locator
215
216                         req, err := http.NewRequest(method, url, nil)
217                         if err != nil {
218                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
219                                 continue
220                         }
221                         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
222                         resp, err := kc.httpClient().Do(req)
223                         if err != nil {
224                                 // Probably a network error, may be transient,
225                                 // can try again.
226                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
227                                 retryList = append(retryList, host)
228                         } else if resp.StatusCode != http.StatusOK {
229                                 var respbody []byte
230                                 respbody, _ = ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 4096})
231                                 resp.Body.Close()
232                                 errs = append(errs, fmt.Sprintf("%s: HTTP %d %q",
233                                         url, resp.StatusCode, bytes.TrimSpace(respbody)))
234
235                                 if resp.StatusCode == 408 ||
236                                         resp.StatusCode == 429 ||
237                                         resp.StatusCode >= 500 {
238                                         // Timeout, too many requests, or other
239                                         // server side failure, transient
240                                         // error, can try again.
241                                         retryList = append(retryList, host)
242                                 } else if resp.StatusCode == 404 {
243                                         count404++
244                                 }
245                         } else {
246                                 // Success.
247                                 if method == "GET" {
248                                         return HashCheckingReader{
249                                                 Reader: resp.Body,
250                                                 Hash:   md5.New(),
251                                                 Check:  locator[0:32],
252                                         }, resp.ContentLength, url, nil
253                                 } else {
254                                         resp.Body.Close()
255                                         return nil, resp.ContentLength, url, nil
256                                 }
257                         }
258
259                 }
260                 serversToTry = retryList
261         }
262         DebugPrintf("DEBUG: %s %s failed: %v", method, locator, errs)
263
264         var err error
265         if count404 == numServers {
266                 err = BlockNotFound
267         } else {
268                 err = &ErrNotFound{multipleResponseError{
269                         error:  fmt.Errorf("%s %s failed: %v", method, locator, errs),
270                         isTemp: len(serversToTry) > 0,
271                 }}
272         }
273         return nil, 0, "", err
274 }
275
276 // Get() retrieves a block, given a locator. Returns a reader, the
277 // expected data length, the URL the block is being fetched from, and
278 // an error.
279 //
280 // If the block checksum does not match, the final Read() on the
281 // reader returned by this method will return a BadChecksum error
282 // instead of EOF.
283 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
284         return kc.getOrHead("GET", locator)
285 }
286
287 // Ask() verifies that a block with the given hash is available and
288 // readable, according to at least one Keep service. Unlike Get, it
289 // does not retrieve the data or verify that the data content matches
290 // the hash specified by the locator.
291 //
292 // Returns the data size (content length) reported by the Keep service
293 // and the URI reporting the data size.
294 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
295         _, size, url, err := kc.getOrHead("HEAD", locator)
296         return size, url, err
297 }
298
299 // GetIndex retrieves a list of blocks stored on the given server whose hashes
300 // begin with the given prefix. The returned reader will return an error (other
301 // than EOF) if the complete index cannot be retrieved.
302 //
303 // This is meant to be used only by system components and admin tools.
304 // It will return an error unless the client is using a "data manager token"
305 // recognized by the Keep services.
306 func (kc *KeepClient) GetIndex(keepServiceUUID, prefix string) (io.Reader, error) {
307         url := kc.LocalRoots()[keepServiceUUID]
308         if url == "" {
309                 return nil, ErrNoSuchKeepServer
310         }
311
312         url += "/index"
313         if prefix != "" {
314                 url += "/" + prefix
315         }
316
317         req, err := http.NewRequest("GET", url, nil)
318         if err != nil {
319                 return nil, err
320         }
321
322         req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
323         resp, err := kc.httpClient().Do(req)
324         if err != nil {
325                 return nil, err
326         }
327
328         defer resp.Body.Close()
329
330         if resp.StatusCode != http.StatusOK {
331                 return nil, fmt.Errorf("Got http status code: %d", resp.StatusCode)
332         }
333
334         var respBody []byte
335         respBody, err = ioutil.ReadAll(resp.Body)
336         if err != nil {
337                 return nil, err
338         }
339
340         // Got index; verify that it is complete
341         // The response should be "\n" if no locators matched the prefix
342         // Else, it should be a list of locators followed by a blank line
343         if !bytes.Equal(respBody, []byte("\n")) && !bytes.HasSuffix(respBody, []byte("\n\n")) {
344                 return nil, ErrIncompleteIndex
345         }
346
347         // Got complete index; strip the trailing newline and send
348         return bytes.NewReader(respBody[0 : len(respBody)-1]), nil
349 }
350
351 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
352 // services: uuid -> baseURI.
353 func (kc *KeepClient) LocalRoots() map[string]string {
354         kc.discoverServices()
355         kc.lock.RLock()
356         defer kc.lock.RUnlock()
357         return kc.localRoots
358 }
359
360 // GatewayRoots() returns the map of Keep remote gateway services:
361 // uuid -> baseURI.
362 func (kc *KeepClient) GatewayRoots() map[string]string {
363         kc.discoverServices()
364         kc.lock.RLock()
365         defer kc.lock.RUnlock()
366         return kc.gatewayRoots
367 }
368
369 // WritableLocalRoots() returns the map of writable local Keep services:
370 // uuid -> baseURI.
371 func (kc *KeepClient) WritableLocalRoots() map[string]string {
372         kc.discoverServices()
373         kc.lock.RLock()
374         defer kc.lock.RUnlock()
375         return kc.writableLocalRoots
376 }
377
378 // SetServiceRoots disables service discovery and updates the
379 // localRoots and gatewayRoots maps, without disrupting operations
380 // that are already in progress.
381 //
382 // The supplied maps must not be modified after calling
383 // SetServiceRoots.
384 func (kc *KeepClient) SetServiceRoots(locals, writables, gateways map[string]string) {
385         kc.disableDiscovery = true
386         kc.setServiceRoots(locals, writables, gateways)
387 }
388
389 func (kc *KeepClient) setServiceRoots(locals, writables, gateways map[string]string) {
390         kc.lock.Lock()
391         defer kc.lock.Unlock()
392         kc.localRoots = locals
393         kc.writableLocalRoots = writables
394         kc.gatewayRoots = gateways
395 }
396
397 // getSortedRoots returns a list of base URIs of Keep services, in the
398 // order they should be attempted in order to retrieve content for the
399 // given locator.
400 func (kc *KeepClient) getSortedRoots(locator string) []string {
401         var found []string
402         for _, hint := range strings.Split(locator, "+") {
403                 if len(hint) < 7 || hint[0:2] != "K@" {
404                         // Not a service hint.
405                         continue
406                 }
407                 if len(hint) == 7 {
408                         // +K@abcde means fetch from proxy at
409                         // keep.abcde.arvadosapi.com
410                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
411                 } else if len(hint) == 29 {
412                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
413                         // from gateway with given uuid
414                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
415                                 found = append(found, gwURI)
416                         }
417                         // else this hint is no use to us; carry on.
418                 }
419         }
420         // After trying all usable service hints, fall back to local roots.
421         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
422         return found
423 }
424
425 func (kc *KeepClient) cache() *BlockCache {
426         if kc.BlockCache != nil {
427                 return kc.BlockCache
428         } else {
429                 return DefaultBlockCache
430         }
431 }
432
433 var (
434         // There are four global http.Client objects for the four
435         // possible permutations of TLS behavior (verify/skip-verify)
436         // and timeout settings (proxy/non-proxy).
437         defaultClient = map[bool]map[bool]HTTPClient{
438                 // defaultClient[false] is used for verified TLS reqs
439                 false: {},
440                 // defaultClient[true] is used for unverified
441                 // (insecure) TLS reqs
442                 true: {},
443         }
444         defaultClientMtx sync.Mutex
445 )
446
447 // httpClient returns the HTTPClient field if it's not nil, otherwise
448 // whichever of the four global http.Client objects is suitable for
449 // the current environment (i.e., TLS verification on/off, keep
450 // services are/aren't proxies).
451 func (kc *KeepClient) httpClient() HTTPClient {
452         if kc.HTTPClient != nil {
453                 return kc.HTTPClient
454         }
455         defaultClientMtx.Lock()
456         defer defaultClientMtx.Unlock()
457         if c, ok := defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc]; ok {
458                 return c
459         }
460
461         var requestTimeout, connectTimeout, keepAlive, tlsTimeout time.Duration
462         if kc.foundNonDiskSvc {
463                 // Use longer timeouts when connecting to a proxy,
464                 // because this usually means the intervening network
465                 // is slower.
466                 requestTimeout = DefaultProxyRequestTimeout
467                 connectTimeout = DefaultProxyConnectTimeout
468                 tlsTimeout = DefaultProxyTLSHandshakeTimeout
469                 keepAlive = DefaultProxyKeepAlive
470         } else {
471                 requestTimeout = DefaultRequestTimeout
472                 connectTimeout = DefaultConnectTimeout
473                 tlsTimeout = DefaultTLSHandshakeTimeout
474                 keepAlive = DefaultKeepAlive
475         }
476
477         transport, ok := http.DefaultTransport.(*http.Transport)
478         if ok {
479                 copy := *transport
480                 transport = &copy
481         } else {
482                 // Evidently the application has replaced
483                 // http.DefaultTransport with a different type, so we
484                 // need to build our own from scratch using the Go 1.8
485                 // defaults.
486                 transport = &http.Transport{
487                         MaxIdleConns:          100,
488                         IdleConnTimeout:       90 * time.Second,
489                         ExpectContinueTimeout: time.Second,
490                 }
491         }
492         transport.DialContext = (&net.Dialer{
493                 Timeout:   connectTimeout,
494                 KeepAlive: keepAlive,
495                 DualStack: true,
496         }).DialContext
497         transport.TLSHandshakeTimeout = tlsTimeout
498         transport.TLSClientConfig = arvadosclient.MakeTLSConfig(kc.Arvados.ApiInsecure)
499         c := &http.Client{
500                 Timeout:   requestTimeout,
501                 Transport: transport,
502         }
503         defaultClient[kc.Arvados.ApiInsecure][kc.foundNonDiskSvc] = c
504         return c
505 }
506
507 type Locator struct {
508         Hash  string
509         Size  int      // -1 if data size is not known
510         Hints []string // Including the size hint, if any
511 }
512
513 func (loc *Locator) String() string {
514         s := loc.Hash
515         if len(loc.Hints) > 0 {
516                 s = s + "+" + strings.Join(loc.Hints, "+")
517         }
518         return s
519 }
520
521 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
522
523 func MakeLocator(path string) (*Locator, error) {
524         sm := locatorMatcher.FindStringSubmatch(path)
525         if sm == nil {
526                 return nil, InvalidLocatorError
527         }
528         loc := Locator{Hash: sm[1], Size: -1}
529         if sm[2] != "" {
530                 loc.Hints = strings.Split(sm[3], "+")
531         } else {
532                 loc.Hints = []string{}
533         }
534         if len(loc.Hints) > 0 {
535                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
536                         loc.Size = size
537                 }
538         }
539         return &loc, nil
540 }