raft.go 20 KB

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