8 "github.com/gorilla/mux"
15 const DEFAULT_PORT = 25107
16 const BLOCKSIZE = 64 * 1024 * 1024
18 var KeepVolumes []string
21 // Look for local keep volumes.
22 KeepVolumes = FindKeepVolumes()
23 if len(KeepVolumes) == 0 {
24 log.Fatal("could not find any keep volumes")
26 for _, v := range KeepVolumes {
27 log.Println("keep volume:", v)
30 // Set up REST handlers.
32 // Start with a router that will route each URL path to an
33 // appropriate handler.
35 rest := mux.NewRouter()
36 rest.HandleFunc("/{hash:[0-9a-f]{32}}", GetBlockHandler).Methods("GET")
38 // Tell the built-in HTTP server to direct all requests to the REST
40 http.Handle("/", rest)
42 // Start listening for requests.
43 port := fmt.Sprintf(":%d", DEFAULT_PORT)
44 http.ListenAndServe(port, nil)
48 // Returns a list of Keep volumes mounted on this system.
50 // A Keep volume is a normal or tmpfs volume with a /keep
51 // directory at the top level of the mount point.
53 func FindKeepVolumes() []string {
54 vols := make([]string, 0)
56 if f, err := os.Open("/proc/mounts"); err != nil {
57 log.Fatal("could not read /proc/mounts: ", err)
59 scanner := bufio.NewScanner(f)
61 args := strings.Fields(scanner.Text())
62 dev, mount := args[0], args[1]
63 if (dev == "tmpfs" || strings.HasPrefix(dev, "/dev/")) && mount != "/" {
64 keep := mount + "/keep"
65 if st, err := os.Stat(keep); err == nil && st.IsDir() {
66 vols = append(vols, keep)
70 if err := scanner.Err(); err != nil {
77 func GetBlockHandler(w http.ResponseWriter, req *http.Request) {
78 hash := mux.Vars(req)["hash"]
80 block, err := GetBlock(hash)
82 http.Error(w, err.Error(), 404)
86 _, err = w.Write(block)
88 log.Printf("GetBlockHandler: writing response: %s", err)
94 func GetBlock(hash string) ([]byte, error) {
95 var buf = make([]byte, BLOCKSIZE)
97 // Attempt to read the requested hash from a keep volume.
98 for _, vol := range KeepVolumes {
103 path := fmt.Sprintf("%s/%s/%s", vol, hash[0:3], hash)
105 f, err = os.Open(path)
107 log.Printf("%s: opening %s: %s\n", vol, path, err)
111 nread, err = f.Read(buf)
113 log.Printf("%s: reading %s: %s\n", vol, path, err)
117 // Double check the file checksum.
119 filehash := fmt.Sprintf("%x", md5.Sum(buf[:nread]))
120 if filehash != hash {
121 // TODO(twp): this condition probably represents a bad disk and
122 // should raise major alarm bells for an administrator: e.g.
123 // they should be sent directly to an event manager at high
124 // priority or logged as urgent problems.
126 log.Printf("%s: checksum mismatch: %s (actual hash %s)\n",
132 return buf[:nread], nil
135 log.Printf("%s: not found on any volumes, giving up\n", hash)
136 return buf, errors.New("not found: " + hash)