raft.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. "log"
  19. "sort"
  20. "sync"
  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/logutil"
  26. "github.com/coreos/etcd/pkg/pbutil"
  27. "github.com/coreos/etcd/pkg/types"
  28. "github.com/coreos/etcd/raft"
  29. "github.com/coreos/etcd/raft/raftpb"
  30. "github.com/coreos/etcd/rafthttp"
  31. "github.com/coreos/etcd/wal"
  32. "github.com/coreos/etcd/wal/walpb"
  33. "github.com/coreos/pkg/capnslog"
  34. "go.uber.org/zap"
  35. )
  36. const (
  37. // The max throughput of etcd will not exceed 100MB/s (100K * 1KB value).
  38. // Assuming the RTT is around 10ms, 1MB max size is large enough.
  39. maxSizePerMsg = 1 * 1024 * 1024
  40. // Never overflow the rafthttp buffer, which is 4096.
  41. // TODO: a better const?
  42. maxInflightMsgs = 4096 / 8
  43. )
  44. var (
  45. // protects raftStatus
  46. raftStatusMu sync.Mutex
  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{} {
  57. raftStatusMu.Lock()
  58. defer raftStatusMu.Unlock()
  59. return raftStatus()
  60. }))
  61. }
  62. // apply contains entries, snapshot to be applied. Once
  63. // an apply is consumed, the entries will be persisted to
  64. // to raft storage concurrently; the application must read
  65. // raftDone before assuming the raft messages are stable.
  66. type apply struct {
  67. entries []raftpb.Entry
  68. snapshot raftpb.Snapshot
  69. // notifyc synchronizes etcd server applies with the raft node
  70. notifyc chan struct{}
  71. }
  72. type raftNode struct {
  73. lg *zap.Logger
  74. tickMu *sync.Mutex
  75. raftNodeConfig
  76. // a chan to send/receive snapshot
  77. msgSnapC chan raftpb.Message
  78. // a chan to send out apply
  79. applyc chan apply
  80. // a chan to send out readState
  81. readStateC chan raft.ReadState
  82. // utility
  83. ticker *time.Ticker
  84. // contention detectors for raft heartbeat message
  85. td *contention.TimeoutDetector
  86. stopped chan struct{}
  87. done chan struct{}
  88. }
  89. type raftNodeConfig struct {
  90. lg *zap.Logger
  91. // to check if msg receiver is removed from cluster
  92. isIDRemoved func(id uint64) bool
  93. raft.Node
  94. raftStorage *raft.MemoryStorage
  95. storage Storage
  96. heartbeat time.Duration // for logging
  97. // transport specifies the transport to send and receive msgs to members.
  98. // Sending messages MUST NOT block. It is okay to drop messages, since
  99. // clients should timeout and reissue their messages.
  100. // If transport is nil, server will panic.
  101. transport rafthttp.Transporter
  102. }
  103. func newRaftNode(cfg raftNodeConfig) *raftNode {
  104. r := &raftNode{
  105. lg: cfg.lg,
  106. tickMu: new(sync.Mutex),
  107. raftNodeConfig: cfg,
  108. // set up contention detectors for raft heartbeat message.
  109. // expect to send a heartbeat within 2 heartbeat intervals.
  110. td: contention.NewTimeoutDetector(2 * cfg.heartbeat),
  111. readStateC: make(chan raft.ReadState, 1),
  112. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  113. applyc: make(chan apply),
  114. stopped: make(chan struct{}),
  115. done: make(chan struct{}),
  116. }
  117. if r.heartbeat == 0 {
  118. r.ticker = &time.Ticker{}
  119. } else {
  120. r.ticker = time.NewTicker(r.heartbeat)
  121. }
  122. return r
  123. }
  124. // raft.Node does not have locks in Raft package
  125. func (r *raftNode) tick() {
  126. r.tickMu.Lock()
  127. r.Tick()
  128. r.tickMu.Unlock()
  129. }
  130. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  131. // to modify the fields after it has been started.
  132. func (r *raftNode) start(rh *raftReadyHandler) {
  133. internalTimeout := time.Second
  134. go func() {
  135. defer r.onStop()
  136. islead := false
  137. for {
  138. select {
  139. case <-r.ticker.C:
  140. r.tick()
  141. case rd := <-r.Ready():
  142. if rd.SoftState != nil {
  143. newLeader := rd.SoftState.Lead != raft.None && rh.getLead() != rd.SoftState.Lead
  144. if newLeader {
  145. leaderChanges.Inc()
  146. }
  147. if rd.SoftState.Lead == raft.None {
  148. hasLeader.Set(0)
  149. } else {
  150. hasLeader.Set(1)
  151. }
  152. rh.updateLead(rd.SoftState.Lead)
  153. islead = rd.RaftState == raft.StateLeader
  154. if islead {
  155. isLeader.Set(1)
  156. } else {
  157. isLeader.Set(0)
  158. }
  159. rh.updateLeadership(newLeader)
  160. r.td.Reset()
  161. }
  162. if len(rd.ReadStates) != 0 {
  163. select {
  164. case r.readStateC <- rd.ReadStates[len(rd.ReadStates)-1]:
  165. case <-time.After(internalTimeout):
  166. if r.lg != nil {
  167. r.lg.Warn("timed out sending read state", zap.Duration("timeout", internalTimeout))
  168. } else {
  169. plog.Warningf("timed out sending read state")
  170. }
  171. case <-r.stopped:
  172. return
  173. }
  174. }
  175. notifyc := make(chan struct{}, 1)
  176. ap := apply{
  177. entries: rd.CommittedEntries,
  178. snapshot: rd.Snapshot,
  179. notifyc: notifyc,
  180. }
  181. updateCommittedIndex(&ap, rh)
  182. select {
  183. case r.applyc <- ap:
  184. case <-r.stopped:
  185. return
  186. }
  187. // the leader can write to its disk in parallel with replicating to the followers and them
  188. // writing to their disks.
  189. // For more details, check raft thesis 10.2.1
  190. if islead {
  191. // gofail: var raftBeforeLeaderSend struct{}
  192. r.transport.Send(r.processMessages(rd.Messages))
  193. }
  194. // gofail: var raftBeforeSave struct{}
  195. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  196. if r.lg != nil {
  197. r.lg.Fatal("failed to save Raft hard state and entries", zap.Error(err))
  198. } else {
  199. plog.Fatalf("raft save state and entries error: %v", err)
  200. }
  201. }
  202. if !raft.IsEmptyHardState(rd.HardState) {
  203. proposalsCommitted.Set(float64(rd.HardState.Commit))
  204. }
  205. // gofail: var raftAfterSave struct{}
  206. if !raft.IsEmptySnap(rd.Snapshot) {
  207. // gofail: var raftBeforeSaveSnap struct{}
  208. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  209. if r.lg != nil {
  210. r.lg.Fatal("failed to save Raft snapshot", zap.Error(err))
  211. } else {
  212. plog.Fatalf("raft save snapshot error: %v", err)
  213. }
  214. }
  215. // etcdserver now claim the snapshot has been persisted onto the disk
  216. notifyc <- struct{}{}
  217. // gofail: var raftAfterSaveSnap struct{}
  218. r.raftStorage.ApplySnapshot(rd.Snapshot)
  219. if r.lg != nil {
  220. r.lg.Info("applied incoming Raft snapshot", zap.Uint64("snapshot-index", rd.Snapshot.Metadata.Index))
  221. } else {
  222. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  223. }
  224. // gofail: var raftAfterApplySnap struct{}
  225. }
  226. r.raftStorage.Append(rd.Entries)
  227. if !islead {
  228. // finish processing incoming messages before we signal raftdone chan
  229. msgs := r.processMessages(rd.Messages)
  230. // now unblocks 'applyAll' that waits on Raft log disk writes before triggering snapshots
  231. notifyc <- struct{}{}
  232. // Candidate or follower needs to wait for all pending configuration
  233. // changes to be applied before sending messages.
  234. // Otherwise we might incorrectly count votes (e.g. votes from removed members).
  235. // Also slow machine's follower raft-layer could proceed to become the leader
  236. // on its own single-node cluster, before apply-layer applies the config change.
  237. // We simply wait for ALL pending entries to be applied for now.
  238. // We might improve this later on if it causes unnecessary long blocking issues.
  239. waitApply := false
  240. for _, ent := range rd.CommittedEntries {
  241. if ent.Type == raftpb.EntryConfChange {
  242. waitApply = true
  243. break
  244. }
  245. }
  246. if waitApply {
  247. // blocks until 'applyAll' calls 'applyWait.Trigger'
  248. // to be in sync with scheduled config-change job
  249. // (assume notifyc has cap of 1)
  250. select {
  251. case notifyc <- struct{}{}:
  252. case <-r.stopped:
  253. return
  254. }
  255. }
  256. // gofail: var raftBeforeFollowerSend struct{}
  257. r.transport.Send(msgs)
  258. } else {
  259. // leader already processed 'MsgSnap' and signaled
  260. notifyc <- struct{}{}
  261. }
  262. r.Advance()
  263. case <-r.stopped:
  264. return
  265. }
  266. }
  267. }()
  268. }
  269. func updateCommittedIndex(ap *apply, rh *raftReadyHandler) {
  270. var ci uint64
  271. if len(ap.entries) != 0 {
  272. ci = ap.entries[len(ap.entries)-1].Index
  273. }
  274. if ap.snapshot.Metadata.Index > ci {
  275. ci = ap.snapshot.Metadata.Index
  276. }
  277. if ci != 0 {
  278. rh.updateCommittedIndex(ci)
  279. }
  280. }
  281. func (r *raftNode) processMessages(ms []raftpb.Message) []raftpb.Message {
  282. sentAppResp := false
  283. for i := len(ms) - 1; i >= 0; i-- {
  284. if r.isIDRemoved(ms[i].To) {
  285. ms[i].To = 0
  286. }
  287. if ms[i].Type == raftpb.MsgAppResp {
  288. if sentAppResp {
  289. ms[i].To = 0
  290. } else {
  291. sentAppResp = true
  292. }
  293. }
  294. if ms[i].Type == raftpb.MsgSnap {
  295. // There are two separate data store: the store for v2, and the KV for v3.
  296. // The msgSnap only contains the most recent snapshot of store without KV.
  297. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  298. // current store snapshot and KV snapshot.
  299. select {
  300. case r.msgSnapC <- ms[i]:
  301. default:
  302. // drop msgSnap if the inflight chan if full.
  303. }
  304. ms[i].To = 0
  305. }
  306. if ms[i].Type == raftpb.MsgHeartbeat {
  307. ok, exceed := r.td.Observe(ms[i].To)
  308. if !ok {
  309. // TODO: limit request rate.
  310. if r.lg != nil {
  311. r.lg.Warn(
  312. "heartbeat took too long to send out; server is overloaded, likely from slow disk",
  313. zap.Duration("exceeded", exceed),
  314. zap.Duration("heartbeat-interval", r.heartbeat),
  315. )
  316. } else {
  317. plog.Warningf("failed to send out heartbeat on time (exceeded the %v timeout for %v)", r.heartbeat, exceed)
  318. plog.Warningf("server is likely overloaded")
  319. }
  320. }
  321. }
  322. }
  323. return ms
  324. }
  325. func (r *raftNode) apply() chan apply {
  326. return r.applyc
  327. }
  328. func (r *raftNode) stop() {
  329. r.stopped <- struct{}{}
  330. <-r.done
  331. }
  332. func (r *raftNode) onStop() {
  333. r.Stop()
  334. r.ticker.Stop()
  335. r.transport.Stop()
  336. if err := r.storage.Close(); err != nil {
  337. if r.lg != nil {
  338. r.lg.Panic("failed to close Raft storage", zap.Error(err))
  339. } else {
  340. plog.Panicf("raft close storage error: %v", err)
  341. }
  342. }
  343. close(r.done)
  344. }
  345. // for testing
  346. func (r *raftNode) pauseSending() {
  347. p := r.transport.(rafthttp.Pausable)
  348. p.Pause()
  349. }
  350. func (r *raftNode) resumeSending() {
  351. p := r.transport.(rafthttp.Pausable)
  352. p.Resume()
  353. }
  354. // advanceTicks advances ticks of Raft node.
  355. // This can be used for fast-forwarding election
  356. // ticks in multi data-center deployments, thus
  357. // speeding up election process.
  358. func (r *raftNode) advanceTicks(ticks int) {
  359. for i := 0; i < ticks; i++ {
  360. r.tick()
  361. }
  362. }
  363. func startNode(cfg ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  364. var err error
  365. member := cl.MemberByName(cfg.Name)
  366. metadata := pbutil.MustMarshal(
  367. &pb.Metadata{
  368. NodeID: uint64(member.ID),
  369. ClusterID: uint64(cl.ID()),
  370. },
  371. )
  372. if w, err = wal.Create(cfg.Logger, cfg.WALDir(), metadata); err != nil {
  373. if cfg.Logger != nil {
  374. cfg.Logger.Fatal("failed to create WAL", zap.Error(err))
  375. } else {
  376. plog.Fatalf("create wal error: %v", err)
  377. }
  378. }
  379. peers := make([]raft.Peer, len(ids))
  380. for i, id := range ids {
  381. var ctx []byte
  382. ctx, err = json.Marshal((*cl).Member(id))
  383. if err != nil {
  384. if cfg.Logger != nil {
  385. cfg.Logger.Panic("failed to marshal member", zap.Error(err))
  386. } else {
  387. plog.Panicf("marshal member should never fail: %v", err)
  388. }
  389. }
  390. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  391. }
  392. id = member.ID
  393. if cfg.Logger != nil {
  394. cfg.Logger.Info(
  395. "starting local member",
  396. zap.String("local-member-id", id.String()),
  397. zap.String("cluster-id", cl.ID().String()),
  398. )
  399. } else {
  400. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  401. }
  402. s = raft.NewMemoryStorage()
  403. c := &raft.Config{
  404. ID: uint64(id),
  405. ElectionTick: cfg.ElectionTicks,
  406. HeartbeatTick: 1,
  407. Storage: s,
  408. MaxSizePerMsg: maxSizePerMsg,
  409. MaxInflightMsgs: maxInflightMsgs,
  410. CheckQuorum: true,
  411. PreVote: cfg.PreVote,
  412. }
  413. if cfg.Logger != nil {
  414. // called after capnslog setting in "init" function
  415. if cfg.LoggerConfig != nil {
  416. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  417. if err != nil {
  418. log.Fatalf("cannot create raft logger %v", err)
  419. }
  420. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  421. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  422. }
  423. }
  424. n = raft.StartNode(c, peers)
  425. raftStatusMu.Lock()
  426. raftStatus = n.Status
  427. raftStatusMu.Unlock()
  428. return id, n, s, w
  429. }
  430. func restartNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  431. var walsnap walpb.Snapshot
  432. if snapshot != nil {
  433. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  434. }
  435. w, id, cid, st, ents := readWAL(cfg.Logger, cfg.WALDir(), walsnap)
  436. if cfg.Logger != nil {
  437. cfg.Logger.Info(
  438. "restarting local member",
  439. zap.String("cluster-id", cid.String()),
  440. zap.String("local-member-id", id.String()),
  441. zap.Uint64("commit-index", st.Commit),
  442. )
  443. } else {
  444. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  445. }
  446. cl := membership.NewCluster(cfg.Logger, "")
  447. cl.SetID(id, cid)
  448. s := raft.NewMemoryStorage()
  449. if snapshot != nil {
  450. s.ApplySnapshot(*snapshot)
  451. }
  452. s.SetHardState(st)
  453. s.Append(ents)
  454. c := &raft.Config{
  455. ID: uint64(id),
  456. ElectionTick: cfg.ElectionTicks,
  457. HeartbeatTick: 1,
  458. Storage: s,
  459. MaxSizePerMsg: maxSizePerMsg,
  460. MaxInflightMsgs: maxInflightMsgs,
  461. CheckQuorum: true,
  462. PreVote: cfg.PreVote,
  463. }
  464. if cfg.Logger != nil {
  465. // called after capnslog setting in "init" function
  466. var err error
  467. if cfg.LoggerConfig != nil {
  468. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  469. if err != nil {
  470. log.Fatalf("cannot create raft logger %v", err)
  471. }
  472. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  473. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  474. }
  475. }
  476. n := raft.RestartNode(c)
  477. raftStatusMu.Lock()
  478. raftStatus = n.Status
  479. raftStatusMu.Unlock()
  480. return id, cl, n, s, w
  481. }
  482. func restartAsStandaloneNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  483. var walsnap walpb.Snapshot
  484. if snapshot != nil {
  485. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  486. }
  487. w, id, cid, st, ents := readWAL(cfg.Logger, cfg.WALDir(), walsnap)
  488. // discard the previously uncommitted entries
  489. for i, ent := range ents {
  490. if ent.Index > st.Commit {
  491. if cfg.Logger != nil {
  492. cfg.Logger.Info(
  493. "discarding uncommitted WAL entries",
  494. zap.Uint64("entry-index", ent.Index),
  495. zap.Uint64("commit-index-from-wal", st.Commit),
  496. zap.Int("number-of-discarded-entries", len(ents)-i),
  497. )
  498. } else {
  499. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  500. }
  501. ents = ents[:i]
  502. break
  503. }
  504. }
  505. // force append the configuration change entries
  506. toAppEnts := createConfigChangeEnts(
  507. cfg.Logger,
  508. getIDs(cfg.Logger, snapshot, ents),
  509. uint64(id),
  510. st.Term,
  511. st.Commit,
  512. )
  513. ents = append(ents, toAppEnts...)
  514. // force commit newly appended entries
  515. err := w.Save(raftpb.HardState{}, toAppEnts)
  516. if err != nil {
  517. if cfg.Logger != nil {
  518. cfg.Logger.Fatal("failed to save hard state and entries", zap.Error(err))
  519. } else {
  520. plog.Fatalf("%v", err)
  521. }
  522. }
  523. if len(ents) != 0 {
  524. st.Commit = ents[len(ents)-1].Index
  525. }
  526. if cfg.Logger != nil {
  527. cfg.Logger.Info(
  528. "forcing restart member",
  529. zap.String("cluster-id", cid.String()),
  530. zap.String("local-member-id", id.String()),
  531. zap.Uint64("commit-index", st.Commit),
  532. )
  533. } else {
  534. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  535. }
  536. cl := membership.NewCluster(cfg.Logger, "")
  537. cl.SetID(id, cid)
  538. s := raft.NewMemoryStorage()
  539. if snapshot != nil {
  540. s.ApplySnapshot(*snapshot)
  541. }
  542. s.SetHardState(st)
  543. s.Append(ents)
  544. c := &raft.Config{
  545. ID: uint64(id),
  546. ElectionTick: cfg.ElectionTicks,
  547. HeartbeatTick: 1,
  548. Storage: s,
  549. MaxSizePerMsg: maxSizePerMsg,
  550. MaxInflightMsgs: maxInflightMsgs,
  551. CheckQuorum: true,
  552. PreVote: cfg.PreVote,
  553. }
  554. if cfg.Logger != nil {
  555. // called after capnslog setting in "init" function
  556. if cfg.LoggerConfig != nil {
  557. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  558. if err != nil {
  559. log.Fatalf("cannot create raft logger %v", err)
  560. }
  561. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  562. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  563. }
  564. }
  565. n := raft.RestartNode(c)
  566. raftStatus = n.Status
  567. return id, cl, n, s, w
  568. }
  569. // getIDs returns an ordered set of IDs included in the given snapshot and
  570. // the entries. The given snapshot/entries can contain two kinds of
  571. // ID-related entry:
  572. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  573. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  574. func getIDs(lg *zap.Logger, snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  575. ids := make(map[uint64]bool)
  576. if snap != nil {
  577. for _, id := range snap.Metadata.ConfState.Nodes {
  578. ids[id] = true
  579. }
  580. }
  581. for _, e := range ents {
  582. if e.Type != raftpb.EntryConfChange {
  583. continue
  584. }
  585. var cc raftpb.ConfChange
  586. pbutil.MustUnmarshal(&cc, e.Data)
  587. switch cc.Type {
  588. case raftpb.ConfChangeAddNode:
  589. ids[cc.NodeID] = true
  590. case raftpb.ConfChangeRemoveNode:
  591. delete(ids, cc.NodeID)
  592. case raftpb.ConfChangeUpdateNode:
  593. // do nothing
  594. default:
  595. if lg != nil {
  596. lg.Panic("unknown ConfChange Type", zap.String("type", cc.Type.String()))
  597. } else {
  598. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  599. }
  600. }
  601. }
  602. sids := make(types.Uint64Slice, 0, len(ids))
  603. for id := range ids {
  604. sids = append(sids, id)
  605. }
  606. sort.Sort(sids)
  607. return []uint64(sids)
  608. }
  609. // createConfigChangeEnts creates a series of Raft entries (i.e.
  610. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  611. // `self` is _not_ removed, even if present in the set.
  612. // If `self` is not inside the given ids, it creates a Raft entry to add a
  613. // default member with the given `self`.
  614. func createConfigChangeEnts(lg *zap.Logger, ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  615. ents := make([]raftpb.Entry, 0)
  616. next := index + 1
  617. found := false
  618. for _, id := range ids {
  619. if id == self {
  620. found = true
  621. continue
  622. }
  623. cc := &raftpb.ConfChange{
  624. Type: raftpb.ConfChangeRemoveNode,
  625. NodeID: id,
  626. }
  627. e := raftpb.Entry{
  628. Type: raftpb.EntryConfChange,
  629. Data: pbutil.MustMarshal(cc),
  630. Term: term,
  631. Index: next,
  632. }
  633. ents = append(ents, e)
  634. next++
  635. }
  636. if !found {
  637. m := membership.Member{
  638. ID: types.ID(self),
  639. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  640. }
  641. ctx, err := json.Marshal(m)
  642. if err != nil {
  643. if lg != nil {
  644. lg.Panic("failed to marshal member", zap.Error(err))
  645. } else {
  646. plog.Panicf("marshal member should never fail: %v", err)
  647. }
  648. }
  649. cc := &raftpb.ConfChange{
  650. Type: raftpb.ConfChangeAddNode,
  651. NodeID: self,
  652. Context: ctx,
  653. }
  654. e := raftpb.Entry{
  655. Type: raftpb.EntryConfChange,
  656. Data: pbutil.MustMarshal(cc),
  657. Term: term,
  658. Index: next,
  659. }
  660. ents = append(ents, e)
  661. }
  662. return ents
  663. }