raft.go 11 KB

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