raft.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. use std::sync::atomic::{AtomicBool, Ordering};
  2. use std::sync::Arc;
  3. use std::time::Duration;
  4. use crossbeam_utils::sync::WaitGroup;
  5. use parking_lot::{Condvar, Mutex};
  6. use serde_derive::{Deserialize, Serialize};
  7. use crate::apply_command::ApplyCommandFnMut;
  8. use crate::daemon_env::{DaemonEnv, ThreadEnv};
  9. use crate::daemon_watch::{Daemon, DaemonWatch};
  10. use crate::election::ElectionState;
  11. use crate::heartbeats::{HeartbeatsDaemon, HEARTBEAT_INTERVAL};
  12. use crate::persister::PersistedRaftState;
  13. use crate::remote_context::RemoteContext;
  14. use crate::remote_peer::RemotePeer;
  15. use crate::snapshot::{RequestSnapshotFnMut, SnapshotDaemon};
  16. use crate::sync_log_entries::SyncLogEntriesComms;
  17. use crate::term_marker::TermMarker;
  18. use crate::verify_authority::VerifyAuthorityDaemon;
  19. use crate::{IndexTerm, Persister, RaftState, RemoteRaft, ReplicableCommand};
  20. #[derive(
  21. Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize,
  22. )]
  23. pub struct Term(pub usize);
  24. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
  25. pub struct Peer(pub usize);
  26. #[derive(Clone)]
  27. pub struct Raft<Command> {
  28. pub(crate) inner_state: Arc<Mutex<RaftState<Command>>>,
  29. pub(crate) peers: Vec<Peer>,
  30. pub(crate) me: Peer,
  31. pub(crate) persister: Arc<dyn Persister>,
  32. pub(crate) sync_log_entries_comms: SyncLogEntriesComms,
  33. pub(crate) apply_command_signal: Arc<Condvar>,
  34. pub(crate) keep_running: Arc<AtomicBool>,
  35. pub(crate) election: Arc<ElectionState>,
  36. pub(crate) snapshot_daemon: SnapshotDaemon,
  37. pub(crate) verify_authority_daemon: VerifyAuthorityDaemon,
  38. pub(crate) heartbeats_daemon: HeartbeatsDaemon,
  39. pub(crate) thread_pool: tokio::runtime::Handle,
  40. pub(crate) daemon_env: DaemonEnv,
  41. stop_wait_group: WaitGroup,
  42. join_handle: Arc<Mutex<Option<RaftJoinHandle>>>,
  43. }
  44. impl<Command: ReplicableCommand> Raft<Command> {
  45. /// Create a new raft instance.
  46. ///
  47. /// Each instance will create at least 4 + (number of peers) threads. The
  48. /// extensive usage of threads is to minimize latency.
  49. pub fn new(
  50. peers: Vec<impl RemoteRaft<Command> + 'static>,
  51. me: usize,
  52. persister: Arc<dyn Persister>,
  53. apply_command: impl ApplyCommandFnMut<Command>,
  54. max_state_size_bytes: Option<usize>,
  55. request_snapshot: impl RequestSnapshotFnMut,
  56. ) -> Self {
  57. let peer_size = peers.len();
  58. assert!(peer_size > me, "My index should be smaller than peer size.");
  59. let mut state = RaftState::create(peer_size, Peer(me));
  60. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT: Initially
  61. // commit_index = log.start() and commit_index + 1 = log.end(). Thus
  62. // log.start() <= commit_index and commit_index < log.end() both hold.
  63. assert_eq!(state.commit_index + 1, state.log.end());
  64. if let Ok(persisted_state) =
  65. PersistedRaftState::try_from(persister.read_state())
  66. {
  67. state.current_term = persisted_state.current_term;
  68. state.voted_for = persisted_state.voted_for;
  69. state.log = persisted_state.log;
  70. state.commit_index = state.log.start();
  71. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT: the saved
  72. // snapshot must have a valid log.start() and log.end(). Thus
  73. // log.start() <= commit_index and commit_index < log.end() hold.
  74. assert!(state.commit_index < state.log.end());
  75. state
  76. .log
  77. .validate(state.current_term)
  78. .expect("Persisted log should not contain error");
  79. }
  80. let inner_state = Arc::new(Mutex::new(state));
  81. let election = Arc::new(ElectionState::create());
  82. election.reset_election_timer();
  83. let term_marker = TermMarker::create(
  84. inner_state.clone(),
  85. election.clone(),
  86. persister.clone(),
  87. );
  88. let verify_authority_daemon = VerifyAuthorityDaemon::create(peer_size);
  89. let remote_peers = peers
  90. .into_iter()
  91. .enumerate()
  92. .map(|(index, remote_raft)| {
  93. RemotePeer::create(
  94. Peer(index),
  95. remote_raft,
  96. verify_authority_daemon.beat_ticker(index),
  97. )
  98. })
  99. .collect();
  100. let context = RemoteContext::create(term_marker, remote_peers);
  101. let daemon_env = DaemonEnv::create();
  102. let thread_env = daemon_env.for_thread();
  103. let thread_pool = tokio::runtime::Builder::new_multi_thread()
  104. .enable_time()
  105. .enable_io()
  106. .thread_name(format!("raft-instance-{}", me))
  107. .worker_threads(peer_size)
  108. .on_thread_start(move || {
  109. context.clone().attach();
  110. thread_env.clone().attach();
  111. })
  112. .on_thread_stop(move || {
  113. RemoteContext::<Command>::detach();
  114. ThreadEnv::detach();
  115. })
  116. .build()
  117. .expect("Creating thread pool should not fail");
  118. let peers = (0..peer_size).filter(|p| *p != me).map(Peer).collect();
  119. let (sync_log_entries_comms, sync_log_entries_daemon) =
  120. crate::sync_log_entries::create(peer_size);
  121. let mut this = Raft {
  122. inner_state,
  123. peers,
  124. me: Peer(me),
  125. persister,
  126. sync_log_entries_comms,
  127. apply_command_signal: Arc::new(Condvar::new()),
  128. keep_running: Arc::new(AtomicBool::new(true)),
  129. election,
  130. snapshot_daemon: SnapshotDaemon::create(),
  131. verify_authority_daemon,
  132. heartbeats_daemon: HeartbeatsDaemon::create(),
  133. thread_pool: thread_pool.handle().clone(),
  134. stop_wait_group: WaitGroup::new(),
  135. daemon_env: daemon_env.clone(),
  136. // The join handle will be created later.
  137. join_handle: Arc::new(Mutex::new(None)),
  138. };
  139. let mut daemon_watch = DaemonWatch::create(daemon_env.for_thread());
  140. // Running in a standalone thread.
  141. let verify_authority_daemon = this.run_verify_authority_daemon();
  142. daemon_watch
  143. .create_daemon(Daemon::VerifyAuthority, verify_authority_daemon);
  144. // Running in a standalone thread.
  145. let snapshot_daemon =
  146. this.run_snapshot_daemon(max_state_size_bytes, request_snapshot);
  147. daemon_watch.create_daemon(Daemon::Snapshot, snapshot_daemon);
  148. // Running in a standalone thread.
  149. let sync_log_entry_daemon =
  150. this.run_log_entry_daemon(sync_log_entries_daemon);
  151. daemon_watch
  152. .create_daemon(Daemon::SyncLogEntries, sync_log_entry_daemon);
  153. // Running in a standalone thread.
  154. let apply_command_daemon = this.run_apply_command_daemon(apply_command);
  155. daemon_watch.create_daemon(Daemon::ApplyCommand, apply_command_daemon);
  156. // One off function that schedules many little tasks, running on the
  157. // internal thread pool.
  158. this.schedule_heartbeats(HEARTBEAT_INTERVAL);
  159. // The last step is to start running election timer.
  160. daemon_watch.create_daemon(Daemon::ElectionTimer, {
  161. let raft = this.clone();
  162. move || raft.run_election_timer()
  163. });
  164. // Create the join handle
  165. this.join_handle.lock().replace(RaftJoinHandle {
  166. stop_wait_group: this.stop_wait_group.clone(),
  167. thread_pool,
  168. daemon_watch,
  169. daemon_env,
  170. });
  171. this
  172. }
  173. }
  174. // Command must be
  175. // 0. 'static: Raft<Command> must be 'static, it is moved to another thread.
  176. // 1. clone: they are copied to the persister.
  177. // 2. send: Arc<Mutex<Vec<LogEntry<Command>>>> must be send, it is moved to another thread.
  178. // 3. serialize: they are converted to bytes to persist.
  179. impl<Command: ReplicableCommand> Raft<Command> {
  180. /// Adds a new command to the log, returns its index and the current term.
  181. ///
  182. /// Returns `None` if we are not the leader. The log entry may not have been
  183. /// committed to the log when this method returns. When and if it is
  184. /// committed, the `apply_command` callback will be called.
  185. pub fn start(&self, command: Command) -> Option<IndexTerm> {
  186. let _guard = self.daemon_env.for_scope();
  187. let mut rf = self.inner_state.lock();
  188. let term = rf.current_term;
  189. if !rf.is_leader() {
  190. return None;
  191. }
  192. let index = rf.log.add_command(term, command);
  193. self.persister.save_state(rf.persisted_state().into());
  194. self.sync_log_entries_comms.update_followers(index);
  195. log::info!("{:?} started new entry at {} {:?}", self.me, index, term);
  196. Some(IndexTerm::pack(index, term))
  197. }
  198. /// Cleanly shutdown this instance. This function never blocks forever. It
  199. /// either panics or returns eventually.
  200. pub fn kill(self) -> RaftJoinHandle {
  201. self.keep_running.store(false, Ordering::Release);
  202. self.election.stop_election_timer();
  203. self.sync_log_entries_comms.kill();
  204. self.apply_command_signal.notify_all();
  205. self.snapshot_daemon.kill();
  206. self.verify_authority_daemon.kill();
  207. self.join_handle.lock().take().unwrap()
  208. }
  209. /// Returns the current term and whether we are the leader.
  210. ///
  211. /// Take a quick peek at the current state of this instance. The returned
  212. /// value is stale as soon as this function returns.
  213. pub fn get_state(&self) -> (Term, bool) {
  214. let state = self.inner_state.lock();
  215. (state.current_term, state.is_leader())
  216. }
  217. }
  218. /// A join handle returned by `Raft::kill()`. Join this handle to cleanly
  219. /// shutdown a Raft instance.
  220. ///
  221. /// All clones of the same Raft instance created by `Raft::clone()` must be
  222. /// dropped before `RaftJoinHandle::join()` can return.
  223. ///
  224. /// After `RaftJoinHandle::join()` returns, all threads and thread pools created
  225. /// by this Raft instance will have stopped. No callbacks will be called. No new
  226. /// commits will be created by this Raft instance.
  227. #[must_use]
  228. pub struct RaftJoinHandle {
  229. stop_wait_group: WaitGroup,
  230. thread_pool: tokio::runtime::Runtime,
  231. daemon_watch: DaemonWatch,
  232. daemon_env: DaemonEnv,
  233. }
  234. impl RaftJoinHandle {
  235. const SHUTDOWN_TIMEOUT: Duration =
  236. Duration::from_millis(HEARTBEAT_INTERVAL.as_millis() as u64 * 2);
  237. /// Waits for the Raft instance to shutdown.
  238. ///
  239. /// See the struct documentation for more details.
  240. pub fn join(self) {
  241. // Wait for all Raft instances to be dropped.
  242. self.stop_wait_group.wait();
  243. self.daemon_watch.wait_for_daemons();
  244. self.thread_pool.shutdown_timeout(Self::SHUTDOWN_TIMEOUT);
  245. // DaemonEnv must be shutdown after the thread pool, since there might
  246. // be tasks logging errors in the pool.
  247. self.daemon_env.shutdown();
  248. }
  249. }
  250. #[cfg(test)]
  251. mod tests {
  252. use crate::utils::do_nothing::{DoNothingPersister, DoNothingRemoteRaft};
  253. use crate::ApplyCommandMessage;
  254. use super::*;
  255. #[test]
  256. fn test_raft_must_sync() {
  257. let optional_raft: Option<super::Raft<i32>> = None;
  258. fn must_sync<T: Sync>(value: T) {
  259. drop(value)
  260. }
  261. must_sync(optional_raft)
  262. // The following raft is not Sync.
  263. // let optional_raft: Option<super::Raft<std::rc::Rc<i32>>> = None;
  264. }
  265. #[test]
  266. fn test_no_me_in_peers() {
  267. let peer_size = 5;
  268. let me = 2;
  269. let raft = Raft::new(
  270. vec![DoNothingRemoteRaft {}; peer_size],
  271. me,
  272. Arc::new(DoNothingPersister {}),
  273. |_: ApplyCommandMessage<i32>| {},
  274. None,
  275. |_| {},
  276. );
  277. assert_eq!(4, raft.peers.len());
  278. for peer in &raft.peers {
  279. assert_ne!(peer.0, me);
  280. }
  281. }
  282. }