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