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.
31 rest := mux.NewRouter()
32 rest.HandleFunc("/{hash:[0-9a-f]{32}}", GetBlockHandler).Methods("GET")
33 http.Handle("/", rest)
35 port := fmt.Sprintf(":%d", DEFAULT_PORT)
36 http.ListenAndServe(port, nil)
39 func GetBlockHandler(w http.ResponseWriter, req *http.Request) {
40 hash := mux.Vars(req)["hash"]
42 block, err := GetBlock(hash)
44 http.Error(w, err.Error(), 404)
48 _, err = w.Write(block)
50 log.Printf("GetBlockHandler: writing response: %s", err)
56 func GetBlock(hash string) ([]byte, error) {
57 var buf = make([]byte, BLOCKSIZE)
59 // Attempt to read the requested hash from a keep volume.
60 for _, vol := range KeepVolumes {
65 path := fmt.Sprintf("%s/%s/%s", vol, hash[0:3], hash)
67 f, err = os.Open(path)
69 log.Printf("%s: opening %s: %s\n", vol, path, err)
73 nread, err = f.Read(buf)
75 log.Printf("%s: reading %s: %s\n", vol, path, err)
79 // Double check the file checksum.
80 filehash := fmt.Sprintf("%x", md5.Sum(buf[:nread]))
82 log.Printf("%s: checksum mismatch: %s (actual hash %s)\n",
88 return buf[:nread], nil
91 log.Printf("%s: all keep volumes failed, giving up\n", hash)
92 return buf, errors.New("not found: " + hash)
96 // Returns a list of Keep volumes mounted on this system.
98 // A Keep volume is a normal or tmpfs volume with a /keep
99 // directory at the top level of the mount point.
101 func FindKeepVolumes() []string {
102 vols := make([]string, 0)
104 if f, err := os.Open("/proc/mounts"); err != nil {
105 log.Fatal("could not read /proc/mounts: ", err)
107 scanner := bufio.NewScanner(f)
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)
118 if err := scanner.Err(); err != nil {