raft.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. // Copyright 2015 CoreOS, Inc.
  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. "os"
  19. "sort"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. "github.com/coreos/etcd/etcdserver/membership"
  25. "github.com/coreos/etcd/pkg/contention"
  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. )
  35. const (
  36. // Number of entries for slow follower to catch-up after compacting
  37. // the raft storage entries.
  38. // We expect the follower has a millisecond level latency with the leader.
  39. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  40. // follower to catch up.
  41. numberOfCatchUpEntries = 5000
  42. // The max throughput of etcd will not exceed 100MB/s (100K * 1KB value).
  43. // Assuming the RTT is around 10ms, 1MB max size is large enough.
  44. maxSizePerMsg = 1 * 1024 * 1024
  45. // Never overflow the rafthttp buffer, which is 4096.
  46. // TODO: a better const?
  47. maxInflightMsgs = 4096 / 8
  48. )
  49. var (
  50. // protects raftStatus
  51. raftStatusMu sync.Mutex
  52. // indirection for expvar func interface
  53. // expvar panics when publishing duplicate name
  54. // expvar does not support remove a registered name
  55. // so only register a func that calls raftStatus
  56. // and change raftStatus as we need.
  57. raftStatus func() raft.Status
  58. )
  59. func init() {
  60. raft.SetLogger(capnslog.NewPackageLogger("github.com/coreos/etcd", "raft"))
  61. expvar.Publish("raft.status", expvar.Func(func() interface{} {
  62. raftStatusMu.Lock()
  63. defer raftStatusMu.Unlock()
  64. return raftStatus()
  65. }))
  66. }
  67. type RaftTimer interface {
  68. Index() uint64
  69. Term() uint64
  70. }
  71. // apply contains entries, snapshot to be applied. Once
  72. // an apply is consumed, the entries will be persisted to
  73. // to raft storage concurrently; the application must read
  74. // raftDone before assuming the raft messages are stable.
  75. type apply struct {
  76. entries []raftpb.Entry
  77. snapshot raftpb.Snapshot
  78. raftDone <-chan struct{} // rx {} after raft has persisted messages
  79. }
  80. type raftNode struct {
  81. // Cache of the latest raft index and raft term the server has seen.
  82. // These three unit64 fields must be the first elements to keep 64-bit
  83. // alignment for atomic access to the fields.
  84. index uint64
  85. term uint64
  86. lead uint64
  87. mu sync.Mutex
  88. // last lead elected time
  89. lt time.Time
  90. raft.Node
  91. // a chan to send out apply
  92. applyc chan apply
  93. // TODO: remove the etcdserver related logic from raftNode
  94. // TODO: add a state machine interface to apply the commit entries
  95. // and do snapshot/recover
  96. s *EtcdServer
  97. // utility
  98. ticker <-chan time.Time
  99. raftStorage *raft.MemoryStorage
  100. storage Storage
  101. // transport specifies the transport to send and receive msgs to members.
  102. // Sending messages MUST NOT block. It is okay to drop messages, since
  103. // clients should timeout and reissue their messages.
  104. // If transport is nil, server will panic.
  105. transport rafthttp.Transporter
  106. td *contention.TimeoutDetector
  107. stopped chan struct{}
  108. done chan struct{}
  109. }
  110. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  111. // to modify the fields after it has been started.
  112. // TODO: Ideally raftNode should get rid of the passed in server structure.
  113. func (r *raftNode) start(s *EtcdServer) {
  114. r.s = s
  115. r.applyc = make(chan apply)
  116. r.stopped = make(chan struct{})
  117. r.done = make(chan struct{})
  118. heartbeat := 200 * time.Millisecond
  119. if s.cfg != nil {
  120. heartbeat = time.Duration(s.cfg.TickMs) * time.Millisecond
  121. }
  122. // set up contention detectors for raft heartbeat message.
  123. // expect to send a heartbeat within 2 heartbeat intervals.
  124. r.td = contention.NewTimeoutDetector(2 * heartbeat)
  125. go func() {
  126. var syncC <-chan time.Time
  127. defer r.onStop()
  128. islead := false
  129. for {
  130. select {
  131. case <-r.ticker:
  132. r.Tick()
  133. case rd := <-r.Ready():
  134. if rd.SoftState != nil {
  135. if lead := atomic.LoadUint64(&r.lead); rd.SoftState.Lead != raft.None && lead != rd.SoftState.Lead {
  136. r.mu.Lock()
  137. r.lt = time.Now()
  138. r.mu.Unlock()
  139. }
  140. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  141. if rd.RaftState == raft.StateLeader {
  142. islead = true
  143. // TODO: raft should send server a notification through chan when
  144. // it promotes or demotes instead of modifying server directly.
  145. syncC = r.s.SyncTicker
  146. if r.s.lessor != nil {
  147. r.s.lessor.Promote(r.s.cfg.electionTimeout())
  148. }
  149. // TODO: remove the nil checking
  150. // current test utility does not provide the stats
  151. if r.s.stats != nil {
  152. r.s.stats.BecomeLeader()
  153. }
  154. if r.s.compactor != nil {
  155. r.s.compactor.Resume()
  156. }
  157. r.td.Reset()
  158. } else {
  159. islead = false
  160. if r.s.lessor != nil {
  161. r.s.lessor.Demote()
  162. }
  163. if r.s.compactor != nil {
  164. r.s.compactor.Pause()
  165. }
  166. syncC = nil
  167. }
  168. }
  169. raftDone := make(chan struct{}, 1)
  170. ap := apply{
  171. entries: rd.CommittedEntries,
  172. snapshot: rd.Snapshot,
  173. raftDone: raftDone,
  174. }
  175. select {
  176. case r.applyc <- ap:
  177. case <-r.stopped:
  178. return
  179. }
  180. // the leader can write to its disk in parallel with replicating to the followers and them
  181. // writing to their disks.
  182. // For more details, check raft thesis 10.2.1
  183. if islead {
  184. r.s.send(rd.Messages)
  185. }
  186. if !raft.IsEmptySnap(rd.Snapshot) {
  187. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  188. plog.Fatalf("raft save snapshot error: %v", err)
  189. }
  190. r.raftStorage.ApplySnapshot(rd.Snapshot)
  191. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  192. }
  193. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  194. plog.Fatalf("raft save state and entries error: %v", err)
  195. }
  196. r.raftStorage.Append(rd.Entries)
  197. if !islead {
  198. r.s.send(rd.Messages)
  199. }
  200. raftDone <- struct{}{}
  201. r.Advance()
  202. case <-syncC:
  203. r.s.sync(r.s.cfg.ReqTimeout())
  204. case <-r.stopped:
  205. return
  206. }
  207. }
  208. }()
  209. }
  210. func (r *raftNode) apply() chan apply {
  211. return r.applyc
  212. }
  213. func (r *raftNode) leadElectedTime() time.Time {
  214. r.mu.Lock()
  215. defer r.mu.Unlock()
  216. return r.lt
  217. }
  218. func (r *raftNode) stop() {
  219. r.stopped <- struct{}{}
  220. <-r.done
  221. }
  222. func (r *raftNode) onStop() {
  223. r.Stop()
  224. r.transport.Stop()
  225. if err := r.storage.Close(); err != nil {
  226. plog.Panicf("raft close storage error: %v", err)
  227. }
  228. close(r.done)
  229. }
  230. // for testing
  231. func (r *raftNode) pauseSending() {
  232. p := r.transport.(rafthttp.Pausable)
  233. p.Pause()
  234. }
  235. func (r *raftNode) resumeSending() {
  236. p := r.transport.(rafthttp.Pausable)
  237. p.Resume()
  238. }
  239. // advanceTicksForElection advances ticks to the node for fast election.
  240. // This reduces the time to wait for first leader election if bootstrapping the whole
  241. // cluster, while leaving at least 1 heartbeat for possible existing leader
  242. // to contact it.
  243. func advanceTicksForElection(n raft.Node, electionTicks int) {
  244. for i := 0; i < electionTicks-1; i++ {
  245. n.Tick()
  246. }
  247. }
  248. func startNode(cfg *ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  249. var err error
  250. member := cl.MemberByName(cfg.Name)
  251. metadata := pbutil.MustMarshal(
  252. &pb.Metadata{
  253. NodeID: uint64(member.ID),
  254. ClusterID: uint64(cl.ID()),
  255. },
  256. )
  257. if err = os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  258. plog.Fatalf("create snapshot directory error: %v", err)
  259. }
  260. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  261. plog.Fatalf("create wal error: %v", err)
  262. }
  263. peers := make([]raft.Peer, len(ids))
  264. for i, id := range ids {
  265. ctx, err := json.Marshal((*cl).Member(id))
  266. if err != nil {
  267. plog.Panicf("marshal member should never fail: %v", err)
  268. }
  269. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  270. }
  271. id = member.ID
  272. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  273. s = raft.NewMemoryStorage()
  274. c := &raft.Config{
  275. ID: uint64(id),
  276. ElectionTick: cfg.ElectionTicks,
  277. HeartbeatTick: 1,
  278. Storage: s,
  279. MaxSizePerMsg: maxSizePerMsg,
  280. MaxInflightMsgs: maxInflightMsgs,
  281. CheckQuorum: true,
  282. }
  283. n = raft.StartNode(c, peers)
  284. raftStatusMu.Lock()
  285. raftStatus = n.Status
  286. raftStatusMu.Unlock()
  287. advanceTicksForElection(n, c.ElectionTick)
  288. return
  289. }
  290. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  291. var walsnap walpb.Snapshot
  292. if snapshot != nil {
  293. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  294. }
  295. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  296. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  297. cl := membership.NewCluster("")
  298. cl.SetID(cid)
  299. s := raft.NewMemoryStorage()
  300. if snapshot != nil {
  301. s.ApplySnapshot(*snapshot)
  302. }
  303. s.SetHardState(st)
  304. s.Append(ents)
  305. c := &raft.Config{
  306. ID: uint64(id),
  307. ElectionTick: cfg.ElectionTicks,
  308. HeartbeatTick: 1,
  309. Storage: s,
  310. MaxSizePerMsg: maxSizePerMsg,
  311. MaxInflightMsgs: maxInflightMsgs,
  312. CheckQuorum: true,
  313. }
  314. n := raft.RestartNode(c)
  315. raftStatusMu.Lock()
  316. raftStatus = n.Status
  317. raftStatusMu.Unlock()
  318. advanceTicksForElection(n, c.ElectionTick)
  319. return id, cl, n, s, w
  320. }
  321. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  322. var walsnap walpb.Snapshot
  323. if snapshot != nil {
  324. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  325. }
  326. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  327. // discard the previously uncommitted entries
  328. for i, ent := range ents {
  329. if ent.Index > st.Commit {
  330. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  331. ents = ents[:i]
  332. break
  333. }
  334. }
  335. // force append the configuration change entries
  336. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  337. ents = append(ents, toAppEnts...)
  338. // force commit newly appended entries
  339. err := w.Save(raftpb.HardState{}, toAppEnts)
  340. if err != nil {
  341. plog.Fatalf("%v", err)
  342. }
  343. if len(ents) != 0 {
  344. st.Commit = ents[len(ents)-1].Index
  345. }
  346. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  347. cl := membership.NewCluster("")
  348. cl.SetID(cid)
  349. s := raft.NewMemoryStorage()
  350. if snapshot != nil {
  351. s.ApplySnapshot(*snapshot)
  352. }
  353. s.SetHardState(st)
  354. s.Append(ents)
  355. c := &raft.Config{
  356. ID: uint64(id),
  357. ElectionTick: cfg.ElectionTicks,
  358. HeartbeatTick: 1,
  359. Storage: s,
  360. MaxSizePerMsg: maxSizePerMsg,
  361. MaxInflightMsgs: maxInflightMsgs,
  362. }
  363. n := raft.RestartNode(c)
  364. raftStatus = n.Status
  365. return id, cl, n, s, w
  366. }
  367. // getIDs returns an ordered set of IDs included in the given snapshot and
  368. // the entries. The given snapshot/entries can contain two kinds of
  369. // ID-related entry:
  370. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  371. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  372. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  373. ids := make(map[uint64]bool)
  374. if snap != nil {
  375. for _, id := range snap.Metadata.ConfState.Nodes {
  376. ids[id] = true
  377. }
  378. }
  379. for _, e := range ents {
  380. if e.Type != raftpb.EntryConfChange {
  381. continue
  382. }
  383. var cc raftpb.ConfChange
  384. pbutil.MustUnmarshal(&cc, e.Data)
  385. switch cc.Type {
  386. case raftpb.ConfChangeAddNode:
  387. ids[cc.NodeID] = true
  388. case raftpb.ConfChangeRemoveNode:
  389. delete(ids, cc.NodeID)
  390. case raftpb.ConfChangeUpdateNode:
  391. // do nothing
  392. default:
  393. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  394. }
  395. }
  396. sids := make(types.Uint64Slice, 0)
  397. for id := range ids {
  398. sids = append(sids, id)
  399. }
  400. sort.Sort(sids)
  401. return []uint64(sids)
  402. }
  403. // createConfigChangeEnts creates a series of Raft entries (i.e.
  404. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  405. // `self` is _not_ removed, even if present in the set.
  406. // If `self` is not inside the given ids, it creates a Raft entry to add a
  407. // default member with the given `self`.
  408. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  409. ents := make([]raftpb.Entry, 0)
  410. next := index + 1
  411. found := false
  412. for _, id := range ids {
  413. if id == self {
  414. found = true
  415. continue
  416. }
  417. cc := &raftpb.ConfChange{
  418. Type: raftpb.ConfChangeRemoveNode,
  419. NodeID: id,
  420. }
  421. e := raftpb.Entry{
  422. Type: raftpb.EntryConfChange,
  423. Data: pbutil.MustMarshal(cc),
  424. Term: term,
  425. Index: next,
  426. }
  427. ents = append(ents, e)
  428. next++
  429. }
  430. if !found {
  431. m := membership.Member{
  432. ID: types.ID(self),
  433. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  434. }
  435. ctx, err := json.Marshal(m)
  436. if err != nil {
  437. plog.Panicf("marshal member should never fail: %v", err)
  438. }
  439. cc := &raftpb.ConfChange{
  440. Type: raftpb.ConfChangeAddNode,
  441. NodeID: self,
  442. Context: ctx,
  443. }
  444. e := raftpb.Entry{
  445. Type: raftpb.EntryConfChange,
  446. Data: pbutil.MustMarshal(cc),
  447. Term: term,
  448. Index: next,
  449. }
  450. ents = append(ents, e)
  451. }
  452. return ents
  453. }