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