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.

306 lines
11 KiB

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