raft.go 19 KB

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