raft_server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/binary"
  6. "encoding/json"
  7. "fmt"
  8. etcdErr "github.com/coreos/etcd/error"
  9. "github.com/coreos/go-raft"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "time"
  14. )
  15. type raftServer struct {
  16. *raft.Server
  17. version string
  18. joinIndex uint64
  19. name string
  20. url string
  21. listenHost string
  22. tlsConf *TLSConfig
  23. tlsInfo *TLSInfo
  24. }
  25. var r *raftServer
  26. func newRaftServer(name string, url string, listenHost string, tlsConf *TLSConfig, tlsInfo *TLSInfo) *raftServer {
  27. // Create transporter for raft
  28. raftTransporter := newTransporter(tlsConf.Scheme, tlsConf.Client)
  29. // Create raft server
  30. server, err := raft.NewServer(name, dirPath, raftTransporter, etcdStore, nil)
  31. check(err)
  32. return &raftServer{
  33. Server: server,
  34. version: raftVersion,
  35. name: name,
  36. url: url,
  37. listenHost: listenHost,
  38. tlsConf: tlsConf,
  39. tlsInfo: tlsInfo,
  40. }
  41. }
  42. // Start the raft server
  43. func (r *raftServer) ListenAndServe() {
  44. // Setup commands.
  45. registerCommands()
  46. // LoadSnapshot
  47. if snapshot {
  48. err := r.LoadSnapshot()
  49. if err == nil {
  50. debugf("%s finished load snapshot", r.name)
  51. } else {
  52. debug(err)
  53. }
  54. }
  55. r.SetElectionTimeout(ElectionTimeout)
  56. r.SetHeartbeatTimeout(HeartbeatTimeout)
  57. r.Start()
  58. if r.IsLogEmpty() {
  59. // start as a leader in a new cluster
  60. if len(cluster) == 0 {
  61. startAsLeader()
  62. } else {
  63. startAsFollower()
  64. }
  65. } else {
  66. // rejoin the previous cluster
  67. cluster = getMachines(nameToRaftURL)
  68. for i := 0; i < len(cluster); i++ {
  69. u, err := url.Parse(cluster[i])
  70. if err != nil {
  71. debug("rejoin cannot parse url: ", err)
  72. }
  73. cluster[i] = u.Host
  74. }
  75. ok := joinCluster(cluster)
  76. if !ok {
  77. warn("the whole cluster dies! restart the cluster")
  78. }
  79. debugf("%s restart as a follower", r.name)
  80. }
  81. // open the snapshot
  82. if snapshot {
  83. go monitorSnapshot()
  84. }
  85. // start to response to raft requests
  86. go r.startTransport(r.tlsConf.Scheme, r.tlsConf.Server)
  87. }
  88. func startAsLeader() {
  89. // leader need to join self as a peer
  90. for {
  91. _, err := r.Do(newJoinCommand())
  92. if err == nil {
  93. break
  94. }
  95. }
  96. debugf("%s start as a leader", r.name)
  97. }
  98. func startAsFollower() {
  99. // start as a follower in a existing cluster
  100. for i := 0; i < retryTimes; i++ {
  101. ok := joinCluster(cluster)
  102. if ok {
  103. return
  104. }
  105. warnf("cannot join to cluster via given machines, retry in %d seconds", RetryInterval)
  106. time.Sleep(time.Second * RetryInterval)
  107. }
  108. fatalf("Cannot join the cluster via given machines after %x retries", retryTimes)
  109. }
  110. // Start to listen and response raft command
  111. func (r *raftServer) startTransport(scheme string, tlsConf tls.Config) {
  112. infof("raft server [%s:%s]", r.name, r.listenHost)
  113. raftMux := http.NewServeMux()
  114. server := &http.Server{
  115. Handler: raftMux,
  116. TLSConfig: &tlsConf,
  117. Addr: r.listenHost,
  118. }
  119. // internal commands
  120. raftMux.HandleFunc("/name", NameHttpHandler)
  121. raftMux.HandleFunc("/version", RaftVersionHttpHandler)
  122. raftMux.Handle("/join", errorHandler(JoinHttpHandler))
  123. raftMux.HandleFunc("/remove/", RemoveHttpHandler)
  124. raftMux.HandleFunc("/vote", VoteHttpHandler)
  125. raftMux.HandleFunc("/log", GetLogHttpHandler)
  126. raftMux.HandleFunc("/log/append", AppendEntriesHttpHandler)
  127. raftMux.HandleFunc("/snapshot", SnapshotHttpHandler)
  128. raftMux.HandleFunc("/snapshotRecovery", SnapshotRecoveryHttpHandler)
  129. raftMux.HandleFunc("/etcdURL", EtcdURLHttpHandler)
  130. if scheme == "http" {
  131. fatal(server.ListenAndServe())
  132. } else {
  133. fatal(server.ListenAndServeTLS(r.tlsInfo.CertFile, r.tlsInfo.KeyFile))
  134. }
  135. }
  136. // getVersion fetches the raft version of a peer. This works for now but we
  137. // will need to do something more sophisticated later when we allow mixed
  138. // version clusters.
  139. func getVersion(t transporter, versionURL url.URL) (string, error) {
  140. resp, err := t.Get(versionURL.String())
  141. if err != nil {
  142. return "", err
  143. }
  144. defer resp.Body.Close()
  145. body, err := ioutil.ReadAll(resp.Body)
  146. return string(body), nil
  147. }
  148. func joinCluster(cluster []string) bool {
  149. for _, machine := range cluster {
  150. if len(machine) == 0 {
  151. continue
  152. }
  153. err := joinByMachine(r.Server, machine, r.tlsConf.Scheme)
  154. if err == nil {
  155. debugf("%s success join to the cluster via machine %s", r.name, machine)
  156. return true
  157. } else {
  158. if _, ok := err.(etcdErr.Error); ok {
  159. fatal(err)
  160. }
  161. debugf("cannot join to cluster via machine %s %s", machine, err)
  162. }
  163. }
  164. return false
  165. }
  166. // Send join requests to machine.
  167. func joinByMachine(s *raft.Server, machine string, scheme string) error {
  168. var b bytes.Buffer
  169. // t must be ok
  170. t, _ := r.Transporter().(transporter)
  171. // Our version must match the leaders version
  172. versionURL := url.URL{Host: machine, Scheme: scheme, Path: "/version"}
  173. version, err := getVersion(t, versionURL)
  174. if err != nil {
  175. return fmt.Errorf("Unable to join: %v", err)
  176. }
  177. // TODO: versioning of the internal protocol. See:
  178. // Documentation/internatl-protocol-versioning.md
  179. if version != r.version {
  180. return fmt.Errorf("Unable to join: internal version mismatch, entire cluster must be running identical versions of etcd")
  181. }
  182. json.NewEncoder(&b).Encode(newJoinCommand())
  183. joinURL := url.URL{Host: machine, Scheme: scheme, Path: "/join"}
  184. debugf("Send Join Request to %s", joinURL.String())
  185. resp, err := t.Post(joinURL.String(), &b)
  186. for {
  187. if err != nil {
  188. return fmt.Errorf("Unable to join: %v", err)
  189. }
  190. if resp != nil {
  191. defer resp.Body.Close()
  192. if resp.StatusCode == http.StatusOK {
  193. b, _ := ioutil.ReadAll(resp.Body)
  194. r.joinIndex, _ = binary.Uvarint(b)
  195. return nil
  196. }
  197. if resp.StatusCode == http.StatusTemporaryRedirect {
  198. address := resp.Header.Get("Location")
  199. debugf("Send Join Request to %s", address)
  200. json.NewEncoder(&b).Encode(newJoinCommand())
  201. resp, err = t.Post(address, &b)
  202. } else if resp.StatusCode == http.StatusBadRequest {
  203. debug("Reach max number machines in the cluster")
  204. decoder := json.NewDecoder(resp.Body)
  205. err := &etcdErr.Error{}
  206. decoder.Decode(err)
  207. return *err
  208. } else {
  209. return fmt.Errorf("Unable to join")
  210. }
  211. }
  212. }
  213. return fmt.Errorf("Unable to join: %v", err)
  214. }
  215. // Register commands to raft server
  216. func registerCommands() {
  217. raft.RegisterCommand(&JoinCommand{})
  218. raft.RegisterCommand(&RemoveCommand{})
  219. raft.RegisterCommand(&SetCommand{})
  220. raft.RegisterCommand(&GetCommand{})
  221. raft.RegisterCommand(&DeleteCommand{})
  222. raft.RegisterCommand(&WatchCommand{})
  223. raft.RegisterCommand(&TestAndSetCommand{})
  224. }