1 /* Provides low-level Get/Put primitives for accessing Arvados Keep blocks. */
22 // A Keep "block" is 64MB.
23 const BLOCKSIZE = 64 * 1024 * 1024
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")
31 const X_Keep_Desired_Replicas = "X-Keep-Desired-Replicas"
32 const X_Keep_Replicas_Stored = "X-Keep-Replicas-Stored"
34 // Information about Arvados and Keep servers.
35 type KeepClient struct {
36 Arvados *sdk.ArvadosClient
39 service_roots *[]string
44 // Create a new KeepClient. This will contact the API server to discover Keep
46 func MakeKeepClient(arv *sdk.ArvadosClient) (kc KeepClient, err error) {
51 Client: &http.Client{Transport: &http.Transport{}}}
53 err = (&kc).DiscoverKeepServers()
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) {
65 // Buffer for reads from 'r'
67 if expectedLength > 0 {
68 if expectedLength > BLOCKSIZE {
69 return "", 0, OversizeBlockError
71 bufsize = int(expectedLength)
76 t := streamer.AsyncStreamFromReader(bufsize, HashCheckingReader{r, md5.New(), hash})
79 return this.putReplicas(hash, t, expectedLength)
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)
90 return this.putReplicas(hash, t, int64(len(buf)))
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)
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 {
112 return this.PutB(buffer)
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, "", "")
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,
132 timestamp string) (reader io.ReadCloser,
133 contentLength int64, url string, err error) {
135 // Calculate the ordering for asking servers
136 sv := this.shuffledServiceRoots(hash)
138 for _, host := range sv {
139 var req *http.Request
143 url = fmt.Sprintf("%s/%s+A%s@%s", host, hash,
144 signature, timestamp)
146 url = fmt.Sprintf("%s/%s", host, hash)
148 if req, err = http.NewRequest("GET", url, nil); err != nil {
152 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
154 var resp *http.Response
155 if resp, err = this.Client.Do(req); err != nil {
159 if resp.StatusCode == http.StatusOK {
160 return HashCheckingReader{resp.Body, md5.New(), hash}, resp.ContentLength, url, nil
164 return nil, 0, "", BlockNotFound
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, "", "")
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)
180 for _, host := range sv {
181 var req *http.Request
184 url = fmt.Sprintf("%s/%s+A%s@%s", host, hash,
185 signature, timestamp)
187 url = fmt.Sprintf("%s/%s", host, hash)
190 if req, err = http.NewRequest("HEAD", url, nil); err != nil {
194 req.Header.Add("Authorization", fmt.Sprintf("OAuth2 %s", this.Arvados.ApiToken))
196 var resp *http.Response
197 if resp, err = this.Client.Do(req); err != nil {
201 if resp.StatusCode == http.StatusOK {
202 return resp.ContentLength, url, nil
206 return 0, "", BlockNotFound
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))))
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
222 roots := make([]string, len(svc))
225 atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&this.service_roots)),
226 unsafe.Pointer(&roots))
229 type Locator struct {
236 func MakeLocator2(hash string, hints string) (locator Locator) {
239 signature_pat, _ := regexp.Compile("^A([[:xdigit:]]+)@([[:xdigit:]]{8})$")
240 for _, hint := range strings.Split(hints, "+") {
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.
251 // Unknown format; not a valid locator.
252 return Locator{"", 0, "", ""}
260 func MakeLocator(path string) Locator {
261 pathpattern, err := regexp.Compile("^([0-9a-f]{32})([+].*)?$")
263 log.Print("Don't like regexp", err)
266 sm := pathpattern.FindStringSubmatch(path)
268 log.Print("Failed match ", path)
269 return Locator{"", 0, "", ""}
272 return MakeLocator2(sm[1], sm[2])