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