raft.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. "os"
  19. "sort"
  20. "sync/atomic"
  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. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  31. )
  32. const (
  33. // Number of entries for slow follower to catch-up after compacting
  34. // the raft storage entries.
  35. // We expect the follower has a millisecond level latency with the leader.
  36. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  37. // follower to catch up.
  38. numberOfCatchUpEntries = 5000
  39. // The max throughput of etcd will not exceed 100MB/s (100K * 1KB value).
  40. // Assuming the RTT is around 10ms, 1MB max size is large enough.
  41. maxSizePerMsg = 1 * 1024 * 1024
  42. // Never overflow the rafthttp buffer, which is 4096.
  43. // TODO: a better const?
  44. maxInflightMsgs = 4096 / 8
  45. )
  46. var (
  47. // indirection for expvar func interface
  48. // expvar panics when publishing duplicate name
  49. // expvar does not support remove a registered name
  50. // so only register a func that calls raftStatus
  51. // and change raftStatus as we need.
  52. raftStatus func() raft.Status
  53. )
  54. func init() {
  55. raft.SetLogger(capnslog.NewPackageLogger("github.com/coreos/etcd", "raft"))
  56. expvar.Publish("raft.status", expvar.Func(func() interface{} { return raftStatus() }))
  57. }
  58. type RaftTimer interface {
  59. Index() uint64
  60. Term() uint64
  61. }
  62. // apply contains entries, snapshot be applied.
  63. // After applied all the items, the application needs
  64. // to send notification to done chan.
  65. type apply struct {
  66. entries []raftpb.Entry
  67. snapshot raftpb.Snapshot
  68. done chan struct{}
  69. }
  70. type raftNode struct {
  71. // Cache of the latest raft index and raft term the server has seen.
  72. // These three unit64 fields must be the first elements to keep 64-bit
  73. // alignment for atomic access to the fields.
  74. index uint64
  75. term uint64
  76. lead uint64
  77. raft.Node
  78. // a chan to send out apply
  79. applyc chan apply
  80. // TODO: remove the etcdserver related logic from raftNode
  81. // TODO: add a state machine interface to apply the commit entries
  82. // and do snapshot/recover
  83. s *EtcdServer
  84. // utility
  85. ticker <-chan time.Time
  86. raftStorage *raft.MemoryStorage
  87. storage Storage
  88. // transport specifies the transport to send and receive msgs to members.
  89. // Sending messages MUST NOT block. It is okay to drop messages, since
  90. // clients should timeout and reissue their messages.
  91. // If transport is nil, server will panic.
  92. transport rafthttp.Transporter
  93. stopped chan struct{}
  94. done chan struct{}
  95. }
  96. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  97. // to modify the fields after it has been started.
  98. // TODO: Ideally raftNode should get rid of the passed in server structure.
  99. func (r *raftNode) start(s *EtcdServer) {
  100. r.s = s
  101. r.applyc = make(chan apply)
  102. r.stopped = make(chan struct{})
  103. r.done = make(chan struct{})
  104. go func() {
  105. var syncC <-chan time.Time
  106. defer r.onStop()
  107. for {
  108. select {
  109. case <-r.ticker:
  110. r.Tick()
  111. case rd := <-r.Ready():
  112. if rd.SoftState != nil {
  113. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  114. if rd.RaftState == raft.StateLeader {
  115. syncC = r.s.SyncTicker
  116. // TODO: remove the nil checking
  117. // current test utility does not provide the stats
  118. if r.s.stats != nil {
  119. r.s.stats.BecomeLeader()
  120. }
  121. } else {
  122. syncC = nil
  123. }
  124. }
  125. apply := apply{
  126. entries: rd.CommittedEntries,
  127. snapshot: rd.Snapshot,
  128. done: make(chan struct{}),
  129. }
  130. select {
  131. case r.applyc <- apply:
  132. case <-r.stopped:
  133. return
  134. }
  135. if !raft.IsEmptySnap(rd.Snapshot) {
  136. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  137. plog.Fatalf("raft save snapshot error: %v", err)
  138. }
  139. r.raftStorage.ApplySnapshot(rd.Snapshot)
  140. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  141. }
  142. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  143. plog.Fatalf("raft save state and entries error: %v", err)
  144. }
  145. r.raftStorage.Append(rd.Entries)
  146. r.s.send(rd.Messages)
  147. select {
  148. case <-apply.done:
  149. case <-r.stopped:
  150. return
  151. }
  152. r.Advance()
  153. case <-syncC:
  154. r.s.sync(r.s.cfg.CommitTimeout())
  155. case <-r.stopped:
  156. return
  157. }
  158. }
  159. }()
  160. }
  161. func (r *raftNode) apply() chan apply {
  162. return r.applyc
  163. }
  164. func (r *raftNode) stop() {
  165. r.stopped <- struct{}{}
  166. <-r.done
  167. }
  168. func (r *raftNode) onStop() {
  169. r.Stop()
  170. r.transport.Stop()
  171. if err := r.storage.Close(); err != nil {
  172. plog.Panicf("raft close storage error: %v", err)
  173. }
  174. close(r.done)
  175. }
  176. // for testing
  177. func (r *raftNode) pauseSending() {
  178. p := r.transport.(rafthttp.Pausable)
  179. p.Pause()
  180. }
  181. func (r *raftNode) resumeSending() {
  182. p := r.transport.(rafthttp.Pausable)
  183. p.Resume()
  184. }
  185. // advanceTicksForElection advances ticks to the node for fast election.
  186. // This reduces the time to wait for first leader election if bootstrapping the whole
  187. // cluster, while leaving at least 1 heartbeat for possible existing leader
  188. // to contact it.
  189. func advanceTicksForElection(n raft.Node, electionTicks int) {
  190. for i := 0; i < electionTicks-1; i++ {
  191. n.Tick()
  192. }
  193. }
  194. func startNode(cfg *ServerConfig, cl *cluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  195. var err error
  196. member := cl.MemberByName(cfg.Name)
  197. metadata := pbutil.MustMarshal(
  198. &pb.Metadata{
  199. NodeID: uint64(member.ID),
  200. ClusterID: uint64(cl.ID()),
  201. },
  202. )
  203. if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  204. plog.Fatalf("create snapshot directory error: %v", err)
  205. }
  206. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  207. plog.Fatalf("create wal error: %v", err)
  208. }
  209. peers := make([]raft.Peer, len(ids))
  210. for i, id := range ids {
  211. ctx, err := json.Marshal((*cl).Member(id))
  212. if err != nil {
  213. plog.Panicf("marshal member should never fail: %v", err)
  214. }
  215. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  216. }
  217. id = member.ID
  218. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  219. s = raft.NewMemoryStorage()
  220. c := &raft.Config{
  221. ID: uint64(id),
  222. ElectionTick: cfg.ElectionTicks,
  223. HeartbeatTick: 1,
  224. Storage: s,
  225. MaxSizePerMsg: maxSizePerMsg,
  226. MaxInflightMsgs: maxInflightMsgs,
  227. }
  228. n = raft.StartNode(c, peers)
  229. raftStatus = n.Status
  230. advanceTicksForElection(n, c.ElectionTick)
  231. return
  232. }
  233. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *cluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  234. var walsnap walpb.Snapshot
  235. if snapshot != nil {
  236. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  237. }
  238. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  239. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  240. cl := newCluster("")
  241. cl.SetID(cid)
  242. s := raft.NewMemoryStorage()
  243. if snapshot != nil {
  244. s.ApplySnapshot(*snapshot)
  245. }
  246. s.SetHardState(st)
  247. s.Append(ents)
  248. c := &raft.Config{
  249. ID: uint64(id),
  250. ElectionTick: cfg.ElectionTicks,
  251. HeartbeatTick: 1,
  252. Storage: s,
  253. MaxSizePerMsg: maxSizePerMsg,
  254. MaxInflightMsgs: maxInflightMsgs,
  255. }
  256. n := raft.RestartNode(c)
  257. raftStatus = n.Status
  258. advanceTicksForElection(n, c.ElectionTick)
  259. return id, cl, n, s, w
  260. }
  261. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *cluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  262. var walsnap walpb.Snapshot
  263. if snapshot != nil {
  264. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  265. }
  266. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  267. // discard the previously uncommitted entries
  268. for i, ent := range ents {
  269. if ent.Index > st.Commit {
  270. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  271. ents = ents[:i]
  272. break
  273. }
  274. }
  275. // force append the configuration change entries
  276. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  277. ents = append(ents, toAppEnts...)
  278. // force commit newly appended entries
  279. err := w.Save(raftpb.HardState{}, toAppEnts)
  280. if err != nil {
  281. plog.Fatalf("%v", err)
  282. }
  283. if len(ents) != 0 {
  284. st.Commit = ents[len(ents)-1].Index
  285. }
  286. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  287. cl := newCluster("")
  288. cl.SetID(cid)
  289. s := raft.NewMemoryStorage()
  290. if snapshot != nil {
  291. s.ApplySnapshot(*snapshot)
  292. }
  293. s.SetHardState(st)
  294. s.Append(ents)
  295. c := &raft.Config{
  296. ID: uint64(id),
  297. ElectionTick: cfg.ElectionTicks,
  298. HeartbeatTick: 1,
  299. Storage: s,
  300. MaxSizePerMsg: maxSizePerMsg,
  301. MaxInflightMsgs: maxInflightMsgs,
  302. }
  303. n := raft.RestartNode(c)
  304. raftStatus = n.Status
  305. return id, cl, n, s, w
  306. }
  307. // getIDs returns an ordered set of IDs included in the given snapshot and
  308. // the entries. The given snapshot/entries can contain two kinds of
  309. // ID-related entry:
  310. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  311. // - ConfChangeAddRemove, in which case the contained ID will be removed from the set.
  312. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  313. ids := make(map[uint64]bool)
  314. if snap != nil {
  315. for _, id := range snap.Metadata.ConfState.Nodes {
  316. ids[id] = true
  317. }
  318. }
  319. for _, e := range ents {
  320. if e.Type != raftpb.EntryConfChange {
  321. continue
  322. }
  323. var cc raftpb.ConfChange
  324. pbutil.MustUnmarshal(&cc, e.Data)
  325. switch cc.Type {
  326. case raftpb.ConfChangeAddNode:
  327. ids[cc.NodeID] = true
  328. case raftpb.ConfChangeRemoveNode:
  329. delete(ids, cc.NodeID)
  330. default:
  331. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  332. }
  333. }
  334. sids := make(types.Uint64Slice, 0)
  335. for id := range ids {
  336. sids = append(sids, id)
  337. }
  338. sort.Sort(sids)
  339. return []uint64(sids)
  340. }
  341. // createConfigChangeEnts creates a series of Raft entries (i.e.
  342. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  343. // `self` is _not_ removed, even if present in the set.
  344. // If `self` is not inside the given ids, it creates a Raft entry to add a
  345. // default member with the given `self`.
  346. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  347. ents := make([]raftpb.Entry, 0)
  348. next := index + 1
  349. found := false
  350. for _, id := range ids {
  351. if id == self {
  352. found = true
  353. continue
  354. }
  355. cc := &raftpb.ConfChange{
  356. Type: raftpb.ConfChangeRemoveNode,
  357. NodeID: id,
  358. }
  359. e := raftpb.Entry{
  360. Type: raftpb.EntryConfChange,
  361. Data: pbutil.MustMarshal(cc),
  362. Term: term,
  363. Index: next,
  364. }
  365. ents = append(ents, e)
  366. next++
  367. }
  368. if !found {
  369. m := Member{
  370. ID: types.ID(self),
  371. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  372. }
  373. ctx, err := json.Marshal(m)
  374. if err != nil {
  375. plog.Panicf("marshal member should never fail: %v", err)
  376. }
  377. cc := &raftpb.ConfChange{
  378. Type: raftpb.ConfChangeAddNode,
  379. NodeID: self,
  380. Context: ctx,
  381. }
  382. e := raftpb.Entry{
  383. Type: raftpb.EntryConfChange,
  384. Data: pbutil.MustMarshal(cc),
  385. Term: term,
  386. Index: next,
  387. }
  388. ents = append(ents, e)
  389. }
  390. return ents
  391. }