3551: Fix source tree layout.
[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         streamer "git.curoverse.com/arvados.git/sdk/go/streamer"
6         arvadosclient "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
7         "crypto/md5"
8         "errors"
9         "fmt"
10         "io"
11         "io/ioutil"
12         "log"
13         "net/http"
14         "regexp"
15         "sort"
16         "strings"
17         "sync"
18         "sync/atomic"
19         "unsafe"
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("Block too big")
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
31 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
32 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
33
34 // Information about Arvados and Keep servers.
35 type KeepClient struct {
36         Arvados       *arvadosclient.ArvadosClient
37         Want_replicas int
38         Using_proxy   bool
39         service_roots *[]string
40         lock          sync.Mutex
41         Client        *http.Client
42 }
43
44 // Create a new KeepClient.  This will contact the API server to discover Keep
45 // servers.
46 func MakeKeepClient(arv *arvadosclient.ArvadosClient) (kc KeepClient, err error) {
47         kc = KeepClient{
48                 Arvados:       arv,
49                 Want_replicas: 2,
50                 Using_proxy:   false,
51                 Client:        &http.Client{Transport: &http.Transport{}}}
52
53         err = (&kc).DiscoverKeepServers()
54
55         return kc, err
56 }
57
58 // Put a block given the block hash, a reader with the block data, and the
59 // expected length of that data.  The desired number of replicas is given in
60 // KeepClient.Want_replicas.  Returns the number of replicas that were written
61 // and if there was an error.  Note this will return InsufficientReplias
62 // whenever 0 <= replicas < this.Wants_replicas.
63 func (this KeepClient) PutHR(hash string, r io.Reader, expectedLength int64) (locator string, replicas int, err error) {
64
65         // Buffer for reads from 'r'
66         var bufsize int
67         if expectedLength > 0 {
68                 if expectedLength > BLOCKSIZE {
69                         return "", 0, OversizeBlockError
70                 }
71                 bufsize = int(expectedLength)
72         } else {
73                 bufsize = BLOCKSIZE
74         }
75
76         t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
77         defer t.Close()
78
79         return this.putReplicas(hash, t, expectedLength)
80 }
81
82 // Put a block given the block hash and a byte buffer.  The desired number of
83 // replicas is given in KeepClient.Want_replicas.  Returns the number of
84 // replicas that were written and if there was an error.  Note this will return
85 // InsufficientReplias whenever 0 <= replicas < this.Wants_replicas.
86 func (this KeepClient) PutHB(hash string, buf []byte) (locator string, replicas int, err error) {
87         t := streamer.AsyncStreamFromSlice(buf)
88         defer t.Close()
89
90         return this.putReplicas(hash, t, int64(len(buf)))
91 }
92
93 // Put a block given a buffer.  The hash will be computed.  The desired number
94 // of replicas is given in KeepClient.Want_replicas.  Returns the number of
95 // replicas that were written and if there was an error.  Note this will return
96 // InsufficientReplias whenever 0 <= replicas < this.Wants_replicas.
97 func (this KeepClient) PutB(buffer []byte) (locator string, replicas int, err error) {
98         hash := fmt.Sprintf("%x", md5.Sum(buffer))
99         return this.PutHB(hash, buffer)
100 }
101
102 // Put a block, given a Reader.  This will read the entire reader into a buffer
103 // to compute the hash.  The desired number of replicas is given in
104 // KeepClient.Want_replicas.  Returns the number of replicas that were written
105 // and if there was an error.  Note this will return InsufficientReplias
106 // whenever 0 <= replicas < this.Wants_replicas.  Also nhote that if the block
107 // hash and data size are available, PutHR() is more efficient.
108 func (this KeepClient) PutR(r io.Reader) (locator string, replicas int, err error) {
109         if buffer, err := ioutil.ReadAll(r); err != nil {
110                 return "", 0, err
111         } else {
112                 return this.PutB(buffer)
113         }
114 }
115
116 // Get a block given a hash.  Return a reader, the expected data length, the
117 // URL the block was fetched from, and if there was an error.  If the block
118 // checksum does not match, the final Read() on the reader returned by this
119 // method will return a BadChecksum error instead of EOF.
120 func (this KeepClient) Get(hash string) (reader io.ReadCloser,
121         contentLength int64, url string, err error) {
122         return this.AuthorizedGet(hash, "", "")
123 }
124
125 // Get a block given a hash, with additional authorization provided by
126 // signature and timestamp.  Return a reader, the expected data length, the URL
127 // the block was fetched from, and if there was an error.  If the block
128 // checksum does not match, the final Read() on the reader returned by this
129 // method will return a BadChecksum error instead of EOF.
130 func (this KeepClient) AuthorizedGet(hash string,
131         signature string,
132         timestamp string) (reader io.ReadCloser,
133         contentLength int64, url string, err error) {
134
135         // Calculate the ordering for asking servers
136         sv := this.shuffledServiceRoots(hash)
137
138         for _, host := range sv {
139                 var req *http.Request
140                 var err error
141                 var url string
142                 if signature != "" {
143                         url = fmt.Sprintf("%s/%s+A%s@%s", host, hash,
144                                 signature, timestamp)
145                 } else {
146                         url = fmt.Sprintf("%s/%s", host, hash)
147                 }
148                 if req, err = http.NewRequest("GET", url, nil); err != nil {
149                         continue
150                 }
151
152                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
153
154                 var resp *http.Response
155                 if resp, err = this.Client.Do(req); err != nil {
156                         continue
157                 }
158
159                 if resp.StatusCode == http.StatusOK {
160                         return HashCheckingReader{resp.Body, md5.New(), hash}, resp.ContentLength, url, nil
161                 }
162         }
163
164         return nil, 0, "", BlockNotFound
165 }
166
167 // Determine if a block with the given hash is available and readable, but does
168 // not return the block contents.
169 func (this KeepClient) Ask(hash string) (contentLength int64, url string, err error) {
170         return this.AuthorizedAsk(hash, "", "")
171 }
172
173 // Determine if a block with the given hash is available and readable with the
174 // given signature and timestamp, but does not return the block contents.
175 func (this KeepClient) AuthorizedAsk(hash string, signature string,
176         timestamp string) (contentLength int64, url string, err error) {
177         // Calculate the ordering for asking servers
178         sv := this.shuffledServiceRoots(hash)
179
180         for _, host := range sv {
181                 var req *http.Request
182                 var err error
183                 if signature != "" {
184                         url = fmt.Sprintf("%s/%s+A%s@%s", host, hash,
185                                 signature, timestamp)
186                 } else {
187                         url = fmt.Sprintf("%s/%s", host, hash)
188                 }
189
190                 if req, err = http.NewRequest("HEAD", url, nil); err != nil {
191                         continue
192                 }
193
194                 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
195
196                 var resp *http.Response
197                 if resp, err = this.Client.Do(req); err != nil {
198                         continue
199                 }
200
201                 if resp.StatusCode == http.StatusOK {
202                         return resp.ContentLength, url, nil
203                 }
204         }
205
206         return 0, "", BlockNotFound
207
208 }
209
210 // Atomically read the service_roots field.
211 func (this *KeepClient) ServiceRoots() []string {
212         r := (*[]string)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&this.service_roots))))
213         return *r
214 }
215
216 // Atomically update the service_roots field.  Enables you to update
217 // service_roots without disrupting any GET or PUT operations that might
218 // already be in progress.
219 func (this *KeepClient) SetServiceRoots(svc []string) {
220         // Must be sorted for ShuffledServiceRoots() to produce consistent
221         // results.
222         roots := make([]string, len(svc))
223         copy(roots, svc)
224         sort.Strings(roots)
225         atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&this.service_roots)),
226                 unsafe.Pointer(&roots))
227 }
228
229 type Locator struct {
230         Hash      string
231         Size      int
232         Signature string
233         Timestamp string
234 }
235
236 func MakeLocator2(hash string, hints string) (locator Locator) {
237         locator.Hash = hash
238         if hints != "" {
239                 signature_pat, _ := regexp.Compile("^A([[:xdigit:]]+)@([[:xdigit:]]{8})$")
240                 for _, hint := range strings.Split(hints, "+") {
241                         if hint != "" {
242                                 if match, _ := regexp.MatchString("^[[:digit:]]+$", hint); match {
243                                         fmt.Sscanf(hint, "%d", &locator.Size)
244                                 } else if m := signature_pat.FindStringSubmatch(hint); m != nil {
245                                         locator.Signature = m[1]
246                                         locator.Timestamp = m[2]
247                                 } else if match, _ := regexp.MatchString("^[:upper:]", hint); match {
248                                         // Any unknown hint that starts with an uppercase letter is
249                                         // presumed to be valid and ignored, to permit forward compatibility.
250                                 } else {
251                                         // Unknown format; not a valid locator.
252                                         return Locator{"", 0, "", ""}
253                                 }
254                         }
255                 }
256         }
257         return locator
258 }
259
260 func MakeLocator(path string) Locator {
261         pathpattern, err := regexp.Compile("^([0-9a-f]{32})([+].*)?$")
262         if err != nil {
263                 log.Print("Don't like regexp", err)
264         }
265
266         sm := pathpattern.FindStringSubmatch(path)
267         if sm == nil {
268                 log.Print("Failed match ", path)
269                 return Locator{"", 0, "", ""}
270         }
271
272         return MakeLocator2(sm[1], sm[2])
273 }