raft.go 12 KB

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