closes #5930. Merge branch '5930-smalldocfix'
[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         "crypto/md5"
6         "crypto/tls"
7         "errors"
8         "fmt"
9         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
10         "git.curoverse.com/arvados.git/sdk/go/streamer"
11         "io"
12         "io/ioutil"
13         "log"
14         "net/http"
15         "os"
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 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
33 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
34
35 // Information about Arvados and Keep servers.
36 type KeepClient struct {
37         Arvados       *arvadosclient.ArvadosClient
38         Want_replicas int
39         Using_proxy   bool
40         localRoots    *map[string]string
41         writableLocalRoots *map[string]string
42         gatewayRoots  *map[string]string
43         lock          sync.RWMutex
44         Client        *http.Client
45 }
46
47 // Create a new KeepClient.  This will contact the API server to discover Keep
48 // servers.
49 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (*KeepClient, error) {
50         var matchTrue = regexp.MustCompile("^(?i:1|yes|true)$")
51         insecure := matchTrue.MatchString(os.Getenv("ARVADOS_API_HOST_INSECURE"))
52         kc := &KeepClient{
53                 Arvados:       arv,
54                 Want_replicas: 2,
55                 Using_proxy:   false,
56                 Client: &http.Client{Transport: &http.Transport{
57                         TLSClientConfig: &tls.Config{InsecureSkipVerify: insecure}}},
58         }
59         return kc, kc.DiscoverKeepServers()
60 }
61
62 // Put a block given the block hash, a reader, and the number of bytes
63 // to read from the reader (which must be between 0 and BLOCKSIZE).
64 //
65 // Returns the locator for the written block, the number of replicas
66 // written, and an error.
67 //
68 // Returns an InsufficientReplicas error if 0 <= replicas <
69 // kc.Wants_replicas.
70 func (kc *KeepClient) PutHR(hash string, r io.Reader, dataBytes int64) (string, int, error) {
71         // Buffer for reads from 'r'
72         var bufsize int
73         if dataBytes > 0 {
74                 if dataBytes > BLOCKSIZE {
75                         return "", 0, OversizeBlockError
76                 }
77                 bufsize = int(dataBytes)
78         } else {
79                 bufsize = BLOCKSIZE
80         }
81
82         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
83         defer t.Close()
84
85         return kc.putReplicas(hash, t, dataBytes)
86 }
87
88 // PutHB writes a block to Keep. The hash of the bytes is given in
89 // hash, and the data is given in buf.
90 //
91 // Return values are the same as for PutHR.
92 func (kc *KeepClient) PutHB(hash string, buf []byte) (string, int, error) {
93         t := streamer.AsyncStreamFromSlice(buf)
94         defer t.Close()
95         return kc.putReplicas(hash, t, int64(len(buf)))
96 }
97
98 // PutB writes a block to Keep. It computes the hash itself.
99 //
100 // Return values are the same as for PutHR.
101 func (kc *KeepClient) PutB(buffer []byte) (string, int, error) {
102         hash := fmt.Sprintf("%x", md5.Sum(buffer))
103         return kc.PutHB(hash, buffer)
104 }
105
106 // PutR writes a block to Keep. It first reads all data from r into a buffer
107 // in order to compute the hash.
108 //
109 // Return values are the same as for PutHR.
110 //
111 // If the block hash and data size are known, PutHR is more efficient.
112 func (kc *KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
113         if buffer, err := ioutil.ReadAll(r); err != nil {
114                 return "", 0, err
115         } else {
116                 return kc.PutB(buffer)
117         }
118 }
119
120 // Get() retrieves a block, given a locator. Returns a reader, the
121 // expected data length, the URL the block is being fetched from, and
122 // an error.
123 //
124 // If the block checksum does not match, the final Read() on the
125 // reader returned by this method will return a BadChecksum error
126 // instead of EOF.
127 func (kc *KeepClient) Get(locator string) (io.ReadCloser, int64, string, error) {
128         var errs []string
129         for _, host := range kc.getSortedRoots(locator) {
130                 url := host + "/" + locator
131                 req, err := http.NewRequest("GET", url, nil)
132                 if err != nil {
133                         continue
134                 }
135                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
136                 resp, err := kc.Client.Do(req)
137                 if err != nil || resp.StatusCode != http.StatusOK {
138                         if resp != nil {
139                                 var respbody []byte
140                                 if resp.Body != nil {
141                                         respbody, _ = ioutil.ReadAll(&io.LimitedReader{resp.Body, 4096})
142                                 }
143                                 errs = append(errs, fmt.Sprintf("%s: %d %s",
144                                         url, resp.StatusCode, strings.TrimSpace(string(respbody))))
145                         } else {
146                                 errs = append(errs, fmt.Sprintf("%s: %v", url, err))
147                         }
148                         continue
149                 }
150                 return HashCheckingReader{
151                         Reader: resp.Body,
152                         Hash:   md5.New(),
153                         Check:  locator[0:32],
154                 }, resp.ContentLength, url, nil
155         }
156         log.Printf("DEBUG: GET %s failed: %v", locator, errs)
157         return nil, 0, "", BlockNotFound
158 }
159
160 // Ask() verifies that a block with the given hash is available and
161 // readable, according to at least one Keep service. Unlike Get, it
162 // does not retrieve the data or verify that the data content matches
163 // the hash specified by the locator.
164 //
165 // Returns the data size (content length) reported by the Keep service
166 // and the URI reporting the data size.
167 func (kc *KeepClient) Ask(locator string) (int64, string, error) {
168         for _, host := range kc.getSortedRoots(locator) {
169                 url := host + "/" + locator
170                 req, err := http.NewRequest("HEAD", url, nil)
171                 if err != nil {
172                         continue
173                 }
174                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", kc.Arvados.ApiToken))
175                 if resp, err := kc.Client.Do(req); err == nil && resp.StatusCode == http.StatusOK {
176                         return resp.ContentLength, url, nil
177                 }
178         }
179         return 0, "", BlockNotFound
180 }
181
182 // LocalRoots() returns the map of local (i.e., disk and proxy) Keep
183 // services: uuid -> baseURI.
184 func (kc *KeepClient) LocalRoots() map[string]string {
185         kc.lock.RLock()
186         defer kc.lock.RUnlock()
187         return *kc.localRoots
188 }
189
190 // GatewayRoots() returns the map of Keep remote gateway services:
191 // uuid -> baseURI.
192 func (kc *KeepClient) GatewayRoots() map[string]string {
193         kc.lock.RLock()
194         defer kc.lock.RUnlock()
195         return *kc.gatewayRoots
196 }
197
198 // WritableLocalRoots() returns the map of writable local Keep services:
199 // uuid -> baseURI.
200 func (kc *KeepClient) WritableLocalRoots() map[string]string {
201         kc.lock.RLock()
202         defer kc.lock.RUnlock()
203         return *kc.writableLocalRoots
204 }
205
206 // SetServiceRoots updates the localRoots and gatewayRoots maps,
207 // without risk of disrupting operations that are already in progress.
208 //
209 // The KeepClient makes its own copy of the supplied maps, so the
210 // caller can reuse/modify them after SetServiceRoots returns, but
211 // they should not be modified by any other goroutine while
212 // SetServiceRoots is running.
213 func (kc *KeepClient) SetServiceRoots(newLocals, newWritableLocals map[string]string, newGateways map[string]string) {
214         locals := make(map[string]string)
215         for uuid, root := range newLocals {
216                 locals[uuid] = root
217         }
218
219         writables := make(map[string]string)
220         for uuid, root := range newWritableLocals {
221                 writables[uuid] = root
222         }
223
224         gateways := make(map[string]string)
225         for uuid, root := range newGateways {
226                 gateways[uuid] = root
227         }
228
229         kc.lock.Lock()
230         defer kc.lock.Unlock()
231         kc.localRoots = &locals
232         kc.writableLocalRoots = &writables
233         kc.gatewayRoots = &gateways
234 }
235
236 // getSortedRoots returns a list of base URIs of Keep services, in the
237 // order they should be attempted in order to retrieve content for the
238 // given locator.
239 func (kc *KeepClient) getSortedRoots(locator string) []string {
240         var found []string
241         for _, hint := range strings.Split(locator, "+") {
242                 if len(hint) < 7 || hint[0:2] != "K@" {
243                         // Not a service hint.
244                         continue
245                 }
246                 if len(hint) == 7 {
247                         // +K@abcde means fetch from proxy at
248                         // keep.abcde.arvadosapi.com
249                         found = append(found, "https://keep."+hint[2:]+".arvadosapi.com")
250                 } else if len(hint) == 29 {
251                         // +K@abcde-abcde-abcdeabcdeabcde means fetch
252                         // from gateway with given uuid
253                         if gwURI, ok := kc.GatewayRoots()[hint[2:]]; ok {
254                                 found = append(found, gwURI)
255                         }
256                         // else this hint is no use to us; carry on.
257                 }
258         }
259         // After trying all usable service hints, fall back to local roots.
260         found = append(found, NewRootSorter(kc.LocalRoots(), locator[0:32]).GetSortedRoots()...)
261         return found
262 }
263
264 type Locator struct {
265         Hash  string
266         Size  int      // -1 if data size is not known
267         Hints []string // Including the size hint, if any
268 }
269
270 func (loc *Locator) String() string {
271         s := loc.Hash
272         if len(loc.Hints) > 0 {
273                 s = s + "+" + strings.Join(loc.Hints, "+")
274         }
275         return s
276 }
277
278 var locatorMatcher = regexp.MustCompile("^([0-9a-f]{32})([+](.*))?$")
279
280 func MakeLocator(path string) (*Locator, error) {
281         sm := locatorMatcher.FindStringSubmatch(path)
282         if sm == nil {
283                 return nil, InvalidLocatorError
284         }
285         loc := Locator{Hash: sm[1], Size: -1}
286         if sm[2] != "" {
287                 loc.Hints = strings.Split(sm[3], "+")
288         } else {
289                 loc.Hints = []string{}
290         }
291         if len(loc.Hints) > 0 {
292                 if size, err := strconv.Atoi(loc.Hints[0]); err == nil {
293                         loc.Size = size
294                 }
295         }
296         return &loc, nil
297 }