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.

284 lines
9.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
13 years ago
13 years ago
13 years ago
  1. package main
  2. import (
  3. "bytes"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "code.google.com/p/weed-fs/go/operation"
  6. "code.google.com/p/weed-fs/go/replication"
  7. "code.google.com/p/weed-fs/go/storage"
  8. "code.google.com/p/weed-fs/go/topology"
  9. "encoding/json"
  10. "errors"
  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. masterWhiteListOption = cmdMaster.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  39. masterWhiteList []string
  40. )
  41. var topo *topology.Topology
  42. var vg *replication.VolumeGrowth
  43. func dirLookupHandler(w http.ResponseWriter, r *http.Request) {
  44. vid := r.FormValue("volumeId")
  45. commaSep := strings.Index(vid, ",")
  46. if commaSep > 0 {
  47. vid = vid[0:commaSep]
  48. }
  49. volumeId, err := storage.NewVolumeId(vid)
  50. if err == nil {
  51. machines := topo.Lookup(volumeId)
  52. if machines != nil {
  53. ret := []map[string]string{}
  54. for _, dn := range machines {
  55. ret = append(ret, map[string]string{"url": dn.Url(), "publicUrl": dn.PublicUrl})
  56. }
  57. writeJsonQuiet(w, r, map[string]interface{}{"locations": ret})
  58. } else {
  59. w.WriteHeader(http.StatusNotFound)
  60. writeJsonQuiet(w, r, map[string]string{"error": "volume id " + volumeId.String() + " not found. "})
  61. }
  62. } else {
  63. w.WriteHeader(http.StatusNotAcceptable)
  64. writeJsonQuiet(w, r, map[string]string{"error": "unknown volumeId format " + vid})
  65. }
  66. }
  67. func dirAssignHandler(w http.ResponseWriter, r *http.Request) {
  68. c, e := strconv.Atoi(r.FormValue("count"))
  69. if e != nil {
  70. c = 1
  71. }
  72. repType := r.FormValue("replication")
  73. if repType == "" {
  74. repType = *defaultRepType
  75. }
  76. dataCenter := r.FormValue("dataCenter")
  77. rt, err := storage.NewReplicationTypeFromString(repType)
  78. if err != nil {
  79. w.WriteHeader(http.StatusNotAcceptable)
  80. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  81. return
  82. }
  83. if topo.GetVolumeLayout(rt).GetActiveVolumeCount(dataCenter) <= 0 {
  84. if topo.FreeSpace() <= 0 {
  85. w.WriteHeader(http.StatusNotFound)
  86. writeJsonQuiet(w, r, map[string]string{"error": "No free volumes left!"})
  87. return
  88. } else {
  89. if _, err = vg.AutomaticGrowByType(rt, dataCenter, topo); err != nil {
  90. writeJsonQuiet(w, r, map[string]string{"error": "Cannot grow volume group! " + err.Error()})
  91. return
  92. }
  93. }
  94. }
  95. fid, count, dn, err := topo.PickForWrite(rt, c, dataCenter)
  96. if err == nil {
  97. writeJsonQuiet(w, r, map[string]interface{}{"fid": fid, "url": dn.Url(), "publicUrl": dn.PublicUrl, "count": count})
  98. } else {
  99. w.WriteHeader(http.StatusNotAcceptable)
  100. writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
  101. }
  102. }
  103. func dirJoinHandler(w http.ResponseWriter, r *http.Request) {
  104. init := r.FormValue("init") == "true"
  105. ip := r.FormValue("ip")
  106. if ip == "" {
  107. ip = r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")]
  108. }
  109. port, _ := strconv.Atoi(r.FormValue("port"))
  110. maxVolumeCount, _ := strconv.Atoi(r.FormValue("maxVolumeCount"))
  111. s := r.RemoteAddr[0:strings.Index(r.RemoteAddr, ":")+1] + r.FormValue("port")
  112. publicUrl := r.FormValue("publicUrl")
  113. volumes := new([]storage.VolumeInfo)
  114. if err := json.Unmarshal([]byte(r.FormValue("volumes")), volumes); err != nil {
  115. writeJsonQuiet(w, r, map[string]string{"error": "Cannot unmarshal \"volumes\": " + err.Error()})
  116. return
  117. }
  118. debug(s, "volumes", r.FormValue("volumes"))
  119. topo.RegisterVolumes(init, *volumes, ip, port, publicUrl, maxVolumeCount, r.FormValue("dataCenter"), r.FormValue("rack"))
  120. m := make(map[string]interface{})
  121. m["VolumeSizeLimit"] = uint64(*volumeSizeLimitMB) * 1024 * 1024
  122. writeJsonQuiet(w, r, m)
  123. }
  124. func dirStatusHandler(w http.ResponseWriter, r *http.Request) {
  125. m := make(map[string]interface{})
  126. m["Version"] = VERSION
  127. m["Topology"] = topo.ToMap()
  128. writeJsonQuiet(w, r, m)
  129. }
  130. func volumeVacuumHandler(w http.ResponseWriter, r *http.Request) {
  131. gcThreshold := r.FormValue("garbageThreshold")
  132. if gcThreshold == "" {
  133. gcThreshold = *garbageThreshold
  134. }
  135. debug("garbageThreshold =", gcThreshold)
  136. topo.Vacuum(gcThreshold)
  137. dirStatusHandler(w, r)
  138. }
  139. func volumeGrowHandler(w http.ResponseWriter, r *http.Request) {
  140. count := 0
  141. rt, err := storage.NewReplicationTypeFromString(r.FormValue("replication"))
  142. if err == nil {
  143. if count, err = strconv.Atoi(r.FormValue("count")); err == nil {
  144. if topo.FreeSpace() < count*rt.GetCopyCount() {
  145. err = errors.New("Only " + strconv.Itoa(topo.FreeSpace()) + " volumes left! Not enough for " + strconv.Itoa(count*rt.GetCopyCount()))
  146. } else {
  147. count, err = vg.GrowByCountAndType(count, rt, r.FormValue("dataCneter"), topo)
  148. }
  149. } else {
  150. err = errors.New("parameter count is not found")
  151. }
  152. }
  153. if err != nil {
  154. w.WriteHeader(http.StatusNotAcceptable)
  155. writeJsonQuiet(w, r, map[string]string{"error": "parameter replication " + err.Error()})
  156. } else {
  157. w.WriteHeader(http.StatusNotAcceptable)
  158. writeJsonQuiet(w, r, map[string]interface{}{"count": count})
  159. }
  160. }
  161. func volumeStatusHandler(w http.ResponseWriter, r *http.Request) {
  162. m := make(map[string]interface{})
  163. m["Version"] = VERSION
  164. m["Volumes"] = topo.ToVolumeMap()
  165. writeJsonQuiet(w, r, m)
  166. }
  167. func redirectHandler(w http.ResponseWriter, r *http.Request) {
  168. vid, _, _, _ := parseURLPath(r.URL.Path)
  169. volumeId, err := storage.NewVolumeId(vid)
  170. if err != nil {
  171. debug("parsing error:", err, r.URL.Path)
  172. return
  173. }
  174. machines := topo.Lookup(volumeId)
  175. if machines != nil && len(machines) > 0 {
  176. http.Redirect(w, r, "http://"+machines[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
  177. } else {
  178. w.WriteHeader(http.StatusNotFound)
  179. writeJsonQuiet(w, r, map[string]string{"error": "volume id " + volumeId.String() + " not found. "})
  180. }
  181. }
  182. func submitFromMasterServerHandler(w http.ResponseWriter, r *http.Request) {
  183. submitForClientHandler(w, r, "localhost:"+strconv.Itoa(*mport))
  184. }
  185. func runMaster(cmd *Command, args []string) bool {
  186. if *mMaxCpu < 1 {
  187. *mMaxCpu = runtime.NumCPU()
  188. }
  189. runtime.GOMAXPROCS(*mMaxCpu)
  190. if *masterWhiteListOption != "" {
  191. masterWhiteList = strings.Split(*masterWhiteListOption, ",")
  192. }
  193. var e error
  194. if topo, e = topology.NewTopology("topo", *confFile, *metaFolder, "weed",
  195. uint64(*volumeSizeLimitMB)*1024*1024, *mpulse); e != nil {
  196. glog.Fatalf("cannot create topology:%s", e)
  197. }
  198. vg = replication.NewDefaultVolumeGrowth()
  199. glog.V(0).Infoln("Volume Size Limit is", *volumeSizeLimitMB, "MB")
  200. http.HandleFunc("/dir/assign", secure(masterWhiteList, dirAssignHandler))
  201. http.HandleFunc("/dir/lookup", secure(masterWhiteList, dirLookupHandler))
  202. http.HandleFunc("/dir/join", secure(masterWhiteList, dirJoinHandler))
  203. http.HandleFunc("/dir/status", secure(masterWhiteList, dirStatusHandler))
  204. http.HandleFunc("/vol/grow", secure(masterWhiteList, volumeGrowHandler))
  205. http.HandleFunc("/vol/status", secure(masterWhiteList, volumeStatusHandler))
  206. http.HandleFunc("/vol/vacuum", secure(masterWhiteList, volumeVacuumHandler))
  207. http.HandleFunc("/submit", secure(masterWhiteList, submitFromMasterServerHandler))
  208. http.HandleFunc("/", redirectHandler)
  209. topo.StartRefreshWritableVolumes(*garbageThreshold)
  210. glog.V(0).Infoln("Start Weed Master", VERSION, "at port", strconv.Itoa(*mport))
  211. srv := &http.Server{
  212. Addr: ":" + strconv.Itoa(*mport),
  213. Handler: http.DefaultServeMux,
  214. ReadTimeout: time.Duration(*mReadTimeout) * time.Second,
  215. }
  216. e = srv.ListenAndServe()
  217. if e != nil {
  218. glog.Fatalf("Fail to start:%s", e)
  219. }
  220. return true
  221. }
  222. func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string) {
  223. m := make(map[string]interface{})
  224. if r.Method != "POST" {
  225. m["error"] = "Only submit via POST!"
  226. writeJsonQuiet(w, r, m)
  227. return
  228. }
  229. debug("parsing upload file...")
  230. fname, data, mimeType, isGzipped, lastModified, pe := storage.ParseUpload(r)
  231. if pe != nil {
  232. writeJsonError(w, r, pe)
  233. return
  234. }
  235. debug("assigning file id for", fname)
  236. assignResult, ae := Assign(masterUrl, 1)
  237. if ae != nil {
  238. writeJsonError(w, r, ae)
  239. return
  240. }
  241. url := "http://" + assignResult.PublicUrl + "/" + assignResult.Fid
  242. if lastModified != 0 {
  243. url = url + "?ts=" + strconv.FormatUint(lastModified, 10)
  244. }
  245. debug("upload file to store", url)
  246. uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType)
  247. if err != nil {
  248. writeJsonError(w, r, err)
  249. return
  250. }
  251. m["fileName"] = fname
  252. m["fid"] = assignResult.Fid
  253. m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
  254. m["size"] = uploadResult.Size
  255. writeJsonQuiet(w, r, m)
  256. return
  257. }