raft.go 11 KB

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