raft.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "log"
  19. "os"
  20. "sort"
  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. )
  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. expvar.Publish("raft.status", expvar.Func(func() interface{} { return raftStatus() }))
  56. }
  57. type RaftTimer interface {
  58. Index() uint64
  59. Term() uint64
  60. }
  61. // apply contains entries, snapshot be applied.
  62. // After applied all the items, the application needs
  63. // to send notification to done chan.
  64. type apply struct {
  65. entries []raftpb.Entry
  66. snapshot raftpb.Snapshot
  67. done chan struct{}
  68. }
  69. type raftNode struct {
  70. raft.Node
  71. // a chan to send out apply
  72. applyc chan apply
  73. // TODO: remove the etcdserver related logic from raftNode
  74. // TODO: add a state machine interface to apply the commit entries
  75. // and do snapshot/recover
  76. s *EtcdServer
  77. // utility
  78. ticker <-chan time.Time
  79. raftStorage *raft.MemoryStorage
  80. storage Storage
  81. // transport specifies the transport to send and receive msgs to members.
  82. // Sending messages MUST NOT block. It is okay to drop messages, since
  83. // clients should timeout and reissue their messages.
  84. // If transport is nil, server will panic.
  85. transport rafthttp.Transporter
  86. // Cache of the latest raft index and raft term the server has seen
  87. index uint64
  88. term uint64
  89. lead uint64
  90. }
  91. func (r *raftNode) run() {
  92. var syncC <-chan time.Time
  93. defer r.stop()
  94. for {
  95. select {
  96. case <-r.ticker:
  97. r.Tick()
  98. case rd := <-r.Ready():
  99. if rd.SoftState != nil {
  100. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  101. if rd.RaftState == raft.StateLeader {
  102. syncC = r.s.SyncTicker
  103. // TODO: remove the nil checking
  104. // current test utility does not provide the stats
  105. if r.s.stats != nil {
  106. r.s.stats.BecomeLeader()
  107. }
  108. } else {
  109. syncC = nil
  110. }
  111. }
  112. apply := apply{
  113. entries: rd.CommittedEntries,
  114. snapshot: rd.Snapshot,
  115. done: make(chan struct{}),
  116. }
  117. select {
  118. case r.applyc <- apply:
  119. case <-r.s.done:
  120. return
  121. }
  122. if !raft.IsEmptySnap(rd.Snapshot) {
  123. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  124. log.Fatalf("etcdraft: save snapshot error: %v", err)
  125. }
  126. r.raftStorage.ApplySnapshot(rd.Snapshot)
  127. log.Printf("etcdraft: applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  128. }
  129. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  130. log.Fatalf("etcdraft: save state and entries error: %v", err)
  131. }
  132. r.raftStorage.Append(rd.Entries)
  133. r.s.send(rd.Messages)
  134. <-apply.done
  135. r.Advance()
  136. case <-syncC:
  137. r.s.sync(defaultSyncTimeout)
  138. case <-r.s.done:
  139. return
  140. }
  141. }
  142. }
  143. func (r *raftNode) apply() chan apply {
  144. return r.applyc
  145. }
  146. func (r *raftNode) stop() {
  147. r.Stop()
  148. r.transport.Stop()
  149. if err := r.storage.Close(); err != nil {
  150. log.Panicf("etcdraft: close storage error: %v", err)
  151. }
  152. }
  153. // for testing
  154. func (r *raftNode) pauseSending() {
  155. p := r.transport.(rafthttp.Pausable)
  156. p.Pause()
  157. }
  158. func (r *raftNode) resumeSending() {
  159. p := r.transport.(rafthttp.Pausable)
  160. p.Resume()
  161. }
  162. func startNode(cfg *ServerConfig, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  163. var err error
  164. member := cfg.Cluster.MemberByName(cfg.Name)
  165. metadata := pbutil.MustMarshal(
  166. &pb.Metadata{
  167. NodeID: uint64(member.ID),
  168. ClusterID: uint64(cfg.Cluster.ID()),
  169. },
  170. )
  171. if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  172. log.Fatalf("etcdserver create snapshot directory error: %v", err)
  173. }
  174. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  175. log.Fatalf("etcdserver: create wal error: %v", err)
  176. }
  177. peers := make([]raft.Peer, len(ids))
  178. for i, id := range ids {
  179. ctx, err := json.Marshal((*cfg.Cluster).Member(id))
  180. if err != nil {
  181. log.Panicf("marshal member should never fail: %v", err)
  182. }
  183. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  184. }
  185. id = member.ID
  186. log.Printf("etcdserver: start member %s in cluster %s", id, cfg.Cluster.ID())
  187. s = raft.NewMemoryStorage()
  188. c := &raft.Config{
  189. ID: uint64(id),
  190. ElectionTick: cfg.ElectionTicks,
  191. HeartbeatTick: 1,
  192. Storage: s,
  193. MaxSizePerMsg: maxSizePerMsg,
  194. MaxInflightMsgs: maxInflightMsgs,
  195. }
  196. n = raft.StartNode(c, peers)
  197. raftStatus = n.Status
  198. return
  199. }
  200. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  201. var walsnap walpb.Snapshot
  202. if snapshot != nil {
  203. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  204. }
  205. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  206. cfg.Cluster.SetID(cid)
  207. log.Printf("etcdserver: restart member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  208. s := raft.NewMemoryStorage()
  209. if snapshot != nil {
  210. s.ApplySnapshot(*snapshot)
  211. }
  212. s.SetHardState(st)
  213. s.Append(ents)
  214. c := &raft.Config{
  215. ID: uint64(id),
  216. ElectionTick: cfg.ElectionTicks,
  217. HeartbeatTick: 1,
  218. Storage: s,
  219. MaxSizePerMsg: maxSizePerMsg,
  220. MaxInflightMsgs: maxInflightMsgs,
  221. }
  222. n := raft.RestartNode(c)
  223. raftStatus = n.Status
  224. return id, n, s, w
  225. }
  226. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  227. var walsnap walpb.Snapshot
  228. if snapshot != nil {
  229. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  230. }
  231. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  232. cfg.Cluster.SetID(cid)
  233. // discard the previously uncommitted entries
  234. for i, ent := range ents {
  235. if ent.Index > st.Commit {
  236. log.Printf("etcdserver: discarding %d uncommitted WAL entries ", len(ents)-i)
  237. ents = ents[:i]
  238. break
  239. }
  240. }
  241. // force append the configuration change entries
  242. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  243. ents = append(ents, toAppEnts...)
  244. // force commit newly appended entries
  245. err := w.Save(raftpb.HardState{}, toAppEnts)
  246. if err != nil {
  247. log.Fatalf("etcdserver: %v", err)
  248. }
  249. if len(ents) != 0 {
  250. st.Commit = ents[len(ents)-1].Index
  251. }
  252. log.Printf("etcdserver: forcing restart of member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  253. s := raft.NewMemoryStorage()
  254. if snapshot != nil {
  255. s.ApplySnapshot(*snapshot)
  256. }
  257. s.SetHardState(st)
  258. s.Append(ents)
  259. c := &raft.Config{
  260. ID: uint64(id),
  261. ElectionTick: cfg.ElectionTicks,
  262. HeartbeatTick: 1,
  263. Storage: s,
  264. MaxSizePerMsg: maxSizePerMsg,
  265. MaxInflightMsgs: maxInflightMsgs,
  266. }
  267. n := raft.RestartNode(c)
  268. raftStatus = n.Status
  269. return id, n, s, w
  270. }
  271. // getIDs returns an ordered set of IDs included in the given snapshot and
  272. // the entries. The given snapshot/entries can contain two kinds of
  273. // ID-related entry:
  274. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  275. // - ConfChangeAddRemove, in which case the contained ID will be removed from the set.
  276. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  277. ids := make(map[uint64]bool)
  278. if snap != nil {
  279. for _, id := range snap.Metadata.ConfState.Nodes {
  280. ids[id] = true
  281. }
  282. }
  283. for _, e := range ents {
  284. if e.Type != raftpb.EntryConfChange {
  285. continue
  286. }
  287. var cc raftpb.ConfChange
  288. pbutil.MustUnmarshal(&cc, e.Data)
  289. switch cc.Type {
  290. case raftpb.ConfChangeAddNode:
  291. ids[cc.NodeID] = true
  292. case raftpb.ConfChangeRemoveNode:
  293. delete(ids, cc.NodeID)
  294. default:
  295. log.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  296. }
  297. }
  298. sids := make(types.Uint64Slice, 0)
  299. for id := range ids {
  300. sids = append(sids, id)
  301. }
  302. sort.Sort(sids)
  303. return []uint64(sids)
  304. }
  305. // createConfigChangeEnts creates a series of Raft entries (i.e.
  306. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  307. // `self` is _not_ removed, even if present in the set.
  308. // If `self` is not inside the given ids, it creates a Raft entry to add a
  309. // default member with the given `self`.
  310. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  311. ents := make([]raftpb.Entry, 0)
  312. next := index + 1
  313. found := false
  314. for _, id := range ids {
  315. if id == self {
  316. found = true
  317. continue
  318. }
  319. cc := &raftpb.ConfChange{
  320. Type: raftpb.ConfChangeRemoveNode,
  321. NodeID: id,
  322. }
  323. e := raftpb.Entry{
  324. Type: raftpb.EntryConfChange,
  325. Data: pbutil.MustMarshal(cc),
  326. Term: term,
  327. Index: next,
  328. }
  329. ents = append(ents, e)
  330. next++
  331. }
  332. if !found {
  333. m := Member{
  334. ID: types.ID(self),
  335. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  336. }
  337. ctx, err := json.Marshal(m)
  338. if err != nil {
  339. log.Panicf("marshal member should never fail: %v", err)
  340. }
  341. cc := &raftpb.ConfChange{
  342. Type: raftpb.ConfChangeAddNode,
  343. NodeID: self,
  344. Context: ctx,
  345. }
  346. e := raftpb.Entry{
  347. Type: raftpb.EntryConfChange,
  348. Data: pbutil.MustMarshal(cc),
  349. Term: term,
  350. Index: next,
  351. }
  352. ents = append(ents, e)
  353. }
  354. return ents
  355. }