raft.go 12 KB

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