raft.go 7.0 KB

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