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