raft.go 13 KB

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