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.

184 lines
4.2 KiB

11 years ago
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) Name() string {
  75. return s.raftServer.Name()
  76. }
  77. func (s *RaftServer) IsLeader() bool {
  78. return s.Leader() == s.raftServer.Name()
  79. }
  80. func (s *RaftServer) Leader() string {
  81. l := s.raftServer.Leader()
  82. if l == "" {
  83. // We are a single node cluster, we are the leader
  84. return s.raftServer.Name()
  85. }
  86. return l
  87. }
  88. func (s *RaftServer) Peers() (members []string) {
  89. peers := s.raftServer.Peers()
  90. for _, p := range peers {
  91. members = append(members, strings.TrimPrefix(p.ConnectionString, "http://"))
  92. }
  93. return
  94. }
  95. // Join joins an existing cluster.
  96. func (s *RaftServer) Join(peers []string) error {
  97. command := &raft.DefaultJoinCommand{
  98. Name: s.raftServer.Name(),
  99. ConnectionString: "http://" + s.httpAddr,
  100. }
  101. var b bytes.Buffer
  102. json.NewEncoder(&b).Encode(command)
  103. for _, m := range peers {
  104. target := fmt.Sprintf("http://%s/cluster/join", strings.TrimSpace(m))
  105. glog.V(0).Infoln("Attempting to connect to:", target)
  106. err := postFollowingOneRedirect(target, "application/json", &b)
  107. if err != nil {
  108. glog.V(0).Infoln("Post returned error: ", err.Error())
  109. if _, ok := err.(*url.Error); ok {
  110. // If we receive a network error try the next member
  111. continue
  112. }
  113. return err
  114. }
  115. return nil
  116. }
  117. return errors.New("Could not connect to any cluster peers")
  118. }
  119. // a workaround because http POST following redirection misses request body
  120. func postFollowingOneRedirect(target string, contentType string, b *bytes.Buffer) error {
  121. backupReader := bytes.NewReader(b.Bytes())
  122. resp, err := http.Post(target, contentType, b)
  123. if err != nil {
  124. return err
  125. }
  126. defer resp.Body.Close()
  127. reply, _ := ioutil.ReadAll(resp.Body)
  128. statusCode := resp.StatusCode
  129. if statusCode == http.StatusMovedPermanently {
  130. var urlStr string
  131. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  132. return errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  133. }
  134. glog.V(0).Infoln("Post redirected to ", urlStr)
  135. resp2, err2 := http.Post(urlStr, contentType, backupReader)
  136. if err2 != nil {
  137. return err2
  138. }
  139. defer resp2.Body.Close()
  140. reply, _ = ioutil.ReadAll(resp2.Body)
  141. statusCode = resp2.StatusCode
  142. }
  143. glog.V(0).Infoln("Post returned status: ", statusCode, string(reply))
  144. if statusCode != http.StatusOK {
  145. return errors.New(string(reply))
  146. }
  147. return nil
  148. }