raft.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  168. var err error
  169. member := cfg.Cluster.MemberByName(cfg.Name)
  170. metadata := pbutil.MustMarshal(
  171. &pb.Metadata{
  172. NodeID: uint64(member.ID),
  173. ClusterID: uint64(cfg.Cluster.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((*cfg.Cluster).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, cfg.Cluster.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, 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. cfg.Cluster.SetID(cid)
  212. log.Printf("etcdserver: restart member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  213. s := raft.NewMemoryStorage()
  214. if snapshot != nil {
  215. s.ApplySnapshot(*snapshot)
  216. }
  217. s.SetHardState(st)
  218. s.Append(ents)
  219. c := &raft.Config{
  220. ID: uint64(id),
  221. ElectionTick: cfg.ElectionTicks,
  222. HeartbeatTick: 1,
  223. Storage: s,
  224. MaxSizePerMsg: maxSizePerMsg,
  225. MaxInflightMsgs: maxInflightMsgs,
  226. }
  227. n := raft.RestartNode(c)
  228. raftStatus = n.Status
  229. return id, n, s, w
  230. }
  231. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, 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. cfg.Cluster.SetID(cid)
  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, cfg.Cluster.ID(), st.Commit)
  258. s := raft.NewMemoryStorage()
  259. if snapshot != nil {
  260. s.ApplySnapshot(*snapshot)
  261. }
  262. s.SetHardState(st)
  263. s.Append(ents)
  264. c := &raft.Config{
  265. ID: uint64(id),
  266. ElectionTick: cfg.ElectionTicks,
  267. HeartbeatTick: 1,
  268. Storage: s,
  269. MaxSizePerMsg: maxSizePerMsg,
  270. MaxInflightMsgs: maxInflightMsgs,
  271. }
  272. n := raft.RestartNode(c)
  273. raftStatus = n.Status
  274. return id, n, s, w
  275. }
  276. // getIDs returns an ordered set of IDs included in the given snapshot and
  277. // the entries. The given snapshot/entries can contain two kinds of
  278. // ID-related entry:
  279. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  280. // - ConfChangeAddRemove, in which case the contained ID will be removed from the set.
  281. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  282. ids := make(map[uint64]bool)
  283. if snap != nil {
  284. for _, id := range snap.Metadata.ConfState.Nodes {
  285. ids[id] = true
  286. }
  287. }
  288. for _, e := range ents {
  289. if e.Type != raftpb.EntryConfChange {
  290. continue
  291. }
  292. var cc raftpb.ConfChange
  293. pbutil.MustUnmarshal(&cc, e.Data)
  294. switch cc.Type {
  295. case raftpb.ConfChangeAddNode:
  296. ids[cc.NodeID] = true
  297. case raftpb.ConfChangeRemoveNode:
  298. delete(ids, cc.NodeID)
  299. default:
  300. log.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  301. }
  302. }
  303. sids := make(types.Uint64Slice, 0)
  304. for id := range ids {
  305. sids = append(sids, id)
  306. }
  307. sort.Sort(sids)
  308. return []uint64(sids)
  309. }
  310. // createConfigChangeEnts creates a series of Raft entries (i.e.
  311. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  312. // `self` is _not_ removed, even if present in the set.
  313. // If `self` is not inside the given ids, it creates a Raft entry to add a
  314. // default member with the given `self`.
  315. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  316. ents := make([]raftpb.Entry, 0)
  317. next := index + 1
  318. found := false
  319. for _, id := range ids {
  320. if id == self {
  321. found = true
  322. continue
  323. }
  324. cc := &raftpb.ConfChange{
  325. Type: raftpb.ConfChangeRemoveNode,
  326. NodeID: id,
  327. }
  328. e := raftpb.Entry{
  329. Type: raftpb.EntryConfChange,
  330. Data: pbutil.MustMarshal(cc),
  331. Term: term,
  332. Index: next,
  333. }
  334. ents = append(ents, e)
  335. next++
  336. }
  337. if !found {
  338. m := Member{
  339. ID: types.ID(self),
  340. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  341. }
  342. ctx, err := json.Marshal(m)
  343. if err != nil {
  344. log.Panicf("marshal member should never fail: %v", err)
  345. }
  346. cc := &raftpb.ConfChange{
  347. Type: raftpb.ConfChangeAddNode,
  348. NodeID: self,
  349. Context: ctx,
  350. }
  351. e := raftpb.Entry{
  352. Type: raftpb.EntryConfChange,
  353. Data: pbutil.MustMarshal(cc),
  354. Term: term,
  355. Index: next,
  356. }
  357. ents = append(ents, e)
  358. }
  359. return ents
  360. }