ATBFINCGG3XKXWT5JJRHWI7GDAY2UDGAF72ZUJLFX5HT7AXSAKKQC
#[macro_use]
extern crate slog;
use slog::Drain;
use std::collections::{HashMap, VecDeque};
use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{str, thread};
use protobuf::Message as PbMessage;
use raft::eraftpb::ConfState;
use raft::storage::MemStorage;
use raft::{prelude::*, StateRole};
use regex::Regex;
fn main() {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain)
.chan_size(4096)
.overflow_strategy(slog_async::OverflowStrategy::Block)
.build()
.fuse();
let logger = slog::Logger::root(drain, o!());
const NUM_NODES: u32 = 5;
// Create 5 mailboxes to send/receive messages. Every node holds a `Receiver` to receive
// messages from others, and uses the respective `Sender` to send messages to others.
let (mut tx_vec, mut rx_vec) = (Vec::new(), Vec::new());
for _ in 0..NUM_NODES {
let (tx, rx) = mpsc::channel();
tx_vec.push(tx);
rx_vec.push(rx);
}
let (tx_stop, rx_stop) = mpsc::channel();
let rx_stop = Arc::new(Mutex::new(rx_stop));
// A global pending proposals queue. New proposals will be pushed back into the queue, and
// after it's committed by the raft cluster, it will be poped from the queue.
let proposals = Arc::new(Mutex::new(VecDeque::<Proposal>::new()));
let mut handles = Vec::new();
for (i, rx) in rx_vec.into_iter().enumerate() {
// A map[peer_id -> sender]. In the example we create 5 nodes, with ids in [1, 5].
let mailboxes = (1..6u64).zip(tx_vec.iter().cloned()).collect();
let mut node = match i {
// Peer 1 is the leader.
0 => Node::create_raft_leader(1, rx, mailboxes, &logger),
// Other peers are followers.
_ => Node::create_raft_follower(rx, mailboxes),
};
let proposals = Arc::clone(&proposals);
// Tick the raft node per 100ms. So use an `Instant` to trace it.
let mut t = Instant::now();
// Clone the stop receiver
let rx_stop_clone = Arc::clone(&rx_stop);
let logger = logger.clone();
// Here we spawn the node on a new thread and keep a handle so we can join on them later.
let handle = thread::spawn(move || loop {
thread::sleep(Duration::from_millis(10));
loop {
// Step raft messages.
match node.my_mailbox.try_recv() {
Ok(msg) => node.step(msg, &logger),
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => return,
}
}
let raft_group = match node.raft_group {
Some(ref mut r) => r,
// When Node::raft_group is `None` it means the node is not initialized.
_ => continue,
};
if t.elapsed() >= Duration::from_millis(100) {
// Tick the raft.
raft_group.tick();
t = Instant::now();
}
// Let the leader pick pending proposals from the global queue.
if raft_group.raft.state == StateRole::Leader {
// Handle new proposals.
let mut proposals = proposals.lock().unwrap();
for p in proposals.iter_mut().skip_while(|p| p.proposed > 0) {
propose(raft_group, p);
}
}
// Handle readies from the raft.
on_ready(
raft_group,
&mut node.kv_pairs,
&node.mailboxes,
&proposals,
&logger,
);
// Check control signals from
if check_signals(&rx_stop_clone) {
return;
};
});
handles.push(handle);
}
// Propose some conf changes so that followers can be initialized.
add_all_followers(proposals.as_ref());
// Put 100 key-value pairs.
info!(
logger,
"We get a 5 nodes Raft cluster now, now propose 100 proposals"
);
(0..100u16)
.filter(|i| {
let (proposal, rx) = Proposal::normal(*i, "hello, world".to_owned());
proposals.lock().unwrap().push_back(proposal);
// After we got a response from `rx`, we can assume the put succeeded and following
// `get` operations can find the key-value pair.
rx.recv().unwrap()
})
.count();
info!(logger, "Propose 100 proposals success!");
// Send terminate signals
for _ in 0..NUM_NODES {
tx_stop.send(Signal::Terminate).unwrap();
}
// Wait for the thread to finish
for th in handles {
th.join().unwrap();
}
}
enum Signal {
Terminate,
}
fn check_signals(receiver: &Arc<Mutex<mpsc::Receiver<Signal>>>) -> bool {
match receiver.lock().unwrap().try_recv() {
Ok(Signal::Terminate) => true,
Err(TryRecvError::Empty) => false,
Err(TryRecvError::Disconnected) => true,
}
}
struct Node {
// None if the raft is not initialized.
raft_group: Option<RawNode<MemStorage>>,
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
// Key-value pairs after applied. `MemStorage` only contains raft logs,
// so we need an additional storage engine.
kv_pairs: HashMap<u16, String>,
}
impl Node {
// Create a raft leader only with itself in its configuration.
fn create_raft_leader(
id: u64,
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
logger: &slog::Logger,
) -> Self {
let mut cfg = example_config();
cfg.id = id;
let logger = logger.new(o!("tag" => format!("peer_{}", id)));
let storage = MemStorage::new_with_conf_state(ConfState::from((vec![id], vec![])));
let raft_group = Some(RawNode::new(&cfg, storage, &logger).unwrap());
Node {
raft_group,
my_mailbox,
mailboxes,
kv_pairs: Default::default(),
}
}
// Create a raft follower.
fn create_raft_follower(
my_mailbox: Receiver<Message>,
mailboxes: HashMap<u64, Sender<Message>>,
) -> Self {
Node {
raft_group: None,
my_mailbox,
mailboxes,
kv_pairs: Default::default(),
}
}
// Initialize raft for followers.
fn initialize_raft_from_message(&mut self, msg: &Message, logger: &slog::Logger) {
if !is_initial_msg(msg) {
return;
}
let mut cfg = example_config();
cfg.id = msg.to;
let logger = logger.new(o!("tag" => format!("peer_{}", msg.to)));
let storage = MemStorage::new();
self.raft_group = Some(RawNode::new(&cfg, storage, &logger).unwrap());
}
// Step a raft message, initialize the raft if need.
fn step(&mut self, msg: Message, logger: &slog::Logger) {
if self.raft_group.is_none() {
if is_initial_msg(&msg) {
self.initialize_raft_from_message(&msg, &logger);
} else {
return;
}
}
let raft_group = self.raft_group.as_mut().unwrap();
let _ = raft_group.step(msg);
}
}
fn on_ready(
raft_group: &mut RawNode<MemStorage>,
kv_pairs: &mut HashMap<u16, String>,
mailboxes: &HashMap<u64, Sender<Message>>,
proposals: &Mutex<VecDeque<Proposal>>,
logger: &slog::Logger,
) {
if !raft_group.has_ready() {
return;
}
let store = raft_group.raft.raft_log.store.clone();
// Get the `Ready` with `RawNode::ready` interface.
let mut ready = raft_group.ready();
// Persistent raft logs. It's necessary because in `RawNode::advance` we stabilize
// raft logs to the latest position.
if let Err(e) = store.wl().append(ready.entries()) {
error!(
logger,
"persist raft log fail: {:?}, need to retry or panic", e
);
return;
}
// Apply the snapshot. It's necessary because in `RawNode::advance` we stabilize the snapshot.
if *ready.snapshot() != Snapshot::default() {
let s = ready.snapshot().clone();
if let Err(e) = store.wl().apply_snapshot(s) {
error!(
logger,
"apply snapshot fail: {:?}, need to retry or panic", e
);
return;
}
}
// Send out the messages come from the node.
for msg in ready.messages.drain(..) {
let to = msg.to;
if mailboxes[&to].send(msg).is_err() {
error!(
logger,
"send raft message to {} fail, let Raft retry it", to
);
}
}
// Apply all committed proposals.
if let Some(committed_entries) = ready.committed_entries.take() {
for entry in &committed_entries {
if entry.data.is_empty() {
// From new elected leaders.
continue;
}
if let EntryType::EntryConfChange = entry.get_entry_type() {
// For conf change messages, make them effective.
let mut cc = ConfChange::default();
cc.merge_from_bytes(&entry.data).unwrap();
let node_id = cc.node_id;
match cc.get_change_type() {
ConfChangeType::AddNode => raft_group.raft.add_node(node_id).unwrap(),
ConfChangeType::RemoveNode => raft_group.raft.remove_node(node_id).unwrap(),
ConfChangeType::AddLearnerNode => raft_group.raft.add_learner(node_id).unwrap(),
}
let cs = raft_group.raft.prs().configuration().to_conf_state();
store.wl().set_conf_state(cs);
} else {
// For normal proposals, extract the key-value pair and then
// insert them into the kv engine.
let data = str::from_utf8(&entry.data).unwrap();
let reg = Regex::new("put ([0-9]+) (.+)").unwrap();
if let Some(caps) = reg.captures(&data) {
kv_pairs.insert(caps[1].parse().unwrap(), caps[2].to_string());
}
}
if raft_group.raft.state == StateRole::Leader {
// The leader should response to the clients, tell them if their proposals
// succeeded or not.
let proposal = proposals.lock().unwrap().pop_front().unwrap();
proposal.propose_success.send(true).unwrap();
}
}
if let Some(last_committed) = committed_entries.last() {
let mut s = store.wl();
s.mut_hard_state().commit = last_committed.index;
s.mut_hard_state().term = last_committed.term;
}
}
// Call `RawNode::advance` interface to update position flags in the raft.
raft_group.advance(ready);
}
fn example_config() -> Config {
Config {
election_tick: 10,
heartbeat_tick: 3,
..Default::default()
}
}
// The message can be used to initialize a raft node or not.
fn is_initial_msg(msg: &Message) -> bool {
let msg_type = msg.get_msg_type();
msg_type == MessageType::MsgRequestVote
|| msg_type == MessageType::MsgRequestPreVote
|| (msg_type == MessageType::MsgHeartbeat && msg.commit == 0)
}
struct Proposal {
normal: Option<(u16, String)>, // key is an u16 integer, and value is a string.
conf_change: Option<ConfChange>, // conf change.
transfer_leader: Option<u64>,
// If it's proposed, it will be set to the index of the entry.
proposed: u64,
propose_success: SyncSender<bool>,
}
impl Proposal {
fn conf_change(cc: &ConfChange) -> (Self, Receiver<bool>) {
let (tx, rx) = mpsc::sync_channel(1);
let proposal = Proposal {
normal: None,
conf_change: Some(cc.clone()),
transfer_leader: None,
proposed: 0,
propose_success: tx,
};
(proposal, rx)
}
fn normal(key: u16, value: String) -> (Self, Receiver<bool>) {
let (tx, rx) = mpsc::sync_channel(1);
let proposal = Proposal {
normal: Some((key, value)),
conf_change: None,
transfer_leader: None,
proposed: 0,
propose_success: tx,
};
(proposal, rx)
}
}
fn propose(raft_group: &mut RawNode<MemStorage>, proposal: &mut Proposal) {
let last_index1 = raft_group.raft.raft_log.last_index() + 1;
if let Some((ref key, ref value)) = proposal.normal {
let data = format!("put {} {}", key, value).into_bytes();
let _ = raft_group.propose(vec![], data);
} else if let Some(ref cc) = proposal.conf_change {
let _ = raft_group.propose_conf_change(vec![], cc.clone());
} else if let Some(_transferee) = proposal.transfer_leader {
// TODO: implement transfer leader.
unimplemented!();
}
let last_index2 = raft_group.raft.raft_log.last_index() + 1;
if last_index2 == last_index1 {
// Propose failed, don't forget to respond to the client.
proposal.propose_success.send(false).unwrap();
} else {
proposal.proposed = last_index1;
}
}
// Proposes some conf change for peers [2, 5].
fn add_all_followers(proposals: &Mutex<VecDeque<Proposal>>) {
for i in 2..6u64 {
let mut conf_change = ConfChange::default();
conf_change.node_id = i;
conf_change.set_change_type(ConfChangeType::AddNode);
loop {
let (proposal, rx) = Proposal::conf_change(&conf_change);
proposals.lock().unwrap().push_back(proposal);
if rx.recv().unwrap() {
break;
}
thread::sleep(Duration::from_millis(100));
}
}
}
# ϩⲟⲩⲣⲁⲧⲉ
/hɔwratɛ/, Sadhidic Coptic for *guardians*.
## A distributed uptime notification system
There are certainly many tools to identify uptime of systems out there, although I'd prefer one that worked completely in house and was pretty minimal, but smart.
Additionally, I want to learn about consensus protocols and gRPC, so this seemed to make a good deal of sense for a little project.
---
The aim is simple: a microservice that runs on all of my VPS's, my NAS and any other machines in my network (some of which are acceptable to be down at any point in time, but can be a part of the collective when up).
Everyone knows who should be awake and when, if that isn't the case, make sure everyone agrees and send me a notification.
If there is no consensus, then attempt to trace any connectivity issue and alert me of what is known.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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]
name = "howrate"
version = "0.1.0"
authors = ["Tim DuBois <tim@neophilus.net>"]
edition = "2018"
[dependencies]
raft = { version = "0.6.0-alpha", features = ["default"] }
protobuf = "2"
regex = "1.1"
slog = "2.2"
slog-stdlog = "4"
slog-envlogger = "2.1.0"
slog-term = "2.4.0"
slog-async = "2.3.0"
[patch.crates-io]
raft = { git = 'https://github.com/tikv/raft-rs' }