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.

227 lines
7.5 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
  1. package main
  2. import (
  3. "code.google.com/p/weed-fs/go/replication"
  4. "code.google.com/p/weed-fs/go/storage"
  5. "code.google.com/p/weed-fs/go/topology"
  6. "encoding/json"
  7. "errors"
  8. "log"
  9. "net/http"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. func init() {
  16. cmdMaster.Run = runMaster // break init cycle
  17. cmdMaster.IsDebug = cmdMaster.Flag.Bool("debug", false, "enable debug mode")
  18. }
  19. var cmdMaster = &Command{
  20. UsageLine: "master -port=9333",
  21. Short: "start a master server",
  22. Long: `start a master server to provide volume=>location mapping service
  23. and sequence number of file ids
  24. `,
  25. }
  26. var (
  27. mport = cmdMaster.Flag.Int("port", 9333, "http listen port")
  28. metaFolder = cmdMaster.Flag.String("mdir", "/tmp", "data directory to store mappings")
  29. volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", 32*1024, "Default Volume Size in MegaBytes")
  30. mpulse = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
  31. confFile = cmdMaster.Flag.String("conf", "/etc/weedfs/weedfs.conf", "xml configuration file")
  32. defaultRepType = cmdMaster.Flag.String("defaultReplicationType", "000", "Default replication type if not specified.")
  33. mReadTimeout = cmdMaster.Flag.Int("readTimeout", 3, "connection read timeout in seconds")
  34. mMaxCpu = cmdMaster.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
  35. garbageThreshold = cmdMaster.Flag.String("garbageThreshold", "0.3", "threshold to vacuum and reclaim spaces")
  36. )
  37. var topo *topology.Topology
  38. var vg *replication.VolumeGrowth
  39. func dirLookupHandler(w http.ResponseWriter, r *http.Request) {
  40. vid := r.FormValue("volumeId")
  41. commaSep := strings.Index(vid, ",")
  42. if commaSep > 0 {
  43. vid = vid[0:commaSep]
  44. }
  45. volumeId, err := storage.NewVolumeId(vid)
  46. if err == nil {
  47. machines := topo.Lookup(volumeId)
  48. if machines != nil {
  49. ret := []map[string]string{}
  50. for _, dn := range machines {
  51. ret = append(ret, map[string]string{"url": dn.Url(), "publicUrl": dn.PublicUrl})
  52. }
  53. writeJsonQuiet(w, r, map[string]interface{}{"locations": ret})
  54. } else {
  55. w.WriteHeader(http.StatusNotFound)
  56. writeJsonQuiet(w, r, map[string]string{"error": "volume id " + volumeId.String() + " not found. "})
  57. }
  58. } else {
  59. w.WriteHeader(http.StatusNotAcceptable)
  60. writeJsonQuiet(w, r, map[string]string{"error": "unknown volumeId format " + vid})
  61. }
  62. }
  63. func dirAssignHandler(w http.ResponseWriter, r *http.Request) {
  64. c, e := strconv.Atoi(r.FormValue("count"))
  65. if e != nil {
  66. c = 1
  67. }
  68. repType := r.FormValue("replication")
  69. if repType == "" {
  70. repType = *defaultRepType
  71. }
  72. rt, err := storage.NewReplicationTypeFromString(repType)
  73. if err != nil {
  74. w.WriteHeader(http.StatusNotAcceptable)
  75. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  76. return
  77. }
  78. if topo.GetVolumeLayout(rt).GetActiveVolumeCount() <= 0 {
  79. if topo.FreeSpace() <= 0 {
  80. w.WriteHeader(http.StatusNotFound)
  81. writeJsonQuiet(w, r, map[string]string{"error": "No free volumes left!"})
  82. return
  83. } else {
  84. if _, err = vg.GrowByType(rt, topo); err != nil {
  85. writeJsonQuiet(w, r, map[string]string{"error": "Cannot grow volume group! " + err.Error()})
  86. return
  87. }
  88. }
  89. }
  90. fid, count, dn, err := topo.PickForWrite(rt, c)
  91. if err == nil {
  92. writeJsonQuiet(w, r, map[string]interface{}{"fid": fid, "url": dn.Url(), "publicUrl": dn.PublicUrl, "count": count})
  93. } else {
  94. w.WriteHeader(http.StatusNotAcceptable)
  95. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  96. }
  97. }
  98. func dirJoinHandler(w http.ResponseWriter, r *http.Request) {
  99. init := r.FormValue("init") == "true"
  100. ip := r.FormValue("ip")
  101. if ip == "" {
  102. ip = r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")]
  103. }
  104. port, _ := strconv.Atoi(r.FormValue("port"))
  105. maxVolumeCount, _ := strconv.Atoi(r.FormValue("maxVolumeCount"))
  106. s := r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")+1] + r.FormValue("port")
  107. publicUrl := r.FormValue("publicUrl")
  108. volumes := new([]storage.VolumeInfo)
  109. if err := json.Unmarshal([]byte(r.FormValue("volumes")), volumes); err != nil {
  110. writeJsonQuiet(w, r, map[string]string{"error": "Cannot unmarshal \"volumes\": " + err.Error()})
  111. return
  112. }
  113. debug(s, "volumes", r.FormValue("volumes"))
  114. topo.RegisterVolumes(init, *volumes, ip, port, publicUrl, maxVolumeCount)
  115. m := make(map[string]interface{})
  116. m["VolumeSizeLimit"] = uint64(*volumeSizeLimitMB) * 1024 * 1024
  117. writeJsonQuiet(w, r, m)
  118. }
  119. func dirStatusHandler(w http.ResponseWriter, r *http.Request) {
  120. m := make(map[string]interface{})
  121. m["Version"] = VERSION
  122. m["Topology"] = topo.ToMap()
  123. writeJsonQuiet(w, r, m)
  124. }
  125. func volumeVacuumHandler(w http.ResponseWriter, r *http.Request) {
  126. gcThreshold := r.FormValue("garbageThreshold")
  127. if gcThreshold == "" {
  128. gcThreshold = *garbageThreshold
  129. }
  130. debug("garbageThreshold =", gcThreshold)
  131. topo.Vacuum(gcThreshold)
  132. dirStatusHandler(w, r)
  133. }
  134. func volumeGrowHandler(w http.ResponseWriter, r *http.Request) {
  135. count := 0
  136. rt, err := storage.NewReplicationTypeFromString(r.FormValue("replication"))
  137. if err == nil {
  138. if count, err = strconv.Atoi(r.FormValue("count")); err == nil {
  139. if topo.FreeSpace() < count*rt.GetCopyCount() {
  140. err = errors.New("Only " + strconv.Itoa(topo.FreeSpace()) + " volumes left! Not enough for " + strconv.Itoa(count*rt.GetCopyCount()))
  141. } else {
  142. count, err = vg.GrowByCountAndType(count, rt, topo)
  143. }
  144. } else {
  145. err = errors.New("parameter count is not found")
  146. }
  147. }
  148. if err != nil {
  149. w.WriteHeader(http.StatusNotAcceptable)
  150. writeJsonQuiet(w, r, map[string]string{"error": "parameter replication " + err.Error()})
  151. } else {
  152. w.WriteHeader(http.StatusNotAcceptable)
  153. writeJsonQuiet(w, r, map[string]interface{}{"count": count})
  154. }
  155. }
  156. func volumeStatusHandler(w http.ResponseWriter, r *http.Request) {
  157. m := make(map[string]interface{})
  158. m["Version"] = VERSION
  159. m["Volumes"] = topo.ToVolumeMap()
  160. writeJsonQuiet(w, r, m)
  161. }
  162. func redirectHandler(w http.ResponseWriter, r *http.Request) {
  163. vid, _, _ := parseURLPath(r.URL.Path)
  164. volumeId, err := storage.NewVolumeId(vid)
  165. if err != nil {
  166. debug("parsing error:", err, r.URL.Path)
  167. return
  168. }
  169. machines := topo.Lookup(volumeId)
  170. if machines != nil && len(machines) > 0 {
  171. http.Redirect(w, r, "http://"+machines[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  172. } else {
  173. w.WriteHeader(http.StatusNotFound)
  174. writeJsonQuiet(w, r, map[string]string{"error": "volume id " + volumeId.String() + " not found. "})
  175. }
  176. }
  177. func runMaster(cmd *Command, args []string) bool {
  178. if *mMaxCpu < 1 {
  179. *mMaxCpu = runtime.NumCPU()
  180. }
  181. runtime.GOMAXPROCS(*mMaxCpu)
  182. var e error
  183. if topo, e = topology.NewTopology("topo", *confFile, *metaFolder, "weed",
  184. uint64(*volumeSizeLimitMB)*1024*1024, *mpulse); e != nil {
  185. log.Fatalf("cannot create topology:%s", e)
  186. }
  187. vg = replication.NewDefaultVolumeGrowth()
  188. log.Println("Volume Size Limit is", *volumeSizeLimitMB, "MB")
  189. http.HandleFunc("/dir/assign", dirAssignHandler)
  190. http.HandleFunc("/dir/lookup", dirLookupHandler)
  191. http.HandleFunc("/dir/join", dirJoinHandler)
  192. http.HandleFunc("/dir/status", dirStatusHandler)
  193. http.HandleFunc("/vol/grow", volumeGrowHandler)
  194. http.HandleFunc("/vol/status", volumeStatusHandler)
  195. http.HandleFunc("/vol/vacuum", volumeVacuumHandler)
  196. http.HandleFunc("/", redirectHandler)
  197. topo.StartRefreshWritableVolumes(*garbageThreshold)
  198. log.Println("Start Weed Master", VERSION, "at port", strconv.Itoa(*mport))
  199. srv := &http.Server{
  200. Addr: ":" + strconv.Itoa(*mport),
  201. Handler: http.DefaultServeMux,
  202. ReadTimeout: time.Duration(*mReadTimeout) * time.Second,
  203. }
  204. e = srv.ListenAndServe()
  205. if e != nil {
  206. log.Fatalf("Fail to start:%s", e)
  207. }
  208. return true
  209. }