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.

386 lines
12 KiB

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