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.

285 lines
9.5 KiB

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