master.go 11 KB

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