master.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package command
  2. import (
  3. "github.com/chrislusf/raft/protobuf"
  4. stats_collect "github.com/chrislusf/seaweedfs/weed/stats"
  5. "github.com/gorilla/mux"
  6. "google.golang.org/grpc/reflection"
  7. "net/http"
  8. "os"
  9. "sort"
  10. "strings"
  11. "time"
  12. "github.com/chrislusf/seaweedfs/weed/util/grace"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/pb"
  15. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  16. "github.com/chrislusf/seaweedfs/weed/security"
  17. "github.com/chrislusf/seaweedfs/weed/server"
  18. "github.com/chrislusf/seaweedfs/weed/storage/backend"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. )
  21. var (
  22. m MasterOptions
  23. )
  24. type MasterOptions struct {
  25. port *int
  26. portGrpc *int
  27. ip *string
  28. ipBind *string
  29. metaFolder *string
  30. peers *string
  31. volumeSizeLimitMB *uint
  32. volumePreallocate *bool
  33. // pulseSeconds *int
  34. defaultReplication *string
  35. garbageThreshold *float64
  36. whiteList *string
  37. disableHttp *bool
  38. metricsAddress *string
  39. metricsIntervalSec *int
  40. raftResumeState *bool
  41. metricsHttpPort *int
  42. }
  43. func init() {
  44. cmdMaster.Run = runMaster // break init cycle
  45. m.port = cmdMaster.Flag.Int("port", 9333, "http listen port")
  46. m.portGrpc = cmdMaster.Flag.Int("port.grpc", 0, "grpc listen port")
  47. m.ip = cmdMaster.Flag.String("ip", util.DetectedHostAddress(), "master <ip>|<server> address, also used as identifier")
  48. m.ipBind = cmdMaster.Flag.String("ip.bind", "", "ip address to bind to")
  49. m.metaFolder = cmdMaster.Flag.String("mdir", os.TempDir(), "data directory to store meta data")
  50. m.peers = cmdMaster.Flag.String("peers", "", "all master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094,127.0.0.1:9095")
  51. m.volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
  52. m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
  53. // m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
  54. m.defaultReplication = cmdMaster.Flag.String("defaultReplication", "", "Default replication type if not specified.")
  55. m.garbageThreshold = cmdMaster.Flag.Float64("garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
  56. m.whiteList = cmdMaster.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
  57. m.disableHttp = cmdMaster.Flag.Bool("disableHttp", false, "disable http requests, only gRPC operations are allowed.")
  58. m.metricsAddress = cmdMaster.Flag.String("metrics.address", "", "Prometheus gateway address <host>:<port>")
  59. m.metricsIntervalSec = cmdMaster.Flag.Int("metrics.intervalSeconds", 15, "Prometheus push interval in seconds")
  60. m.metricsHttpPort = cmdMaster.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
  61. m.raftResumeState = cmdMaster.Flag.Bool("resumeState", false, "resume previous state on start master server")
  62. }
  63. var cmdMaster = &Command{
  64. UsageLine: "master -port=9333",
  65. Short: "start a master server",
  66. Long: `start a master server to provide volume=>location mapping service and sequence number of file ids
  67. The configuration file "security.toml" is read from ".", "$HOME/.seaweedfs/", "/usr/local/etc/seaweedfs/", or "/etc/seaweedfs/", in that order.
  68. The example security.toml configuration file can be generated by "weed scaffold -config=security"
  69. `,
  70. }
  71. var (
  72. masterCpuProfile = cmdMaster.Flag.String("cpuprofile", "", "cpu profile output file")
  73. masterMemProfile = cmdMaster.Flag.String("memprofile", "", "memory profile output file")
  74. )
  75. func runMaster(cmd *Command, args []string) bool {
  76. util.LoadConfiguration("security", false)
  77. util.LoadConfiguration("master", false)
  78. grace.SetupProfiling(*masterCpuProfile, *masterMemProfile)
  79. parent, _ := util.FullPath(*m.metaFolder).DirAndName()
  80. if util.FileExists(string(parent)) && !util.FileExists(*m.metaFolder) {
  81. os.MkdirAll(*m.metaFolder, 0755)
  82. }
  83. if err := util.TestFolderWritable(util.ResolvePath(*m.metaFolder)); err != nil {
  84. glog.Fatalf("Check Meta Folder (-mdir) Writable %s : %s", *m.metaFolder, err)
  85. }
  86. var masterWhiteList []string
  87. if *m.whiteList != "" {
  88. masterWhiteList = strings.Split(*m.whiteList, ",")
  89. }
  90. if *m.volumeSizeLimitMB > util.VolumeSizeLimitGB*1000 {
  91. glog.Fatalf("volumeSizeLimitMB should be smaller than 30000")
  92. }
  93. go stats_collect.StartMetricsServer(*m.metricsHttpPort)
  94. startMaster(m, masterWhiteList)
  95. return true
  96. }
  97. func startMaster(masterOption MasterOptions, masterWhiteList []string) {
  98. backend.LoadConfiguration(util.GetViper())
  99. if *masterOption.portGrpc == 0 {
  100. *masterOption.portGrpc = 10000 + *masterOption.port
  101. }
  102. myMasterAddress, peers := checkPeers(*masterOption.ip, *masterOption.port, *masterOption.portGrpc, *masterOption.peers)
  103. r := mux.NewRouter()
  104. ms := weed_server.NewMasterServer(r, masterOption.toMasterOption(masterWhiteList), peers)
  105. listeningAddress := util.JoinHostPort(*masterOption.ipBind, *masterOption.port)
  106. glog.V(0).Infof("Start Seaweed Master %s at %s", util.Version(), listeningAddress)
  107. masterListener, e := util.NewListener(listeningAddress, 0)
  108. if e != nil {
  109. glog.Fatalf("Master startup error: %v", e)
  110. }
  111. // start raftServer
  112. raftServer, err := weed_server.NewRaftServer(security.LoadClientTLS(util.GetViper(), "grpc.master"),
  113. peers, myMasterAddress, util.ResolvePath(*masterOption.metaFolder), ms.Topo, *masterOption.raftResumeState)
  114. if raftServer == nil {
  115. glog.Fatalf("please verify %s is writable, see https://github.com/chrislusf/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
  116. }
  117. ms.SetRaftServer(raftServer)
  118. r.HandleFunc("/cluster/status", raftServer.StatusHandler).Methods("GET")
  119. // starting grpc server
  120. grpcPort := *masterOption.portGrpc
  121. grpcL, err := util.NewListener(util.JoinHostPort(*masterOption.ipBind, grpcPort), 0)
  122. if err != nil {
  123. glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
  124. }
  125. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.master"))
  126. master_pb.RegisterSeaweedServer(grpcS, ms)
  127. protobuf.RegisterRaftServer(grpcS, raftServer)
  128. reflection.Register(grpcS)
  129. glog.V(0).Infof("Start Seaweed Master %s grpc server at %s:%d", util.Version(), *masterOption.ipBind, grpcPort)
  130. go grpcS.Serve(grpcL)
  131. go func() {
  132. time.Sleep(1500 * time.Millisecond)
  133. if ms.Topo.RaftServer.Leader() == "" && ms.Topo.RaftServer.IsLogEmpty() && isTheFirstOne(myMasterAddress, peers) {
  134. if ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress) == "" {
  135. raftServer.DoJoinCommand()
  136. }
  137. }
  138. }()
  139. go ms.MasterClient.KeepConnectedToMaster()
  140. // start http server
  141. httpS := &http.Server{Handler: r}
  142. go httpS.Serve(masterListener)
  143. select {}
  144. }
  145. func checkPeers(masterIp string, masterPort int, masterGrpcPort int, peers string) (masterAddress pb.ServerAddress, cleanedPeers []pb.ServerAddress) {
  146. glog.V(0).Infof("current: %s:%d peers:%s", masterIp, masterPort, peers)
  147. masterAddress = pb.NewServerAddress(masterIp, masterPort, masterGrpcPort)
  148. cleanedPeers = pb.ServerAddresses(peers).ToAddresses()
  149. hasSelf := false
  150. for _, peer := range cleanedPeers {
  151. if peer.ToHttpAddress() == masterAddress.ToHttpAddress() {
  152. hasSelf = true
  153. break
  154. }
  155. }
  156. if !hasSelf {
  157. cleanedPeers = append(cleanedPeers, masterAddress)
  158. }
  159. if len(cleanedPeers)%2 == 0 {
  160. glog.Fatalf("Only odd number of masters are supported: %+v", cleanedPeers)
  161. }
  162. return
  163. }
  164. func isTheFirstOne(self pb.ServerAddress, peers []pb.ServerAddress) bool {
  165. sort.Slice(peers, func(i, j int) bool {
  166. return strings.Compare(string(peers[i]), string(peers[j])) < 0
  167. })
  168. if len(peers) <= 0 {
  169. return true
  170. }
  171. return self == peers[0]
  172. }
  173. func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOption {
  174. masterAddress := pb.NewServerAddress(*m.ip, *m.port, *m.portGrpc)
  175. return &weed_server.MasterOption{
  176. Master: masterAddress,
  177. MetaFolder: *m.metaFolder,
  178. VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
  179. VolumePreallocate: *m.volumePreallocate,
  180. // PulseSeconds: *m.pulseSeconds,
  181. DefaultReplicaPlacement: *m.defaultReplication,
  182. GarbageThreshold: *m.garbageThreshold,
  183. WhiteList: whiteList,
  184. DisableHttp: *m.disableHttp,
  185. MetricsAddress: *m.metricsAddress,
  186. MetricsIntervalSec: *m.metricsIntervalSec,
  187. }
  188. }