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.

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