raft.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdserver
  15. import (
  16. "encoding/json"
  17. "expvar"
  18. "log"
  19. "os"
  20. "sort"
  21. "time"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/pkg/pbutil"
  24. "github.com/coreos/etcd/pkg/types"
  25. "github.com/coreos/etcd/raft"
  26. "github.com/coreos/etcd/raft/raftpb"
  27. "github.com/coreos/etcd/rafthttp"
  28. "github.com/coreos/etcd/wal"
  29. "github.com/coreos/etcd/wal/walpb"
  30. )
  31. const (
  32. // Number of entries for slow follower to catch-up after compacting
  33. // the raft storage entries.
  34. // We expect the follower has a millisecond level latency with the leader.
  35. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  36. // follower to catch up.
  37. numberOfCatchUpEntries = 5000
  38. )
  39. var (
  40. // indirection for expvar func interface
  41. // expvar panics when publishing duplicate name
  42. // expvar does not support remove a registered name
  43. // so only register a func that calls raftStatus
  44. // and change raftStatus as we need.
  45. raftStatus func() raft.Status
  46. )
  47. func init() {
  48. expvar.Publish("raft.status", expvar.Func(func() interface{} { return raftStatus() }))
  49. }
  50. type RaftTimer interface {
  51. Index() uint64
  52. Term() uint64
  53. }
  54. type raftNode struct {
  55. raft.Node
  56. // config
  57. snapCount uint64 // number of entries to trigger a snapshot
  58. // utility
  59. ticker <-chan time.Time
  60. raftStorage *raft.MemoryStorage
  61. storage Storage
  62. // transport specifies the transport to send and receive msgs to members.
  63. // Sending messages MUST NOT block. It is okay to drop messages, since
  64. // clients should timeout and reissue their messages.
  65. // If transport is nil, server will panic.
  66. transport rafthttp.Transporter
  67. // Cache of the latest raft index and raft term the server has seen
  68. index uint64
  69. term uint64
  70. lead uint64
  71. }
  72. // for testing
  73. func (r *raftNode) pauseSending() {
  74. p := r.transport.(rafthttp.Pausable)
  75. p.Pause()
  76. }
  77. func (r *raftNode) resumeSending() {
  78. p := r.transport.(rafthttp.Pausable)
  79. p.Resume()
  80. }
  81. func startNode(cfg *ServerConfig, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  82. var err error
  83. member := cfg.Cluster.MemberByName(cfg.Name)
  84. metadata := pbutil.MustMarshal(
  85. &pb.Metadata{
  86. NodeID: uint64(member.ID),
  87. ClusterID: uint64(cfg.Cluster.ID()),
  88. },
  89. )
  90. if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  91. log.Fatalf("etcdserver create snapshot directory error: %v", err)
  92. }
  93. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  94. log.Fatalf("etcdserver: create wal error: %v", err)
  95. }
  96. peers := make([]raft.Peer, len(ids))
  97. for i, id := range ids {
  98. ctx, err := json.Marshal((*cfg.Cluster).Member(id))
  99. if err != nil {
  100. log.Panicf("marshal member should never fail: %v", err)
  101. }
  102. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  103. }
  104. id = member.ID
  105. log.Printf("etcdserver: start member %s in cluster %s", id, cfg.Cluster.ID())
  106. s = raft.NewMemoryStorage()
  107. n = raft.StartNode(uint64(id), peers, cfg.ElectionTicks, 1, s)
  108. raftStatus = n.Status
  109. return
  110. }
  111. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  112. var walsnap walpb.Snapshot
  113. if snapshot != nil {
  114. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  115. }
  116. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  117. cfg.Cluster.SetID(cid)
  118. log.Printf("etcdserver: restart member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  119. s := raft.NewMemoryStorage()
  120. if snapshot != nil {
  121. s.ApplySnapshot(*snapshot)
  122. }
  123. s.SetHardState(st)
  124. s.Append(ents)
  125. n := raft.RestartNode(uint64(id), cfg.ElectionTicks, 1, s, 0)
  126. raftStatus = n.Status
  127. return id, n, s, w
  128. }
  129. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  130. var walsnap walpb.Snapshot
  131. if snapshot != nil {
  132. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  133. }
  134. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  135. cfg.Cluster.SetID(cid)
  136. // discard the previously uncommitted entries
  137. for i, ent := range ents {
  138. if ent.Index > st.Commit {
  139. log.Printf("etcdserver: discarding %d uncommitted WAL entries ", len(ents)-i)
  140. ents = ents[:i]
  141. break
  142. }
  143. }
  144. // force append the configuration change entries
  145. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  146. ents = append(ents, toAppEnts...)
  147. // force commit newly appended entries
  148. err := w.Save(raftpb.HardState{}, toAppEnts)
  149. if err != nil {
  150. log.Fatalf("etcdserver: %v", err)
  151. }
  152. if len(ents) != 0 {
  153. st.Commit = ents[len(ents)-1].Index
  154. }
  155. log.Printf("etcdserver: forcing restart of member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  156. s := raft.NewMemoryStorage()
  157. if snapshot != nil {
  158. s.ApplySnapshot(*snapshot)
  159. }
  160. s.SetHardState(st)
  161. s.Append(ents)
  162. n := raft.RestartNode(uint64(id), cfg.ElectionTicks, 1, s, 0)
  163. raftStatus = n.Status
  164. return id, n, s, w
  165. }
  166. // getIDs returns an ordered set of IDs included in the given snapshot and
  167. // the entries. The given snapshot/entries can contain two kinds of
  168. // ID-related entry:
  169. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  170. // - ConfChangeAddRemove, in which case the contained ID will be removed from the set.
  171. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  172. ids := make(map[uint64]bool)
  173. if snap != nil {
  174. for _, id := range snap.Metadata.ConfState.Nodes {
  175. ids[id] = true
  176. }
  177. }
  178. for _, e := range ents {
  179. if e.Type != raftpb.EntryConfChange {
  180. continue
  181. }
  182. var cc raftpb.ConfChange
  183. pbutil.MustUnmarshal(&cc, e.Data)
  184. switch cc.Type {
  185. case raftpb.ConfChangeAddNode:
  186. ids[cc.NodeID] = true
  187. case raftpb.ConfChangeRemoveNode:
  188. delete(ids, cc.NodeID)
  189. default:
  190. log.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  191. }
  192. }
  193. sids := make(types.Uint64Slice, 0)
  194. for id := range ids {
  195. sids = append(sids, id)
  196. }
  197. sort.Sort(sids)
  198. return []uint64(sids)
  199. }
  200. // createConfigChangeEnts creates a series of Raft entries (i.e.
  201. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  202. // `self` is _not_ removed, even if present in the set.
  203. // If `self` is not inside the given ids, it creates a Raft entry to add a
  204. // default member with the given `self`.
  205. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  206. ents := make([]raftpb.Entry, 0)
  207. next := index + 1
  208. found := false
  209. for _, id := range ids {
  210. if id == self {
  211. found = true
  212. continue
  213. }
  214. cc := &raftpb.ConfChange{
  215. Type: raftpb.ConfChangeRemoveNode,
  216. NodeID: id,
  217. }
  218. e := raftpb.Entry{
  219. Type: raftpb.EntryConfChange,
  220. Data: pbutil.MustMarshal(cc),
  221. Term: term,
  222. Index: next,
  223. }
  224. ents = append(ents, e)
  225. next++
  226. }
  227. if !found {
  228. m := Member{
  229. ID: types.ID(self),
  230. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  231. }
  232. ctx, err := json.Marshal(m)
  233. if err != nil {
  234. log.Panicf("marshal member should never fail: %v", err)
  235. }
  236. cc := &raftpb.ConfChange{
  237. Type: raftpb.ConfChangeAddNode,
  238. NodeID: self,
  239. Context: ctx,
  240. }
  241. e := raftpb.Entry{
  242. Type: raftpb.EntryConfChange,
  243. Data: pbutil.MustMarshal(cc),
  244. Term: term,
  245. Index: next,
  246. }
  247. ents = append(ents, e)
  248. }
  249. return ents
  250. }