raft.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. if r.s.compactor != nil {
  143. r.s.compactor.Resume()
  144. }
  145. } else {
  146. if r.s.lessor != nil {
  147. r.s.lessor.Demote()
  148. }
  149. if r.s.compactor != nil {
  150. r.s.compactor.Pause()
  151. }
  152. syncC = nil
  153. }
  154. }
  155. raftDone := make(chan struct{}, 1)
  156. ap := apply{
  157. entries: rd.CommittedEntries,
  158. snapshot: rd.Snapshot,
  159. raftDone: raftDone,
  160. }
  161. select {
  162. case r.applyc <- ap:
  163. case <-r.stopped:
  164. return
  165. }
  166. if !raft.IsEmptySnap(rd.Snapshot) {
  167. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  168. plog.Fatalf("raft save snapshot error: %v", err)
  169. }
  170. r.raftStorage.ApplySnapshot(rd.Snapshot)
  171. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  172. }
  173. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  174. plog.Fatalf("raft save state and entries error: %v", err)
  175. }
  176. r.raftStorage.Append(rd.Entries)
  177. r.s.send(rd.Messages)
  178. raftDone <- struct{}{}
  179. r.Advance()
  180. case <-syncC:
  181. r.s.sync(r.s.cfg.ReqTimeout())
  182. case <-r.stopped:
  183. return
  184. }
  185. }
  186. }()
  187. }
  188. func (r *raftNode) apply() chan apply {
  189. return r.applyc
  190. }
  191. func (r *raftNode) leadElectedTime() time.Time {
  192. r.mu.Lock()
  193. defer r.mu.Unlock()
  194. return r.lt
  195. }
  196. func (r *raftNode) stop() {
  197. r.stopped <- struct{}{}
  198. <-r.done
  199. }
  200. func (r *raftNode) onStop() {
  201. r.Stop()
  202. r.transport.Stop()
  203. if err := r.storage.Close(); err != nil {
  204. plog.Panicf("raft close storage error: %v", err)
  205. }
  206. close(r.done)
  207. }
  208. // for testing
  209. func (r *raftNode) pauseSending() {
  210. p := r.transport.(rafthttp.Pausable)
  211. p.Pause()
  212. }
  213. func (r *raftNode) resumeSending() {
  214. p := r.transport.(rafthttp.Pausable)
  215. p.Resume()
  216. }
  217. // advanceTicksForElection advances ticks to the node for fast election.
  218. // This reduces the time to wait for first leader election if bootstrapping the whole
  219. // cluster, while leaving at least 1 heartbeat for possible existing leader
  220. // to contact it.
  221. func advanceTicksForElection(n raft.Node, electionTicks int) {
  222. for i := 0; i < electionTicks-1; i++ {
  223. n.Tick()
  224. }
  225. }
  226. func startNode(cfg *ServerConfig, cl *cluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  227. var err error
  228. member := cl.MemberByName(cfg.Name)
  229. metadata := pbutil.MustMarshal(
  230. &pb.Metadata{
  231. NodeID: uint64(member.ID),
  232. ClusterID: uint64(cl.ID()),
  233. },
  234. )
  235. if err = os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  236. plog.Fatalf("create snapshot directory error: %v", err)
  237. }
  238. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  239. plog.Fatalf("create wal error: %v", err)
  240. }
  241. peers := make([]raft.Peer, len(ids))
  242. for i, id := range ids {
  243. ctx, err := json.Marshal((*cl).Member(id))
  244. if err != nil {
  245. plog.Panicf("marshal member should never fail: %v", err)
  246. }
  247. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  248. }
  249. id = member.ID
  250. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  251. s = raft.NewMemoryStorage()
  252. c := &raft.Config{
  253. ID: uint64(id),
  254. ElectionTick: cfg.ElectionTicks,
  255. HeartbeatTick: 1,
  256. Storage: s,
  257. MaxSizePerMsg: maxSizePerMsg,
  258. MaxInflightMsgs: maxInflightMsgs,
  259. }
  260. n = raft.StartNode(c, peers)
  261. raftStatusMu.Lock()
  262. raftStatus = n.Status
  263. raftStatusMu.Unlock()
  264. advanceTicksForElection(n, c.ElectionTick)
  265. return
  266. }
  267. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *cluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  268. var walsnap walpb.Snapshot
  269. if snapshot != nil {
  270. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  271. }
  272. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  273. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  274. cl := newCluster("")
  275. cl.SetID(cid)
  276. s := raft.NewMemoryStorage()
  277. if snapshot != nil {
  278. s.ApplySnapshot(*snapshot)
  279. }
  280. s.SetHardState(st)
  281. s.Append(ents)
  282. c := &raft.Config{
  283. ID: uint64(id),
  284. ElectionTick: cfg.ElectionTicks,
  285. HeartbeatTick: 1,
  286. Storage: s,
  287. MaxSizePerMsg: maxSizePerMsg,
  288. MaxInflightMsgs: maxInflightMsgs,
  289. }
  290. n := raft.RestartNode(c)
  291. raftStatusMu.Lock()
  292. raftStatus = n.Status
  293. raftStatusMu.Unlock()
  294. advanceTicksForElection(n, c.ElectionTick)
  295. return id, cl, n, s, w
  296. }
  297. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *cluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  298. var walsnap walpb.Snapshot
  299. if snapshot != nil {
  300. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  301. }
  302. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  303. // discard the previously uncommitted entries
  304. for i, ent := range ents {
  305. if ent.Index > st.Commit {
  306. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  307. ents = ents[:i]
  308. break
  309. }
  310. }
  311. // force append the configuration change entries
  312. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  313. ents = append(ents, toAppEnts...)
  314. // force commit newly appended entries
  315. err := w.Save(raftpb.HardState{}, toAppEnts)
  316. if err != nil {
  317. plog.Fatalf("%v", err)
  318. }
  319. if len(ents) != 0 {
  320. st.Commit = ents[len(ents)-1].Index
  321. }
  322. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  323. cl := newCluster("")
  324. cl.SetID(cid)
  325. s := raft.NewMemoryStorage()
  326. if snapshot != nil {
  327. s.ApplySnapshot(*snapshot)
  328. }
  329. s.SetHardState(st)
  330. s.Append(ents)
  331. c := &raft.Config{
  332. ID: uint64(id),
  333. ElectionTick: cfg.ElectionTicks,
  334. HeartbeatTick: 1,
  335. Storage: s,
  336. MaxSizePerMsg: maxSizePerMsg,
  337. MaxInflightMsgs: maxInflightMsgs,
  338. }
  339. n := raft.RestartNode(c)
  340. raftStatus = n.Status
  341. return id, cl, n, s, w
  342. }
  343. // getIDs returns an ordered set of IDs included in the given snapshot and
  344. // the entries. The given snapshot/entries can contain two kinds of
  345. // ID-related entry:
  346. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  347. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  348. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  349. ids := make(map[uint64]bool)
  350. if snap != nil {
  351. for _, id := range snap.Metadata.ConfState.Nodes {
  352. ids[id] = true
  353. }
  354. }
  355. for _, e := range ents {
  356. if e.Type != raftpb.EntryConfChange {
  357. continue
  358. }
  359. var cc raftpb.ConfChange
  360. pbutil.MustUnmarshal(&cc, e.Data)
  361. switch cc.Type {
  362. case raftpb.ConfChangeAddNode:
  363. ids[cc.NodeID] = true
  364. case raftpb.ConfChangeRemoveNode:
  365. delete(ids, cc.NodeID)
  366. case raftpb.ConfChangeUpdateNode:
  367. // do nothing
  368. default:
  369. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  370. }
  371. }
  372. sids := make(types.Uint64Slice, 0)
  373. for id := range ids {
  374. sids = append(sids, id)
  375. }
  376. sort.Sort(sids)
  377. return []uint64(sids)
  378. }
  379. // createConfigChangeEnts creates a series of Raft entries (i.e.
  380. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  381. // `self` is _not_ removed, even if present in the set.
  382. // If `self` is not inside the given ids, it creates a Raft entry to add a
  383. // default member with the given `self`.
  384. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  385. ents := make([]raftpb.Entry, 0)
  386. next := index + 1
  387. found := false
  388. for _, id := range ids {
  389. if id == self {
  390. found = true
  391. continue
  392. }
  393. cc := &raftpb.ConfChange{
  394. Type: raftpb.ConfChangeRemoveNode,
  395. NodeID: id,
  396. }
  397. e := raftpb.Entry{
  398. Type: raftpb.EntryConfChange,
  399. Data: pbutil.MustMarshal(cc),
  400. Term: term,
  401. Index: next,
  402. }
  403. ents = append(ents, e)
  404. next++
  405. }
  406. if !found {
  407. m := Member{
  408. ID: types.ID(self),
  409. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  410. }
  411. ctx, err := json.Marshal(m)
  412. if err != nil {
  413. plog.Panicf("marshal member should never fail: %v", err)
  414. }
  415. cc := &raftpb.ConfChange{
  416. Type: raftpb.ConfChangeAddNode,
  417. NodeID: self,
  418. Context: ctx,
  419. }
  420. e := raftpb.Entry{
  421. Type: raftpb.EntryConfChange,
  422. Data: pbutil.MustMarshal(cc),
  423. Term: term,
  424. Index: next,
  425. }
  426. ents = append(ents, e)
  427. }
  428. return ents
  429. }