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.

372 lines
11 KiB

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