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