election.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. use std::sync::atomic::Ordering;
  2. use std::sync::Arc;
  3. use std::time::{Duration, Instant};
  4. use parking_lot::{Condvar, Mutex};
  5. use rand::{thread_rng, Rng};
  6. use crate::term_marker::TermMarker;
  7. use crate::utils::{retry_rpc, RPC_DEADLINE};
  8. use crate::{Peer, Raft, RaftState, RequestVoteArgs, RpcClient, State, Term};
  9. #[derive(Default)]
  10. pub(crate) struct ElectionState {
  11. // Timer will be removed upon shutdown or elected.
  12. timer: Mutex<(usize, Option<Instant>)>,
  13. // Wake up the timer thread when the timer is reset or cancelled.
  14. signal: Condvar,
  15. }
  16. const ELECTION_TIMEOUT_BASE_MILLIS: u64 = 150;
  17. const ELECTION_TIMEOUT_VAR_MILLIS: u64 = 250;
  18. impl ElectionState {
  19. pub(crate) fn create() -> Self {
  20. Self {
  21. timer: Mutex::new((0, None)),
  22. signal: Condvar::new(),
  23. }
  24. }
  25. pub(crate) fn reset_election_timer(&self) {
  26. let mut guard = self.timer.lock();
  27. guard.0 += 1;
  28. guard.1.replace(Self::election_timeout());
  29. self.signal.notify_one();
  30. }
  31. fn try_reset_election_timer(&self, timer_count: usize) -> bool {
  32. let mut guard = self.timer.lock();
  33. if guard.0 != timer_count {
  34. return false;
  35. }
  36. guard.0 += 1;
  37. guard.1.replace(Self::election_timeout());
  38. self.signal.notify_one();
  39. true
  40. }
  41. fn election_timeout() -> Instant {
  42. Instant::now()
  43. + Duration::from_millis(
  44. ELECTION_TIMEOUT_BASE_MILLIS
  45. + thread_rng().gen_range(0..ELECTION_TIMEOUT_VAR_MILLIS),
  46. )
  47. }
  48. pub(crate) fn stop_election_timer(&self) {
  49. let mut guard = self.timer.lock();
  50. guard.0 += 1;
  51. guard.1.take();
  52. self.signal.notify_one();
  53. }
  54. }
  55. // Command must be
  56. // 0. 'static: Raft<Command> must be 'static, it is moved to another thread.
  57. // 1. clone: they are copied to the persister.
  58. // 2. send: Arc<Mutex<Vec<LogEntry<Command>>>> must be send, it is moved to another thread.
  59. // 3. serialize: they are converted to bytes to persist.
  60. impl<Command> Raft<Command>
  61. where
  62. Command: 'static + Clone + Send + serde::Serialize,
  63. {
  64. /// Runs the election timer daemon that triggers elections.
  65. ///
  66. /// The daemon holds a counter and an optional deadline in a mutex. Each
  67. /// time the timer is reset, the counter is increased by one. The deadline
  68. /// will be replaced with a randomized timeout. No other data is held.
  69. ///
  70. /// The daemon runs in a loop. In each iteration, the timer either fires, or
  71. /// is reset. At the beginning of each iteration, a new election will be
  72. /// started if
  73. /// 1. In the last iteration, the timer fired, and
  74. /// 2. Since the fired timer was set until now, the timer has not been
  75. /// reset, i.e. the counter has not been updated.
  76. ///
  77. /// If both conditions are met, an election is started. We keep a cancel
  78. /// token for the running election. Canceling is a courtesy and does not
  79. /// impact correctness. A should-have-been-cancelled election would cancel
  80. /// itself after counting enough votes ("term has changed").
  81. ///
  82. /// In each election, the first thing that happens is resetting the election
  83. /// timer. This reset and condition 2 above is tested and applied in the
  84. /// same atomic operation. Then one RPC is sent to each peer, asking for a
  85. /// vote. A task is created to wait for those RPCs to return and then count
  86. /// the votes.
  87. ///
  88. /// At the same time, the daemon locks the counter and the timeout. It
  89. /// expects the counter to increase by 1 but no more than that. If that
  90. /// expectation is not met, the daemon knows the election either did not
  91. /// happen, or the timer has been reset after the election starts. In that
  92. /// case it considers the timer not fired and skips the wait described
  93. /// below.
  94. ///
  95. /// If the expectation is met, the daemon waits util the timer fires, or
  96. /// the timer is reset, which ever happens first. If both happen when daemon
  97. /// wakes up, the reset takes precedence and the timer is considered not
  98. /// fired. The result (timer fired or is reset) is recorded so that it could
  99. /// be used in the next iteration.
  100. ///
  101. /// The daemon cancels the running election after waking up, no matter what
  102. /// happens. The iteration ends here.
  103. ///
  104. /// Before the first iteration, the timer is considered reset and not fired.
  105. ///
  106. /// The vote-counting task operates independently of the daemon. If it
  107. /// collects enough votes and the term has not yet passed, it resets the
  108. /// election timer. There could be more than one vote-counting tasks running
  109. /// at the same time, but all earlier tasks except the newest one will
  110. /// eventually realize the term they were competing for has passed and quit.
  111. pub(crate) fn run_election_timer(&self) {
  112. let this = self.clone();
  113. let join_handle = std::thread::spawn(move || {
  114. // Note: do not change this to `let _ = ...`.
  115. let _guard = this.daemon_env.for_scope();
  116. let election = this.election.clone();
  117. let mut should_run = None;
  118. while this.keep_running.load(Ordering::SeqCst) {
  119. let mut cancel_handle = should_run
  120. .map(|last_timer_count| this.run_election(last_timer_count))
  121. .flatten();
  122. let mut guard = election.timer.lock();
  123. let (timer_count, deadline) = *guard;
  124. // If the timer is reset
  125. // 0. Zero times. We know should_run is None. If should_run has
  126. // a value, the election would have been started and the timer
  127. // reset by the election. That means the timer did not fire in
  128. // the last iteration. We should just wait.
  129. // 1. One time. We know that the timer is either reset by the
  130. // election or by someone else before the election, in which
  131. // case the election was never started. We should just wait.
  132. // 2. More than one time. We know that the timer is first reset
  133. // by the election, and then reset by someone else, in that
  134. // order. We should cancel the election and just wait.
  135. if let Some(last_timer_count) = should_run {
  136. assert!(timer_count >= last_timer_count + 1);
  137. // If the timer was changed more than once, we know the
  138. // last scheduled election should have been cancelled.
  139. if timer_count > last_timer_count + 1 {
  140. cancel_handle.take().map(|c| c.send(()));
  141. }
  142. }
  143. // check the running signal before sleeping. We are holding the
  144. // timer lock, so no one can change it. The kill() method will
  145. // not be able to notify this thread before `wait` is called.
  146. if !this.keep_running.load(Ordering::SeqCst) {
  147. break;
  148. }
  149. should_run = match deadline {
  150. Some(timeout) => loop {
  151. let ret =
  152. election.signal.wait_until(&mut guard, timeout);
  153. let fired = ret.timed_out() && Instant::now() > timeout;
  154. // If the timer has been updated, do not schedule,
  155. // break so that we could cancel.
  156. if timer_count != guard.0 {
  157. // Timer has been updated, cancel current
  158. // election, and block on timeout again.
  159. break None;
  160. } else if fired {
  161. // Timer has fired, remove the timer and allow
  162. // running the next election at timer_count.
  163. // If the next election is cancelled before we
  164. // are back on wait, timer_count will be set to
  165. // a different value.
  166. guard.0 += 1;
  167. guard.1.take();
  168. break Some(guard.0);
  169. }
  170. },
  171. None => {
  172. election.signal.wait(&mut guard);
  173. // The timeout has changed, check again.
  174. None
  175. }
  176. };
  177. drop(guard);
  178. // Whenever woken up, cancel the current running election.
  179. // There are 3 cases we could reach here
  180. // 1. We received an AppendEntries, or decided to vote for
  181. // a peer, and thus turned into a follower. In this case we'll
  182. // be notified by the election signal.
  183. // 2. We are a follower but didn't receive a heartbeat on time,
  184. // or we are a candidate but didn't not collect enough vote on
  185. // time. In this case we'll have a timeout.
  186. // 3. When become a leader, or are shutdown. In this case we'll
  187. // be notified by the election signal.
  188. cancel_handle.map(|c| c.send(()));
  189. }
  190. let stop_wait_group = this.stop_wait_group.clone();
  191. // Making sure the rest of `this` is dropped before the wait group.
  192. drop(this);
  193. drop(stop_wait_group);
  194. });
  195. self.daemon_env.watch_daemon(join_handle);
  196. }
  197. fn run_election(
  198. &self,
  199. timer_count: usize,
  200. ) -> Option<futures_channel::oneshot::Sender<()>> {
  201. let me = self.me;
  202. let (term, args) = {
  203. let mut rf = self.inner_state.lock();
  204. // The previous election is faster and reached the critical section
  205. // before us. We should stop and not run this election.
  206. // Or someone else increased the term and the timer is reset.
  207. if !self.election.try_reset_election_timer(timer_count) {
  208. return None;
  209. }
  210. rf.current_term.0 += 1;
  211. rf.voted_for = Some(me);
  212. rf.state = State::Candidate;
  213. self.persister.save_state(rf.persisted_state().into());
  214. let term = rf.current_term;
  215. let (last_log_index, last_log_term) =
  216. rf.log.last_index_term().unpack();
  217. (
  218. term,
  219. RequestVoteArgs {
  220. term,
  221. candidate_id: me,
  222. last_log_index,
  223. last_log_term,
  224. },
  225. )
  226. };
  227. let mut votes = vec![];
  228. let term_marker = self.term_marker();
  229. for (index, rpc_client) in self.peers.iter().enumerate() {
  230. if index != self.me.0 {
  231. // RpcClient must be cloned so that it lives long enough for
  232. // spawn(), which requires static life time.
  233. // RPCs are started right away.
  234. let one_vote = self.thread_pool.spawn(Self::request_vote(
  235. rpc_client.clone(),
  236. args.clone(),
  237. term_marker.clone(),
  238. ));
  239. votes.push(one_vote);
  240. }
  241. }
  242. let (tx, rx) = futures_channel::oneshot::channel();
  243. self.thread_pool.spawn(Self::count_vote_util_cancelled(
  244. me,
  245. term,
  246. self.inner_state.clone(),
  247. votes,
  248. rx,
  249. self.election.clone(),
  250. self.new_log_entry.clone().unwrap(),
  251. ));
  252. Some(tx)
  253. }
  254. const REQUEST_VOTE_RETRY: usize = 1;
  255. async fn request_vote(
  256. rpc_client: Arc<RpcClient>,
  257. args: RequestVoteArgs,
  258. term_marker: TermMarker<Command>,
  259. ) -> Option<bool> {
  260. let term = args.term;
  261. // See the comment in send_heartbeat() for this override.
  262. let rpc_client = rpc_client.as_ref();
  263. let reply =
  264. retry_rpc(Self::REQUEST_VOTE_RETRY, RPC_DEADLINE, move |_round| {
  265. rpc_client.call_request_vote(args.clone())
  266. })
  267. .await;
  268. if let Ok(reply) = reply {
  269. term_marker.mark(reply.term);
  270. return Some(reply.vote_granted && reply.term == term);
  271. }
  272. None
  273. }
  274. async fn count_vote_util_cancelled(
  275. me: Peer,
  276. term: Term,
  277. rf: Arc<Mutex<RaftState<Command>>>,
  278. votes: Vec<tokio::task::JoinHandle<Option<bool>>>,
  279. cancel_token: futures_channel::oneshot::Receiver<()>,
  280. election: Arc<ElectionState>,
  281. new_log_entry: std::sync::mpsc::Sender<Option<Peer>>,
  282. ) {
  283. let quorum = votes.len() >> 1;
  284. let mut vote_count = 0;
  285. let mut against_count = 0;
  286. let mut cancel_token = cancel_token;
  287. let mut futures_vec = votes;
  288. while vote_count < quorum
  289. && against_count <= quorum
  290. && !futures_vec.is_empty()
  291. {
  292. // Mixing tokio futures with futures-rs ones. Fingers crossed.
  293. let selected = futures_util::future::select(
  294. cancel_token,
  295. futures_util::future::select_all(futures_vec),
  296. )
  297. .await;
  298. let ((one_vote, _, rest), new_token) = match selected {
  299. futures_util::future::Either::Left(_) => break,
  300. futures_util::future::Either::Right(tuple) => tuple,
  301. };
  302. futures_vec = rest;
  303. cancel_token = new_token;
  304. if let Ok(Some(vote)) = one_vote {
  305. if vote {
  306. vote_count += 1
  307. } else {
  308. against_count += 1
  309. }
  310. }
  311. }
  312. if vote_count < quorum {
  313. return;
  314. }
  315. let mut rf = rf.lock();
  316. if rf.current_term == term && rf.state == State::Candidate {
  317. // We are the leader now. The election timer can be stopped.
  318. election.stop_election_timer();
  319. rf.state = State::Leader;
  320. rf.leader_id = me;
  321. let log_len = rf.log.end();
  322. for item in rf.next_index.iter_mut() {
  323. *item = log_len;
  324. }
  325. for item in rf.match_index.iter_mut() {
  326. *item = 0;
  327. }
  328. for item in rf.current_step.iter_mut() {
  329. *item = 0;
  330. }
  331. // Sync all logs now.
  332. let _ = new_log_entry.send(None);
  333. }
  334. }
  335. }