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.

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