sync_log_entries.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. use std::sync::atomic::Ordering;
  2. use std::sync::Arc;
  3. use parking_lot::{Condvar, Mutex};
  4. use crate::daemon_env::ErrorKind;
  5. use crate::heartbeats::HEARTBEAT_INTERVAL;
  6. use crate::peer_progress::PeerProgress;
  7. use crate::remote_context::RemoteContext;
  8. use crate::utils::{retry_rpc, SharedSender, RPC_DEADLINE};
  9. use crate::{
  10. check_or_record, AppendEntriesArgs, Index, IndexTerm, InstallSnapshotArgs,
  11. Peer, Raft, RaftState, ReplicableCommand, Term,
  12. };
  13. #[derive(Eq, PartialEq)]
  14. enum Event {
  15. NewTerm(Term, Index),
  16. NewLogEntry(Index),
  17. Rerun(Peer),
  18. Shutdown,
  19. }
  20. impl Event {
  21. fn should_schedule(&self, peer: Peer) -> bool {
  22. match self {
  23. Event::NewTerm(..) => true,
  24. Event::NewLogEntry(_index) => true,
  25. Event::Rerun(p) => p == &peer,
  26. Event::Shutdown => false,
  27. }
  28. }
  29. }
  30. #[derive(Clone)]
  31. pub(crate) struct SyncLogEntriesComms {
  32. tx: crate::utils::SharedSender<Event>,
  33. }
  34. impl SyncLogEntriesComms {
  35. pub fn update_followers(&self, index: Index) {
  36. // Ignore the error. The log syncing thread must have died.
  37. let _ = self.tx.send(Event::NewLogEntry(index));
  38. }
  39. pub fn reset_progress(&self, term: Term, index: Index) {
  40. let index = std::cmp::max(index, 1);
  41. let _ = self.tx.send(Event::NewTerm(term, index));
  42. }
  43. pub fn kill(&self) {
  44. // The sync log entry daemon might have exited.
  45. let _ = self.tx.send(Event::Shutdown);
  46. }
  47. fn rerun(&self, peer: Peer) {
  48. // Ignore the error. The log syncing thread must have died.
  49. let _ = self.tx.send(Event::Rerun(peer));
  50. }
  51. }
  52. pub(crate) struct SyncLogEntriesDaemon {
  53. rx: std::sync::mpsc::Receiver<Event>,
  54. peer_progress: Vec<PeerProgress>,
  55. }
  56. pub(crate) fn create(
  57. peer_size: usize,
  58. ) -> (SyncLogEntriesComms, SyncLogEntriesDaemon) {
  59. let (tx, rx) = std::sync::mpsc::channel();
  60. let tx = SharedSender::new(tx);
  61. let peer_progress = (0..peer_size).map(PeerProgress::create).collect();
  62. (
  63. SyncLogEntriesComms { tx },
  64. SyncLogEntriesDaemon { rx, peer_progress },
  65. )
  66. }
  67. enum SyncLogEntriesOperation<Command> {
  68. AppendEntries(AppendEntriesArgs<Command>),
  69. InstallSnapshot(InstallSnapshotArgs),
  70. None,
  71. }
  72. enum SyncLogEntriesResult {
  73. TermElapsed(Term),
  74. Archived(IndexTerm),
  75. Diverged(IndexTerm),
  76. Success,
  77. }
  78. #[derive(Clone, Copy, Debug)]
  79. struct TaskNumber(usize);
  80. // Command must be
  81. // 0. 'static: Raft<Command> must be 'static, it is moved to another thread.
  82. // 1. clone: they are copied to the persister.
  83. // 2. send: Arc<Mutex<Vec<LogEntry<Command>>>> must be send, it is moved to another thread.
  84. // 3. serialize: they are converted to bytes to persist.
  85. impl<Command: ReplicableCommand> Raft<Command> {
  86. /// Runs a daemon thread that syncs log entries to peers.
  87. ///
  88. /// This daemon watches the `new_log_entry` channel. Each item delivered by
  89. /// the channel is a request to sync log entries to either a peer
  90. /// (`Some(peer_index)`) or all peers (`None`).
  91. ///
  92. /// The daemon tries to collapse requests about the same peer together. A
  93. /// new task is only scheduled when the pending requests number turns from
  94. /// zero to one. Even then there could still be more than one tasks syncing
  95. /// logs to the same peer at the same time.
  96. ///
  97. /// New tasks will still be scheduled when we are not the leader. The task
  98. /// will exist without not do anything in that case.
  99. ///
  100. /// See comments on [`Raft::sync_log_entries`] to learn about the syncing
  101. /// and backoff strategy.
  102. pub(crate) fn run_log_entry_daemon(
  103. &self,
  104. SyncLogEntriesDaemon { rx, peer_progress }: SyncLogEntriesDaemon,
  105. ) -> impl FnOnce() {
  106. // Clone everything that the thread needs.
  107. let this = self.clone();
  108. move || {
  109. log::info!("{:?} sync log entries daemon running ...", this.me);
  110. let mut task_number = 0;
  111. while let Ok(event) = rx.recv() {
  112. if !this.keep_running.load(Ordering::Relaxed) {
  113. break;
  114. }
  115. if !this.inner_state.lock().is_leader() {
  116. continue;
  117. }
  118. for peer in this.peers.clone().into_iter() {
  119. if peer != this.me && event.should_schedule(peer) {
  120. let progress = &peer_progress[peer.0];
  121. if let Event::NewTerm(_term, index) = event {
  122. progress.reset_progress(index);
  123. }
  124. // Only schedule a new task if the last task has cleared
  125. // the queue of RPC requests.
  126. if progress.should_schedule() {
  127. task_number += 1;
  128. this.thread_pool.spawn(Self::sync_log_entries(
  129. this.inner_state.clone(),
  130. this.sync_log_entries_comms.clone(),
  131. progress.clone(),
  132. this.apply_command_signal.clone(),
  133. TaskNumber(task_number),
  134. ));
  135. }
  136. }
  137. }
  138. }
  139. log::info!("{:?} sync log entries daemon done.", this.me);
  140. }
  141. }
  142. /// Syncs log entries to a peer once, requests a new sync if that fails.
  143. ///
  144. /// Sends an `AppendEntries` request if the planned next log entry to sync
  145. /// is after log start (and thus not covered by the log snapshot). Sends an
  146. /// `InstallSnapshot` request otherwise. The responses of those two types of
  147. /// requests are handled in a similar way.
  148. ///
  149. /// The peer might respond with
  150. /// * Success. Updates the internal record of how much log the peer holds.
  151. /// Marks new log entries as committed if we have a quorum of peers that
  152. /// have persisted the log entries. Note that we do not check if there are
  153. /// more items that can be sent to the peer. A new task will be scheduled
  154. /// for that outside of this daemon.
  155. ///
  156. /// * Nothing at all. A new request to sync log entries will be added to the
  157. /// `new_log_entry` queue.
  158. ///
  159. /// * The log has diverged. The peer disagrees with the request. We'll move
  160. /// the "planned next log entry to sync" towards the log start and request
  161. /// to sync again via the `new_log_entry` queue. The backoff will be
  162. /// exponential until it exceeds the log start, at which point the request
  163. /// becomes a `InstallSnapshot`. Note this case is impossible in a response
  164. /// to a `InstallSnapshot` RPC.
  165. ///
  166. /// * The log entry has been archived. The peer has taken a snapshot at that
  167. /// position and thus cannot verify the request. Along with this response,
  168. /// the peer sends back its commit index, which is guaranteed not to be
  169. /// shadowed by that snapshot. The sync will be retried at that commit index
  170. /// via the `new_log_entry` queue. Note the follow up sync could still fail
  171. /// for the same reason, as the peer might have moved its commit index.
  172. /// However syncing will eventually succeed, since the peer cannot move its
  173. /// commit index indefinitely without accepting any log sync requests from
  174. /// the leader.
  175. ///
  176. /// In the last two cases, the "planned next index to sync" can move towards
  177. /// the log start and end, respectively. We will not move back and forth in
  178. /// a mixed sequence of those two failures. The reasoning is that after a
  179. /// failure of the last case, we will never hit the other failure again,
  180. /// since in the last case we always sync log entry at a committed index,
  181. /// and a committed log entry can never diverge.
  182. async fn sync_log_entries(
  183. rf: Arc<Mutex<RaftState<Command>>>,
  184. comms: SyncLogEntriesComms,
  185. progress: PeerProgress,
  186. apply_command_signal: Arc<Condvar>,
  187. task_number: TaskNumber,
  188. ) {
  189. if !progress.take_task() {
  190. return;
  191. }
  192. let peer = progress.peer;
  193. let operation =
  194. Self::build_sync_log_entries(&rf, &progress, task_number);
  195. let (term, prev_log_index, match_index, succeeded) = match operation {
  196. SyncLogEntriesOperation::AppendEntries(args) => {
  197. let term = args.term;
  198. let prev_log_index = args.prev_log_index;
  199. let match_index = args.prev_log_index + args.entries.len();
  200. let succeeded = Self::append_entries(peer, args).await;
  201. (term, prev_log_index, match_index, succeeded)
  202. }
  203. SyncLogEntriesOperation::InstallSnapshot(args) => {
  204. let term = args.term;
  205. let prev_log_index = args.last_included_index;
  206. let match_index = args.last_included_index;
  207. let succeeded = Self::install_snapshot(peer, args).await;
  208. (term, prev_log_index, match_index, succeeded)
  209. }
  210. SyncLogEntriesOperation::None => return,
  211. };
  212. match succeeded {
  213. Ok(SyncLogEntriesResult::Success) => {
  214. let mut rf = rf.lock();
  215. if !rf.is_leader() {
  216. return;
  217. }
  218. if rf.current_term != term {
  219. return;
  220. }
  221. check_or_record!(
  222. match_index < rf.log.end(),
  223. ErrorKind::LeaderLogShrunk(match_index),
  224. "The leader log shrunk",
  225. &rf
  226. );
  227. progress.record_success(match_index);
  228. let peer_index = peer.0;
  229. if match_index > rf.match_index[peer_index] {
  230. rf.match_index[peer_index] = match_index;
  231. let mut matched = rf.match_index.to_vec();
  232. let mid = matched.len() / 2 + 1;
  233. matched.sort_unstable();
  234. let new_commit_index = matched[mid];
  235. if new_commit_index > rf.commit_index
  236. && rf.log.at(new_commit_index).term == rf.current_term
  237. {
  238. log::info!(
  239. "{:?} moving leader commit index to {} in {:?}",
  240. rf.leader_id,
  241. new_commit_index,
  242. task_number
  243. );
  244. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT:
  245. // Index new_commit_index exists in the log array,
  246. // which implies new_commit_index is in range
  247. // [log.start(), log.end()).
  248. rf.commit_index = new_commit_index;
  249. apply_command_signal.notify_one();
  250. }
  251. }
  252. // After each round of install snapshot, we must schedule
  253. // another round of append entries. The extra round must be run
  254. // even if match_index did not move after the snapshot is
  255. // installed.
  256. // For example,
  257. // 1. Leader committed index 10, received another request at
  258. // index 11.
  259. // 2. Leader sends append entries to all peers.
  260. // 3. Leader commits index 11. At this time, append entries to
  261. // peer X has not returned, while other append entries have.
  262. // 4. Leader snapshots index 11, received another request at
  263. // index 12.
  264. // 5. Leader needs to update peer X, but does not have the
  265. // commit at index 11 any more. Leader then sends install
  266. // snapshot to peer X at index 11.
  267. // 6. The original append entries request to peer X returns
  268. // successfully, moving match_index to 11.
  269. // 7. The install snapshot request returns successfully.
  270. //
  271. // The installed snapshot is at index 11, which is already sent
  272. // by the previous append entries request. Thus the match index
  273. // did not move. Still, we need the extra round of append
  274. // entries to peer X for log entry at index 12.
  275. if prev_log_index == match_index {
  276. // If we did not make any progress this time, try again.
  277. // This can only happen when installing snapshots.
  278. comms.rerun(peer);
  279. }
  280. }
  281. Ok(SyncLogEntriesResult::Archived(committed)) => {
  282. let rf = rf.lock();
  283. check_or_record!(
  284. prev_log_index < committed.index,
  285. ErrorKind::RefusedSnapshotAfterCommitted(
  286. prev_log_index,
  287. committed.index
  288. ),
  289. format!(
  290. "{:?} misbehaves: claimed log index {} is archived, \
  291. but commit index is at {:?}) which is before that",
  292. peer, prev_log_index, committed
  293. ),
  294. &rf
  295. );
  296. Self::check_committed(&rf, peer, committed.clone());
  297. // Next index moves towards the log end. This is the only place
  298. // where that happens. committed.index should be between log
  299. // start and end, guaranteed by check_committed() above.
  300. progress.record_success(committed.index + 1);
  301. comms.rerun(peer);
  302. }
  303. Ok(SyncLogEntriesResult::Diverged(committed)) => {
  304. let rf = rf.lock();
  305. check_or_record!(
  306. prev_log_index > committed.index,
  307. ErrorKind::DivergedBeforeCommitted(
  308. prev_log_index,
  309. committed.index
  310. ),
  311. format!(
  312. "{:?} claimed log index {} does not match, \
  313. but commit index is at {:?}) which is after that.",
  314. peer, prev_log_index, committed
  315. ),
  316. &rf
  317. );
  318. Self::check_committed(&rf, peer, committed.clone());
  319. progress.record_failure(committed.index);
  320. comms.rerun(peer);
  321. }
  322. // Do nothing, not our term anymore.
  323. Ok(SyncLogEntriesResult::TermElapsed(term)) => {
  324. RemoteContext::<Command>::term_marker().mark(term);
  325. }
  326. Err(_) => {
  327. tokio::time::sleep(HEARTBEAT_INTERVAL).await;
  328. comms.rerun(peer);
  329. }
  330. };
  331. }
  332. fn check_committed(
  333. rf: &RaftState<Command>,
  334. peer: Peer,
  335. committed: IndexTerm,
  336. ) {
  337. if committed.index < rf.log.start() {
  338. return;
  339. }
  340. check_or_record!(
  341. committed.index < rf.log.end(),
  342. ErrorKind::CommittedBeyondEnd(committed.index),
  343. format!(
  344. "Follower {:?} committed a log entry {:?} that is
  345. beyond the end of the leader log at {:?}",
  346. peer,
  347. committed,
  348. rf.log.end(),
  349. ),
  350. rf
  351. );
  352. let local_term = rf.log.at(committed.index).term;
  353. check_or_record!(
  354. committed.term == local_term,
  355. ErrorKind::DivergedAtCommitted(committed.index),
  356. format!(
  357. "{:?} committed log diverged at {:?}: {:?} v.s. leader {:?}",
  358. peer, committed.index, committed.term, local_term
  359. ),
  360. rf
  361. );
  362. }
  363. fn build_sync_log_entries(
  364. rf: &Mutex<RaftState<Command>>,
  365. progress: &PeerProgress,
  366. task_number: TaskNumber,
  367. ) -> SyncLogEntriesOperation<Command> {
  368. let rf = rf.lock();
  369. if !rf.is_leader() {
  370. return SyncLogEntriesOperation::None;
  371. }
  372. let peer = progress.peer;
  373. // To send AppendEntries request, next_index must be strictly larger
  374. // than start(). Otherwise we won't be able to know the log term of the
  375. // entry right before next_index.
  376. let next_index = progress.next_index();
  377. if next_index > rf.log.start() {
  378. if next_index < rf.log.end() {
  379. log::debug!(
  380. "{:?} building append entries {:?} from {} to {:?}",
  381. rf.leader_id,
  382. task_number,
  383. next_index - 1,
  384. peer
  385. );
  386. SyncLogEntriesOperation::AppendEntries(
  387. Self::build_append_entries(&rf, next_index),
  388. )
  389. } else {
  390. log::debug!(
  391. "{:?} nothing in append entries {:?} to {:?}",
  392. rf.leader_id,
  393. task_number,
  394. peer
  395. );
  396. SyncLogEntriesOperation::None
  397. }
  398. } else {
  399. log::debug!(
  400. "{:?} installing snapshot {:?} at {} to {:?}",
  401. rf.leader_id,
  402. task_number,
  403. rf.log.first_index_term().index,
  404. peer,
  405. );
  406. SyncLogEntriesOperation::InstallSnapshot(
  407. Self::build_install_snapshot(&rf),
  408. )
  409. }
  410. }
  411. fn build_append_entries(
  412. rf: &RaftState<Command>,
  413. next_index: Index,
  414. ) -> AppendEntriesArgs<Command> {
  415. // It is guaranteed that next_index <= rf.log.end(). Panic otherwise.
  416. let prev_log_index = next_index - 1;
  417. let prev_log_term = rf.log.at(prev_log_index).term;
  418. AppendEntriesArgs {
  419. term: rf.current_term,
  420. leader_id: rf.leader_id,
  421. prev_log_index,
  422. prev_log_term,
  423. entries: rf.log.after(next_index).to_vec(),
  424. leader_commit: rf.commit_index,
  425. }
  426. }
  427. const APPEND_ENTRIES_RETRY: usize = 1;
  428. async fn append_entries(
  429. peer: Peer,
  430. args: AppendEntriesArgs<Command>,
  431. ) -> std::io::Result<SyncLogEntriesResult> {
  432. let beat_ticker = RemoteContext::<Command>::beat_ticker(peer);
  433. let rpc_client = RemoteContext::<Command>::rpc_client(peer);
  434. let term = args.term;
  435. let beat = beat_ticker.next_beat();
  436. let reply = retry_rpc(
  437. Self::APPEND_ENTRIES_RETRY,
  438. RPC_DEADLINE,
  439. move |_round| rpc_client.append_entries(args.clone()),
  440. )
  441. .await?;
  442. Ok(if reply.term == term {
  443. beat_ticker.tick(beat);
  444. if let Some(committed) = reply.committed {
  445. if reply.success {
  446. SyncLogEntriesResult::Archived(committed)
  447. } else {
  448. SyncLogEntriesResult::Diverged(committed)
  449. }
  450. } else {
  451. SyncLogEntriesResult::Success
  452. }
  453. } else {
  454. SyncLogEntriesResult::TermElapsed(reply.term)
  455. })
  456. }
  457. fn build_install_snapshot(rf: &RaftState<Command>) -> InstallSnapshotArgs {
  458. let (last, snapshot) = rf.log.snapshot();
  459. InstallSnapshotArgs {
  460. term: rf.current_term,
  461. leader_id: rf.leader_id,
  462. last_included_index: last.index,
  463. last_included_term: last.term,
  464. data: snapshot.to_owned(),
  465. offset: 0,
  466. done: true,
  467. }
  468. }
  469. const INSTALL_SNAPSHOT_RETRY: usize = 1;
  470. async fn install_snapshot(
  471. peer: Peer,
  472. args: InstallSnapshotArgs,
  473. ) -> std::io::Result<SyncLogEntriesResult> {
  474. let beat_ticker = RemoteContext::<Command>::beat_ticker(peer);
  475. let rpc_client = RemoteContext::<Command>::rpc_client(peer);
  476. let term = args.term;
  477. let beat = beat_ticker.next_beat();
  478. let reply = retry_rpc(
  479. Self::INSTALL_SNAPSHOT_RETRY,
  480. RPC_DEADLINE,
  481. move |_round| rpc_client.install_snapshot(args.clone()),
  482. )
  483. .await?;
  484. Ok(if reply.term == term {
  485. beat_ticker.tick(beat);
  486. if let Some(committed) = reply.committed {
  487. SyncLogEntriesResult::Archived(committed)
  488. } else {
  489. SyncLogEntriesResult::Success
  490. }
  491. } else {
  492. SyncLogEntriesResult::TermElapsed(reply.term)
  493. })
  494. }
  495. }