verify_authority.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. use crate::beat_ticker::{Beat, SharedBeatTicker};
  2. use crate::daemon_env::Daemon;
  3. use crate::{Index, Raft, Term, HEARTBEAT_INTERVAL_MILLIS};
  4. use crossbeam_utils::sync::{Parker, Unparker};
  5. use parking_lot::Mutex;
  6. use std::collections::VecDeque;
  7. use std::future::Future;
  8. use std::sync::atomic::Ordering;
  9. use std::sync::Arc;
  10. use std::time::{Duration, Instant};
  11. /// The result returned to a verify authority request.
  12. /// This request is not directly exposed to end users. Instead it is used
  13. /// internally to implement no-commit read-only requests.
  14. pub(crate) enum VerifyAuthorityResult {
  15. Success,
  16. TermElapsed,
  17. TimedOut,
  18. }
  19. /// Token stored in the internal queue for authority verification. Each token
  20. /// represents one verification request.
  21. struct VerifyAuthorityToken {
  22. commit_index: Index,
  23. beats_moment: Vec<Beat>,
  24. rough_time: Instant,
  25. sender: tokio::sync::oneshot::Sender<VerifyAuthorityResult>,
  26. }
  27. #[derive(Clone, Copy, Default, Eq, Ord, PartialOrd, PartialEq)]
  28. struct QueueIndex(usize);
  29. /// The state of this daemon, should bee protected by a mutex.
  30. struct VerifyAuthorityState {
  31. /// The current term. Might be behind the real term in the cluster.
  32. term: Term,
  33. /// Pending requests to verify authority.
  34. queue: VecDeque<VerifyAuthorityToken>,
  35. /// Number of requests that have been processed.
  36. start: QueueIndex,
  37. /// A vector of queue indexes. Each element in this vector indicates the
  38. /// index of the first request that has not been confirmed by the
  39. /// corresponding peer.
  40. /// These indexes include all processed requests. They will never go down.
  41. covered: Vec<QueueIndex>,
  42. }
  43. impl VerifyAuthorityState {
  44. pub fn create(peer_count: usize) -> Self {
  45. VerifyAuthorityState {
  46. term: Term(0),
  47. queue: Default::default(),
  48. start: QueueIndex(0),
  49. covered: vec![QueueIndex(0); peer_count],
  50. }
  51. }
  52. pub fn reset(&mut self, term: Term) {
  53. self.clear_tickets();
  54. self.term = term;
  55. self.start = QueueIndex(0);
  56. for item in self.covered.iter_mut() {
  57. *item = QueueIndex(0)
  58. }
  59. }
  60. pub fn clear_tickets(&mut self) {
  61. for token in self.queue.drain(..) {
  62. let _ = token.sender.send(VerifyAuthorityResult::TermElapsed);
  63. }
  64. }
  65. }
  66. #[derive(Clone)]
  67. pub(crate) struct VerifyAuthorityDaemon {
  68. state: Arc<Mutex<VerifyAuthorityState>>,
  69. beat_tickers: Vec<SharedBeatTicker>,
  70. unparker: Option<Unparker>,
  71. }
  72. impl VerifyAuthorityDaemon {
  73. pub fn create(peer_count: usize) -> Self {
  74. Self {
  75. state: Arc::new(Mutex::new(VerifyAuthorityState::create(
  76. peer_count,
  77. ))),
  78. beat_tickers: (0..peer_count)
  79. .map(|_| SharedBeatTicker::create())
  80. .collect(),
  81. unparker: None,
  82. }
  83. }
  84. pub fn reset_state(&self, term: Term) {
  85. self.state.lock().reset(term);
  86. // Increase all beats by one to make sure upcoming verify authority
  87. // requests wait for beats in the current term. This in fact creates
  88. // phantom beats that will never be marked as completed by themselves.
  89. // They will be automatically `ticked()` when newer (real) beats are
  90. // created, sent and `ticked()`.
  91. for beat_ticker in self.beat_tickers.iter() {
  92. beat_ticker.next_beat();
  93. }
  94. }
  95. /// Enqueues a verify authority request. Returns a receiver of the
  96. /// verification result. Returns None if the term has passed.
  97. pub fn verify_authority_async(
  98. &self,
  99. current_term: Term,
  100. commit_index: Index,
  101. ) -> Option<tokio::sync::oneshot::Receiver<VerifyAuthorityResult>> {
  102. // The inflight beats are sent at least for `current_term`. This is
  103. // guaranteed by the fact that we immediately increase beats for all
  104. // peers after being elected. It further guarantees that the newest
  105. // beats we get here are at least as new as the phantom beats created by
  106. // `Self::reset_state()`.
  107. let beats_moment = self
  108. .beat_tickers
  109. .iter()
  110. .map(|beat_ticker| beat_ticker.current_beat())
  111. .collect();
  112. // The inflight beats could also be for any term after `current_term`.
  113. // We must check if the term stored in the daemon is the same as
  114. // `current_term`.
  115. // `state.term` could be smaller than `current_term`, if a new term is
  116. // started by someone else and we lost leadership.
  117. // `state.term` could be greater than `current_term`, if we lost
  118. // leadership but are elected leader again in a following term.
  119. // In both cases, we cannot confirm the leadership at `current_term`.
  120. let mut state = self.state.lock();
  121. if state.term != current_term {
  122. return None;
  123. }
  124. let (sender, receiver) = tokio::sync::oneshot::channel();
  125. let token = VerifyAuthorityToken {
  126. commit_index,
  127. beats_moment,
  128. rough_time: Instant::now(),
  129. sender,
  130. };
  131. state.queue.push_back(token);
  132. Some(receiver)
  133. }
  134. /// Run one iteration of the verify authority daemon.
  135. pub fn run_verify_authority_iteration(
  136. &self,
  137. current_term: Term,
  138. commit_index: Index,
  139. ) {
  140. // Opportunistic check: do nothing if we don't have any requests.
  141. if self.state.lock().queue.is_empty() {
  142. return;
  143. }
  144. self.clear_committed_requests(current_term, commit_index);
  145. self.clear_ticked_requests();
  146. self.removed_expired_requests(current_term);
  147. }
  148. /// Clears all requests that have seen at least one commit.
  149. /// This function handles the following scenario: a verify authority request
  150. /// was received, when the `commit_index` was at C. Later as the leader we
  151. /// moved the commit index to at least C+1. That implies that when the
  152. /// request was first received, no other new commits after C could have been
  153. /// added to the log, either by this replica or others. It then follows that
  154. /// we can claim we had authority at that point.
  155. fn clear_committed_requests(
  156. &self,
  157. current_term: Term,
  158. commit_index: Index,
  159. ) {
  160. let mut state = self.state.lock();
  161. if current_term != state.term {
  162. return;
  163. }
  164. // Note the commit_index in the queue might not be in increasing order.
  165. // We could still have requests that have a smaller commit_index after
  166. // this sweep. That is an acceptable tradeoff we are taking.
  167. while let Some(head) = state.queue.pop_front() {
  168. if head.commit_index >= commit_index {
  169. state.queue.push_front(head);
  170. break;
  171. }
  172. let _ = head.sender.send(VerifyAuthorityResult::Success);
  173. state.start.0 += 1;
  174. }
  175. }
  176. /// Fetches the newest successful RPC response from peers, and mark verify
  177. /// authority requests as complete if they are covered by more than half of
  178. /// the replicas.
  179. fn clear_ticked_requests(&self) {
  180. for (peer_index, beat_ticker) in self.beat_tickers.iter().enumerate() {
  181. // Fetches the newest successful RPC response from the current peer.
  182. let ticked = beat_ticker.ticked();
  183. let mut state = self.state.lock();
  184. // Update progress with `ticked`. All requests that came before
  185. // `ticked` now have one more votes of leader authority from the
  186. // current peer.
  187. let first_not_ticked_index = state.queue.partition_point(|token| {
  188. token.beats_moment[peer_index] <= ticked
  189. });
  190. assert!(first_not_ticked_index >= state.covered[peer_index].0);
  191. state.covered[peer_index].0 = first_not_ticked_index;
  192. // Count the requests that has more than N / 2 votes. We always have
  193. // the vote from ourselves, but the value is 0 in `covered` array.
  194. let mut sorted_covered = state.covered.to_owned();
  195. sorted_covered.sort_unstable();
  196. let mid = sorted_covered.len() / 2 + 1;
  197. let new_start = sorted_covered[mid];
  198. // All requests before `new_start` is now verified.
  199. let verified = new_start.0 - state.start.0;
  200. for token in state.queue.drain(..verified) {
  201. for (index, beat) in token.beats_moment.iter().enumerate() {
  202. assert!(self.beat_tickers[index].ticked() >= *beat);
  203. }
  204. let _ = token.sender.send(VerifyAuthorityResult::Success);
  205. }
  206. // Move the queue starting point.
  207. state.start = new_start;
  208. }
  209. }
  210. const VERIFY_AUTHORITY_REQUEST_EXPIRATION: Duration =
  211. Duration::from_millis(HEARTBEAT_INTERVAL_MILLIS * 2);
  212. /// Remove expired requests if we are no longer the leader.
  213. /// If we have lost leadership, we are unlikely to receive confirmations
  214. /// of past leadership state from peers. Requests are expired after two
  215. /// heartbeat period have passed. We do not immediately cancel all incoming
  216. /// requests, in hope that we could still answer them accurately without
  217. /// breaking the consistency guarantee.
  218. fn removed_expired_requests(&self, current_term: Term) {
  219. let mut state = self.state.lock();
  220. // Return if we are still the leader, or we become the leader again.
  221. //
  222. // Note that we do not hold the main raft state lock, thus the value of
  223. // `current_term` might not be up-to-date. We only update `state.term`
  224. // after an election. If in a term after `current_term`, we are elected
  225. // leader again, `state.term` could be updated and thus greater than the
  226. // (now stale) `current_term`. In that case, the queue should have been
  227. // reset. There will be no expired request to remove.
  228. if state.term >= current_term {
  229. return;
  230. }
  231. let expiring_line =
  232. Instant::now() - Self::VERIFY_AUTHORITY_REQUEST_EXPIRATION;
  233. // Assuming bounded clock skew, otherwise we will lose efficiency.
  234. let expired =
  235. |head: &VerifyAuthorityToken| head.rough_time < expiring_line;
  236. // Note rough_time might not be in increasing order, so we might still
  237. // have requests that are expired in the queue after the sweep.
  238. while state.queue.front().map_or(false, expired) {
  239. state
  240. .queue
  241. .pop_front()
  242. .map(|head| head.sender.send(VerifyAuthorityResult::TimedOut));
  243. state.start.0 += 1;
  244. }
  245. }
  246. pub fn kill(&self) {
  247. if let Some(unparker) = self.unparker.as_ref() {
  248. unparker.unpark();
  249. }
  250. }
  251. }
  252. impl<Command: 'static + Send> Raft<Command> {
  253. const BEAT_RECORDING_MAX_PAUSE: Duration = Duration::from_millis(20);
  254. /// Create a thread and runs the verify authority daemon.
  255. pub(crate) fn run_verify_authority_daemon(&mut self) {
  256. let parker = Parker::new();
  257. let unparker = parker.unparker().clone();
  258. self.verify_authority_daemon.unparker.replace(unparker);
  259. let keep_running = self.keep_running.clone();
  260. let this_daemon = self.verify_authority_daemon.clone();
  261. let rf = self.inner_state.clone();
  262. let join_handle = std::thread::spawn(move || {
  263. while keep_running.load(Ordering::Acquire) {
  264. parker.park_timeout(Self::BEAT_RECORDING_MAX_PAUSE);
  265. let (current_term, commit_index) = {
  266. let rf = rf.lock();
  267. (rf.current_term, rf.commit_index)
  268. };
  269. this_daemon
  270. .run_verify_authority_iteration(current_term, commit_index);
  271. }
  272. });
  273. self.daemon_env
  274. .watch_daemon(Daemon::VerifyAuthority, join_handle);
  275. }
  276. /// Create a verify authority request. Returns None if we are not the
  277. /// leader.
  278. #[allow(dead_code)]
  279. pub(crate) fn verify_authority_async(
  280. &self,
  281. ) -> Option<impl Future<Output = VerifyAuthorityResult>> {
  282. let (term, commit_index) = {
  283. let rf = self.inner_state.lock();
  284. if !rf.is_leader() {
  285. return None;
  286. }
  287. (rf.current_term, rf.commit_index)
  288. };
  289. let receiver = self
  290. .verify_authority_daemon
  291. .verify_authority_async(term, commit_index);
  292. receiver.map(|receiver| async move {
  293. receiver
  294. .await
  295. .expect("Verify authority daemon never drops senders")
  296. })
  297. }
  298. }