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.

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