[][src]Crate raft

Creating a Raft node

You can use RawNode::new to create the Raft node. To create the Raft node, you need to provide a Storage component, and a Config to the RawNode::new function.

use raft::{
    Config,
    storage::MemStorage,
    raw_node::RawNode,
};

// Select some defaults, then change what we need.
let config = Config {
    id: 1,
    ..Default::default()
};
// ... Make any configuration changes.
// After, make sure it's valid!
config.validate().unwrap();
// We'll use the built-in `MemStorage`, but you will likely want your own.
// Finally, create our Raft node!
let storage = MemStorage::new_with_conf_state((vec![1], vec![]));
let mut node = RawNode::new(&config, storage).unwrap();
// We will coax it into being the lead of a single node cluster for exploration.
node.raft.become_candidate();
node.raft.become_leader();

Ticking the Raft node

Use a timer to tick the Raft node at regular intervals. See the following example using Rust channel recv_timeout to drive the Raft node at least every 100ms, calling tick() each time.

use std::{sync::mpsc::{channel, RecvTimeoutError}, time::{Instant, Duration}};

// We're using a channel, but this could be any stream of events.
let (tx, rx) = channel();
let timeout = Duration::from_millis(100);
let mut remaining_timeout = timeout;

// Send the `tx` somewhere else...

loop {
    let now = Instant::now();

    match rx.recv_timeout(remaining_timeout) {
        Ok(()) => {
            // Let's save this for later.
            unimplemented!()
        },
        Err(RecvTimeoutError::Timeout) => (),
        Err(RecvTimeoutError::Disconnected) => unimplemented!(),
    }

    let elapsed = now.elapsed();
    if elapsed >= remaining_timeout {
        remaining_timeout = timeout;
        // We drive Raft every 100ms.
        node.tick();
    } else {
        remaining_timeout -= elapsed;
    }
}

Proposing to, and stepping the Raft node

Using the propose function you can drive the Raft node when the client sends a request to the Raft server. You can call propose to add the request to the Raft log explicitly.

In most cases, the client needs to wait for a response for the request. For example, if the client writes a value to a key and wants to know whether the write succeeds or not, but the write flow is asynchronous in Raft, so the write log entry must be replicated to other followers, then committed and at last applied to the state machine, so here we need a way to notify the client after the write is finished.

One simple way is to use a unique ID for the client request, and save the associated callback function in a hash map. When the log entry is applied, we can get the ID from the decoded entry, call the corresponding callback, and notify the client.

You can call the step function when you receive the Raft messages from other nodes.

Here is a simple example to use propose and step:

enum Msg {
    Propose {
        id: u8,
        callback: Box<Fn() + Send>,
    },
    Raft(Message),
}

// Simulate a message coming down the stream.
tx.send(Msg::Propose { id: 1, callback: Box::new(|| ()) });

let mut cbs = HashMap::new();
loop {
    let now = Instant::now();

    match rx.recv_timeout(remaining_timeout) {
        Ok(Msg::Propose { id, callback }) => {
            cbs.insert(id, callback);
            node.propose(vec![], vec![id]).unwrap();
        }
        Ok(Msg::Raft(m)) => node.step(m).unwrap(),
        Err(RecvTimeoutError::Timeout) => (),
        Err(RecvTimeoutError::Disconnected) => unimplemented!(),
    }

    let elapsed = now.elapsed();
    if elapsed >= remaining_timeout {
        remaining_timeout = timeout;
        // We drive Raft every 100ms.
        node.tick();
    } else {
        remaining_timeout -= elapsed;
    }
    break;
}

In the above example, we use a channel to receive the propose and step messages. We only propose the request ID to the Raft log. In your own practice, you can embed the ID in your request and propose the encoded binary request data.

Processing the Ready State

When your Raft node is ticked and running, Raft should enter a Ready state. You need to first use has_ready to check whether Raft is ready. If yes, use the ready function to get a Ready state:

This example is not tested
if !node.has_ready() {
    return;
}

// The Raft is ready, we can do something now.
let mut ready = node.ready();

The Ready state contains quite a bit of information, and you need to check and process them one by one:

  1. Check whether snapshot is empty or not. If not empty, it means that the Raft node has received a Raft snapshot from the leader and we must apply the snapshot:

    This example is not tested
    if !raft::is_empty_snap(ready.snapshot()) {
        // This is a snapshot, we need to apply the snapshot at first.
        node.mut_store()
            .wl()
            .apply_snapshot(ready.snapshot().clone())
            .unwrap();
    }
    
  2. Check whether entries is empty or not. If not empty, it means that there are newly added entries but has not been committed yet, we must append the entries to the Raft log:

    This example is not tested
    if !ready.entries.is_empty() {
        // Append entries to the Raft log
        node.mut_store().wl().append(ready.entries()).unwrap();
    }
    
  3. Check whether hs is empty or not. If not empty, it means that the HardState of the node has changed. For example, the node may vote for a new leader, or the commit index has been increased. We must persist the changed HardState:

    This example is not tested
    if let Some(hs) = ready.hs() {
        // Raft HardState changed, and we need to persist it.
        node.mut_store().wl().set_hardstate(hs.clone());
    }
  4. Check whether messages is empty or not. If not, it means that the node will send messages to other nodes. There has been an optimization for sending messages: if the node is a leader, this can be done together with step 1 in parallel; if the node is not a leader, it needs to reply the messages to the leader after appending the Raft entries:

    This example is not tested
    if !is_leader {
        // If not leader, the follower needs to reply the messages to
        // the leader after appending Raft entries.
        let msgs = ready.messages.drain(..);
        for _msg in msgs {
            // Send messages to other peers.
        }
    }
  5. Check whether committed_entires is empty or not. If not, it means that there are some newly committed log entries which you must apply to the state machine. Of course, after applying, you need to update the applied index and resume apply later:

    This example is not tested
    if let Some(committed_entries) = ready.committed_entries.take() {
        let mut _last_apply_index = 0;
        for entry in committed_entries {
            // Mostly, you need to save the last apply index to resume applying
            // after restart. Here we just ignore this because we use a Memory storage.
            _last_apply_index = entry.index;
    
            if entry.data.is_empty() {
                // Emtpy entry, when the peer becomes Leader it will send an empty entry.
                continue;
            }
    
            match entry.get_entry_type() {
                EntryType::EntryNormal => handle_normal(entry),
                EntryType::EntryConfChange => handle_conf_change(entry),
            }
        }
    }
  6. Call advance to prepare for the next Ready state.

    This example is not tested
    node.advance(ready);

For more information, check out an example.

Arbitrary Membership Changes

Note: This is an experimental feature.

When building a resilient, scalable distributed system there is a strong need to be able to change the membership of a peer group dynamically, without downtime. This Raft crate supports this via Joint Consensus (Raft paper, section 6).

It permits resilient arbitrary dynamic membership changes. A membership change can do any or all of the following:

  • Add peer (learner or voter) n to the group.
  • Remove peer n from the group.
  • Remove a leader (unmanaged, via stepdown)
  • Promote a learner to a voter.
  • Replace a node n with another node m.

It (currently) does not:

  • Allow control of the replacement leader during a stepdown.
  • Optionally roll back a change during a peer group pause where the new peer group configuration fails.
  • Provide automated promotion of newly added voters from learner to voter when they are caught up. This must be done as a two stage process for now.

PRs to enable these are welcome! We'd love to mentor/support you through implementing it.

This means it's possible to do:

use raft::{Config, storage::MemStorage, raw_node::RawNode, eraftpb::*};
use protobuf::Message as PbMessage;
let mut config = Config { id: 1, ..Default::default() };
let store = MemStorage::new_with_conf_state((vec![1, 2], vec![]));
let mut node = RawNode::new(&mut config, store).unwrap();
node.raft.become_candidate();
node.raft.become_leader();

// Call this on the leader, or send the command via a normal `MsgPropose`.
node.raft.propose_membership_change((
    // Any IntoIterator<Item=u64>.
    // Voters
    vec![1,3], // Remove 2, add 3.
    // Learners
    vec![4,5,6], // Add 4, 5, 6.
)).unwrap();

// ...Later when the begin entry is recieved from a `ready()` in the `entries` field...
let mut conf_change = ConfChange::default();
conf_change.merge_from_bytes(&entry.data).unwrap();
node.raft.begin_membership_change(&conf_change).unwrap();
assert!(node.raft.is_in_membership_change());
assert!(node.raft.prs().voter_ids().contains(&2));
assert!(node.raft.prs().voter_ids().contains(&3));
// ...Later, when the finalize entry is recieved from a `ready()` in the `entries` field...
let mut conf_change = ConfChange::default();
conf_change.merge_from_bytes(&entry.data).unwrap();
node.raft.finalize_membership_change(&conf_change).unwrap();
assert!(!node.raft.prs().voter_ids().contains(&2));
assert!(node.raft.prs().voter_ids().contains(&3));
assert!(!node.raft.is_in_membership_change());

This process is a two-phase process, during the midst of it the peer group's leader is managing two independent, possibly overlapping peer sets.

Note: In order to maintain resiliency guarantees (progress while a majority of both peer sets is active), it is very important to wait until the entire peer group has exited the transition phase before taking old, removed peers offline.

Re-exports

pub use self::raft_log::NO_LIMIT;
pub use self::raw_node::is_empty_snap;
pub use self::raw_node::Peer;
pub use self::raw_node::RawNode;
pub use self::raw_node::Ready;
pub use self::raw_node::SnapshotStatus;
pub use self::storage::RaftState;
pub use self::storage::Storage;

Modules

eraftpb

Generated file from eraftpb.proto

prelude

A "prelude" for crates using the raft crate.

raw_node

The raw node of the raft module.

storage

Represents the storage trait and example implementation.

util

This module contains a collection of various tools to use to manipulate and control messages and data associated with raft.

Structs

Config

Config contains the parameters to start a raft.

Configuration

A Raft internal representation of a Configuration.

Inflights

A buffer of inflight messages.

Progress

The progress of catching up from a restart.

ProgressSet

ProgressSet contains several Progresses, which could be Leader, Follower and Learner.

Raft

A struct that represents the raft consensus itself. Stores details concerning the current and possible state the system can take.

RaftLog

Raft log implementation

ReadState

ReadState provides state for read only query. It's caller's responsibility to send MsgReadIndex first before getting this state from ready. It's also caller's duty to differentiate if this state is what it requests through request_ctx, e.g. given a unique id as request_ctx.

SoftState

SoftState provides state that is useful for logging and debugging. The state is volatile and does not need to be persisted to the WAL.

Status

Represents the current status of the raft

StatusRef

Represents the current status of the raft

Unstable

The unstable.entries[i] has raft log position i+unstable.offset. Note that unstable.offset may be less than the highest log position in storage; this means that the next write to storage might need to truncate the log before persisting unstable.entries.

Enums

Error

The base error type for raft

ProgressState

The state of the progress.

ReadOnlyOption

Determines the relative safety of and consistency of read only requests.

StateRole

The role of the node.

StorageError

An error with the storage.

Constants

INVALID_ID

A constant represents invalid id of raft.

INVALID_INDEX

A constant represents invalid index of raft log.

Functions

majority

Get the majority number of given nodes count.

vote_resp_msg_type

Maps vote and pre_vote message types to their correspond responses.

Type Definitions

Result

A result type that wraps up the raft errors.