raft.go 14 KB

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