raft.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. // to check if msg receiver is removed from cluster
  90. isIDRemoved func(id uint64) bool
  91. raft.Node
  92. // a chan to send/receive snapshot
  93. msgSnapC chan raftpb.Message
  94. // a chan to send out apply
  95. applyc chan apply
  96. // a chan to send out readState
  97. readStateC chan raft.ReadState
  98. // utility
  99. ticker <-chan time.Time
  100. // contention detectors for raft heartbeat message
  101. td *contention.TimeoutDetector
  102. heartbeat time.Duration // for logging
  103. raftStorage *raft.MemoryStorage
  104. storage Storage
  105. // transport specifies the transport to send and receive msgs to members.
  106. // Sending messages MUST NOT block. It is okay to drop messages, since
  107. // clients should timeout and reissue their messages.
  108. // If transport is nil, server will panic.
  109. transport rafthttp.Transporter
  110. stopped chan struct{}
  111. done chan struct{}
  112. }
  113. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  114. // to modify the fields after it has been started.
  115. func (r *raftNode) start(rh *raftReadyHandler) {
  116. r.applyc = make(chan apply)
  117. r.stopped = make(chan struct{})
  118. r.done = make(chan struct{})
  119. internalTimeout := time.Second
  120. go func() {
  121. defer r.onStop()
  122. islead := false
  123. for {
  124. select {
  125. case <-r.ticker:
  126. r.Tick()
  127. case rd := <-r.Ready():
  128. if rd.SoftState != nil {
  129. if lead := atomic.LoadUint64(&r.lead); rd.SoftState.Lead != raft.None && lead != rd.SoftState.Lead {
  130. r.mu.Lock()
  131. r.lt = time.Now()
  132. r.mu.Unlock()
  133. leaderChanges.Inc()
  134. }
  135. if rd.SoftState.Lead == raft.None {
  136. hasLeader.Set(0)
  137. } else {
  138. hasLeader.Set(1)
  139. }
  140. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  141. islead = rd.RaftState == raft.StateLeader
  142. rh.leadershipUpdate()
  143. }
  144. if len(rd.ReadStates) != 0 {
  145. select {
  146. case r.readStateC <- rd.ReadStates[len(rd.ReadStates)-1]:
  147. case <-time.After(internalTimeout):
  148. plog.Warningf("timed out sending read state")
  149. case <-r.stopped:
  150. return
  151. }
  152. }
  153. raftDone := make(chan struct{}, 1)
  154. ap := apply{
  155. entries: rd.CommittedEntries,
  156. snapshot: rd.Snapshot,
  157. raftDone: raftDone,
  158. }
  159. select {
  160. case r.applyc <- ap:
  161. case <-r.stopped:
  162. return
  163. }
  164. // the leader can write to its disk in parallel with replicating to the followers and them
  165. // writing to their disks.
  166. // For more details, check raft thesis 10.2.1
  167. if islead {
  168. // gofail: var raftBeforeLeaderSend struct{}
  169. r.sendMessages(rd.Messages)
  170. }
  171. // gofail: var raftBeforeSave struct{}
  172. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  173. plog.Fatalf("raft save state and entries error: %v", err)
  174. }
  175. if !raft.IsEmptyHardState(rd.HardState) {
  176. proposalsCommitted.Set(float64(rd.HardState.Commit))
  177. }
  178. // gofail: var raftAfterSave struct{}
  179. if !raft.IsEmptySnap(rd.Snapshot) {
  180. // gofail: var raftBeforeSaveSnap struct{}
  181. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  182. plog.Fatalf("raft save snapshot error: %v", err)
  183. }
  184. // gofail: var raftAfterSaveSnap struct{}
  185. r.raftStorage.ApplySnapshot(rd.Snapshot)
  186. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  187. // gofail: var raftAfterApplySnap struct{}
  188. }
  189. r.raftStorage.Append(rd.Entries)
  190. if !islead {
  191. // gofail: var raftBeforeFollowerSend struct{}
  192. r.sendMessages(rd.Messages)
  193. }
  194. raftDone <- struct{}{}
  195. r.Advance()
  196. case <-r.stopped:
  197. return
  198. }
  199. }
  200. }()
  201. }
  202. func (r *raftNode) sendMessages(ms []raftpb.Message) {
  203. sentAppResp := false
  204. for i := len(ms) - 1; i >= 0; i-- {
  205. if r.isIDRemoved(ms[i].To) {
  206. ms[i].To = 0
  207. }
  208. if ms[i].Type == raftpb.MsgAppResp {
  209. if sentAppResp {
  210. ms[i].To = 0
  211. } else {
  212. sentAppResp = true
  213. }
  214. }
  215. if ms[i].Type == raftpb.MsgSnap {
  216. // There are two separate data store: the store for v2, and the KV for v3.
  217. // The msgSnap only contains the most recent snapshot of store without KV.
  218. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  219. // current store snapshot and KV snapshot.
  220. select {
  221. case r.msgSnapC <- ms[i]:
  222. default:
  223. // drop msgSnap if the inflight chan if full.
  224. }
  225. ms[i].To = 0
  226. }
  227. if ms[i].Type == raftpb.MsgHeartbeat {
  228. ok, exceed := r.td.Observe(ms[i].To)
  229. if !ok {
  230. // TODO: limit request rate.
  231. plog.Warningf("failed to send out heartbeat on time (exceeded the %v timeout for %v)", r.heartbeat, exceed)
  232. plog.Warningf("server is likely overloaded")
  233. }
  234. }
  235. }
  236. r.transport.Send(ms)
  237. }
  238. func (r *raftNode) apply() chan apply {
  239. return r.applyc
  240. }
  241. func (r *raftNode) leadElectedTime() time.Time {
  242. r.mu.Lock()
  243. defer r.mu.Unlock()
  244. return r.lt
  245. }
  246. func (r *raftNode) stop() {
  247. r.stopped <- struct{}{}
  248. <-r.done
  249. }
  250. func (r *raftNode) onStop() {
  251. r.Stop()
  252. r.transport.Stop()
  253. if err := r.storage.Close(); err != nil {
  254. plog.Panicf("raft close storage error: %v", err)
  255. }
  256. close(r.done)
  257. }
  258. // for testing
  259. func (r *raftNode) pauseSending() {
  260. p := r.transport.(rafthttp.Pausable)
  261. p.Pause()
  262. }
  263. func (r *raftNode) resumeSending() {
  264. p := r.transport.(rafthttp.Pausable)
  265. p.Resume()
  266. }
  267. // advanceTicksForElection advances ticks to the node for fast election.
  268. // This reduces the time to wait for first leader election if bootstrapping the whole
  269. // cluster, while leaving at least 1 heartbeat for possible existing leader
  270. // to contact it.
  271. func advanceTicksForElection(n raft.Node, electionTicks int) {
  272. for i := 0; i < electionTicks-1; i++ {
  273. n.Tick()
  274. }
  275. }
  276. func startNode(cfg *ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  277. var err error
  278. member := cl.MemberByName(cfg.Name)
  279. metadata := pbutil.MustMarshal(
  280. &pb.Metadata{
  281. NodeID: uint64(member.ID),
  282. ClusterID: uint64(cl.ID()),
  283. },
  284. )
  285. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  286. plog.Fatalf("create wal error: %v", err)
  287. }
  288. peers := make([]raft.Peer, len(ids))
  289. for i, id := range ids {
  290. ctx, err := json.Marshal((*cl).Member(id))
  291. if err != nil {
  292. plog.Panicf("marshal member should never fail: %v", err)
  293. }
  294. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  295. }
  296. id = member.ID
  297. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  298. s = raft.NewMemoryStorage()
  299. c := &raft.Config{
  300. ID: uint64(id),
  301. ElectionTick: cfg.ElectionTicks,
  302. HeartbeatTick: 1,
  303. Storage: s,
  304. MaxSizePerMsg: maxSizePerMsg,
  305. MaxInflightMsgs: maxInflightMsgs,
  306. CheckQuorum: true,
  307. }
  308. n = raft.StartNode(c, peers)
  309. raftStatusMu.Lock()
  310. raftStatus = n.Status
  311. raftStatusMu.Unlock()
  312. advanceTicksForElection(n, c.ElectionTick)
  313. return
  314. }
  315. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  316. var walsnap walpb.Snapshot
  317. if snapshot != nil {
  318. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  319. }
  320. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  321. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  322. cl := membership.NewCluster("")
  323. cl.SetID(cid)
  324. s := raft.NewMemoryStorage()
  325. if snapshot != nil {
  326. s.ApplySnapshot(*snapshot)
  327. }
  328. s.SetHardState(st)
  329. s.Append(ents)
  330. c := &raft.Config{
  331. ID: uint64(id),
  332. ElectionTick: cfg.ElectionTicks,
  333. HeartbeatTick: 1,
  334. Storage: s,
  335. MaxSizePerMsg: maxSizePerMsg,
  336. MaxInflightMsgs: maxInflightMsgs,
  337. CheckQuorum: true,
  338. }
  339. n := raft.RestartNode(c)
  340. raftStatusMu.Lock()
  341. raftStatus = n.Status
  342. raftStatusMu.Unlock()
  343. advanceTicksForElection(n, c.ElectionTick)
  344. return id, cl, n, s, w
  345. }
  346. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  347. var walsnap walpb.Snapshot
  348. if snapshot != nil {
  349. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  350. }
  351. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  352. // discard the previously uncommitted entries
  353. for i, ent := range ents {
  354. if ent.Index > st.Commit {
  355. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  356. ents = ents[:i]
  357. break
  358. }
  359. }
  360. // force append the configuration change entries
  361. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  362. ents = append(ents, toAppEnts...)
  363. // force commit newly appended entries
  364. err := w.Save(raftpb.HardState{}, toAppEnts)
  365. if err != nil {
  366. plog.Fatalf("%v", err)
  367. }
  368. if len(ents) != 0 {
  369. st.Commit = ents[len(ents)-1].Index
  370. }
  371. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  372. cl := membership.NewCluster("")
  373. cl.SetID(cid)
  374. s := raft.NewMemoryStorage()
  375. if snapshot != nil {
  376. s.ApplySnapshot(*snapshot)
  377. }
  378. s.SetHardState(st)
  379. s.Append(ents)
  380. c := &raft.Config{
  381. ID: uint64(id),
  382. ElectionTick: cfg.ElectionTicks,
  383. HeartbeatTick: 1,
  384. Storage: s,
  385. MaxSizePerMsg: maxSizePerMsg,
  386. MaxInflightMsgs: maxInflightMsgs,
  387. }
  388. n := raft.RestartNode(c)
  389. raftStatus = n.Status
  390. return id, cl, n, s, w
  391. }
  392. // getIDs returns an ordered set of IDs included in the given snapshot and
  393. // the entries. The given snapshot/entries can contain two kinds of
  394. // ID-related entry:
  395. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  396. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  397. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  398. ids := make(map[uint64]bool)
  399. if snap != nil {
  400. for _, id := range snap.Metadata.ConfState.Nodes {
  401. ids[id] = true
  402. }
  403. }
  404. for _, e := range ents {
  405. if e.Type != raftpb.EntryConfChange {
  406. continue
  407. }
  408. var cc raftpb.ConfChange
  409. pbutil.MustUnmarshal(&cc, e.Data)
  410. switch cc.Type {
  411. case raftpb.ConfChangeAddNode:
  412. ids[cc.NodeID] = true
  413. case raftpb.ConfChangeRemoveNode:
  414. delete(ids, cc.NodeID)
  415. case raftpb.ConfChangeUpdateNode:
  416. // do nothing
  417. default:
  418. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  419. }
  420. }
  421. sids := make(types.Uint64Slice, 0, len(ids))
  422. for id := range ids {
  423. sids = append(sids, id)
  424. }
  425. sort.Sort(sids)
  426. return []uint64(sids)
  427. }
  428. // createConfigChangeEnts creates a series of Raft entries (i.e.
  429. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  430. // `self` is _not_ removed, even if present in the set.
  431. // If `self` is not inside the given ids, it creates a Raft entry to add a
  432. // default member with the given `self`.
  433. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  434. ents := make([]raftpb.Entry, 0)
  435. next := index + 1
  436. found := false
  437. for _, id := range ids {
  438. if id == self {
  439. found = true
  440. continue
  441. }
  442. cc := &raftpb.ConfChange{
  443. Type: raftpb.ConfChangeRemoveNode,
  444. NodeID: id,
  445. }
  446. e := raftpb.Entry{
  447. Type: raftpb.EntryConfChange,
  448. Data: pbutil.MustMarshal(cc),
  449. Term: term,
  450. Index: next,
  451. }
  452. ents = append(ents, e)
  453. next++
  454. }
  455. if !found {
  456. m := membership.Member{
  457. ID: types.ID(self),
  458. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  459. }
  460. ctx, err := json.Marshal(m)
  461. if err != nil {
  462. plog.Panicf("marshal member should never fail: %v", err)
  463. }
  464. cc := &raftpb.ConfChange{
  465. Type: raftpb.ConfChangeAddNode,
  466. NodeID: self,
  467. Context: ctx,
  468. }
  469. e := raftpb.Entry{
  470. Type: raftpb.EntryConfChange,
  471. Data: pbutil.MustMarshal(cc),
  472. Term: term,
  473. Index: next,
  474. }
  475. ents = append(ents, e)
  476. }
  477. return ents
  478. }