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.

180 lines
4.1 KiB

11 years ago
11 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/goraft/raft"
  9. "github.com/gorilla/mux"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. )
  16. type RaftServer struct {
  17. peers []string // initial peers to join with
  18. raftServer raft.Server
  19. dataDir string
  20. httpAddr string
  21. version string
  22. router *mux.Router
  23. }
  24. func NewRaftServer(r *mux.Router, version string, peers []string, httpAddr string, dataDir string) *RaftServer {
  25. s := &RaftServer{
  26. version: version,
  27. peers: peers,
  28. httpAddr: httpAddr,
  29. dataDir: dataDir,
  30. router: r,
  31. }
  32. if glog.V(4) {
  33. raft.SetLogLevel(2)
  34. }
  35. var err error
  36. transporter := raft.NewHTTPTransporter("/cluster")
  37. s.raftServer, err = raft.NewServer(s.httpAddr, s.dataDir, transporter, nil, nil, "")
  38. if err != nil {
  39. glog.V(0).Infoln(err)
  40. return nil
  41. }
  42. transporter.Install(s.raftServer, s)
  43. s.raftServer.SetHeartbeatInterval(1 * time.Second)
  44. s.raftServer.SetElectionTimeout(1500 * time.Millisecond)
  45. s.raftServer.Start()
  46. s.router.HandleFunc("/cluster/join", s.joinHandler).Methods("POST")
  47. s.router.HandleFunc("/cluster/status", s.statusHandler).Methods("GET")
  48. // Join to leader if specified.
  49. if len(s.peers) > 0 {
  50. glog.V(0).Infoln("Joining cluster:", strings.Join(s.peers, ","))
  51. if !s.raftServer.IsLogEmpty() {
  52. glog.V(0).Infoln("Cannot join with an existing log")
  53. }
  54. if err := s.Join(s.peers); err != nil {
  55. return nil
  56. }
  57. glog.V(0).Infoln("Joined cluster")
  58. // Initialize the server by joining itself.
  59. } else if s.raftServer.IsLogEmpty() {
  60. glog.V(0).Infoln("Initializing new cluster")
  61. _, err := s.raftServer.Do(&raft.DefaultJoinCommand{
  62. Name: s.raftServer.Name(),
  63. ConnectionString: "http://" + s.httpAddr,
  64. })
  65. if err != nil {
  66. glog.V(0).Infoln(err)
  67. return nil
  68. }
  69. } else {
  70. glog.V(0).Infoln("Recovered from log")
  71. }
  72. return s
  73. }
  74. func (s *RaftServer) IsLeader() bool {
  75. return s.Leader() == s.raftServer.Name()
  76. }
  77. func (s *RaftServer) Leader() string {
  78. l := s.raftServer.Leader()
  79. if l == "" {
  80. // We are a single node cluster, we are the leader
  81. return s.raftServer.Name()
  82. }
  83. return l
  84. }
  85. func (s *RaftServer) Peers() (members []string) {
  86. peers := s.raftServer.Peers()
  87. for _, p := range peers {
  88. members = append(members, strings.TrimPrefix(p.ConnectionString, "http://"))
  89. }
  90. return
  91. }
  92. // Join joins an existing cluster.
  93. func (s *RaftServer) Join(peers []string) error {
  94. command := &raft.DefaultJoinCommand{
  95. Name: s.raftServer.Name(),
  96. ConnectionString: "http://" + s.httpAddr,
  97. }
  98. var b bytes.Buffer
  99. json.NewEncoder(&b).Encode(command)
  100. for _, m := range peers {
  101. target := fmt.Sprintf("http://%s/cluster/join", strings.TrimSpace(m))
  102. glog.V(0).Infoln("Attempting to connect to:", target)
  103. err := postFollowingOneRedirect(target, "application/json", &b)
  104. if err != nil {
  105. glog.V(0).Infoln("Post returned error: ", err)
  106. if _, ok := err.(*url.Error); ok {
  107. // If we receive a network error try the next member
  108. continue
  109. }
  110. return err
  111. }
  112. return nil
  113. }
  114. return errors.New("Could not connect to any cluster peers")
  115. }
  116. // a workaround because http POST following redirection misses request body
  117. func postFollowingOneRedirect(target string, contentType string, b *bytes.Buffer) error {
  118. backupReader := bytes.NewReader(b.Bytes())
  119. resp, err := http.Post(target, contentType, b)
  120. if err != nil {
  121. return err
  122. }
  123. defer resp.Body.Close()
  124. reply, _ := ioutil.ReadAll(resp.Body)
  125. statusCode := resp.StatusCode
  126. if statusCode == http.StatusMovedPermanently {
  127. var urlStr string
  128. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  129. return errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  130. }
  131. glog.V(0).Infoln("Post redirected to ", urlStr)
  132. resp2, err2 := http.Post(urlStr, contentType, backupReader)
  133. if err2 != nil {
  134. return err2
  135. }
  136. defer resp2.Body.Close()
  137. reply, _ = ioutil.ReadAll(resp2.Body)
  138. statusCode = resp2.StatusCode
  139. }
  140. glog.V(0).Infoln("Post returned status: ", statusCode, string(reply))
  141. if statusCode != http.StatusOK {
  142. return errors.New(string(reply))
  143. }
  144. return nil
  145. }