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