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.

278 lines
9.9 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
3 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. masterPeers := make(map[string]pb.ServerAddress)
  112. for _, peer := range peers {
  113. masterPeers[peer.String()] = peer
  114. }
  115. r := mux.NewRouter()
  116. ms := weed_server.NewMasterServer(r, masterOption.toMasterOption(masterWhiteList), masterPeers)
  117. listeningAddress := util.JoinHostPort(*masterOption.ipBind, *masterOption.port)
  118. glog.V(0).Infof("Start Seaweed Master %s at %s", util.Version(), listeningAddress)
  119. masterListener, masterLocalListner, e := util.NewIpAndLocalListeners(*masterOption.ipBind, *masterOption.port, 0)
  120. if e != nil {
  121. glog.Fatalf("Master startup error: %v", e)
  122. }
  123. // start raftServer
  124. raftServerOption := &weed_server.RaftServerOption{
  125. GrpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.master"),
  126. Peers: masterPeers,
  127. ServerAddr: myMasterAddress,
  128. DataDir: util.ResolvePath(*masterOption.metaFolder),
  129. Topo: ms.Topo,
  130. RaftResumeState: *masterOption.raftResumeState,
  131. HeartbeatInterval: *masterOption.heartbeatInterval,
  132. ElectionTimeout: *masterOption.electionTimeout,
  133. }
  134. raftServer, err := weed_server.NewRaftServer(raftServerOption)
  135. if raftServer == nil {
  136. glog.Fatalf("please verify %s is writable, see https://github.com/chrislusf/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
  137. }
  138. ms.SetRaftServer(raftServer)
  139. r.HandleFunc("/cluster/status", raftServer.StatusHandler).Methods("GET")
  140. // starting grpc server
  141. grpcPort := *masterOption.portGrpc
  142. grpcL, grpcLocalL, err := util.NewIpAndLocalListeners(*masterOption.ipBind, grpcPort, 0)
  143. if err != nil {
  144. glog.Fatalf("master failed to listen on grpc port %d: %v", grpcPort, err)
  145. }
  146. grpcS := pb.NewGrpcServer(security.LoadServerTLS(util.GetViper(), "grpc.master"))
  147. master_pb.RegisterSeaweedServer(grpcS, ms)
  148. protobuf.RegisterRaftServer(grpcS, raftServer)
  149. reflection.Register(grpcS)
  150. glog.V(0).Infof("Start Seaweed Master %s grpc server at %s:%d", util.Version(), *masterOption.ipBind, grpcPort)
  151. if grpcLocalL != nil {
  152. go grpcS.Serve(grpcLocalL)
  153. }
  154. go grpcS.Serve(grpcL)
  155. go func() {
  156. time.Sleep(1500 * time.Millisecond)
  157. if ms.Topo.RaftServer.Leader() == "" && ms.Topo.RaftServer.IsLogEmpty() && isTheFirstOne(myMasterAddress, peers) {
  158. if ms.MasterClient.FindLeaderFromOtherPeers(myMasterAddress) == "" {
  159. raftServer.DoJoinCommand()
  160. }
  161. }
  162. }()
  163. go ms.MasterClient.KeepConnectedToMaster()
  164. // start http server
  165. var (
  166. clientCertFile,
  167. certFile,
  168. keyFile string
  169. )
  170. useTLS := false
  171. useMTLS := false
  172. if viper.GetString("https.master.key") != "" {
  173. useTLS = true
  174. certFile = viper.GetString("https.master.cert")
  175. keyFile = viper.GetString("https.master.key")
  176. }
  177. if viper.GetString("https.master.ca") != "" {
  178. useMTLS = true
  179. clientCertFile = viper.GetString("https.master.ca")
  180. }
  181. httpS := &http.Server{Handler: r}
  182. if masterLocalListner != nil {
  183. go httpS.Serve(masterLocalListner)
  184. }
  185. if useMTLS {
  186. httpS.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
  187. }
  188. if useTLS {
  189. go httpS.ServeTLS(masterListener, certFile, keyFile)
  190. } else {
  191. go httpS.Serve(masterListener)
  192. }
  193. select {}
  194. }
  195. func checkPeers(masterIp string, masterPort int, masterGrpcPort int, peers string) (masterAddress pb.ServerAddress, cleanedPeers []pb.ServerAddress) {
  196. glog.V(0).Infof("current: %s:%d peers:%s", masterIp, masterPort, peers)
  197. masterAddress = pb.NewServerAddress(masterIp, masterPort, masterGrpcPort)
  198. cleanedPeers = pb.ServerAddresses(peers).ToAddresses()
  199. hasSelf := false
  200. for _, peer := range cleanedPeers {
  201. if peer.ToHttpAddress() == masterAddress.ToHttpAddress() {
  202. hasSelf = true
  203. break
  204. }
  205. }
  206. if !hasSelf {
  207. cleanedPeers = append(cleanedPeers, masterAddress)
  208. }
  209. if len(cleanedPeers)%2 == 0 {
  210. glog.Fatalf("Only odd number of masters are supported: %+v", cleanedPeers)
  211. }
  212. return
  213. }
  214. func isTheFirstOne(self pb.ServerAddress, peers []pb.ServerAddress) bool {
  215. sort.Slice(peers, func(i, j int) bool {
  216. return strings.Compare(string(peers[i]), string(peers[j])) < 0
  217. })
  218. if len(peers) <= 0 {
  219. return true
  220. }
  221. return self == peers[0]
  222. }
  223. func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOption {
  224. masterAddress := pb.NewServerAddress(*m.ip, *m.port, *m.portGrpc)
  225. return &weed_server.MasterOption{
  226. Master: masterAddress,
  227. MetaFolder: *m.metaFolder,
  228. VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
  229. VolumePreallocate: *m.volumePreallocate,
  230. // PulseSeconds: *m.pulseSeconds,
  231. DefaultReplicaPlacement: *m.defaultReplication,
  232. GarbageThreshold: *m.garbageThreshold,
  233. WhiteList: whiteList,
  234. DisableHttp: *m.disableHttp,
  235. MetricsAddress: *m.metricsAddress,
  236. MetricsIntervalSec: *m.metricsIntervalSec,
  237. }
  238. }