etcd/raft/node.go

423 lines
12 KiB
Go
Raw Normal View History

/*
Copyright 2014 CoreOS, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package raft
import (
2014-09-01 05:49:07 +04:00
"errors"
2014-09-03 07:21:58 +04:00
"log"
"reflect"
2014-09-01 05:49:07 +04:00
2014-10-14 11:35:28 +04:00
"github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
2014-08-28 05:53:18 +04:00
pb "github.com/coreos/etcd/raft/raftpb"
)
2014-06-05 21:49:34 +04:00
2014-09-09 08:15:35 +04:00
var (
2014-09-16 04:35:02 +04:00
emptyState = pb.HardState{}
2014-10-08 02:22:35 +04:00
// ErrStopped is returned by methods on Nodes that have been stopped.
2014-09-09 08:15:35 +04:00
ErrStopped = errors.New("raft: stopped")
)
2014-09-01 05:49:07 +04:00
2014-09-16 04:35:02 +04:00
// SoftState provides state that is useful for logging and debugging.
// The state is volatile and does not need to be persisted to the WAL.
type SoftState struct {
Lead uint64
RaftState StateType
Nodes []uint64
2014-09-16 04:35:02 +04:00
}
func (a *SoftState) equal(b *SoftState) bool {
2014-10-07 11:53:53 +04:00
return reflect.DeepEqual(a, b)
2014-09-16 04:35:02 +04:00
}
// Ready encapsulates the entries and messages that are ready to read,
// be saved to stable storage, committed or sent to other peers.
// All fields in Ready are read-only.
type Ready struct {
2014-09-16 04:35:02 +04:00
// The current volatile state of a Node.
// SoftState will be nil if there is no update.
// It is not required to consume or store SoftState.
*SoftState
// The current state of a Node to be saved to stable storage BEFORE
// Messages are sent.
// HardState will be equal to empty state if there is no update.
pb.HardState
// Entries specifies entries to be saved to stable storage BEFORE
// Messages are sent.
2014-08-28 05:53:18 +04:00
Entries []pb.Entry
2014-09-17 05:18:45 +04:00
// Snapshot specifies the snapshot to be saved to stable storage.
Snapshot pb.Snapshot
// CommittedEntries specifies entries to be committed to a
// store/state-machine. These have previously been committed to stable
// store.
2014-08-28 05:53:18 +04:00
CommittedEntries []pb.Entry
// Messages specifies outbound messages to be sent AFTER Entries are
// committed to stable storage.
2014-08-28 05:53:18 +04:00
Messages []pb.Message
}
type compact struct {
2014-10-08 14:29:53 +04:00
index uint64
nodes []uint64
data []byte
}
func isHardStateEqual(a, b pb.HardState) bool {
2014-09-16 01:34:23 +04:00
return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
2014-08-25 07:09:06 +04:00
}
2014-05-29 00:53:26 +04:00
2014-10-08 02:22:35 +04:00
// IsEmptyHardState returns true if the given HardState is empty.
func IsEmptyHardState(st pb.HardState) bool {
return isHardStateEqual(st, emptyState)
2014-09-09 08:45:10 +04:00
}
2014-10-08 02:22:35 +04:00
// IsEmptySnap returns true if the given Snapshot is empty.
2014-09-17 05:18:45 +04:00
func IsEmptySnap(sp pb.Snapshot) bool {
return sp.Index == 0
}
func (rd Ready) containsUpdates() bool {
2014-09-17 05:18:45 +04:00
return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) || !IsEmptySnap(rd.Snapshot) ||
len(rd.Entries) > 0 || len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0
2014-06-05 21:49:34 +04:00
}
2014-10-08 02:22:35 +04:00
// Node represents a node in a raft cluster.
2014-09-17 23:23:44 +04:00
type Node interface {
// Tick increments the internal logical clock for the Node by a single tick. Election
// timeouts and heartbeat timeouts are in units of ticks.
Tick()
// Campaign causes the Node to transition to candidate state and start campaigning to become leader.
2014-09-17 23:23:44 +04:00
Campaign(ctx context.Context) error
// Propose proposes that data be appended to the log.
Propose(ctx context.Context, data []byte) error
2014-09-23 23:02:44 +04:00
// ProposeConfChange proposes config change.
// At most one ConfChange can be in the process of going through consensus.
// Application needs to call ApplyConfChange when applying EntryConfChange type entry.
ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
2014-09-17 23:23:44 +04:00
// Step advances the state machine using the given message. ctx.Err() will be returned, if any.
Step(ctx context.Context, msg pb.Message) error
// Ready returns a channel that returns the current point-in-time state
// Users of the Node must call Advance after applying the state returned by Ready
2014-09-17 23:23:44 +04:00
Ready() <-chan Ready
// Advance notifies the Node that the application has applied and saved progress up to the last Ready.
// It prepares the node to return the next available Ready.
Advance()
2014-09-23 23:02:44 +04:00
// ApplyConfChange applies config change to the local node.
// TODO: reject existing node when add node
// TODO: reject non-existant node when remove node
2014-09-23 23:02:44 +04:00
ApplyConfChange(cc pb.ConfChange)
2014-09-17 23:23:44 +04:00
// Stop performs any necessary termination of the Node
Stop()
// Compact discards the entrire log up to the given index. It also
// generates a raft snapshot containing the given nodes configuration
// and the given snapshot data.
// It is the caller's responsibility to ensure the given configuration
// and snapshot data match the actual point-in-time configuration and snapshot
// at the given index.
2014-10-08 14:29:53 +04:00
Compact(index uint64, nodes []uint64, d []byte)
}
type Peer struct {
ID uint64
Context []byte
}
2014-09-17 23:23:44 +04:00
// StartNode returns a new Node given a unique raft id, a list of raft peers, and
// the election and heartbeat timeouts in units of ticks.
// It appends a ConfChangeAddNode entry for each given peer to the initial log.
func StartNode(id uint64, peers []Peer, election, heartbeat int) Node {
2014-09-05 08:15:39 +04:00
n := newNode()
r := newRaft(id, nil, election, heartbeat)
2014-10-11 15:20:14 +04:00
for _, peer := range peers {
cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
2014-10-11 15:20:14 +04:00
d, err := cc.Marshal()
if err != nil {
panic("unexpected marshal error")
}
2014-10-11 15:20:14 +04:00
e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d}
r.raftLog.append(r.raftLog.lastIndex(), e)
}
2014-10-11 15:20:14 +04:00
r.raftLog.committed = r.raftLog.lastIndex()
2014-09-05 08:15:39 +04:00
go n.run(r)
2014-09-17 23:23:44 +04:00
return &n
2014-09-05 08:15:39 +04:00
}
2014-09-17 23:23:44 +04:00
// RestartNode is identical to StartNode but takes an initial State and a slice
// of entries. Generally this is used when restarting from a stable storage
// log.
func RestartNode(id uint64, election, heartbeat int, snapshot *pb.Snapshot, st pb.HardState, ents []pb.Entry) Node {
2014-09-05 08:15:39 +04:00
n := newNode()
r := newRaft(id, nil, election, heartbeat)
2014-09-17 05:18:45 +04:00
if snapshot != nil {
r.restore(*snapshot)
r.raftLog.appliedTo(snapshot.Index)
2014-09-17 05:18:45 +04:00
}
2014-11-04 02:16:41 +03:00
if !isHardStateEqual(st, emptyState) {
r.loadState(st)
}
if len(ents) != 0 {
r.loadEnts(ents)
}
2014-09-05 08:15:39 +04:00
go n.run(r)
2014-09-17 23:23:44 +04:00
return &n
}
// node is the canonical implementation of the Node interface
type node struct {
propc chan pb.Message
recvc chan pb.Message
compactc chan compact
2014-09-23 23:02:44 +04:00
confc chan pb.ConfChange
2014-09-17 23:23:44 +04:00
readyc chan Ready
advancec chan struct{}
2014-09-17 23:23:44 +04:00
tickc chan struct{}
done chan struct{}
2014-11-12 23:32:20 +03:00
stop chan struct{}
2014-09-05 08:15:39 +04:00
}
2014-09-17 23:23:44 +04:00
func newNode() node {
return node{
2014-09-17 05:18:45 +04:00
propc: make(chan pb.Message),
recvc: make(chan pb.Message),
compactc: make(chan compact),
2014-09-23 23:02:44 +04:00
confc: make(chan pb.ConfChange),
2014-09-17 05:18:45 +04:00
readyc: make(chan Ready),
advancec: make(chan struct{}),
2014-09-17 05:18:45 +04:00
tickc: make(chan struct{}),
done: make(chan struct{}),
2014-11-12 23:32:20 +03:00
stop: make(chan struct{}),
2014-08-25 07:09:06 +04:00
}
}
2014-09-17 23:23:44 +04:00
func (n *node) Stop() {
select {
case n.stop <- struct{}{}:
// Not already stopped, so trigger it
case <-n.done:
// Node has already been stopped - no need to do anything
return
}
// Block until the stop has been acknowledged by run()
<-n.done
2014-09-01 05:49:07 +04:00
}
2014-09-17 23:23:44 +04:00
func (n *node) run(r *raft) {
var propc chan pb.Message
var readyc chan Ready
var advancec chan struct{}
var prevLastUnstablei uint64
var havePrevLastUnstablei bool
var rd Ready
2014-06-20 01:39:17 +04:00
2014-09-16 04:35:02 +04:00
lead := None
prevSoftSt := r.softState()
prevHardSt := r.HardState
2014-09-17 05:18:45 +04:00
prevSnapi := r.raftLog.snapshot.Index
2014-09-05 08:15:39 +04:00
2014-08-25 07:09:06 +04:00
for {
if advancec != nil {
2014-09-16 04:35:02 +04:00
readyc = nil
} else {
rd = newReady(r, prevSoftSt, prevHardSt, prevSnapi)
if rd.containsUpdates() {
readyc = n.readyc
} else {
readyc = nil
}
2014-09-16 04:35:02 +04:00
if rd.SoftState != nil && lead != rd.SoftState.Lead {
if r.hasLeader() {
if lead == None {
log.Printf("raft: elected leader %x at term %d", rd.SoftState.Lead, r.Term)
} else {
log.Printf("raft: leader changed from %x to %x at term %d", lead, rd.SoftState.Lead, r.Term)
}
propc = n.propc
} else {
log.Printf("raft: lost leader %x at term %d", lead, r.Term)
propc = nil
}
lead = rd.SoftState.Lead
2014-09-03 07:21:58 +04:00
}
}
2014-08-25 07:09:06 +04:00
select {
// TODO: maybe buffer the config propose if there exists one (the way
// described in raft dissertation)
// Currently it is dropped in Step silently.
case m := <-propc:
m.From = r.id
r.Step(m)
2014-08-25 07:09:06 +04:00
case m := <-n.recvc:
r.Step(m) // raft never returns an error
case c := <-n.compactc:
r.compact(c.index, c.nodes, c.data)
case cc := <-n.confc:
if cc.NodeID == None {
r.resetPendingConf()
break
}
switch cc.Type {
2014-09-23 23:02:44 +04:00
case pb.ConfChangeAddNode:
r.addNode(cc.NodeID)
2014-09-23 23:02:44 +04:00
case pb.ConfChangeRemoveNode:
r.removeNode(cc.NodeID)
case pb.ConfChangeUpdateNode:
r.resetPendingConf()
default:
panic("unexpected conf type")
}
2014-08-25 07:09:06 +04:00
case <-n.tickc:
2014-09-03 03:59:29 +04:00
r.tick()
case readyc <- rd:
2014-09-16 04:35:02 +04:00
if rd.SoftState != nil {
prevSoftSt = rd.SoftState
}
if len(rd.Entries) > 0 {
prevLastUnstablei = rd.Entries[len(rd.Entries)-1].Index
havePrevLastUnstablei = true
}
if !IsEmptyHardState(rd.HardState) {
2014-09-16 04:35:02 +04:00
prevHardSt = rd.HardState
}
2014-09-17 05:18:45 +04:00
if !IsEmptySnap(rd.Snapshot) {
prevSnapi = rd.Snapshot.Index
if prevSnapi > prevLastUnstablei {
prevLastUnstablei = prevSnapi
havePrevLastUnstablei = true
}
2014-09-17 05:18:45 +04:00
}
2014-08-25 07:09:06 +04:00
r.msgs = nil
advancec = n.advancec
case <-advancec:
if prevHardSt.Commit != 0 {
r.raftLog.appliedTo(prevHardSt.Commit)
}
if havePrevLastUnstablei {
r.raftLog.stableTo(prevLastUnstablei)
havePrevLastUnstablei = false
}
advancec = nil
2014-11-12 23:32:20 +03:00
case <-n.stop:
close(n.done)
2014-08-25 07:09:06 +04:00
return
2014-07-15 10:41:19 +04:00
}
2014-05-29 00:53:26 +04:00
}
}
2014-06-05 21:49:34 +04:00
// Tick increments the internal logical clock for this Node. Election timeouts
// and heartbeat timeouts are in units of ticks.
2014-09-17 23:23:44 +04:00
func (n *node) Tick() {
2014-08-25 07:09:06 +04:00
select {
case n.tickc <- struct{}{}:
2014-09-01 05:49:07 +04:00
case <-n.done:
2014-06-08 13:50:39 +04:00
}
2014-06-05 21:49:34 +04:00
}
2014-09-17 23:23:44 +04:00
func (n *node) Campaign(ctx context.Context) error {
2014-10-12 11:34:22 +04:00
return n.step(ctx, pb.Message{Type: pb.MsgHup})
2014-08-29 03:41:42 +04:00
}
2014-09-17 23:23:44 +04:00
func (n *node) Propose(ctx context.Context, data []byte) error {
2014-10-12 11:34:22 +04:00
return n.step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
}
func (n *node) Step(ctx context.Context, m pb.Message) error {
// ignore unexpected local messages receiving over network
2014-10-12 11:34:22 +04:00
if m.Type == pb.MsgHup || m.Type == pb.MsgBeat {
// TODO: return an error?
return nil
}
return n.step(ctx, m)
2014-07-25 01:11:53 +04:00
}
2014-07-31 04:21:27 +04:00
2014-09-23 23:02:44 +04:00
func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
data, err := cc.Marshal()
if err != nil {
return err
}
2014-10-12 11:34:22 +04:00
return n.Step(ctx, pb.Message{Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange, Data: data}}})
}
2014-08-28 04:22:34 +04:00
// Step advances the state machine using msgs. The ctx.Err() will be returned,
2014-08-25 23:49:14 +04:00
// if any.
func (n *node) step(ctx context.Context, m pb.Message) error {
2014-08-28 04:22:34 +04:00
ch := n.recvc
2014-10-12 11:34:22 +04:00
if m.Type == pb.MsgProp {
2014-08-28 04:22:34 +04:00
ch = n.propc
}
2014-08-28 04:22:34 +04:00
select {
case ch <- m:
return nil
case <-ctx.Done():
return ctx.Err()
2014-09-01 05:49:07 +04:00
case <-n.done:
return ErrStopped
2014-08-01 02:18:44 +04:00
}
2014-07-31 04:21:27 +04:00
}
2014-09-17 23:23:44 +04:00
func (n *node) Ready() <-chan Ready {
return n.readyc
2014-07-31 04:21:27 +04:00
}
2014-09-09 08:50:04 +04:00
func (n *node) Advance() {
select {
case n.advancec <- struct{}{}:
case <-n.done:
}
}
2014-09-23 23:02:44 +04:00
func (n *node) ApplyConfChange(cc pb.ConfChange) {
2014-09-17 05:18:45 +04:00
select {
case n.confc <- cc:
2014-09-17 05:18:45 +04:00
case <-n.done:
}
}
2014-10-08 14:29:53 +04:00
func (n *node) Compact(index uint64, nodes []uint64, d []byte) {
select {
case n.compactc <- compact{index, nodes, d}:
case <-n.done:
}
}
2014-10-08 14:29:53 +04:00
func newReady(r *raft, prevSoftSt *SoftState, prevHardSt pb.HardState, prevSnapi uint64) Ready {
2014-09-09 08:50:04 +04:00
rd := Ready{
Entries: r.raftLog.unstableEnts(),
CommittedEntries: r.raftLog.nextEnts(),
Messages: r.msgs,
}
2014-09-16 04:35:02 +04:00
if softSt := r.softState(); !softSt.equal(prevSoftSt) {
rd.SoftState = softSt
}
if !isHardStateEqual(r.HardState, prevHardSt) {
2014-09-16 04:35:02 +04:00
rd.HardState = r.HardState
2014-09-09 08:50:04 +04:00
}
2014-09-17 05:18:45 +04:00
if prevSnapi != r.raftLog.snapshot.Index {
rd.Snapshot = r.raftLog.snapshot
}
2014-09-09 08:50:04 +04:00
return rd
}