raft.go 20 KB

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