raft.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. use crossbeam_utils::sync::WaitGroup;
  2. use std::sync::atomic::{AtomicBool, Ordering};
  3. use std::sync::Arc;
  4. use std::time::Duration;
  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).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. let election_timer = this.run_election_timer();
  161. daemon_watch.create_daemon(Daemon::ElectionTimer, election_timer);
  162. // Create the join handle
  163. this.join_handle.lock().replace(RaftJoinHandle {
  164. stop_wait_group: this.stop_wait_group.clone(),
  165. thread_pool,
  166. daemon_watch,
  167. daemon_env,
  168. });
  169. this
  170. }
  171. }
  172. // Command must be
  173. // 0. 'static: Raft<Command> must be 'static, it is moved to another thread.
  174. // 1. clone: they are copied to the persister.
  175. // 2. send: Arc<Mutex<Vec<LogEntry<Command>>>> must be send, it is moved to another thread.
  176. // 3. serialize: they are converted to bytes to persist.
  177. impl<Command: ReplicableCommand> Raft<Command> {
  178. /// Adds a new command to the log, returns its index and the current term.
  179. ///
  180. /// Returns `None` if we are not the leader. The log entry may not have been
  181. /// committed to the log when this method returns. When and if it is
  182. /// committed, the `apply_command` callback will be called.
  183. pub fn start(&self, command: Command) -> Option<IndexTerm> {
  184. let _guard = self.daemon_env.for_scope();
  185. let mut rf = self.inner_state.lock();
  186. let term = rf.current_term;
  187. if !rf.is_leader() {
  188. return None;
  189. }
  190. let index = rf.log.add_command(term, command);
  191. self.persister.save_state(rf.persisted_state().into());
  192. self.sync_log_entries_comms.update_followers(index);
  193. log::info!("{:?} started new entry at {} {:?}", self.me, index, term);
  194. Some(IndexTerm::pack(index, term))
  195. }
  196. /// Cleanly shutdown this instance. This function never blocks forever. It
  197. /// either panics or returns eventually.
  198. pub fn kill(self) -> RaftJoinHandle {
  199. self.keep_running.store(false, Ordering::Release);
  200. self.election.stop_election_timer();
  201. self.sync_log_entries_comms.kill();
  202. self.apply_command_signal.notify_all();
  203. self.snapshot_daemon.kill();
  204. self.verify_authority_daemon.kill();
  205. self.join_handle.lock().take().unwrap()
  206. }
  207. /// Returns the current term and whether we are the leader.
  208. ///
  209. /// Take a quick peek at the current state of this instance. The returned
  210. /// value is stale as soon as this function returns.
  211. pub fn get_state(&self) -> (Term, bool) {
  212. let state = self.inner_state.lock();
  213. (state.current_term, state.is_leader())
  214. }
  215. }
  216. /// A join handle returned by `Raft::kill()`. Join this handle to cleanly
  217. /// shutdown a Raft instance.
  218. ///
  219. /// All clones of the same Raft instance created by `Raft::clone()` must be
  220. /// dropped before `RaftJoinHandle::join()` can return.
  221. ///
  222. /// After `RaftJoinHandle::join()` returns, all threads and thread pools created
  223. /// by this Raft instance will have stopped. No callbacks will be called. No new
  224. /// commits will be created by this Raft instance.
  225. #[must_use]
  226. pub struct RaftJoinHandle {
  227. stop_wait_group: WaitGroup,
  228. thread_pool: tokio::runtime::Runtime,
  229. daemon_watch: DaemonWatch,
  230. daemon_env: DaemonEnv,
  231. }
  232. impl RaftJoinHandle {
  233. const SHUTDOWN_TIMEOUT: Duration =
  234. Duration::from_millis(HEARTBEAT_INTERVAL.as_millis() as u64 * 2);
  235. /// Waits for the Raft instance to shutdown.
  236. ///
  237. /// See the struct documentation for more details.
  238. pub fn join(self) {
  239. // Wait for all Raft instances to be dropped.
  240. self.stop_wait_group.wait();
  241. self.daemon_watch.wait_for_daemons();
  242. self.thread_pool.shutdown_timeout(Self::SHUTDOWN_TIMEOUT);
  243. // DaemonEnv must be shutdown after the thread pool, since there might
  244. // be tasks logging errors in the pool.
  245. self.daemon_env.shutdown();
  246. }
  247. }
  248. #[cfg(test)]
  249. mod tests {
  250. #[test]
  251. fn test_raft_must_sync() {
  252. let optional_raft: Option<super::Raft<i32>> = None;
  253. fn must_sync<T: Sync>(value: T) {
  254. drop(value)
  255. }
  256. must_sync(optional_raft)
  257. // The following raft is not Sync.
  258. // let optional_raft: Option<super::Raft<std::rc::Rc<i32>>> = None;
  259. }
  260. }