3 // REST handlers for Keep are implemented here.
5 // GetBlockHandler (GET /locator)
6 // PutBlockHandler (PUT /locator)
7 // IndexHandler (GET /index, GET /index/prefix)
8 // StatusHandler (GET /status.json)
17 "github.com/gorilla/mux"
30 // MakeRESTRouter returns a new mux.Router that forwards all Keep
31 // requests to the appropriate handlers.
33 func MakeRESTRouter() *mux.Router {
34 rest := mux.NewRouter()
37 `/{hash:[0-9a-f]{32}}`, GetBlockHandler).Methods("GET", "HEAD")
39 `/{hash:[0-9a-f]{32}}+{hints}`,
40 GetBlockHandler).Methods("GET", "HEAD")
42 rest.HandleFunc(`/{hash:[0-9a-f]{32}}`, PutBlockHandler).Methods("PUT")
43 rest.HandleFunc(`/{hash:[0-9a-f]{32}}`, DeleteHandler).Methods("DELETE")
45 // For IndexHandler we support:
46 // /index - returns all locators
47 // /index/{prefix} - returns all locators that begin with {prefix}
48 // {prefix} is a string of hexadecimal digits between 0 and 32 digits.
49 // If {prefix} is the empty string, return an index of all locators
50 // (so /index and /index/ behave identically)
51 // A client may supply a full 32-digit locator string, in which
52 // case the server will return an index with either zero or one
53 // entries. This usage allows a client to check whether a block is
54 // present, and its size and upload time, without retrieving the
57 rest.HandleFunc(`/index`, IndexHandler).Methods("GET", "HEAD")
59 `/index/{prefix:[0-9a-f]{0,32}}`, IndexHandler).Methods("GET", "HEAD")
60 rest.HandleFunc(`/status.json`, StatusHandler).Methods("GET", "HEAD")
62 // The PullHandler and TrashHandler process "PUT /pull" and "PUT
63 // /trash" requests from Data Manager. These requests instruct
64 // Keep to replicate or delete blocks; see
65 // https://arvados.org/projects/arvados/wiki/Keep_Design_Doc
68 // Each handler parses the JSON list of block management requests
69 // in the message body, and replaces any existing pull queue or
70 // trash queue with their contentes.
72 rest.HandleFunc(`/pull`, PullHandler).Methods("PUT")
73 rest.HandleFunc(`/trash`, TrashHandler).Methods("PUT")
75 // Any request which does not match any of these routes gets
77 rest.NotFoundHandler = http.HandlerFunc(BadRequestHandler)
82 func BadRequestHandler(w http.ResponseWriter, r *http.Request) {
83 http.Error(w, BadRequestError.Error(), BadRequestError.HTTPCode)
86 // FindKeepVolumes scans all mounted volumes on the system for Keep
87 // volumes, and returns a list of matching paths.
89 // A device is assumed to be a Keep volume if it is a normal or tmpfs
90 // volume and has a "/keep" directory directly underneath the mount
93 func FindKeepVolumes() []string {
94 vols := make([]string, 0)
96 if f, err := os.Open(PROC_MOUNTS); err != nil {
97 log.Fatalf("opening %s: %s\n", PROC_MOUNTS, err)
99 scanner := bufio.NewScanner(f)
101 args := strings.Fields(scanner.Text())
102 dev, mount := args[0], args[1]
104 (dev == "tmpfs" || strings.HasPrefix(dev, "/dev/")) {
105 keep := mount + "/keep"
106 if st, err := os.Stat(keep); err == nil && st.IsDir() {
107 vols = append(vols, keep)
111 if err := scanner.Err(); err != nil {
118 func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
119 hash := mux.Vars(req)["hash"]
121 hints := mux.Vars(req)["hints"]
123 // Parse the locator string and hints from the request.
124 // TODO(twp): implement a Locator type.
125 var signature, timestamp string
127 signature_pat, _ := regexp.Compile("^A([[:xdigit:]]+)@([[:xdigit:]]{8})$")
128 for _, hint := range strings.Split(hints, "+") {
129 if match, _ := regexp.MatchString("^[[:digit:]]+$", hint); match {
130 // Server ignores size hints
131 } else if m := signature_pat.FindStringSubmatch(hint); m != nil {
134 } else if match, _ := regexp.MatchString("^[[:upper:]]", hint); match {
135 // Any unknown hint that starts with an uppercase letter is
136 // presumed to be valid and ignored, to permit forward compatibility.
138 // Unknown format; not a valid locator.
139 http.Error(resp, BadRequestError.Error(), BadRequestError.HTTPCode)
145 // If permission checking is in effect, verify this
146 // request's permission signature.
147 if enforce_permissions {
148 if signature == "" || timestamp == "" {
149 http.Error(resp, PermissionError.Error(), PermissionError.HTTPCode)
151 } else if IsExpired(timestamp) {
152 http.Error(resp, ExpiredError.Error(), ExpiredError.HTTPCode)
155 req_locator := req.URL.Path[1:] // strip leading slash
156 if !VerifySignature(req_locator, GetApiToken(req)) {
157 http.Error(resp, PermissionError.Error(), PermissionError.HTTPCode)
163 block, err := GetBlock(hash, false)
165 // Garbage collect after each GET. Fixes #2865.
166 // TODO(twp): review Keep memory usage and see if there's
167 // a better way to do this than blindly garbage collecting
168 // after every block.
172 // This type assertion is safe because the only errors
173 // GetBlock can return are DiskHashError or NotFoundError.
174 http.Error(resp, err.Error(), err.(*KeepError).HTTPCode)
178 resp.Header().Set("Content-Length", fmt.Sprintf("%d", len(block)))
180 _, err = resp.Write(block)
185 func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
186 // Garbage collect after each PUT. Fixes #2865.
187 // See also GetBlockHandler.
190 hash := mux.Vars(req)["hash"]
192 // Read the block data to be stored.
193 // If the request exceeds BLOCKSIZE bytes, issue a HTTP 500 error.
195 if req.ContentLength > BLOCKSIZE {
196 http.Error(resp, TooLongError.Error(), TooLongError.HTTPCode)
200 buf := make([]byte, req.ContentLength)
201 nread, err := io.ReadFull(req.Body, buf)
203 http.Error(resp, err.Error(), 500)
204 } else if int64(nread) < req.ContentLength {
205 http.Error(resp, "request truncated", 500)
207 if err := PutBlock(buf, hash); err == nil {
208 // Success; add a size hint, sign the locator if
209 // possible, and return it to the client.
210 return_hash := fmt.Sprintf("%s+%d", hash, len(buf))
211 api_token := GetApiToken(req)
212 if PermissionSecret != nil && api_token != "" {
213 expiry := time.Now().Add(permission_ttl)
214 return_hash = SignLocator(return_hash, api_token, expiry)
216 resp.Write([]byte(return_hash + "\n"))
218 ke := err.(*KeepError)
219 http.Error(resp, ke.Error(), ke.HTTPCode)
226 // A HandleFunc to address /index and /index/{prefix} requests.
228 func IndexHandler(resp http.ResponseWriter, req *http.Request) {
229 // Reject unauthorized requests.
230 if !IsDataManagerToken(GetApiToken(req)) {
231 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
235 prefix := mux.Vars(req)["prefix"]
238 for _, vol := range KeepVM.Volumes() {
239 index = index + vol.Index(prefix)
241 resp.Write([]byte(index))
245 // Responds to /status.json requests with the current node status,
246 // described in a JSON structure.
248 // The data given in a status.json response includes:
249 // volumes - a list of Keep volumes currently in use by this server
250 // each volume is an object with the following fields:
252 // * device_num (an integer identifying the underlying filesystem)
256 type VolumeStatus struct {
257 MountPoint string `json:"mount_point"`
258 DeviceNum uint64 `json:"device_num"`
259 BytesFree uint64 `json:"bytes_free"`
260 BytesUsed uint64 `json:"bytes_used"`
263 type NodeStatus struct {
264 Volumes []*VolumeStatus `json:"volumes"`
267 func StatusHandler(resp http.ResponseWriter, req *http.Request) {
268 st := GetNodeStatus()
269 if jstat, err := json.Marshal(st); err == nil {
272 log.Printf("json.Marshal: %s\n", err)
273 log.Printf("NodeStatus = %v\n", st)
274 http.Error(resp, err.Error(), 500)
279 // Returns a NodeStatus struct describing this Keep
280 // node's current status.
282 func GetNodeStatus() *NodeStatus {
283 st := new(NodeStatus)
285 st.Volumes = make([]*VolumeStatus, len(KeepVM.Volumes()))
286 for i, vol := range KeepVM.Volumes() {
287 st.Volumes[i] = vol.Status()
293 // Returns a VolumeStatus describing the requested volume.
295 func GetVolumeStatus(volume string) *VolumeStatus {
296 var fs syscall.Statfs_t
299 if fi, err := os.Stat(volume); err == nil {
300 devnum = fi.Sys().(*syscall.Stat_t).Dev
302 log.Printf("GetVolumeStatus: os.Stat: %s\n", err)
306 err := syscall.Statfs(volume, &fs)
308 log.Printf("GetVolumeStatus: statfs: %s\n", err)
311 // These calculations match the way df calculates disk usage:
312 // "free" space is measured by fs.Bavail, but "used" space
313 // uses fs.Blocks - fs.Bfree.
314 free := fs.Bavail * uint64(fs.Bsize)
315 used := (fs.Blocks - fs.Bfree) * uint64(fs.Bsize)
316 return &VolumeStatus{volume, devnum, free, used}
319 // DeleteHandler processes DELETE requests.
321 // DELETE /{hash:[0-9a-f]{32} will delete the block with the specified hash
322 // from all connected volumes.
324 // Only the Data Manager, or an Arvados admin with scope "all", are
325 // allowed to issue DELETE requests. If a DELETE request is not
326 // authenticated or is issued by a non-admin user, the server returns
327 // a PermissionError.
329 // Upon receiving a valid request from an authorized user,
330 // DeleteHandler deletes all copies of the specified block on local
335 // If the requested blocks was not found on any volume, the response
336 // code is HTTP 404 Not Found.
338 // Otherwise, the response code is 200 OK, with a response body
339 // consisting of the JSON message
341 // {"copies_deleted":d,"copies_failed":f}
343 // where d and f are integers representing the number of blocks that
344 // were successfully and unsuccessfully deleted.
346 func DeleteHandler(resp http.ResponseWriter, req *http.Request) {
347 hash := mux.Vars(req)["hash"]
349 // Confirm that this user is an admin and has a token with unlimited scope.
350 var tok = GetApiToken(req)
351 if tok == "" || !CanDelete(tok) {
352 http.Error(resp, PermissionError.Error(), PermissionError.HTTPCode)
357 http.Error(resp, MethodDisabledError.Error(), MethodDisabledError.HTTPCode)
361 // Delete copies of this block from all available volumes. Report
362 // how many blocks were successfully and unsuccessfully
365 Deleted int `json:"copies_deleted"`
366 Failed int `json:"copies_failed"`
368 for _, vol := range KeepVM.Volumes() {
369 if err := vol.Delete(hash); err == nil {
371 } else if os.IsNotExist(err) {
375 log.Println("DeleteHandler:", err)
381 if result.Deleted == 0 && result.Failed == 0 {
382 st = http.StatusNotFound
389 if st == http.StatusOK {
390 if body, err := json.Marshal(result); err == nil {
393 log.Printf("json.Marshal: %s (result = %v)\n", err, result)
394 http.Error(resp, err.Error(), 500)
399 /* PullHandler processes "PUT /pull" requests for the data manager.
400 The request body is a JSON message containing a list of pull
401 requests in the following format:
405 "locator":"e4d909c290d0fb1ca068ffaddf22cbd0+4985",
407 "keep0.qr1hi.arvadosapi.com:25107",
408 "keep1.qr1hi.arvadosapi.com:25108"
412 "locator":"55ae4d45d2db0793d53f03e805f656e5+658395",
422 Each pull request in the list consists of a block locator string
423 and an ordered list of servers. Keepstore should try to fetch the
424 block from each server in turn.
426 If the request has not been sent by the Data Manager, return 401
429 If the JSON unmarshalling fails, return 400 Bad Request.
432 type PullRequest struct {
433 Locator string `json:"locator"`
434 Servers []string `json:"servers"`
437 func PullHandler(resp http.ResponseWriter, req *http.Request) {
438 // Reject unauthorized requests.
439 if !IsDataManagerToken(GetApiToken(req)) {
440 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
444 // Parse the request body.
446 r := json.NewDecoder(req.Body)
447 if err := r.Decode(&pr); err != nil {
448 http.Error(resp, BadRequestError.Error(), BadRequestError.HTTPCode)
452 // We have a properly formatted pull list sent from the data
453 // manager. Report success and send the list to the pull list
454 // manager for further handling.
455 resp.WriteHeader(http.StatusOK)
457 fmt.Sprintf("Received %d pull requests\n", len(pr))))
460 for _, p := range pr {
463 pullq.ReplaceQueue(plist)
466 type TrashRequest struct {
467 Locator string `json:"locator"`
468 BlockMtime int64 `json:"block_mtime"`
471 func TrashHandler(resp http.ResponseWriter, req *http.Request) {
472 // Reject unauthorized requests.
473 if !IsDataManagerToken(GetApiToken(req)) {
474 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
478 // Parse the request body.
479 var trash []TrashRequest
480 r := json.NewDecoder(req.Body)
481 if err := r.Decode(&trash); err != nil {
482 http.Error(resp, BadRequestError.Error(), BadRequestError.HTTPCode)
486 // We have a properly formatted trash list sent from the data
487 // manager. Report success and send the list to the trash work
488 // queue for further handling.
489 resp.WriteHeader(http.StatusOK)
491 fmt.Sprintf("Received %d trash requests\n", len(trash))))
494 for _, t := range trash {
497 trashq.ReplaceQueue(tlist)
500 // ==============================
501 // GetBlock and PutBlock implement lower-level code for handling
502 // blocks by rooting through volumes connected to the local machine.
503 // Once the handler has determined that system policy permits the
504 // request, it calls these methods to perform the actual operation.
506 // TODO(twp): this code would probably be better located in the
507 // VolumeManager interface. As an abstraction, the VolumeManager
508 // should be the only part of the code that cares about which volume a
509 // block is stored on, so it should be responsible for figuring out
510 // which volume to check for fetching blocks, storing blocks, etc.
512 // ==============================
513 // GetBlock fetches and returns the block identified by "hash". If
514 // the update_timestamp argument is true, GetBlock also updates the
515 // block's file modification time (for the sake of PutBlock, which
516 // must update the file's timestamp when the block already exists).
518 // On success, GetBlock returns a byte slice with the block data, and
521 // If the block cannot be found on any volume, returns NotFoundError.
523 // If the block found does not have the correct MD5 hash, returns
527 func GetBlock(hash string, update_timestamp bool) ([]byte, error) {
528 // Attempt to read the requested hash from a keep volume.
529 error_to_caller := NotFoundError
531 for _, vol := range KeepVM.Volumes() {
532 if buf, err := vol.Get(hash); err != nil {
533 // IsNotExist is an expected error and may be ignored.
534 // (If all volumes report IsNotExist, we return a NotFoundError)
535 // All other errors should be logged but we continue trying to
538 case os.IsNotExist(err):
541 log.Printf("GetBlock: reading %s: %s\n", hash, err)
544 // Double check the file checksum.
546 filehash := fmt.Sprintf("%x", md5.Sum(buf))
547 if filehash != hash {
548 // TODO(twp): this condition probably represents a bad disk and
549 // should raise major alarm bells for an administrator: e.g.
550 // they should be sent directly to an event manager at high
551 // priority or logged as urgent problems.
553 log.Printf("%s: checksum mismatch for request %s (actual %s)\n",
555 error_to_caller = DiskHashError
558 if error_to_caller != NotFoundError {
559 log.Printf("%s: checksum mismatch for request %s but a good copy was found on another volume and returned\n",
562 // Update the timestamp if the caller requested.
563 // If we could not update the timestamp, continue looking on
565 if update_timestamp {
566 if vol.Touch(hash) != nil {
575 if error_to_caller != NotFoundError {
576 log.Printf("%s: checksum mismatch, no good copy found\n", hash)
578 return nil, error_to_caller
581 /* PutBlock(block, hash)
582 Stores the BLOCK (identified by the content id HASH) in Keep.
584 The MD5 checksum of the block must be identical to the content id HASH.
585 If not, an error is returned.
587 PutBlock stores the BLOCK on the first Keep volume with free space.
588 A failure code is returned to the user only if all volumes fail.
590 On success, PutBlock returns nil.
591 On failure, it returns a KeepError with one of the following codes:
594 A different block with the same hash already exists on this
597 The MD5 hash of the BLOCK does not match the argument HASH.
599 There was not enough space left in any Keep volume to store
602 The object could not be stored for some other reason (e.g.
603 all writes failed). The text of the error message should
604 provide as much detail as possible.
607 func PutBlock(block []byte, hash string) error {
608 // Check that BLOCK's checksum matches HASH.
609 blockhash := fmt.Sprintf("%x", md5.Sum(block))
610 if blockhash != hash {
611 log.Printf("%s: MD5 checksum %s did not match request", hash, blockhash)
612 return RequestHashError
615 // If we already have a block on disk under this identifier, return
616 // success (but check for MD5 collisions). While fetching the block,
617 // update its timestamp.
618 // The only errors that GetBlock can return are DiskHashError and NotFoundError.
619 // In either case, we want to write our new (good) block to disk,
620 // so there is nothing special to do if err != nil.
622 if oldblock, err := GetBlock(hash, true); err == nil {
623 if bytes.Compare(block, oldblock) == 0 {
624 // The block already exists; return success.
627 return CollisionError
631 // Choose a Keep volume to write to.
632 // If this volume fails, try all of the volumes in order.
633 vol := KeepVM.Choose()
634 if err := vol.Put(hash, block); err == nil {
635 return nil // success!
638 for _, vol := range KeepVM.Volumes() {
639 err := vol.Put(hash, block)
641 return nil // success!
643 if err != FullError {
644 // The volume is not full but the write did not succeed.
645 // Report the error and continue trying.
647 log.Printf("%s: Write(%s): %s\n", vol, hash, err)
652 log.Printf("all Keep volumes full")
655 log.Printf("all Keep volumes failed")
662 // Return true if the specified string is a valid Keep locator.
663 // When Keep is extended to support hash types other than MD5,
664 // this should be updated to cover those as well.
666 func IsValidLocator(loc string) bool {
667 match, err := regexp.MatchString(`^[0-9a-f]{32}$`, loc)
671 log.Printf("IsValidLocator: %s\n", err)
675 // GetApiToken returns the OAuth2 token from the Authorization
676 // header of a HTTP request, or an empty string if no matching
678 func GetApiToken(req *http.Request) string {
679 if auth, ok := req.Header["Authorization"]; ok {
680 if pat, err := regexp.Compile(`^OAuth2\s+(.*)`); err != nil {
682 } else if match := pat.FindStringSubmatch(auth[0]); match != nil {
689 // IsExpired returns true if the given Unix timestamp (expressed as a
690 // hexadecimal string) is in the past, or if timestamp_hex cannot be
691 // parsed as a hexadecimal string.
692 func IsExpired(timestamp_hex string) bool {
693 ts, err := strconv.ParseInt(timestamp_hex, 16, 0)
695 log.Printf("IsExpired: %s\n", err)
698 return time.Unix(ts, 0).Before(time.Now())
701 // CanDelete returns true if the user identified by api_token is
702 // allowed to delete blocks.
703 func CanDelete(api_token string) bool {
707 // Blocks may be deleted only when Keep has been configured with a
709 if IsDataManagerToken(api_token) {
712 // TODO(twp): look up api_token with the API server
713 // return true if is_admin is true and if the token
714 // has unlimited scope
718 // IsDataManagerToken returns true if api_token represents the data
720 func IsDataManagerToken(api_token string) bool {
721 return data_manager_token != "" && api_token == data_manager_token