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.

397 lines
12 KiB

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