raft.go 14 KB

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