raft.go 12 KB

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