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)
16 "github.com/gorilla/mux"
29 // MakeRESTRouter returns a new mux.Router that forwards all Keep
30 // requests to the appropriate handlers.
32 func MakeRESTRouter() *mux.Router {
33 rest := mux.NewRouter()
36 `/{hash:[0-9a-f]{32}}`, GetBlockHandler).Methods("GET", "HEAD")
38 `/{hash:[0-9a-f]{32}}+{hints}`,
39 GetBlockHandler).Methods("GET", "HEAD")
41 rest.HandleFunc(`/{hash:[0-9a-f]{32}}`, PutBlockHandler).Methods("PUT")
42 rest.HandleFunc(`/{hash:[0-9a-f]{32}}`, DeleteHandler).Methods("DELETE")
43 // List all blocks stored here. Privileged client only.
44 rest.HandleFunc(`/index`, IndexHandler).Methods("GET", "HEAD")
45 // List blocks stored here whose hash has the given prefix.
46 // Privileged client only.
47 rest.HandleFunc(`/index/{prefix:[0-9a-f]{0,32}}`, IndexHandler).Methods("GET", "HEAD")
49 // Internals/debugging info (runtime.MemStats)
50 rest.HandleFunc(`/debug.json`, DebugHandler).Methods("GET", "HEAD")
52 // List volumes: path, device number, bytes used/avail.
53 rest.HandleFunc(`/status.json`, StatusHandler).Methods("GET", "HEAD")
55 // Replace the current pull queue.
56 rest.HandleFunc(`/pull`, PullHandler).Methods("PUT")
58 // Replace the current trash queue.
59 rest.HandleFunc(`/trash`, TrashHandler).Methods("PUT")
61 // Untrash moves blocks from trash back into store
62 rest.HandleFunc(`/untrash/{hash:[0-9a-f]{32}}`, UntrashHandler).Methods("PUT")
64 // Any request which does not match any of these routes gets
66 rest.NotFoundHandler = http.HandlerFunc(BadRequestHandler)
71 // BadRequestHandler is a HandleFunc to address bad requests.
72 func BadRequestHandler(w http.ResponseWriter, r *http.Request) {
73 http.Error(w, BadRequestError.Error(), BadRequestError.HTTPCode)
76 // GetBlockHandler is a HandleFunc to address Get block requests.
77 func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
78 ctx, cancel := contextForResponse(context.TODO(), resp)
81 if theConfig.RequireSignatures {
82 locator := req.URL.Path[1:] // strip leading slash
83 if err := VerifySignature(locator, GetAPIToken(req)); err != nil {
84 http.Error(resp, err.Error(), err.(*KeepError).HTTPCode)
89 // TODO: Probe volumes to check whether the block _might_
90 // exist. Some volumes/types could support a quick existence
91 // check without causing other operations to suffer. If all
92 // volumes support that, and assure us the block definitely
93 // isn't here, we can return 404 now instead of waiting for a
96 buf, err := getBufferWithContext(ctx, bufs, BlockSize)
98 http.Error(resp, err.Error(), http.StatusServiceUnavailable)
103 size, err := GetBlock(ctx, mux.Vars(req)["hash"], buf, resp)
105 code := http.StatusInternalServerError
106 if err, ok := err.(*KeepError); ok {
109 http.Error(resp, err.Error(), code)
113 resp.Header().Set("Content-Length", strconv.Itoa(size))
114 resp.Header().Set("Content-Type", "application/octet-stream")
115 resp.Write(buf[:size])
118 // Return a new context that gets cancelled by resp's CloseNotifier.
119 func contextForResponse(parent context.Context, resp http.ResponseWriter) (context.Context, context.CancelFunc) {
120 ctx, cancel := context.WithCancel(parent)
121 if cn, ok := resp.(http.CloseNotifier); ok {
122 go func(c <-chan bool) {
125 theConfig.debugLogf("cancel context")
134 // Get a buffer from the pool -- but give up and return a non-nil
135 // error if ctx ends before we get a buffer.
136 func getBufferWithContext(ctx context.Context, bufs *bufferPool, bufSize int) ([]byte, error) {
137 bufReady := make(chan []byte)
139 bufReady <- bufs.Get(bufSize)
142 case buf := <-bufReady:
146 // Even if closeNotifier happened first, we
147 // need to keep waiting for our buf so we can
148 // return it to the pool.
151 return nil, ErrClientDisconnect
155 // PutBlockHandler is a HandleFunc to address Put block requests.
156 func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
157 ctx, cancel := contextForResponse(context.TODO(), resp)
160 hash := mux.Vars(req)["hash"]
162 // Detect as many error conditions as possible before reading
163 // the body: avoid transmitting data that will not end up
164 // being written anyway.
166 if req.ContentLength == -1 {
167 http.Error(resp, SizeRequiredError.Error(), SizeRequiredError.HTTPCode)
171 if req.ContentLength > BlockSize {
172 http.Error(resp, TooLongError.Error(), TooLongError.HTTPCode)
176 if len(KeepVM.AllWritable()) == 0 {
177 http.Error(resp, FullError.Error(), FullError.HTTPCode)
181 buf, err := getBufferWithContext(ctx, bufs, int(req.ContentLength))
183 http.Error(resp, err.Error(), http.StatusServiceUnavailable)
187 _, err = io.ReadFull(req.Body, buf)
189 http.Error(resp, err.Error(), 500)
194 replication, err := PutBlock(ctx, buf, hash)
198 code := http.StatusInternalServerError
199 if err, ok := err.(*KeepError); ok {
202 http.Error(resp, err.Error(), code)
206 // Success; add a size hint, sign the locator if possible, and
207 // return it to the client.
208 returnHash := fmt.Sprintf("%s+%d", hash, req.ContentLength)
209 apiToken := GetAPIToken(req)
210 if theConfig.blobSigningKey != nil && apiToken != "" {
211 expiry := time.Now().Add(theConfig.BlobSignatureTTL.Duration())
212 returnHash = SignLocator(returnHash, apiToken, expiry)
214 resp.Header().Set("X-Keep-Replicas-Stored", strconv.Itoa(replication))
215 resp.Write([]byte(returnHash + "\n"))
218 // IndexHandler is a HandleFunc to address /index and /index/{prefix} requests.
219 func IndexHandler(resp http.ResponseWriter, req *http.Request) {
220 // Reject unauthorized requests.
221 if !IsSystemAuth(GetAPIToken(req)) {
222 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
226 prefix := mux.Vars(req)["prefix"]
228 for _, vol := range KeepVM.AllReadable() {
229 if err := vol.IndexTo(prefix, resp); err != nil {
230 // The only errors returned by IndexTo are
231 // write errors returned by resp.Write(),
232 // which probably means the client has
233 // disconnected and this error will never be
234 // reported to the client -- but it will
235 // appear in our own error log.
236 http.Error(resp, err.Error(), http.StatusInternalServerError)
240 // An empty line at EOF is the only way the client can be
241 // assured the entire index was received.
242 resp.Write([]byte{'\n'})
246 type PoolStatus struct {
247 Alloc uint64 `json:"BytesAllocated"`
248 Cap int `json:"BuffersMax"`
249 Len int `json:"BuffersInUse"`
253 type NodeStatus struct {
254 Volumes []*VolumeStatus `json:"volumes"`
255 BufferPool PoolStatus
256 PullQueue WorkQueueStatus
257 TrashQueue WorkQueueStatus
261 var stLock sync.Mutex
263 // DebugHandler addresses /debug.json requests.
264 func DebugHandler(resp http.ResponseWriter, req *http.Request) {
265 type debugStats struct {
266 MemStats runtime.MemStats
269 runtime.ReadMemStats(&ds.MemStats)
270 err := json.NewEncoder(resp).Encode(&ds)
272 http.Error(resp, err.Error(), 500)
276 // StatusHandler addresses /status.json requests.
277 func StatusHandler(resp http.ResponseWriter, req *http.Request) {
280 jstat, err := json.Marshal(&st)
285 log.Printf("json.Marshal: %s", err)
286 log.Printf("NodeStatus = %v", &st)
287 http.Error(resp, err.Error(), 500)
291 // populate the given NodeStatus struct with current values.
292 func readNodeStatus(st *NodeStatus) {
293 vols := KeepVM.AllReadable()
294 if cap(st.Volumes) < len(vols) {
295 st.Volumes = make([]*VolumeStatus, len(vols))
297 st.Volumes = st.Volumes[:0]
298 for _, vol := range vols {
299 if s := vol.Status(); s != nil {
300 st.Volumes = append(st.Volumes, s)
303 st.BufferPool.Alloc = bufs.Alloc()
304 st.BufferPool.Cap = bufs.Cap()
305 st.BufferPool.Len = bufs.Len()
306 st.PullQueue = getWorkQueueStatus(pullq)
307 st.TrashQueue = getWorkQueueStatus(trashq)
310 // return a WorkQueueStatus for the given queue. If q is nil (which
311 // should never happen except in test suites), return a zero status
312 // value instead of crashing.
313 func getWorkQueueStatus(q *WorkQueue) WorkQueueStatus {
315 // This should only happen during tests.
316 return WorkQueueStatus{}
321 // DeleteHandler processes DELETE requests.
323 // DELETE /{hash:[0-9a-f]{32} will delete the block with the specified hash
324 // from all connected volumes.
326 // Only the Data Manager, or an Arvados admin with scope "all", are
327 // allowed to issue DELETE requests. If a DELETE request is not
328 // authenticated or is issued by a non-admin user, the server returns
329 // a PermissionError.
331 // Upon receiving a valid request from an authorized user,
332 // DeleteHandler deletes all copies of the specified block on local
337 // If the requested blocks was not found on any volume, the response
338 // code is HTTP 404 Not Found.
340 // Otherwise, the response code is 200 OK, with a response body
341 // consisting of the JSON message
343 // {"copies_deleted":d,"copies_failed":f}
345 // where d and f are integers representing the number of blocks that
346 // were successfully and unsuccessfully deleted.
348 func DeleteHandler(resp http.ResponseWriter, req *http.Request) {
349 hash := mux.Vars(req)["hash"]
351 // Confirm that this user is an admin and has a token with unlimited scope.
352 var tok = GetAPIToken(req)
353 if tok == "" || !CanDelete(tok) {
354 http.Error(resp, PermissionError.Error(), PermissionError.HTTPCode)
358 if !theConfig.EnableDelete {
359 http.Error(resp, MethodDisabledError.Error(), MethodDisabledError.HTTPCode)
363 // Delete copies of this block from all available volumes.
364 // Report how many blocks were successfully deleted, and how
365 // many were found on writable volumes but not deleted.
367 Deleted int `json:"copies_deleted"`
368 Failed int `json:"copies_failed"`
370 for _, vol := range KeepVM.AllWritable() {
371 if err := vol.Trash(hash); err == nil {
373 } else if os.IsNotExist(err) {
377 log.Println("DeleteHandler:", err)
383 if result.Deleted == 0 && result.Failed == 0 {
384 st = http.StatusNotFound
391 if st == http.StatusOK {
392 if body, err := json.Marshal(result); err == nil {
395 log.Printf("json.Marshal: %s (result = %v)", err, result)
396 http.Error(resp, err.Error(), 500)
401 /* PullHandler processes "PUT /pull" requests for the data manager.
402 The request body is a JSON message containing a list of pull
403 requests in the following format:
407 "locator":"e4d909c290d0fb1ca068ffaddf22cbd0+4985",
409 "keep0.qr1hi.arvadosapi.com:25107",
410 "keep1.qr1hi.arvadosapi.com:25108"
414 "locator":"55ae4d45d2db0793d53f03e805f656e5+658395",
424 Each pull request in the list consists of a block locator string
425 and an ordered list of servers. Keepstore should try to fetch the
426 block from each server in turn.
428 If the request has not been sent by the Data Manager, return 401
431 If the JSON unmarshalling fails, return 400 Bad Request.
434 // PullRequest consists of a block locator and an ordered list of servers
435 type PullRequest struct {
436 Locator string `json:"locator"`
437 Servers []string `json:"servers"`
440 // PullHandler processes "PUT /pull" requests for the data manager.
441 func PullHandler(resp http.ResponseWriter, req *http.Request) {
442 // Reject unauthorized requests.
443 if !IsSystemAuth(GetAPIToken(req)) {
444 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
448 // Parse the request body.
450 r := json.NewDecoder(req.Body)
451 if err := r.Decode(&pr); err != nil {
452 http.Error(resp, err.Error(), BadRequestError.HTTPCode)
456 // We have a properly formatted pull list sent from the data
457 // manager. Report success and send the list to the pull list
458 // manager for further handling.
459 resp.WriteHeader(http.StatusOK)
461 fmt.Sprintf("Received %d pull requests\n", len(pr))))
464 for _, p := range pr {
467 pullq.ReplaceQueue(plist)
470 // TrashRequest consists of a block locator and it's Mtime
471 type TrashRequest struct {
472 Locator string `json:"locator"`
473 BlockMtime int64 `json:"block_mtime"`
476 // TrashHandler processes /trash requests.
477 func TrashHandler(resp http.ResponseWriter, req *http.Request) {
478 // Reject unauthorized requests.
479 if !IsSystemAuth(GetAPIToken(req)) {
480 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
484 // Parse the request body.
485 var trash []TrashRequest
486 r := json.NewDecoder(req.Body)
487 if err := r.Decode(&trash); err != nil {
488 http.Error(resp, err.Error(), BadRequestError.HTTPCode)
492 // We have a properly formatted trash list sent from the data
493 // manager. Report success and send the list to the trash work
494 // queue for further handling.
495 resp.WriteHeader(http.StatusOK)
497 fmt.Sprintf("Received %d trash requests\n", len(trash))))
500 for _, t := range trash {
503 trashq.ReplaceQueue(tlist)
506 // UntrashHandler processes "PUT /untrash/{hash:[0-9a-f]{32}}" requests for the data manager.
507 func UntrashHandler(resp http.ResponseWriter, req *http.Request) {
508 // Reject unauthorized requests.
509 if !IsSystemAuth(GetAPIToken(req)) {
510 http.Error(resp, UnauthorizedError.Error(), UnauthorizedError.HTTPCode)
514 hash := mux.Vars(req)["hash"]
516 if len(KeepVM.AllWritable()) == 0 {
517 http.Error(resp, "No writable volumes", http.StatusNotFound)
521 var untrashedOn, failedOn []string
523 for _, vol := range KeepVM.AllWritable() {
524 err := vol.Untrash(hash)
526 if os.IsNotExist(err) {
528 } else if err != nil {
529 log.Printf("Error untrashing %v on volume %v", hash, vol.String())
530 failedOn = append(failedOn, vol.String())
532 log.Printf("Untrashed %v on volume %v", hash, vol.String())
533 untrashedOn = append(untrashedOn, vol.String())
537 if numNotFound == len(KeepVM.AllWritable()) {
538 http.Error(resp, "Block not found on any of the writable volumes", http.StatusNotFound)
542 if len(failedOn) == len(KeepVM.AllWritable()) {
543 http.Error(resp, "Failed to untrash on all writable volumes", http.StatusInternalServerError)
545 respBody := "Successfully untrashed on: " + strings.Join(untrashedOn, ",")
546 if len(failedOn) > 0 {
547 respBody += "; Failed to untrash on: " + strings.Join(failedOn, ",")
549 resp.Write([]byte(respBody))
553 // GetBlock and PutBlock implement lower-level code for handling
554 // blocks by rooting through volumes connected to the local machine.
555 // Once the handler has determined that system policy permits the
556 // request, it calls these methods to perform the actual operation.
558 // TODO(twp): this code would probably be better located in the
559 // VolumeManager interface. As an abstraction, the VolumeManager
560 // should be the only part of the code that cares about which volume a
561 // block is stored on, so it should be responsible for figuring out
562 // which volume to check for fetching blocks, storing blocks, etc.
564 // GetBlock fetches the block identified by "hash" into the provided
565 // buf, and returns the data size.
567 // If the block cannot be found on any volume, returns NotFoundError.
569 // If the block found does not have the correct MD5 hash, returns
572 func GetBlock(ctx context.Context, hash string, buf []byte, resp http.ResponseWriter) (int, error) {
573 // Attempt to read the requested hash from a keep volume.
574 errorToCaller := NotFoundError
576 for _, vol := range KeepVM.AllReadable() {
577 size, err := vol.Get(ctx, hash, buf)
580 return 0, ErrClientDisconnect
584 // IsNotExist is an expected error and may be
585 // ignored. All other errors are logged. In
586 // any case we continue trying to read other
587 // volumes. If all volumes report IsNotExist,
588 // we return a NotFoundError.
589 if !os.IsNotExist(err) {
590 log.Printf("%s: Get(%s): %s", vol, hash, err)
594 // Check the file checksum.
596 filehash := fmt.Sprintf("%x", md5.Sum(buf[:size]))
597 if filehash != hash {
598 // TODO: Try harder to tell a sysadmin about
600 log.Printf("%s: checksum mismatch for request %s (actual %s)",
602 errorToCaller = DiskHashError
605 if errorToCaller == DiskHashError {
606 log.Printf("%s: checksum mismatch for request %s but a good copy was found on another volume and returned",
611 return 0, errorToCaller
614 // PutBlock Stores the BLOCK (identified by the content id HASH) in Keep.
616 // PutBlock(ctx, block, hash)
617 // Stores the BLOCK (identified by the content id HASH) in Keep.
619 // The MD5 checksum of the block must be identical to the content id HASH.
620 // If not, an error is returned.
622 // PutBlock stores the BLOCK on the first Keep volume with free space.
623 // A failure code is returned to the user only if all volumes fail.
625 // On success, PutBlock returns nil.
626 // On failure, it returns a KeepError with one of the following codes:
629 // A different block with the same hash already exists on this
632 // The MD5 hash of the BLOCK does not match the argument HASH.
634 // There was not enough space left in any Keep volume to store
637 // The object could not be stored for some other reason (e.g.
638 // all writes failed). The text of the error message should
639 // provide as much detail as possible.
641 func PutBlock(ctx context.Context, block []byte, hash string) (int, error) {
642 // Check that BLOCK's checksum matches HASH.
643 blockhash := fmt.Sprintf("%x", md5.Sum(block))
644 if blockhash != hash {
645 log.Printf("%s: MD5 checksum %s did not match request", hash, blockhash)
646 return 0, RequestHashError
649 // If we already have this data, it's intact on disk, and we
650 // can update its timestamp, return success. If we have
651 // different data with the same hash, return failure.
652 if n, err := CompareAndTouch(ctx, hash, block); err == nil || err == CollisionError {
654 } else if ctx.Err() != nil {
655 return 0, ErrClientDisconnect
658 // Choose a Keep volume to write to.
659 // If this volume fails, try all of the volumes in order.
660 if vol := KeepVM.NextWritable(); vol != nil {
661 if err := vol.Put(ctx, hash, block); err == nil {
662 return vol.Replication(), nil // success!
664 if ctx.Err() != nil {
665 return 0, ErrClientDisconnect
669 writables := KeepVM.AllWritable()
670 if len(writables) == 0 {
671 log.Print("No writable volumes.")
676 for _, vol := range writables {
677 err := vol.Put(ctx, hash, block)
678 if ctx.Err() != nil {
679 return 0, ErrClientDisconnect
682 return vol.Replication(), nil // success!
684 if err != FullError {
685 // The volume is not full but the
686 // write did not succeed. Report the
687 // error and continue trying.
689 log.Printf("%s: Write(%s): %s", vol, hash, err)
694 log.Print("All volumes are full.")
697 // Already logged the non-full errors.
698 return 0, GenericError
701 // CompareAndTouch returns the current replication level if one of the
702 // volumes already has the given content and it successfully updates
703 // the relevant block's modification time in order to protect it from
704 // premature garbage collection. Otherwise, it returns a non-nil
706 func CompareAndTouch(ctx context.Context, hash string, buf []byte) (int, error) {
707 var bestErr error = NotFoundError
708 for _, vol := range KeepVM.AllWritable() {
709 err := vol.Compare(ctx, hash, buf)
710 if ctx.Err() != nil {
712 } else if err == CollisionError {
713 // Stop if we have a block with same hash but
714 // different content. (It will be impossible
715 // to tell which one is wanted if we have
716 // both, so there's no point writing it even
717 // on a different volume.)
718 log.Printf("%s: Compare(%s): %s", vol, hash, err)
720 } else if os.IsNotExist(err) {
721 // Block does not exist. This is the only
722 // "normal" error: we don't log anything.
724 } else if err != nil {
725 // Couldn't open file, data is corrupt on
726 // disk, etc.: log this abnormal condition,
727 // and try the next volume.
728 log.Printf("%s: Compare(%s): %s", vol, hash, err)
731 if err := vol.Touch(hash); err != nil {
732 log.Printf("%s: Touch %s failed: %s", vol, hash, err)
736 // Compare and Touch both worked --> done.
737 return vol.Replication(), nil
742 var validLocatorRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
744 // IsValidLocator returns true if the specified string is a valid Keep locator.
745 // When Keep is extended to support hash types other than MD5,
746 // this should be updated to cover those as well.
748 func IsValidLocator(loc string) bool {
749 return validLocatorRe.MatchString(loc)
752 var authRe = regexp.MustCompile(`^OAuth2\s+(.*)`)
754 // GetAPIToken returns the OAuth2 token from the Authorization
755 // header of a HTTP request, or an empty string if no matching
757 func GetAPIToken(req *http.Request) string {
758 if auth, ok := req.Header["Authorization"]; ok {
759 if match := authRe.FindStringSubmatch(auth[0]); match != nil {
766 // IsExpired returns true if the given Unix timestamp (expressed as a
767 // hexadecimal string) is in the past, or if timestampHex cannot be
768 // parsed as a hexadecimal string.
769 func IsExpired(timestampHex string) bool {
770 ts, err := strconv.ParseInt(timestampHex, 16, 0)
772 log.Printf("IsExpired: %s", err)
775 return time.Unix(ts, 0).Before(time.Now())
778 // CanDelete returns true if the user identified by apiToken is
779 // allowed to delete blocks.
780 func CanDelete(apiToken string) bool {
784 // Blocks may be deleted only when Keep has been configured with a
786 if IsSystemAuth(apiToken) {
789 // TODO(twp): look up apiToken with the API server
790 // return true if is_admin is true and if the token
791 // has unlimited scope
795 // IsSystemAuth returns true if the given token is allowed to perform
796 // system level actions like deleting data.
797 func IsSystemAuth(token string) bool {
798 return token != "" && token == theConfig.systemAuthToken