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.

278 lines
8.9 KiB

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