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.

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