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.

378 lines
11 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
13 years ago
13 years ago
  1. package main
  2. import (
  3. "bytes"
  4. "log"
  5. "math/rand"
  6. "mime"
  7. "net/http"
  8. "os"
  9. "code.google.com/p/weed-fs/go/operation"
  10. "code.google.com/p/weed-fs/go/storage"
  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. writeJson(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. writeJson(w, r, map[string]string{"error": ""})
  49. } else {
  50. writeJson(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. writeJson(w, r, map[string]interface{}{"error": "", "result": ret})
  58. } else {
  59. writeJson(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. writeJson(w, r, map[string]string{"error": ""})
  67. } else {
  68. writeJson(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. writeJson(w, r, map[string]interface{}{"error": ""})
  76. } else {
  77. writeJson(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. GetHandler(w, r)
  85. case "DELETE":
  86. DeleteHandler(w, r)
  87. case "POST":
  88. PostHandler(w, r)
  89. }
  90. }
  91. func GetHandler(w http.ResponseWriter, r *http.Request) {
  92. n := new(storage.Needle)
  93. vid, fid, ext := parseURLPath(r.URL.Path)
  94. volumeId, err := storage.NewVolumeId(vid)
  95. if err != nil {
  96. debug("parsing error:", err, r.URL.Path)
  97. return
  98. }
  99. n.ParsePath(fid)
  100. debug("volume", volumeId, "reading", n)
  101. if !store.HasVolume(volumeId) {
  102. lookupResult, err := operation.Lookup(*masterNode, volumeId)
  103. debug("volume", volumeId, "found on", lookupResult, "error", err)
  104. if err == nil {
  105. http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  106. } else {
  107. debug("lookup error:", err, r.URL.Path)
  108. w.WriteHeader(http.StatusNotFound)
  109. }
  110. return
  111. }
  112. cookie := n.Cookie
  113. count, e := store.Read(volumeId, n)
  114. debug("read bytes", count, "error", e)
  115. if e != nil || count <= 0 {
  116. debug("read error:", e, r.URL.Path)
  117. w.WriteHeader(http.StatusNotFound)
  118. return
  119. }
  120. if n.Cookie != cookie {
  121. log.Println("request with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  122. w.WriteHeader(http.StatusNotFound)
  123. return
  124. }
  125. if n.NameSize > 0 {
  126. fname := string(n.Name)
  127. dotIndex := strings.LastIndex(fname, ".")
  128. if dotIndex > 0 {
  129. ext = fname[dotIndex:]
  130. }
  131. }
  132. mtype := ""
  133. if ext != "" {
  134. mtype = mime.TypeByExtension(ext)
  135. }
  136. if n.MimeSize > 0 {
  137. mtype = string(n.Mime)
  138. }
  139. if mtype != "" {
  140. w.Header().Set("Content-Type", mtype)
  141. }
  142. if n.NameSize > 0 {
  143. w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(string(n.Name)))
  144. }
  145. if ext != ".gz" {
  146. if n.IsGzipped() {
  147. if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  148. w.Header().Set("Content-Encoding", "gzip")
  149. } else {
  150. if n.Data, err = storage.UnGzipData(n.Data); err != nil {
  151. debug("lookup error:", err, r.URL.Path)
  152. }
  153. }
  154. }
  155. }
  156. w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
  157. w.Write(n.Data)
  158. }
  159. func PostHandler(w http.ResponseWriter, r *http.Request) {
  160. r.ParseForm()
  161. vid, _, _ := parseURLPath(r.URL.Path)
  162. volumeId, e := storage.NewVolumeId(vid)
  163. if e != nil {
  164. writeJson(w, r, e)
  165. } else {
  166. needle, filename, ne := storage.NewNeedle(r)
  167. if ne != nil {
  168. writeJson(w, r, ne)
  169. } else {
  170. ret, err := store.Write(volumeId, needle)
  171. errorStatus := ""
  172. needToReplicate := !store.HasVolume(volumeId)
  173. if err != nil {
  174. errorStatus = "Failed to write to local disk (" + err.Error() + ")"
  175. } else if ret > 0 {
  176. needToReplicate = needToReplicate || store.GetVolume(volumeId).NeedToReplicate()
  177. } else {
  178. errorStatus = "Failed to write to local disk"
  179. }
  180. if !needToReplicate && ret > 0 {
  181. needToReplicate = store.GetVolume(volumeId).NeedToReplicate()
  182. }
  183. if needToReplicate { //send to other replica locations
  184. if r.FormValue("type") != "standard" {
  185. if !distributedOperation(volumeId, func(location operation.Location) bool {
  186. _, err := operation.Upload("http://"+location.Url+r.URL.Path+"?type=standard", filename, bytes.NewReader(needle.Data))
  187. return err == nil
  188. }) {
  189. ret = 0
  190. errorStatus = "Failed to write to replicas for volume " + volumeId.String()
  191. }
  192. }
  193. }
  194. m := make(map[string]interface{})
  195. if errorStatus == "" {
  196. w.WriteHeader(http.StatusCreated)
  197. } else {
  198. store.Delete(volumeId, needle)
  199. distributedOperation(volumeId, func(location operation.Location) bool {
  200. return nil == operation.Delete("http://"+location.Url+r.URL.Path+"?type=standard")
  201. })
  202. w.WriteHeader(http.StatusInternalServerError)
  203. m["error"] = errorStatus
  204. }
  205. m["size"] = ret
  206. writeJson(w, r, m)
  207. }
  208. }
  209. }
  210. func DeleteHandler(w http.ResponseWriter, r *http.Request) {
  211. n := new(storage.Needle)
  212. vid, fid, _ := parseURLPath(r.URL.Path)
  213. volumeId, _ := storage.NewVolumeId(vid)
  214. n.ParsePath(fid)
  215. debug("deleting", n)
  216. cookie := n.Cookie
  217. count, ok := store.Read(volumeId, n)
  218. if ok != nil {
  219. m := make(map[string]uint32)
  220. m["size"] = 0
  221. writeJson(w, r, m)
  222. return
  223. }
  224. if n.Cookie != cookie {
  225. log.Println("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
  226. return
  227. }
  228. n.Size = 0
  229. ret, err := store.Delete(volumeId, n)
  230. if err != nil {
  231. log.Println("delete error:", err)
  232. return
  233. }
  234. needToReplicate := !store.HasVolume(volumeId)
  235. if !needToReplicate && ret > 0 {
  236. needToReplicate = store.GetVolume(volumeId).NeedToReplicate()
  237. }
  238. if needToReplicate { //send to other replica locations
  239. if r.FormValue("type") != "standard" {
  240. if !distributedOperation(volumeId, func(location operation.Location) bool {
  241. return nil == operation.Delete("http://"+location.Url+r.URL.Path+"?type=standard")
  242. }) {
  243. ret = 0
  244. }
  245. }
  246. }
  247. if ret != 0 {
  248. w.WriteHeader(http.StatusAccepted)
  249. } else {
  250. w.WriteHeader(http.StatusInternalServerError)
  251. }
  252. m := make(map[string]uint32)
  253. m["size"] = uint32(count)
  254. writeJson(w, r, m)
  255. }
  256. func parseURLPath(path string) (vid, fid, ext string) {
  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. return
  274. }
  275. func distributedOperation(volumeId storage.VolumeId, op func(location operation.Location) bool) bool {
  276. if lookupResult, lookupErr := operation.Lookup(*masterNode, volumeId); lookupErr == nil {
  277. length := 0
  278. selfUrl := (*ip + ":" + strconv.Itoa(*vport))
  279. results := make(chan bool)
  280. for _, location := range lookupResult.Locations {
  281. if location.Url != selfUrl {
  282. length++
  283. go func(location operation.Location, results chan bool) {
  284. results <- op(location)
  285. }(location, results)
  286. }
  287. }
  288. ret := true
  289. for i := 0; i < length; i++ {
  290. ret = ret && <-results
  291. }
  292. return ret
  293. } else {
  294. log.Println("Failed to lookup for", volumeId, lookupErr.Error())
  295. }
  296. return false
  297. }
  298. func runVolume(cmd *Command, args []string) bool {
  299. if *vMaxCpu < 1 {
  300. *vMaxCpu = runtime.NumCPU()
  301. }
  302. runtime.GOMAXPROCS(*vMaxCpu)
  303. fileInfo, err := os.Stat(*volumeFolder)
  304. if err != nil {
  305. log.Fatalf("No Existing Folder:%s", *volumeFolder)
  306. }
  307. if !fileInfo.IsDir() {
  308. log.Fatalf("Volume Folder should not be a file:%s", *volumeFolder)
  309. }
  310. perm := fileInfo.Mode().Perm()
  311. log.Println("Volume Folder permission:", perm)
  312. if *publicUrl == "" {
  313. *publicUrl = *ip + ":" + strconv.Itoa(*vport)
  314. }
  315. store = storage.NewStore(*vport, *ip, *publicUrl, *volumeFolder, *maxVolumeCount)
  316. defer store.Close()
  317. http.HandleFunc("/", storeHandler)
  318. http.HandleFunc("/status", statusHandler)
  319. http.HandleFunc("/admin/assign_volume", assignVolumeHandler)
  320. http.HandleFunc("/admin/vacuum_volume_check", vacuumVolumeCheckHandler)
  321. http.HandleFunc("/admin/vacuum_volume_compact", vacuumVolumeCompactHandler)
  322. http.HandleFunc("/admin/vacuum_volume_commit", vacuumVolumeCommitHandler)
  323. go func() {
  324. connected := true
  325. store.SetMaster(*masterNode)
  326. for {
  327. err := store.Join()
  328. if err == nil {
  329. if !connected {
  330. connected = true
  331. log.Println("Reconnected with master")
  332. }
  333. } else {
  334. if connected {
  335. connected = false
  336. }
  337. }
  338. time.Sleep(time.Duration(float32(*vpulse*1e3)*(1+rand.Float32())) * time.Millisecond)
  339. }
  340. }()
  341. log.Println("store joined at", *masterNode)
  342. log.Println("Start Weed volume server", VERSION, "at http://"+*ip+":"+strconv.Itoa(*vport))
  343. srv := &http.Server{
  344. Addr: ":" + strconv.Itoa(*vport),
  345. Handler: http.DefaultServeMux,
  346. ReadTimeout: (time.Duration(*vReadTimeout) * time.Second),
  347. }
  348. e := srv.ListenAndServe()
  349. if e != nil {
  350. log.Fatalf("Fail to start:%s", e.Error())
  351. }
  352. return true
  353. }