raft.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. "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. )
  31. var (
  32. // indirection for expvar func interface
  33. // expvar panics when publishing duplicate name
  34. // expvar does not support remove a registered name
  35. // so only register a func that calls raftStatus
  36. // and change raftStatus as we need.
  37. raftStatus func() raft.Status
  38. )
  39. func init() {
  40. expvar.Publish("raft.status", expvar.Func(func() interface{} { return raftStatus() }))
  41. }
  42. type RaftTimer interface {
  43. Index() uint64
  44. Term() uint64
  45. }
  46. type raftNode struct {
  47. raft.Node
  48. // config
  49. snapCount uint64 // number of entries to trigger a snapshot
  50. // utility
  51. ticker <-chan time.Time
  52. raftStorage *raft.MemoryStorage
  53. storage Storage
  54. // transport specifies the transport to send and receive msgs to members.
  55. // Sending messages MUST NOT block. It is okay to drop messages, since
  56. // clients should timeout and reissue their messages.
  57. // If transport is nil, server will panic.
  58. transport rafthttp.Transporter
  59. // Cache of the latest raft index and raft term the server has seen
  60. index uint64
  61. term uint64
  62. lead uint64
  63. }
  64. // for testing
  65. func (r *raftNode) pauseSending() {
  66. p := r.transport.(rafthttp.Pausable)
  67. p.Pause()
  68. }
  69. func (r *raftNode) resumeSending() {
  70. p := r.transport.(rafthttp.Pausable)
  71. p.Resume()
  72. }
  73. func startNode(cfg *ServerConfig, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  74. var err error
  75. member := cfg.Cluster.MemberByName(cfg.Name)
  76. metadata := pbutil.MustMarshal(
  77. &pb.Metadata{
  78. NodeID: uint64(member.ID),
  79. ClusterID: uint64(cfg.Cluster.ID()),
  80. },
  81. )
  82. if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
  83. log.Fatalf("etcdserver create snapshot directory error: %v", err)
  84. }
  85. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  86. log.Fatalf("etcdserver: create wal error: %v", err)
  87. }
  88. peers := make([]raft.Peer, len(ids))
  89. for i, id := range ids {
  90. ctx, err := json.Marshal((*cfg.Cluster).Member(id))
  91. if err != nil {
  92. log.Panicf("marshal member should never fail: %v", err)
  93. }
  94. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  95. }
  96. id = member.ID
  97. log.Printf("etcdserver: start member %s in cluster %s", id, cfg.Cluster.ID())
  98. s = raft.NewMemoryStorage()
  99. n = raft.StartNode(uint64(id), peers, cfg.ElectionTicks, 1, s)
  100. raftStatus = n.Status
  101. return
  102. }
  103. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  104. var walsnap walpb.Snapshot
  105. if snapshot != nil {
  106. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  107. }
  108. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  109. cfg.Cluster.SetID(cid)
  110. log.Printf("etcdserver: restart member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  111. s := raft.NewMemoryStorage()
  112. if snapshot != nil {
  113. s.ApplySnapshot(*snapshot)
  114. }
  115. s.SetHardState(st)
  116. s.Append(ents)
  117. n := raft.RestartNode(uint64(id), cfg.ElectionTicks, 1, s, 0)
  118. raftStatus = n.Status
  119. return id, n, s, w
  120. }
  121. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  122. var walsnap walpb.Snapshot
  123. if snapshot != nil {
  124. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  125. }
  126. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  127. cfg.Cluster.SetID(cid)
  128. // discard the previously uncommitted entries
  129. for i, ent := range ents {
  130. if ent.Index > st.Commit {
  131. log.Printf("etcdserver: discarding %d uncommitted WAL entries ", len(ents)-i)
  132. ents = ents[:i]
  133. break
  134. }
  135. }
  136. // force append the configuration change entries
  137. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  138. ents = append(ents, toAppEnts...)
  139. // force commit newly appended entries
  140. err := w.Save(raftpb.HardState{}, toAppEnts)
  141. if err != nil {
  142. log.Fatalf("etcdserver: %v", err)
  143. }
  144. if len(ents) != 0 {
  145. st.Commit = ents[len(ents)-1].Index
  146. }
  147. log.Printf("etcdserver: forcing restart of member %s in cluster %s at commit index %d", id, cfg.Cluster.ID(), st.Commit)
  148. s := raft.NewMemoryStorage()
  149. if snapshot != nil {
  150. s.ApplySnapshot(*snapshot)
  151. }
  152. s.SetHardState(st)
  153. s.Append(ents)
  154. n := raft.RestartNode(uint64(id), cfg.ElectionTicks, 1, s, 0)
  155. raftStatus = n.Status
  156. return id, n, s, w
  157. }
  158. // getIDs returns an ordered set of IDs included in the given snapshot and
  159. // the entries. The given snapshot/entries can contain two kinds of
  160. // ID-related entry:
  161. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  162. // - ConfChangeAddRemove, in which case the contained ID will be removed from the set.
  163. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  164. ids := make(map[uint64]bool)
  165. if snap != nil {
  166. for _, id := range snap.Metadata.ConfState.Nodes {
  167. ids[id] = true
  168. }
  169. }
  170. for _, e := range ents {
  171. if e.Type != raftpb.EntryConfChange {
  172. continue
  173. }
  174. var cc raftpb.ConfChange
  175. pbutil.MustUnmarshal(&cc, e.Data)
  176. switch cc.Type {
  177. case raftpb.ConfChangeAddNode:
  178. ids[cc.NodeID] = true
  179. case raftpb.ConfChangeRemoveNode:
  180. delete(ids, cc.NodeID)
  181. default:
  182. log.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  183. }
  184. }
  185. sids := make(types.Uint64Slice, 0)
  186. for id := range ids {
  187. sids = append(sids, id)
  188. }
  189. sort.Sort(sids)
  190. return []uint64(sids)
  191. }
  192. // createConfigChangeEnts creates a series of Raft entries (i.e.
  193. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  194. // `self` is _not_ removed, even if present in the set.
  195. // If `self` is not inside the given ids, it creates a Raft entry to add a
  196. // default member with the given `self`.
  197. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  198. ents := make([]raftpb.Entry, 0)
  199. next := index + 1
  200. found := false
  201. for _, id := range ids {
  202. if id == self {
  203. found = true
  204. continue
  205. }
  206. cc := &raftpb.ConfChange{
  207. Type: raftpb.ConfChangeRemoveNode,
  208. NodeID: id,
  209. }
  210. e := raftpb.Entry{
  211. Type: raftpb.EntryConfChange,
  212. Data: pbutil.MustMarshal(cc),
  213. Term: term,
  214. Index: next,
  215. }
  216. ents = append(ents, e)
  217. next++
  218. }
  219. if !found {
  220. m := Member{
  221. ID: types.ID(self),
  222. RaftAttributes: RaftAttributes{PeerURLs: []string{"http://localhost:7001", "http://localhost:2380"}},
  223. }
  224. ctx, err := json.Marshal(m)
  225. if err != nil {
  226. log.Panicf("marshal member should never fail: %v", err)
  227. }
  228. cc := &raftpb.ConfChange{
  229. Type: raftpb.ConfChangeAddNode,
  230. NodeID: self,
  231. Context: ctx,
  232. }
  233. e := raftpb.Entry{
  234. Type: raftpb.EntryConfChange,
  235. Data: pbutil.MustMarshal(cc),
  236. Term: term,
  237. Index: next,
  238. }
  239. ents = append(ents, e)
  240. }
  241. return ents
  242. }