lib.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. extern crate bincode;
  2. extern crate futures_channel;
  3. extern crate futures_util;
  4. extern crate labrpc;
  5. extern crate rand;
  6. #[macro_use]
  7. extern crate serde_derive;
  8. extern crate tokio;
  9. use std::convert::TryFrom;
  10. use std::sync::atomic::{AtomicBool, Ordering};
  11. use std::sync::Arc;
  12. use std::time::Duration;
  13. use crossbeam_utils::sync::WaitGroup;
  14. use parking_lot::{Condvar, Mutex};
  15. use crate::apply_command::ApplyCommandFnMut;
  16. pub use crate::apply_command::ApplyCommandMessage;
  17. use crate::daemon_env::{DaemonEnv, ThreadEnv};
  18. use crate::election::ElectionState;
  19. use crate::index_term::IndexTerm;
  20. use crate::persister::PersistedRaftState;
  21. pub use crate::persister::Persister;
  22. pub(crate) use crate::raft_state::RaftState;
  23. pub(crate) use crate::raft_state::State;
  24. pub use crate::rpcs::RpcClient;
  25. pub use crate::snapshot::Snapshot;
  26. use crate::snapshot::{RequestSnapshotFnMut, SnapshotDaemon};
  27. mod apply_command;
  28. mod daemon_env;
  29. mod election;
  30. mod heartbeats;
  31. mod index_term;
  32. mod log_array;
  33. mod persister;
  34. mod process_append_entries;
  35. mod process_install_snapshot;
  36. mod process_request_vote;
  37. mod raft_state;
  38. pub mod rpcs;
  39. mod snapshot;
  40. mod sync_log_entries;
  41. pub mod utils;
  42. #[derive(
  43. Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize,
  44. )]
  45. pub struct Term(pub usize);
  46. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
  47. struct Peer(usize);
  48. pub type Index = usize;
  49. #[derive(Clone, Debug, Serialize, Deserialize)]
  50. struct LogEntry<Command> {
  51. index: Index,
  52. term: Term,
  53. command: Command,
  54. }
  55. #[derive(Clone)]
  56. pub struct Raft<Command> {
  57. inner_state: Arc<Mutex<RaftState<Command>>>,
  58. peers: Vec<Arc<RpcClient>>,
  59. me: Peer,
  60. persister: Arc<dyn Persister>,
  61. new_log_entry: Option<std::sync::mpsc::Sender<Option<Peer>>>,
  62. apply_command_signal: Arc<Condvar>,
  63. keep_running: Arc<AtomicBool>,
  64. election: Arc<ElectionState>,
  65. snapshot_daemon: SnapshotDaemon,
  66. thread_pool: Arc<tokio::runtime::Runtime>,
  67. daemon_env: DaemonEnv,
  68. stop_wait_group: WaitGroup,
  69. }
  70. #[derive(Clone, Debug, Serialize, Deserialize)]
  71. struct RequestVoteArgs {
  72. term: Term,
  73. candidate_id: Peer,
  74. last_log_index: Index,
  75. last_log_term: Term,
  76. }
  77. #[derive(Clone, Debug, Serialize, Deserialize)]
  78. struct RequestVoteReply {
  79. term: Term,
  80. vote_granted: bool,
  81. }
  82. #[derive(Clone, Debug, Serialize, Deserialize)]
  83. struct AppendEntriesArgs<Command> {
  84. term: Term,
  85. leader_id: Peer,
  86. prev_log_index: Index,
  87. prev_log_term: Term,
  88. entries: Vec<LogEntry<Command>>,
  89. leader_commit: Index,
  90. }
  91. #[derive(Clone, Debug, Serialize, Deserialize)]
  92. struct AppendEntriesReply {
  93. term: Term,
  94. success: bool,
  95. committed: Option<IndexTerm>,
  96. }
  97. #[derive(Clone, Debug, Serialize, Deserialize)]
  98. struct InstallSnapshotArgs {
  99. pub(crate) term: Term,
  100. leader_id: Peer,
  101. pub(crate) last_included_index: Index,
  102. last_included_term: Term,
  103. // TODO(ditsing): Serde cannot handle Vec<u8> as efficient as expected.
  104. data: Vec<u8>,
  105. offset: usize,
  106. done: bool,
  107. }
  108. #[derive(Clone, Debug, Serialize, Deserialize)]
  109. struct InstallSnapshotReply {
  110. term: Term,
  111. committed: Option<IndexTerm>,
  112. }
  113. // Commands must be
  114. // 0. 'static: they have to live long enough for thread pools.
  115. // 1. clone: they are put in vectors and request messages.
  116. // 2. serializable: they are sent over RPCs and persisted.
  117. // 3. deserializable: they are restored from storage.
  118. // 4. send: they are referenced in futures.
  119. // 5. default, because we need an element for the first entry.
  120. impl<Command> Raft<Command>
  121. where
  122. Command: 'static
  123. + Clone
  124. + serde::Serialize
  125. + serde::de::DeserializeOwned
  126. + Send
  127. + Default,
  128. {
  129. /// Create a new raft instance.
  130. ///
  131. /// Each instance will create at least 4 + (number of peers) threads. The
  132. /// extensive usage of threads is to minimize latency.
  133. pub fn new(
  134. peers: Vec<RpcClient>,
  135. me: usize,
  136. persister: Arc<dyn Persister>,
  137. apply_command: impl ApplyCommandFnMut<Command>,
  138. max_state_size_bytes: Option<usize>,
  139. request_snapshot: impl RequestSnapshotFnMut,
  140. ) -> Self {
  141. let peer_size = peers.len();
  142. assert!(peer_size > me, "My index should be smaller than peer size.");
  143. let mut state = RaftState::create(peer_size, Peer(me));
  144. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT: Initially
  145. // commit_index = log.start() and commit_index + 1 = log.end(). Thus
  146. // log.start() <= commit_index and commit_index < log.end() both hold.
  147. assert_eq!(state.commit_index + 1, state.log.end());
  148. if let Ok(persisted_state) =
  149. PersistedRaftState::try_from(persister.read_state())
  150. {
  151. state.current_term = persisted_state.current_term;
  152. state.voted_for = persisted_state.voted_for;
  153. state.log = persisted_state.log;
  154. state.commit_index = state.log.start();
  155. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT: the saved
  156. // snapshot must have a valid log.start() and log.end(). Thus
  157. // log.start() <= commit_index and commit_index < log.end() hold.
  158. assert!(state.commit_index < state.log.end());
  159. }
  160. let election = ElectionState::create();
  161. election.reset_election_timer();
  162. let daemon_env = DaemonEnv::create();
  163. let thread_env = daemon_env.for_thread();
  164. let thread_pool = tokio::runtime::Builder::new_multi_thread()
  165. .enable_time()
  166. .thread_name(format!("raft-instance-{}", me))
  167. .worker_threads(peer_size)
  168. .on_thread_start(move || thread_env.clone().attach())
  169. .on_thread_stop(ThreadEnv::detach)
  170. .build()
  171. .expect("Creating thread pool should not fail");
  172. let peers = peers.into_iter().map(Arc::new).collect();
  173. let mut this = Raft {
  174. inner_state: Arc::new(Mutex::new(state)),
  175. peers,
  176. me: Peer(me),
  177. persister,
  178. new_log_entry: None,
  179. apply_command_signal: Arc::new(Default::default()),
  180. keep_running: Arc::new(Default::default()),
  181. election: Arc::new(election),
  182. snapshot_daemon: Default::default(),
  183. thread_pool: Arc::new(thread_pool),
  184. daemon_env,
  185. stop_wait_group: WaitGroup::new(),
  186. };
  187. this.keep_running.store(true, Ordering::SeqCst);
  188. // Running in a standalone thread.
  189. this.run_snapshot_daemon(max_state_size_bytes, request_snapshot);
  190. // Running in a standalone thread.
  191. this.run_log_entry_daemon();
  192. // Running in a standalone thread.
  193. this.run_apply_command_daemon(apply_command);
  194. // One off function that schedules many little tasks, running on the
  195. // internal thread pool.
  196. this.schedule_heartbeats(Duration::from_millis(
  197. HEARTBEAT_INTERVAL_MILLIS,
  198. ));
  199. // The last step is to start running election timer.
  200. this.run_election_timer();
  201. this
  202. }
  203. }
  204. // Command must be
  205. // 0. 'static: Raft<Command> must be 'static, it is moved to another thread.
  206. // 1. clone: they are copied to the persister.
  207. // 2. send: Arc<Mutex<Vec<LogEntry<Command>>>> must be send, it is moved to another thread.
  208. // 3. serialize: they are converted to bytes to persist.
  209. // 4. default: a default value is used as the first element of log.
  210. impl<Command> Raft<Command>
  211. where
  212. Command: 'static + Clone + Send + serde::Serialize + Default,
  213. {
  214. /// Adds a new command to the log, returns its index and the current term.
  215. ///
  216. /// Returns `None` if we are not the leader. The log entry may not have been
  217. /// committed to the log when this method returns. When and if it is
  218. /// committed, the `apply_command` callback will be called.
  219. pub fn start(&self, command: Command) -> Option<(Term, Index)> {
  220. let mut rf = self.inner_state.lock();
  221. let term = rf.current_term;
  222. if !rf.is_leader() {
  223. return None;
  224. }
  225. let index = rf.log.add_command(term, command);
  226. self.persister.save_state(rf.persisted_state().into());
  227. let _ = self.new_log_entry.clone().unwrap().send(None);
  228. Some((term, index))
  229. }
  230. /// Cleanly shutdown this instance. This function never blocks forever. It
  231. /// either panics or returns eventually.
  232. pub fn kill(mut self) {
  233. self.keep_running.store(false, Ordering::SeqCst);
  234. self.election.stop_election_timer();
  235. self.new_log_entry.take().map(|n| n.send(None));
  236. self.apply_command_signal.notify_all();
  237. self.snapshot_daemon.kill();
  238. self.stop_wait_group.wait();
  239. std::sync::Arc::try_unwrap(self.thread_pool)
  240. .expect(
  241. "All references to the thread pool should have been dropped.",
  242. )
  243. .shutdown_timeout(Duration::from_millis(
  244. HEARTBEAT_INTERVAL_MILLIS * 2,
  245. ));
  246. // DaemonEnv must be shutdown after the thread pool, since there might
  247. // be tasks logging errors in the pool.
  248. self.daemon_env.shutdown();
  249. }
  250. /// Returns the current term and whether we are the leader.
  251. ///
  252. /// Take a quick peek at the current state of this instance. The returned
  253. /// value is stale as soon as this function returns.
  254. pub fn get_state(&self) -> (Term, bool) {
  255. let state = self.inner_state.lock();
  256. (state.current_term, state.is_leader())
  257. }
  258. }
  259. pub(crate) const HEARTBEAT_INTERVAL_MILLIS: u64 = 150;
  260. impl<C> Raft<C> {
  261. /// Pass this function to [`Raft::new`] if the application will not accept
  262. /// any request for taking snapshots.
  263. pub const NO_SNAPSHOT: fn(Index) = |_| {};
  264. }