raft.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. "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. "heartbeat took too long to send out; server is overloaded, likely from slow disk",
  328. zap.Duration("exceeded", exceed),
  329. zap.Duration("heartbeat-interval", r.heartbeat),
  330. )
  331. } else {
  332. plog.Warningf("failed to send out heartbeat on time (exceeded the %v timeout for %v)", r.heartbeat, exceed)
  333. plog.Warningf("server is likely overloaded")
  334. }
  335. }
  336. }
  337. }
  338. return ms
  339. }
  340. func (r *raftNode) apply() chan apply {
  341. return r.applyc
  342. }
  343. func (r *raftNode) stop() {
  344. r.stopped <- struct{}{}
  345. <-r.done
  346. }
  347. func (r *raftNode) onStop() {
  348. r.Stop()
  349. r.ticker.Stop()
  350. r.transport.Stop()
  351. if err := r.storage.Close(); err != nil {
  352. if r.lg != nil {
  353. r.lg.Panic("failed to close Raft storage", zap.Error(err))
  354. } else {
  355. plog.Panicf("raft close storage error: %v", err)
  356. }
  357. }
  358. close(r.done)
  359. }
  360. // for testing
  361. func (r *raftNode) pauseSending() {
  362. p := r.transport.(rafthttp.Pausable)
  363. p.Pause()
  364. }
  365. func (r *raftNode) resumeSending() {
  366. p := r.transport.(rafthttp.Pausable)
  367. p.Resume()
  368. }
  369. // advanceTicks advances ticks of Raft node.
  370. // This can be used for fast-forwarding election
  371. // ticks in multi data-center deployments, thus
  372. // speeding up election process.
  373. func (r *raftNode) advanceTicks(ticks int) {
  374. for i := 0; i < ticks; i++ {
  375. r.tick()
  376. }
  377. }
  378. func startNode(cfg ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  379. var err error
  380. member := cl.MemberByName(cfg.Name)
  381. metadata := pbutil.MustMarshal(
  382. &pb.Metadata{
  383. NodeID: uint64(member.ID),
  384. ClusterID: uint64(cl.ID()),
  385. },
  386. )
  387. if w, err = wal.Create(cfg.Logger, cfg.WALDir(), metadata); err != nil {
  388. if cfg.Logger != nil {
  389. cfg.Logger.Fatal("failed to create WAL", zap.Error(err))
  390. } else {
  391. plog.Fatalf("create wal error: %v", err)
  392. }
  393. }
  394. peers := make([]raft.Peer, len(ids))
  395. for i, id := range ids {
  396. var ctx []byte
  397. ctx, err = json.Marshal((*cl).Member(id))
  398. if err != nil {
  399. if cfg.Logger != nil {
  400. cfg.Logger.Panic("failed to marshal member", zap.Error(err))
  401. } else {
  402. plog.Panicf("marshal member should never fail: %v", err)
  403. }
  404. }
  405. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  406. }
  407. id = member.ID
  408. if cfg.Logger != nil {
  409. cfg.Logger.Info(
  410. "starting local member",
  411. zap.String("local-member-id", id.String()),
  412. zap.String("cluster-id", cl.ID().String()),
  413. )
  414. } else {
  415. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  416. }
  417. s = raft.NewMemoryStorage()
  418. c := &raft.Config{
  419. ID: uint64(id),
  420. ElectionTick: cfg.ElectionTicks,
  421. HeartbeatTick: 1,
  422. Storage: s,
  423. MaxSizePerMsg: maxSizePerMsg,
  424. MaxInflightMsgs: maxInflightMsgs,
  425. CheckQuorum: true,
  426. PreVote: cfg.PreVote,
  427. }
  428. if cfg.Logger != nil {
  429. // called after capnslog setting in "init" function
  430. if cfg.LoggerConfig != nil {
  431. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  432. if err != nil {
  433. log.Fatalf("cannot create raft logger %v", err)
  434. }
  435. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  436. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  437. }
  438. }
  439. n = raft.StartNode(c, peers)
  440. raftStatusMu.Lock()
  441. raftStatus = n.Status
  442. raftStatusMu.Unlock()
  443. return id, n, s, w
  444. }
  445. func restartNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  446. var walsnap walpb.Snapshot
  447. if snapshot != nil {
  448. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  449. }
  450. w, id, cid, st, ents := readWAL(cfg.Logger, cfg.WALDir(), walsnap)
  451. if cfg.Logger != nil {
  452. cfg.Logger.Info(
  453. "restarting local member",
  454. zap.String("cluster-id", cid.String()),
  455. zap.String("local-member-id", id.String()),
  456. zap.Uint64("commit-index", st.Commit),
  457. )
  458. } else {
  459. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  460. }
  461. cl := membership.NewCluster(cfg.Logger, "")
  462. cl.SetID(id, cid)
  463. s := raft.NewMemoryStorage()
  464. if snapshot != nil {
  465. s.ApplySnapshot(*snapshot)
  466. }
  467. s.SetHardState(st)
  468. s.Append(ents)
  469. c := &raft.Config{
  470. ID: uint64(id),
  471. ElectionTick: cfg.ElectionTicks,
  472. HeartbeatTick: 1,
  473. Storage: s,
  474. MaxSizePerMsg: maxSizePerMsg,
  475. MaxInflightMsgs: maxInflightMsgs,
  476. CheckQuorum: true,
  477. PreVote: cfg.PreVote,
  478. }
  479. if cfg.Logger != nil {
  480. // called after capnslog setting in "init" function
  481. var err error
  482. if cfg.LoggerConfig != nil {
  483. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  484. if err != nil {
  485. log.Fatalf("cannot create raft logger %v", err)
  486. }
  487. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  488. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  489. }
  490. }
  491. n := raft.RestartNode(c)
  492. raftStatusMu.Lock()
  493. raftStatus = n.Status
  494. raftStatusMu.Unlock()
  495. return id, cl, n, s, w
  496. }
  497. func restartAsStandaloneNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  498. var walsnap walpb.Snapshot
  499. if snapshot != nil {
  500. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  501. }
  502. w, id, cid, st, ents := readWAL(cfg.Logger, cfg.WALDir(), walsnap)
  503. // discard the previously uncommitted entries
  504. for i, ent := range ents {
  505. if ent.Index > st.Commit {
  506. if cfg.Logger != nil {
  507. cfg.Logger.Info(
  508. "discarding uncommitted WAL entries",
  509. zap.Uint64("entry-index", ent.Index),
  510. zap.Uint64("commit-index-from-wal", st.Commit),
  511. zap.Int("number-of-discarded-entries", len(ents)-i),
  512. )
  513. } else {
  514. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  515. }
  516. ents = ents[:i]
  517. break
  518. }
  519. }
  520. // force append the configuration change entries
  521. toAppEnts := createConfigChangeEnts(
  522. cfg.Logger,
  523. getIDs(cfg.Logger, snapshot, ents),
  524. uint64(id),
  525. st.Term,
  526. st.Commit,
  527. )
  528. ents = append(ents, toAppEnts...)
  529. // force commit newly appended entries
  530. err := w.Save(raftpb.HardState{}, toAppEnts)
  531. if err != nil {
  532. if cfg.Logger != nil {
  533. cfg.Logger.Fatal("failed to save hard state and entries", zap.Error(err))
  534. } else {
  535. plog.Fatalf("%v", err)
  536. }
  537. }
  538. if len(ents) != 0 {
  539. st.Commit = ents[len(ents)-1].Index
  540. }
  541. if cfg.Logger != nil {
  542. cfg.Logger.Info(
  543. "forcing restart member",
  544. zap.String("cluster-id", cid.String()),
  545. zap.String("local-member-id", id.String()),
  546. zap.Uint64("commit-index", st.Commit),
  547. )
  548. } else {
  549. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  550. }
  551. cl := membership.NewCluster(cfg.Logger, "")
  552. cl.SetID(id, cid)
  553. s := raft.NewMemoryStorage()
  554. if snapshot != nil {
  555. s.ApplySnapshot(*snapshot)
  556. }
  557. s.SetHardState(st)
  558. s.Append(ents)
  559. c := &raft.Config{
  560. ID: uint64(id),
  561. ElectionTick: cfg.ElectionTicks,
  562. HeartbeatTick: 1,
  563. Storage: s,
  564. MaxSizePerMsg: maxSizePerMsg,
  565. MaxInflightMsgs: maxInflightMsgs,
  566. CheckQuorum: true,
  567. PreVote: cfg.PreVote,
  568. }
  569. if cfg.Logger != nil {
  570. // called after capnslog setting in "init" function
  571. if cfg.LoggerConfig != nil {
  572. c.Logger, err = logutil.NewRaftLogger(cfg.LoggerConfig)
  573. if err != nil {
  574. log.Fatalf("cannot create raft logger %v", err)
  575. }
  576. } else if cfg.LoggerCore != nil && cfg.LoggerWriteSyncer != nil {
  577. c.Logger = logutil.NewRaftLoggerFromZapCore(cfg.LoggerCore, cfg.LoggerWriteSyncer)
  578. }
  579. }
  580. n := raft.RestartNode(c)
  581. raftStatus = n.Status
  582. return id, cl, n, s, w
  583. }
  584. // getIDs returns an ordered set of IDs included in the given snapshot and
  585. // the entries. The given snapshot/entries can contain two kinds of
  586. // ID-related entry:
  587. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  588. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  589. func getIDs(lg *zap.Logger, snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  590. ids := make(map[uint64]bool)
  591. if snap != nil {
  592. for _, id := range snap.Metadata.ConfState.Nodes {
  593. ids[id] = true
  594. }
  595. }
  596. for _, e := range ents {
  597. if e.Type != raftpb.EntryConfChange {
  598. continue
  599. }
  600. var cc raftpb.ConfChange
  601. pbutil.MustUnmarshal(&cc, e.Data)
  602. switch cc.Type {
  603. case raftpb.ConfChangeAddNode:
  604. ids[cc.NodeID] = true
  605. case raftpb.ConfChangeRemoveNode:
  606. delete(ids, cc.NodeID)
  607. case raftpb.ConfChangeUpdateNode:
  608. // do nothing
  609. default:
  610. if lg != nil {
  611. lg.Panic("unknown ConfChange Type", zap.String("type", cc.Type.String()))
  612. } else {
  613. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  614. }
  615. }
  616. }
  617. sids := make(types.Uint64Slice, 0, len(ids))
  618. for id := range ids {
  619. sids = append(sids, id)
  620. }
  621. sort.Sort(sids)
  622. return []uint64(sids)
  623. }
  624. // createConfigChangeEnts creates a series of Raft entries (i.e.
  625. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  626. // `self` is _not_ removed, even if present in the set.
  627. // If `self` is not inside the given ids, it creates a Raft entry to add a
  628. // default member with the given `self`.
  629. func createConfigChangeEnts(lg *zap.Logger, ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  630. ents := make([]raftpb.Entry, 0)
  631. next := index + 1
  632. found := false
  633. for _, id := range ids {
  634. if id == self {
  635. found = true
  636. continue
  637. }
  638. cc := &raftpb.ConfChange{
  639. Type: raftpb.ConfChangeRemoveNode,
  640. NodeID: id,
  641. }
  642. e := raftpb.Entry{
  643. Type: raftpb.EntryConfChange,
  644. Data: pbutil.MustMarshal(cc),
  645. Term: term,
  646. Index: next,
  647. }
  648. ents = append(ents, e)
  649. next++
  650. }
  651. if !found {
  652. m := membership.Member{
  653. ID: types.ID(self),
  654. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  655. }
  656. ctx, err := json.Marshal(m)
  657. if err != nil {
  658. if lg != nil {
  659. lg.Panic("failed to marshal member", zap.Error(err))
  660. } else {
  661. plog.Panicf("marshal member should never fail: %v", err)
  662. }
  663. }
  664. cc := &raftpb.ConfChange{
  665. Type: raftpb.ConfChangeAddNode,
  666. NodeID: self,
  667. Context: ctx,
  668. }
  669. e := raftpb.Entry{
  670. Type: raftpb.EntryConfChange,
  671. Data: pbutil.MustMarshal(cc),
  672. Term: term,
  673. Index: next,
  674. }
  675. ents = append(ents, e)
  676. }
  677. return ents
  678. }