raft.go 11 KB

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