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.

343 lines
10 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 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", 7, "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. dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
  37. rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
  38. store *storage.Store
  39. )
  40. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  41. func statusHandler(w http.ResponseWriter, r *http.Request) {
  42. m := make(map[string]interface{})
  43. m["Version"] = VERSION
  44. m["Volumes"] = store.Status()
  45. writeJsonQuiet(w, r, m)
  46. }
  47. func assignVolumeHandler(w http.ResponseWriter, r *http.Request) {
  48. err := store.AddVolume(r.FormValue("volume"), r.FormValue("replicationType"))
  49. if err == nil {
  50. writeJsonQuiet(w, r, map[string]string{"error": ""})
  51. } else {
  52. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  53. }
  54. debug("assign volume =", r.FormValue("volume"), ", replicationType =", r.FormValue("replicationType"), ", error =", err)
  55. }
  56. func vacuumVolumeCheckHandler(w http.ResponseWriter, r *http.Request) {
  57. err, ret := store.CheckCompactVolume(r.FormValue("volume"), r.FormValue("garbageThreshold"))
  58. if err == nil {
  59. writeJsonQuiet(w, r, map[string]interface{}{"error": "", "result": ret})
  60. } else {
  61. writeJsonQuiet(w, r, map[string]interface{}{"error": err.Error(), "result": false})
  62. }
  63. debug("checked compacting volume =", r.FormValue("volume"), "garbageThreshold =", r.FormValue("garbageThreshold"), "vacuum =", ret)
  64. }
  65. func vacuumVolumeCompactHandler(w http.ResponseWriter, r *http.Request) {
  66. err := store.CompactVolume(r.FormValue("volume"))
  67. if err == nil {
  68. writeJsonQuiet(w, r, map[string]string{"error": ""})
  69. } else {
  70. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  71. }
  72. debug("compacted volume =", r.FormValue("volume"), ", error =", err)
  73. }
  74. func vacuumVolumeCommitHandler(w http.ResponseWriter, r *http.Request) {
  75. err := store.CommitCompactVolume(r.FormValue("volume"))
  76. if err == nil {
  77. writeJsonQuiet(w, r, map[string]interface{}{"error": ""})
  78. } else {
  79. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  80. }
  81. debug("commit compact volume =", r.FormValue("volume"), ", error =", err)
  82. }
  83. func freezeVolumeHandler(w http.ResponseWriter, r *http.Request) {
  84. //TODO: notify master that this volume will be read-only
  85. err := store.FreezeVolume(r.FormValue("volume"))
  86. if err == nil {
  87. writeJsonQuiet(w, r, map[string]interface{}{"error": ""})
  88. } else {
  89. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  90. }
  91. debug("freeze volume =", r.FormValue("volume"), ", error =", err)
  92. }
  93. func storeHandler(w http.ResponseWriter, r *http.Request) {
  94. switch r.Method {
  95. case "GET":
  96. GetOrHeadHandler(w, r, true)
  97. case "HEAD":
  98. GetOrHeadHandler(w, r, false)
  99. case "DELETE":
  100. DeleteHandler(w, r)
  101. case "POST":
  102. PostHandler(w, r)
  103. }
  104. }
  105. func GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  106. n := new(storage.Needle)
  107. vid, fid, ext := parseURLPath(r.URL.Path)
  108. volumeId, err := storage.NewVolumeId(vid)
  109. if err != nil {
  110. debug("parsing error:", err, r.URL.Path)
  111. return
  112. }
  113. n.ParsePath(fid)
  114. debug("volume", volumeId, "reading", n)
  115. if !store.HasVolume(volumeId) {
  116. lookupResult, err := operation.Lookup(*masterNode, volumeId)
  117. debug("volume", volumeId, "found on", lookupResult, "error", err)
  118. if err == nil {
  119. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  120. } else {
  121. debug("lookup error:", err, r.URL.Path)
  122. w.WriteHeader(http.StatusNotFound)
  123. }
  124. return
  125. }
  126. cookie := n.Cookie
  127. count, e := store.Read(volumeId, n)
  128. debug("read bytes", count, "error", e)
  129. if e != nil || count <= 0 {
  130. debug("read error:", e, r.URL.Path)
  131. w.WriteHeader(http.StatusNotFound)
  132. return
  133. }
  134. if n.Cookie != cookie {
  135. log.Println("request with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  136. w.WriteHeader(http.StatusNotFound)
  137. return
  138. }
  139. if n.NameSize > 0 {
  140. fname := string(n.Name)
  141. dotIndex := strings.LastIndex(fname, ".")
  142. if dotIndex > 0 {
  143. ext = fname[dotIndex:]
  144. }
  145. }
  146. mtype := ""
  147. if ext != "" {
  148. mtype = mime.TypeByExtension(ext)
  149. }
  150. if n.MimeSize > 0 {
  151. mtype = string(n.Mime)
  152. }
  153. if mtype != "" {
  154. w.Header().Set("Content-Type", mtype)
  155. }
  156. if n.NameSize > 0 {
  157. w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(string(n.Name)))
  158. }
  159. if n.LastModified != 0 {
  160. println("file time is", n.LastModified)
  161. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).Format(http.TimeFormat))
  162. }
  163. if ext != ".gz" {
  164. if n.IsGzipped() {
  165. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  166. w.Header().Set("Content-Encoding", "gzip")
  167. } else {
  168. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  169. debug("lookup error:", err, r.URL.Path)
  170. }
  171. }
  172. }
  173. }
  174. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  175. if isGetMethod {
  176. if _, e = w.Write(n.Data); e != nil {
  177. debug("response write error:", e)
  178. }
  179. }
  180. }
  181. func PostHandler(w http.ResponseWriter, r *http.Request) {
  182. if e := r.ParseForm(); e != nil {
  183. debug("form parse error:", e)
  184. writeJsonQuiet(w, r, e)
  185. return
  186. }
  187. vid, _, _ := parseURLPath(r.URL.Path)
  188. volumeId, e := storage.NewVolumeId(vid)
  189. if e != nil {
  190. debug("NewVolumeId error:", e)
  191. writeJsonQuiet(w, r, e)
  192. return
  193. }
  194. if e != nil {
  195. writeJsonQuiet(w, r, e)
  196. } else {
  197. needle, ne := storage.NewNeedle(r)
  198. if ne != nil {
  199. writeJsonQuiet(w, r, ne)
  200. } else {
  201. ret, errorStatus := replication.ReplicatedWrite(*masterNode, store, volumeId, needle, r)
  202. m := make(map[string]interface{})
  203. if errorStatus == "" {
  204. w.WriteHeader(http.StatusCreated)
  205. } else {
  206. w.WriteHeader(http.StatusInternalServerError)
  207. m["error"] = errorStatus
  208. }
  209. m["size"] = ret
  210. writeJsonQuiet(w, r, m)
  211. }
  212. }
  213. }
  214. func DeleteHandler(w http.ResponseWriter, r *http.Request) {
  215. n := new(storage.Needle)
  216. vid, fid, _ := parseURLPath(r.URL.Path)
  217. volumeId, _ := storage.NewVolumeId(vid)
  218. n.ParsePath(fid)
  219. debug("deleting", n)
  220. cookie := n.Cookie
  221. count, ok := store.Read(volumeId, n)
  222. if ok != nil {
  223. m := make(map[string]uint32)
  224. m["size"] = 0
  225. writeJsonQuiet(w, r, m)
  226. return
  227. }
  228. if n.Cookie != cookie {
  229. log.Println("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  230. return
  231. }
  232. n.Size = 0
  233. ret := replication.ReplicatedDelete(*masterNode, store, volumeId, n, r)
  234. if ret != 0 {
  235. w.WriteHeader(http.StatusAccepted)
  236. } else {
  237. w.WriteHeader(http.StatusInternalServerError)
  238. }
  239. m := make(map[string]uint32)
  240. m["size"] = uint32(count)
  241. writeJsonQuiet(w, r, m)
  242. }
  243. func parseURLPath(path string) (vid, fid, ext string) {
  244. sepIndex := strings.LastIndex(path, "/")
  245. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  246. if commaIndex <= 0 {
  247. if "favicon.ico" != path[sepIndex+1:] {
  248. log.Println("unknown file id", path[sepIndex+1:])
  249. }
  250. return
  251. }
  252. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  253. vid = path[sepIndex+1 : commaIndex]
  254. fid = path[commaIndex+1:]
  255. ext = ""
  256. if dotIndex > 0 {
  257. fid = path[commaIndex+1 : dotIndex]
  258. ext = path[dotIndex:]
  259. }
  260. return
  261. }
  262. func runVolume(cmd *Command, args []string) bool {
  263. if *vMaxCpu < 1 {
  264. *vMaxCpu = runtime.NumCPU()
  265. }
  266. runtime.GOMAXPROCS(*vMaxCpu)
  267. fileInfo, err := os.Stat(*volumeFolder)
  268. if err != nil {
  269. log.Fatalf("No Existing Folder:%s", *volumeFolder)
  270. }
  271. if !fileInfo.IsDir() {
  272. log.Fatalf("Volume Folder should not be a file:%s", *volumeFolder)
  273. }
  274. perm := fileInfo.Mode().Perm()
  275. log.Println("Volume Folder permission:", perm)
  276. if *publicUrl == "" {
  277. *publicUrl = *ip + ":" + strconv.Itoa(*vport)
  278. }
  279. store = storage.NewStore(*vport, *ip, *publicUrl, *volumeFolder, *maxVolumeCount)
  280. defer store.Close()
  281. http.HandleFunc("/", storeHandler)
  282. http.HandleFunc("/status", statusHandler)
  283. http.HandleFunc("/admin/assign_volume", assignVolumeHandler)
  284. http.HandleFunc("/admin/vacuum_volume_check", vacuumVolumeCheckHandler)
  285. http.HandleFunc("/admin/vacuum_volume_compact", vacuumVolumeCompactHandler)
  286. http.HandleFunc("/admin/vacuum_volume_commit", vacuumVolumeCommitHandler)
  287. http.HandleFunc("/admin/freeze_volume", freezeVolumeHandler)
  288. go func() {
  289. connected := true
  290. store.SetMaster(*masterNode)
  291. store.SetDataCenter(*dataCenter)
  292. store.SetRack(*rack)
  293. for {
  294. err := store.Join()
  295. if err == nil {
  296. if !connected {
  297. connected = true
  298. log.Println("Reconnected with master")
  299. }
  300. } else {
  301. if connected {
  302. connected = false
  303. }
  304. }
  305. time.Sleep(time.Duration(float32(*vpulse*1e3)*(1+rand.Float32())) * time.Millisecond)
  306. }
  307. }()
  308. log.Println("store joined at", *masterNode)
  309. log.Println("Start Weed volume server", VERSION, "at http://"+*ip+":"+strconv.Itoa(*vport))
  310. srv := &http.Server{
  311. Addr: ":" + strconv.Itoa(*vport),
  312. Handler: http.DefaultServeMux,
  313. ReadTimeout: (time.Duration(*vReadTimeout) * time.Second),
  314. }
  315. e := srv.ListenAndServe()
  316. if e != nil {
  317. log.Fatalf("Fail to start:%s", e.Error())
  318. }
  319. return true
  320. }