You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

324 lines
9.2 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. package main
  2. import (
  3. "code.google.com/p/weed-fs/go/operation"
  4. "code.google.com/p/weed-fs/go/replication"
  5. "code.google.com/p/weed-fs/go/storage"
  6. "log"
  7. "math/rand"
  8. "mime"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. func init() {
  17. cmdVolume.Run = runVolume // break init cycle
  18. cmdVolume.IsDebug = cmdVolume.Flag.Bool("debug", false, "enable debug mode")
  19. }
  20. var cmdVolume = &Command{
  21. UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
  22. Short: "start a volume server",
  23. Long: `start a volume server to provide storage spaces
  24. `,
  25. }
  26. var (
  27. vport = cmdVolume.Flag.Int("port", 8080, "http listen port")
  28. volumeFolder = cmdVolume.Flag.String("dir", "/tmp", "directory to store data files")
  29. ip = cmdVolume.Flag.String("ip", "localhost", "ip or server name")
  30. publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible <ip|server_name>:<port>")
  31. masterNode = cmdVolume.Flag.String("mserver", "localhost:9333", "master server location")
  32. vpulse = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than the master's setting")
  33. maxVolumeCount = cmdVolume.Flag.Int("max", 5, "maximum number of volumes")
  34. vReadTimeout = cmdVolume.Flag.Int("readTimeout", 3, "connection read timeout in seconds")
  35. vMaxCpu = cmdVolume.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
  36. store *storage.Store
  37. )
  38. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  39. func statusHandler(w http.ResponseWriter, r *http.Request) {
  40. m := make(map[string]interface{})
  41. m["Version"] = VERSION
  42. m["Volumes"] = store.Status()
  43. writeJsonQuiet(w, r, m)
  44. }
  45. func assignVolumeHandler(w http.ResponseWriter, r *http.Request) {
  46. err := store.AddVolume(r.FormValue("volume"), r.FormValue("replicationType"))
  47. if err == nil {
  48. writeJsonQuiet(w, r, map[string]string{"error": ""})
  49. } else {
  50. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  51. }
  52. debug("assign volume =", r.FormValue("volume"), ", replicationType =", r.FormValue("replicationType"), ", error =", err)
  53. }
  54. func vacuumVolumeCheckHandler(w http.ResponseWriter, r *http.Request) {
  55. err, ret := store.CheckCompactVolume(r.FormValue("volume"), r.FormValue("garbageThreshold"))
  56. if err == nil {
  57. writeJsonQuiet(w, r, map[string]interface{}{"error": "", "result": ret})
  58. } else {
  59. writeJsonQuiet(w, r, map[string]interface{}{"error": err.Error(), "result": false})
  60. }
  61. debug("checked compacting volume =", r.FormValue("volume"), "garbageThreshold =", r.FormValue("garbageThreshold"), "vacuum =", ret)
  62. }
  63. func vacuumVolumeCompactHandler(w http.ResponseWriter, r *http.Request) {
  64. err := store.CompactVolume(r.FormValue("volume"))
  65. if err == nil {
  66. writeJsonQuiet(w, r, map[string]string{"error": ""})
  67. } else {
  68. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  69. }
  70. debug("compacted volume =", r.FormValue("volume"), ", error =", err)
  71. }
  72. func vacuumVolumeCommitHandler(w http.ResponseWriter, r *http.Request) {
  73. err := store.CommitCompactVolume(r.FormValue("volume"))
  74. if err == nil {
  75. writeJsonQuiet(w, r, map[string]interface{}{"error": ""})
  76. } else {
  77. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  78. }
  79. debug("commit compact volume =", r.FormValue("volume"), ", error =", err)
  80. }
  81. func storeHandler(w http.ResponseWriter, r *http.Request) {
  82. switch r.Method {
  83. case "GET":
  84. GetOrHeadHandler(w, r, true)
  85. case "HEAD":
  86. GetOrHeadHandler(w, r, false)
  87. case "DELETE":
  88. DeleteHandler(w, r)
  89. case "POST":
  90. PostHandler(w, r)
  91. }
  92. }
  93. func GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  94. n := new(storage.Needle)
  95. vid, fid, ext := parseURLPath(r.URL.Path)
  96. volumeId, err := storage.NewVolumeId(vid)
  97. if err != nil {
  98. debug("parsing error:", err, r.URL.Path)
  99. return
  100. }
  101. n.ParsePath(fid)
  102. debug("volume", volumeId, "reading", n)
  103. if !store.HasVolume(volumeId) {
  104. lookupResult, err := operation.Lookup(*masterNode, volumeId)
  105. debug("volume", volumeId, "found on", lookupResult, "error", err)
  106. if err == nil {
  107. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  108. } else {
  109. debug("lookup error:", err, r.URL.Path)
  110. w.WriteHeader(http.StatusNotFound)
  111. }
  112. return
  113. }
  114. cookie := n.Cookie
  115. count, e := store.Read(volumeId, n)
  116. debug("read bytes", count, "error", e)
  117. if e != nil || count <= 0 {
  118. debug("read error:", e, r.URL.Path)
  119. w.WriteHeader(http.StatusNotFound)
  120. return
  121. }
  122. if n.Cookie != cookie {
  123. log.Println("request with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  124. w.WriteHeader(http.StatusNotFound)
  125. return
  126. }
  127. if n.NameSize > 0 {
  128. fname := string(n.Name)
  129. dotIndex := strings.LastIndex(fname, ".")
  130. if dotIndex > 0 {
  131. ext = fname[dotIndex:]
  132. }
  133. }
  134. mtype := ""
  135. if ext != "" {
  136. mtype = mime.TypeByExtension(ext)
  137. }
  138. if n.MimeSize > 0 {
  139. mtype = string(n.Mime)
  140. }
  141. if mtype != "" {
  142. w.Header().Set("Content-Type", mtype)
  143. }
  144. if n.NameSize > 0 {
  145. w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(string(n.Name)))
  146. }
  147. if ext != ".gz" {
  148. if n.IsGzipped() {
  149. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  150. w.Header().Set("Content-Encoding", "gzip")
  151. } else {
  152. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  153. debug("lookup error:", err, r.URL.Path)
  154. }
  155. }
  156. }
  157. }
  158. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  159. if isGetMethod {
  160. if _, e = w.Write(n.Data); e != nil {
  161. debug("response write error:", e)
  162. }
  163. }
  164. }
  165. func PostHandler(w http.ResponseWriter, r *http.Request) {
  166. if e := r.ParseForm(); e != nil {
  167. debug("form parse error:", e)
  168. writeJsonQuiet(w, r, e)
  169. return
  170. }
  171. vid, _, _ := parseURLPath(r.URL.Path)
  172. volumeId, e := storage.NewVolumeId(vid)
  173. if e != nil {
  174. debug("NewVolumeId error:", e)
  175. writeJsonQuiet(w, r, e)
  176. return
  177. }
  178. if e != nil {
  179. writeJsonQuiet(w, r, e)
  180. } else {
  181. needle, ne := storage.NewNeedle(r)
  182. if ne != nil {
  183. writeJsonQuiet(w, r, ne)
  184. } else {
  185. ret, errorStatus := replication.ReplicatedWrite(*masterNode, store, volumeId, needle, r)
  186. m := make(map[string]interface{})
  187. if errorStatus == "" {
  188. w.WriteHeader(http.StatusCreated)
  189. } else {
  190. w.WriteHeader(http.StatusInternalServerError)
  191. m["error"] = errorStatus
  192. }
  193. m["size"] = ret
  194. writeJsonQuiet(w, r, m)
  195. }
  196. }
  197. }
  198. func DeleteHandler(w http.ResponseWriter, r *http.Request) {
  199. n := new(storage.Needle)
  200. vid, fid, _ := parseURLPath(r.URL.Path)
  201. volumeId, _ := storage.NewVolumeId(vid)
  202. n.ParsePath(fid)
  203. debug("deleting", n)
  204. cookie := n.Cookie
  205. count, ok := store.Read(volumeId, n)
  206. if ok != nil {
  207. m := make(map[string]uint32)
  208. m["size"] = 0
  209. writeJsonQuiet(w, r, m)
  210. return
  211. }
  212. if n.Cookie != cookie {
  213. log.Println("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  214. return
  215. }
  216. n.Size = 0
  217. ret := replication.ReplicatedDelete(*masterNode, store, volumeId, n, r)
  218. if ret != 0 {
  219. w.WriteHeader(http.StatusAccepted)
  220. } else {
  221. w.WriteHeader(http.StatusInternalServerError)
  222. }
  223. m := make(map[string]uint32)
  224. m["size"] = uint32(count)
  225. writeJsonQuiet(w, r, m)
  226. }
  227. func parseURLPath(path string) (vid, fid, ext string) {
  228. sepIndex := strings.LastIndex(path, "/")
  229. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  230. if commaIndex <= 0 {
  231. if "favicon.ico" != path[sepIndex+1:] {
  232. log.Println("unknown file id", path[sepIndex+1:])
  233. }
  234. return
  235. }
  236. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  237. vid = path[sepIndex+1 : commaIndex]
  238. fid = path[commaIndex+1:]
  239. ext = ""
  240. if dotIndex > 0 {
  241. fid = path[commaIndex+1 : dotIndex]
  242. ext = path[dotIndex:]
  243. }
  244. return
  245. }
  246. func runVolume(cmd *Command, args []string) bool {
  247. if *vMaxCpu < 1 {
  248. *vMaxCpu = runtime.NumCPU()
  249. }
  250. runtime.GOMAXPROCS(*vMaxCpu)
  251. fileInfo, err := os.Stat(*volumeFolder)
  252. if err != nil {
  253. log.Fatalf("No Existing Folder:%s", *volumeFolder)
  254. }
  255. if !fileInfo.IsDir() {
  256. log.Fatalf("Volume Folder should not be a file:%s", *volumeFolder)
  257. }
  258. perm := fileInfo.Mode().Perm()
  259. log.Println("Volume Folder permission:", perm)
  260. if *publicUrl == "" {
  261. *publicUrl = *ip + ":" + strconv.Itoa(*vport)
  262. }
  263. store = storage.NewStore(*vport, *ip, *publicUrl, *volumeFolder, *maxVolumeCount)
  264. defer store.Close()
  265. http.HandleFunc("/", storeHandler)
  266. http.HandleFunc("/status", statusHandler)
  267. http.HandleFunc("/admin/assign_volume", assignVolumeHandler)
  268. http.HandleFunc("/admin/vacuum_volume_check", vacuumVolumeCheckHandler)
  269. http.HandleFunc("/admin/vacuum_volume_compact", vacuumVolumeCompactHandler)
  270. http.HandleFunc("/admin/vacuum_volume_commit", vacuumVolumeCommitHandler)
  271. go func() {
  272. connected := true
  273. store.SetMaster(*masterNode)
  274. for {
  275. err := store.Join()
  276. if err == nil {
  277. if !connected {
  278. connected = true
  279. log.Println("Reconnected with master")
  280. }
  281. } else {
  282. if connected {
  283. connected = false
  284. }
  285. }
  286. time.Sleep(time.Duration(float32(*vpulse*1e3)*(1+rand.Float32())) * time.Millisecond)
  287. }
  288. }()
  289. log.Println("store joined at", *masterNode)
  290. log.Println("Start Weed volume server", VERSION, "at http://"+*ip+":"+strconv.Itoa(*vport))
  291. srv := &http.Server{
  292. Addr: ":" + strconv.Itoa(*vport),
  293. Handler: http.DefaultServeMux,
  294. ReadTimeout: (time.Duration(*vReadTimeout) * time.Second),
  295. }
  296. e := srv.ListenAndServe()
  297. if e != nil {
  298. log.Fatalf("Fail to start:%s", e.Error())
  299. }
  300. return true
  301. }