lib.rs 10 KB

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