raft.go 11 KB

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