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