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.

381 lines
12 KiB

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. "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. Increase this if uploading large files.")
  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 submitFromVolumeServerHandler(w http.ResponseWriter, r *http.Request) {
  95. submitForClientHandler(w, r, *masterNode)
  96. }
  97. func storeHandler(w http.ResponseWriter, r *http.Request) {
  98. switch r.Method {
  99. case "GET":
  100. GetOrHeadHandler(w, r, true)
  101. case "HEAD":
  102. GetOrHeadHandler(w, r, false)
  103. case "DELETE":
  104. DeleteHandler(w, r)
  105. case "POST":
  106. PostHandler(w, r)
  107. }
  108. }
  109. func GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
  110. n := new(storage.Needle)
  111. vid, fid, filename, ext := parseURLPath(r.URL.Path)
  112. volumeId, err := storage.NewVolumeId(vid)
  113. if err != nil {
  114. debug("parsing error:", err, r.URL.Path)
  115. return
  116. }
  117. n.ParsePath(fid)
  118. debug("volume", volumeId, "reading", n)
  119. if !store.HasVolume(volumeId) {
  120. lookupResult, err := operation.Lookup(*masterNode, volumeId)
  121. debug("volume", volumeId, "found on", lookupResult, "error", err)
  122. if err == nil {
  123. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  124. } else {
  125. debug("lookup error:", err, r.URL.Path)
  126. w.WriteHeader(http.StatusNotFound)
  127. }
  128. return
  129. }
  130. cookie := n.Cookie
  131. count, e := store.Read(volumeId, n)
  132. debug("read bytes", count, "error", e)
  133. if e != nil || count <= 0 {
  134. debug("read error:", e, r.URL.Path)
  135. w.WriteHeader(http.StatusNotFound)
  136. return
  137. }
  138. if n.Cookie != cookie {
  139. log.Println("request with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  140. w.WriteHeader(http.StatusNotFound)
  141. return
  142. }
  143. if n.LastModified != 0 {
  144. w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
  145. if r.Header.Get("If-Modified-Since") != "" {
  146. if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
  147. if t.Unix() >= int64(n.LastModified) {
  148. w.WriteHeader(http.StatusNotModified)
  149. return
  150. }
  151. }
  152. }
  153. }
  154. if n.NameSize > 0 && filename == "" {
  155. filename := string(n.Name)
  156. dotIndex := strings.LastIndex(filename, ".")
  157. if dotIndex > 0 {
  158. ext = filename[dotIndex:]
  159. }
  160. }
  161. mtype := ""
  162. if ext != "" {
  163. mtype = mime.TypeByExtension(ext)
  164. }
  165. if n.MimeSize > 0 {
  166. mtype = string(n.Mime)
  167. }
  168. if mtype != "" {
  169. w.Header().Set("Content-Type", mtype)
  170. }
  171. if filename != "" {
  172. w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(filename))
  173. }
  174. if ext != ".gz" {
  175. if n.IsGzipped() {
  176. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  177. w.Header().Set("Content-Encoding", "gzip")
  178. } else {
  179. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  180. debug("lookup error:", err, r.URL.Path)
  181. }
  182. }
  183. }
  184. }
  185. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  186. if isGetMethod {
  187. if _, e = w.Write(n.Data); e != nil {
  188. debug("response write error:", e)
  189. }
  190. }
  191. }
  192. func PostHandler(w http.ResponseWriter, r *http.Request) {
  193. m := make(map[string]interface{})
  194. if e := r.ParseForm(); e != nil {
  195. debug("form parse error:", e)
  196. writeJsonError(w, r, e)
  197. return
  198. }
  199. vid, _, _, _ := parseURLPath(r.URL.Path)
  200. volumeId, ve := storage.NewVolumeId(vid)
  201. if ve != nil {
  202. debug("NewVolumeId error:", ve)
  203. writeJsonError(w, r, ve)
  204. return
  205. }
  206. needle, ne := storage.NewNeedle(r)
  207. if ne != nil {
  208. writeJsonError(w, r, ne)
  209. return
  210. }
  211. ret, errorStatus := replication.ReplicatedWrite(*masterNode, store, volumeId, needle, r)
  212. if errorStatus == "" {
  213. w.WriteHeader(http.StatusCreated)
  214. } else {
  215. w.WriteHeader(http.StatusInternalServerError)
  216. m["error"] = errorStatus
  217. }
  218. m["size"] = ret
  219. writeJsonQuiet(w, r, m)
  220. }
  221. func DeleteHandler(w http.ResponseWriter, r *http.Request) {
  222. n := new(storage.Needle)
  223. vid, fid, _, _ := parseURLPath(r.URL.Path)
  224. volumeId, _ := storage.NewVolumeId(vid)
  225. n.ParsePath(fid)
  226. debug("deleting", n)
  227. cookie := n.Cookie
  228. count, ok := store.Read(volumeId, n)
  229. if ok != nil {
  230. m := make(map[string]uint32)
  231. m["size"] = 0
  232. writeJsonQuiet(w, r, m)
  233. return
  234. }
  235. if n.Cookie != cookie {
  236. log.Println("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  237. return
  238. }
  239. n.Size = 0
  240. ret := replication.ReplicatedDelete(*masterNode, store, volumeId, n, r)
  241. if ret != 0 {
  242. w.WriteHeader(http.StatusAccepted)
  243. } else {
  244. w.WriteHeader(http.StatusInternalServerError)
  245. }
  246. m := make(map[string]uint32)
  247. m["size"] = uint32(count)
  248. writeJsonQuiet(w, r, m)
  249. }
  250. func parseURLPath(path string) (vid, fid, filename, ext string) {
  251. switch strings.Count(path, "/") {
  252. case 3:
  253. parts := strings.Split(path, "/")
  254. vid, fid, filename = parts[1], parts[2], parts[3]
  255. ext = filepath.Ext(filename)
  256. case 2:
  257. parts := strings.Split(path, "/")
  258. vid, fid = parts[1], parts[2]
  259. dotIndex := strings.LastIndex(fid, ".")
  260. if dotIndex > 0 {
  261. ext = fid[dotIndex:]
  262. fid = fid[0:dotIndex]
  263. }
  264. default:
  265. sepIndex := strings.LastIndex(path, "/")
  266. commaIndex := strings.LastIndex(path[sepIndex:], ",")
  267. if commaIndex <= 0 {
  268. if "favicon.ico" != path[sepIndex+1:] {
  269. log.Println("unknown file id", path[sepIndex+1:])
  270. }
  271. return
  272. }
  273. dotIndex := strings.LastIndex(path[sepIndex:], ".")
  274. vid = path[sepIndex+1 : commaIndex]
  275. fid = path[commaIndex+1:]
  276. ext = ""
  277. if dotIndex > 0 {
  278. fid = path[commaIndex+1 : dotIndex]
  279. ext = path[dotIndex:]
  280. }
  281. }
  282. return
  283. }
  284. func runVolume(cmd *Command, args []string) bool {
  285. if *vMaxCpu < 1 {
  286. *vMaxCpu = runtime.NumCPU()
  287. }
  288. runtime.GOMAXPROCS(*vMaxCpu)
  289. folders := strings.Split(*volumeFolders, ",")
  290. maxCountStrings := strings.Split(*maxVolumeCounts, ",")
  291. maxCounts := make([]int, 0)
  292. for _, maxString := range maxCountStrings {
  293. if max, e := strconv.Atoi(maxString); e == nil {
  294. maxCounts = append(maxCounts, max)
  295. } else {
  296. log.Fatalf("The max specified in -max not a valid number %s", max)
  297. }
  298. }
  299. if len(folders) != len(maxCounts) {
  300. log.Fatalf("%d directories by -dir, but only %d max is set by -max", len(folders), len(maxCounts))
  301. }
  302. for _, folder := range folders {
  303. fileInfo, err := os.Stat(folder)
  304. if err != nil {
  305. log.Fatalf("No Existing Folder:%s", folder)
  306. }
  307. if !fileInfo.IsDir() {
  308. log.Fatalf("Volume Folder should not be a file:%s", folder)
  309. }
  310. perm := fileInfo.Mode().Perm()
  311. log.Println("Volume Folder", folder)
  312. log.Println("Permission:", perm)
  313. }
  314. if *publicUrl == "" {
  315. *publicUrl = *ip + ":" + strconv.Itoa(*vport)
  316. }
  317. store = storage.NewStore(*vport, *ip, *publicUrl, folders, maxCounts)
  318. defer store.Close()
  319. http.HandleFunc("/", storeHandler)
  320. http.HandleFunc("/submit", submitFromVolumeServerHandler)
  321. http.HandleFunc("/status", statusHandler)
  322. http.HandleFunc("/admin/assign_volume", assignVolumeHandler)
  323. http.HandleFunc("/admin/vacuum_volume_check", vacuumVolumeCheckHandler)
  324. http.HandleFunc("/admin/vacuum_volume_compact", vacuumVolumeCompactHandler)
  325. http.HandleFunc("/admin/vacuum_volume_commit", vacuumVolumeCommitHandler)
  326. http.HandleFunc("/admin/freeze_volume", freezeVolumeHandler)
  327. go func() {
  328. connected := true
  329. store.SetMaster(*masterNode)
  330. store.SetDataCenter(*dataCenter)
  331. store.SetRack(*rack)
  332. for {
  333. err := store.Join()
  334. if err == nil {
  335. if !connected {
  336. connected = true
  337. log.Println("Reconnected with master")
  338. }
  339. } else {
  340. if connected {
  341. connected = false
  342. }
  343. }
  344. time.Sleep(time.Duration(float32(*vpulse*1e3)*(1+rand.Float32())) * time.Millisecond)
  345. }
  346. }()
  347. log.Println("store joined at", *masterNode)
  348. log.Println("Start Weed volume server", VERSION, "at http://"+*ip+":"+strconv.Itoa(*vport))
  349. srv := &http.Server{
  350. Addr: ":" + strconv.Itoa(*vport),
  351. Handler: http.DefaultServeMux,
  352. ReadTimeout: (time.Duration(*vReadTimeout) * time.Second),
  353. }
  354. e := srv.ListenAndServe()
  355. if e != nil {
  356. log.Fatalf("Fail to start:%s", e.Error())
  357. }
  358. return true
  359. }