Adding unit tests for GetBlock. (refs #2291)
[arvados.git] / services / keep / keep.go
1 package main
2
3 import (
4         "bufio"
5         "crypto/md5"
6         "errors"
7         "fmt"
8         "github.com/gorilla/mux"
9         "log"
10         "net/http"
11         "os"
12         "strings"
13 )
14
15 const DEFAULT_PORT = 25107
16 const BLOCKSIZE = 64 * 1024 * 1024
17
18 var KeepVolumes []string
19
20 func main() {
21         // Look for local keep volumes.
22         KeepVolumes = FindKeepVolumes()
23         if len(KeepVolumes) == 0 {
24                 log.Fatal("could not find any keep volumes")
25         }
26         for _, v := range KeepVolumes {
27                 log.Println("keep volume:", v)
28         }
29
30         // Set up REST handlers.
31         rest := mux.NewRouter()
32         rest.HandleFunc("/{hash:[0-9a-f]{32}}", GetBlockHandler).Methods("GET")
33         http.Handle("/", rest)
34
35         port := fmt.Sprintf(":%d", DEFAULT_PORT)
36         http.ListenAndServe(port, nil)
37 }
38
39 func GetBlockHandler(w http.ResponseWriter, req *http.Request) {
40         hash := mux.Vars(req)["hash"]
41
42         block, err := GetBlock(hash)
43         if err != nil {
44                 http.Error(w, err.Error(), 404)
45                 return
46         }
47
48         _, err = w.Write(block)
49         if err != nil {
50                 log.Printf("GetBlockHandler: writing response: %s", err)
51         }
52
53         return
54 }
55
56 func GetBlock(hash string) ([]byte, error) {
57         var buf = make([]byte, BLOCKSIZE)
58
59         // Attempt to read the requested hash from a keep volume.
60         for _, vol := range KeepVolumes {
61                 var f *os.File
62                 var err error
63                 var nread int
64
65                 path := fmt.Sprintf("%s/%s/%s", vol, hash[0:3], hash)
66
67                 f, err = os.Open(path)
68                 if err != nil {
69                         log.Printf("%s: opening %s: %s\n", vol, path, err)
70                         continue
71                 }
72
73                 nread, err = f.Read(buf)
74                 if err != nil {
75                         log.Printf("%s: reading %s: %s\n", vol, path, err)
76                         continue
77                 }
78
79                 // Double check the file checksum.
80                 filehash := fmt.Sprintf("%x", md5.Sum(buf[:nread]))
81                 if filehash != hash {
82                         log.Printf("%s: checksum mismatch: %s (actual hash %s)\n",
83                                 vol, path, filehash)
84                         continue
85                 }
86
87                 // Success!
88                 return buf[:nread], nil
89         }
90
91         log.Printf("%s: all keep volumes failed, giving up\n", hash)
92         return buf, errors.New("not found: " + hash)
93 }
94
95 // FindKeepVolumes
96 //     Returns a list of Keep volumes mounted on this system.
97 //
98 //     A Keep volume is a normal or tmpfs volume with a /keep
99 //     directory at the top level of the mount point.
100 //
101 func FindKeepVolumes() []string {
102         vols := make([]string, 0)
103
104         if f, err := os.Open("/proc/mounts"); err != nil {
105                 log.Fatal("could not read /proc/mounts: ", err)
106         } else {
107                 scanner := bufio.NewScanner(f)
108                 for scanner.Scan() {
109                         args := strings.Fields(scanner.Text())
110                         dev, mount := args[0], args[1]
111                         if (dev == "tmpfs" || strings.HasPrefix(dev, "/dev/")) && mount != "/" {
112                                 keep := mount + "/keep"
113                                 if st, err := os.Stat(keep); err == nil && st.IsDir() {
114                                         vols = append(vols, keep)
115                                 }
116                         }
117                 }
118                 if err := scanner.Err(); err != nil {
119                         log.Fatal(err)
120                 }
121         }
122         return vols
123 }