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.

273 lines
9.7 KiB

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