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.

176 lines
4.1 KiB

5 years ago
5 years ago
11 years ago
5 years ago
6 years ago
  1. package weed_server
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. "reflect"
  8. "sort"
  9. "time"
  10. "google.golang.org/grpc"
  11. "github.com/chrislusf/seaweedfs/weed/pb"
  12. "github.com/chrislusf/raft"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/topology"
  15. )
  16. type RaftServer struct {
  17. peers []string // initial peers to join with
  18. raftServer raft.Server
  19. dataDir string
  20. serverAddr string
  21. topo *topology.Topology
  22. *raft.GrpcServer
  23. }
  24. type StateMachine struct {
  25. raft.StateMachine
  26. topo *topology.Topology
  27. }
  28. func (s StateMachine) Save() ([]byte, error) {
  29. state := topology.MaxVolumeIdCommand{
  30. MaxVolumeId: s.topo.GetMaxVolumeId(),
  31. }
  32. glog.V(1).Infof("Save raft state %+v", state)
  33. return json.Marshal(state)
  34. }
  35. func (s StateMachine) Recovery(data []byte) error {
  36. state := topology.MaxVolumeIdCommand{}
  37. err := json.Unmarshal(data, &state)
  38. if err != nil {
  39. return err
  40. }
  41. glog.V(1).Infof("Recovery raft state %+v", state)
  42. s.topo.UpAdjustMaxVolumeId(state.MaxVolumeId)
  43. return nil
  44. }
  45. func NewRaftServer(grpcDialOption grpc.DialOption, peers []string, serverAddr, dataDir string, topo *topology.Topology, pulseSeconds int, raftResumeState bool) (*RaftServer, error) {
  46. s := &RaftServer{
  47. peers: peers,
  48. serverAddr: serverAddr,
  49. dataDir: dataDir,
  50. topo: topo,
  51. }
  52. if glog.V(4) {
  53. raft.SetLogLevel(2)
  54. }
  55. raft.RegisterCommand(&topology.MaxVolumeIdCommand{})
  56. var err error
  57. transporter := raft.NewGrpcTransporter(grpcDialOption)
  58. glog.V(0).Infof("Starting RaftServer with %v", serverAddr)
  59. if !raftResumeState {
  60. // always clear previous metadata
  61. os.RemoveAll(path.Join(s.dataDir, "conf"))
  62. os.RemoveAll(path.Join(s.dataDir, "log"))
  63. os.RemoveAll(path.Join(s.dataDir, "snapshot"))
  64. }
  65. if err := os.MkdirAll(path.Join(s.dataDir, "snapshot"), 0600); err != nil {
  66. return nil, err
  67. }
  68. // Clear old cluster configurations if peers are changed
  69. if oldPeers, changed := isPeersChanged(s.dataDir, serverAddr, s.peers); changed {
  70. glog.V(0).Infof("Peers Change: %v => %v", oldPeers, s.peers)
  71. }
  72. stateMachine := StateMachine{topo: topo}
  73. s.raftServer, err = raft.NewServer(s.serverAddr, s.dataDir, transporter, stateMachine, topo, "")
  74. if err != nil {
  75. glog.V(0).Infoln(err)
  76. return nil, err
  77. }
  78. s.raftServer.SetHeartbeatInterval(500 * time.Millisecond)
  79. s.raftServer.SetElectionTimeout(time.Duration(pulseSeconds) * 500 * time.Millisecond)
  80. if err := s.raftServer.LoadSnapshot(); err != nil {
  81. return nil, err
  82. }
  83. if err := s.raftServer.Start(); err != nil {
  84. return nil, err
  85. }
  86. for _, peer := range s.peers {
  87. if err := s.raftServer.AddPeer(peer, pb.ServerToGrpcAddress(peer)); err != nil {
  88. return nil, err
  89. }
  90. }
  91. s.GrpcServer = raft.NewGrpcServer(s.raftServer)
  92. if s.raftServer.IsLogEmpty() && isTheFirstOne(serverAddr, s.peers) {
  93. // Initialize the server by joining itself.
  94. glog.V(0).Infoln("Initializing new cluster")
  95. _, err := s.raftServer.Do(&raft.DefaultJoinCommand{
  96. Name: s.raftServer.Name(),
  97. ConnectionString: pb.ServerToGrpcAddress(s.serverAddr),
  98. })
  99. if err != nil {
  100. glog.V(0).Infoln(err)
  101. return nil, err
  102. }
  103. }
  104. glog.V(0).Infof("current cluster leader: %v", s.raftServer.Leader())
  105. return s, nil
  106. }
  107. func (s *RaftServer) Peers() (members []string) {
  108. peers := s.raftServer.Peers()
  109. for _, p := range peers {
  110. members = append(members, p.Name)
  111. }
  112. return
  113. }
  114. func isPeersChanged(dir string, self string, peers []string) (oldPeers []string, changed bool) {
  115. confPath := path.Join(dir, "conf")
  116. // open conf file
  117. b, err := ioutil.ReadFile(confPath)
  118. if err != nil {
  119. return oldPeers, true
  120. }
  121. conf := &raft.Config{}
  122. if err = json.Unmarshal(b, conf); err != nil {
  123. return oldPeers, true
  124. }
  125. for _, p := range conf.Peers {
  126. oldPeers = append(oldPeers, p.Name)
  127. }
  128. oldPeers = append(oldPeers, self)
  129. if len(peers) == 0 && len(oldPeers) <= 1 {
  130. return oldPeers, false
  131. }
  132. sort.Strings(peers)
  133. sort.Strings(oldPeers)
  134. return oldPeers, !reflect.DeepEqual(peers, oldPeers)
  135. }
  136. func isTheFirstOne(self string, peers []string) bool {
  137. sort.Strings(peers)
  138. if len(peers) <= 0 {
  139. return true
  140. }
  141. return self == peers[0]
  142. }