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.

229 lines
7.6 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. dataCenter := r.FormValue("dataCenter")
  73. rt, err := storage.NewReplicationTypeFromString(repType)
  74. if err != nil {
  75. w.WriteHeader(http.StatusNotAcceptable)
  76. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  77. return
  78. }
  79. if topo.GetVolumeLayout(rt).GetActiveVolumeCount(dataCenter) <= 0 {
  80. if topo.FreeSpace() <= 0 {
  81. w.WriteHeader(http.StatusNotFound)
  82. writeJsonQuiet(w, r, map[string]string{"error": "No free volumes left!"})
  83. return
  84. } else {
  85. if _, err = vg.GrowByType(rt, dataCenter, topo); err != nil {
  86. writeJsonQuiet(w, r, map[string]string{"error": "Cannot grow volume group! " + err.Error()})
  87. return
  88. }
  89. }
  90. }
  91. fid, count, dn, err := topo.PickForWrite(rt, c, dataCenter)
  92. if err == nil {
  93. writeJsonQuiet(w, r, map[string]interface{}{"fid": fid, "url": dn.Url(), "publicUrl": dn.PublicUrl, "count": count})
  94. } else {
  95. w.WriteHeader(http.StatusNotAcceptable)
  96. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  97. }
  98. }
  99. func dirJoinHandler(w http.ResponseWriter, r *http.Request) {
  100. init := r.FormValue("init") == "true"
  101. ip := r.FormValue("ip")
  102. if ip == "" {
  103. ip = r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")]
  104. }
  105. port, _ := strconv.Atoi(r.FormValue("port"))
  106. maxVolumeCount, _ := strconv.Atoi(r.FormValue("maxVolumeCount"))
  107. s := r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")+1] + r.FormValue("port")
  108. publicUrl := r.FormValue("publicUrl")
  109. volumes := new([]storage.VolumeInfo)
  110. if err := json.Unmarshal([]byte(r.FormValue("volumes")), volumes); err != nil {
  111. writeJsonQuiet(w, r, map[string]string{"error": "Cannot unmarshal \"volumes\": " + err.Error()})
  112. return
  113. }
  114. debug(s, "volumes", r.FormValue("volumes"))
  115. topo.RegisterVolumes(init, *volumes, ip, port, publicUrl, maxVolumeCount, r.FormValue("dataCenter"), r.FormValue("rack"))
  116. m := make(map[string]interface{})
  117. m["VolumeSizeLimit"] = uint64(*volumeSizeLimitMB) * 1024 * 1024
  118. writeJsonQuiet(w, r, m)
  119. }
  120. func dirStatusHandler(w http.ResponseWriter, r *http.Request) {
  121. m := make(map[string]interface{})
  122. m["Version"] = VERSION
  123. m["Topology"] = topo.ToMap()
  124. writeJsonQuiet(w, r, m)
  125. }
  126. func volumeVacuumHandler(w http.ResponseWriter, r *http.Request) {
  127. gcThreshold := r.FormValue("garbageThreshold")
  128. if gcThreshold == "" {
  129. gcThreshold = *garbageThreshold
  130. }
  131. debug("garbageThreshold =", gcThreshold)
  132. topo.Vacuum(gcThreshold)
  133. dirStatusHandler(w, r)
  134. }
  135. func volumeGrowHandler(w http.ResponseWriter, r *http.Request) {
  136. count := 0
  137. rt, err := storage.NewReplicationTypeFromString(r.FormValue("replication"))
  138. if err == nil {
  139. if count, err = strconv.Atoi(r.FormValue("count")); err == nil {
  140. if topo.FreeSpace() < count*rt.GetCopyCount() {
  141. err = errors.New("Only " + strconv.Itoa(topo.FreeSpace()) + " volumes left! Not enough for " + strconv.Itoa(count*rt.GetCopyCount()))
  142. } else {
  143. count, err = vg.GrowByCountAndType(count, rt, r.FormValue("dataCneter"), topo)
  144. }
  145. } else {
  146. err = errors.New("parameter count is not found")
  147. }
  148. }
  149. if err != nil {
  150. w.WriteHeader(http.StatusNotAcceptable)
  151. writeJsonQuiet(w, r, map[string]string{"error": "parameter replication " + err.Error()})
  152. } else {
  153. w.WriteHeader(http.StatusNotAcceptable)
  154. writeJsonQuiet(w, r, map[string]interface{}{"count": count})
  155. }
  156. }
  157. func volumeStatusHandler(w http.ResponseWriter, r *http.Request) {
  158. m := make(map[string]interface{})
  159. m["Version"] = VERSION
  160. m["Volumes"] = topo.ToVolumeMap()
  161. writeJsonQuiet(w, r, m)
  162. }
  163. func redirectHandler(w http.ResponseWriter, r *http.Request) {
  164. vid, _, _ := parseURLPath(r.URL.Path)
  165. volumeId, err := storage.NewVolumeId(vid)
  166. if err != nil {
  167. debug("parsing error:", err, r.URL.Path)
  168. return
  169. }
  170. machines := topo.Lookup(volumeId)
  171. if machines != nil && len(machines) > 0 {
  172. http.Redirect(w, r, "http://"+machines[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  173. } else {
  174. w.WriteHeader(http.StatusNotFound)
  175. writeJsonQuiet(w, r, map[string]string{"error": "volume id " + volumeId.String() + " not found. "})
  176. }
  177. }
  178. func runMaster(cmd *Command, args []string) bool {
  179. if *mMaxCpu < 1 {
  180. *mMaxCpu = runtime.NumCPU()
  181. }
  182. runtime.GOMAXPROCS(*mMaxCpu)
  183. var e error
  184. if topo, e = topology.NewTopology("topo", *confFile, *metaFolder, "weed",
  185. uint64(*volumeSizeLimitMB)*1024*1024, *mpulse); e != nil {
  186. log.Fatalf("cannot create topology:%s", e)
  187. }
  188. vg = replication.NewDefaultVolumeGrowth()
  189. log.Println("Volume Size Limit is", *volumeSizeLimitMB, "MB")
  190. http.HandleFunc("/dir/assign", dirAssignHandler)
  191. http.HandleFunc("/dir/lookup", dirLookupHandler)
  192. http.HandleFunc("/dir/join", dirJoinHandler)
  193. http.HandleFunc("/dir/status", dirStatusHandler)
  194. http.HandleFunc("/vol/grow", volumeGrowHandler)
  195. http.HandleFunc("/vol/status", volumeStatusHandler)
  196. http.HandleFunc("/vol/vacuum", volumeVacuumHandler)
  197. http.HandleFunc("/", redirectHandler)
  198. topo.StartRefreshWritableVolumes(*garbageThreshold)
  199. log.Println("Start Weed Master", VERSION, "at port", strconv.Itoa(*mport))
  200. srv := &http.Server{
  201. Addr: ":" + strconv.Itoa(*mport),
  202. Handler: http.DefaultServeMux,
  203. ReadTimeout: time.Duration(*mReadTimeout) * time.Second,
  204. }
  205. e = srv.ListenAndServe()
  206. if e != nil {
  207. log.Fatalf("Fail to start:%s", e)
  208. }
  209. return true
  210. }