raft.go 12 KB

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