sync_log_entries.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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: 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.iter() {
  119. let peer = *peer;
  120. if event.should_schedule(peer) {
  121. let progress = &peer_progress[peer.0];
  122. if let Event::NewTerm(_term, index) = event {
  123. progress.reset_progress(index);
  124. }
  125. // Only schedule a new task if the last task has cleared
  126. // the queue of RPC requests.
  127. if progress.should_schedule() {
  128. task_number += 1;
  129. this.thread_pool.spawn(Self::sync_log_entries(
  130. this.inner_state.clone(),
  131. this.sync_log_entries_comms.clone(),
  132. progress.clone(),
  133. this.apply_command_signal.clone(),
  134. TaskNumber(task_number),
  135. ));
  136. }
  137. }
  138. }
  139. }
  140. log::info!("{:?} sync log entries daemon done.", this.me);
  141. }
  142. }
  143. /// Syncs log entries to a peer once, requests a new sync if that fails.
  144. ///
  145. /// Sends an `AppendEntries` request if the planned next log entry to sync
  146. /// is after log start (and thus not covered by the log snapshot). Sends an
  147. /// `InstallSnapshot` request otherwise. The responses of those two types of
  148. /// requests are handled in a similar way.
  149. ///
  150. /// The peer might respond with
  151. /// * Success. Updates the internal record of how much log the peer holds.
  152. /// Marks new log entries as committed if we have a quorum of peers that
  153. /// have persisted the log entries. Note that we do not check if there are
  154. /// more items that can be sent to the peer. A new task will be scheduled
  155. /// for that outside of this daemon.
  156. ///
  157. /// * Nothing at all. A new request to sync log entries will be added to the
  158. /// `new_log_entry` queue.
  159. ///
  160. /// * The log has diverged. The peer disagrees with the request. We'll move
  161. /// the "planned next log entry to sync" towards the log start and request
  162. /// to sync again via the `new_log_entry` queue. The backoff will be
  163. /// exponential until it exceeds the log start, at which point the request
  164. /// becomes a `InstallSnapshot`. Note this case is impossible in a response
  165. /// to a `InstallSnapshot` RPC.
  166. ///
  167. /// * The log entry has been archived. The peer has taken a snapshot at that
  168. /// position and thus cannot verify the request. Along with this response,
  169. /// the peer sends back its commit index, which is guaranteed not to be
  170. /// shadowed by that snapshot. The sync will be retried at that commit index
  171. /// via the `new_log_entry` queue. Note the follow up sync could still fail
  172. /// for the same reason, as the peer might have moved its commit index.
  173. /// However syncing will eventually succeed, since the peer cannot move its
  174. /// commit index indefinitely without accepting any log sync requests from
  175. /// the leader.
  176. ///
  177. /// In the last two cases, the "planned next index to sync" can move towards
  178. /// the log start and end, respectively. We will not move back and forth in
  179. /// a mixed sequence of those two failures. The reasoning is that after a
  180. /// failure of the last case, we will never hit the other failure again,
  181. /// since in the last case we always sync log entry at a committed index,
  182. /// and a committed log entry can never diverge.
  183. async fn sync_log_entries(
  184. rf: Arc<Mutex<RaftState<Command>>>,
  185. comms: SyncLogEntriesComms,
  186. progress: PeerProgress,
  187. apply_command_signal: Arc<Condvar>,
  188. task_number: TaskNumber,
  189. ) {
  190. if !progress.take_task() {
  191. return;
  192. }
  193. let peer = progress.peer;
  194. let operation =
  195. Self::build_sync_log_entries(&rf, &progress, task_number);
  196. let (term, prev_log_index, match_index, succeeded) = match operation {
  197. SyncLogEntriesOperation::AppendEntries(args) => {
  198. let term = args.term;
  199. let prev_log_index = args.prev_log_index;
  200. let match_index = args.prev_log_index + args.entries.len();
  201. let succeeded = Self::append_entries(peer, args).await;
  202. (term, prev_log_index, match_index, succeeded)
  203. }
  204. SyncLogEntriesOperation::InstallSnapshot(args) => {
  205. let term = args.term;
  206. let prev_log_index = args.last_included_index;
  207. let match_index = args.last_included_index;
  208. let succeeded = Self::install_snapshot(peer, args).await;
  209. (term, prev_log_index, match_index, succeeded)
  210. }
  211. SyncLogEntriesOperation::None => return,
  212. };
  213. match succeeded {
  214. Ok(SyncLogEntriesResult::Success) => {
  215. let mut rf = rf.lock();
  216. if !rf.is_leader() {
  217. return;
  218. }
  219. if rf.current_term != term {
  220. return;
  221. }
  222. check_or_record!(
  223. match_index < rf.log.end(),
  224. ErrorKind::LeaderLogShrunk(match_index),
  225. "The leader log shrunk",
  226. &rf
  227. );
  228. progress.record_success(match_index);
  229. let peer_index = peer.0;
  230. if match_index > rf.match_index[peer_index] {
  231. rf.match_index[peer_index] = match_index;
  232. let mut matched = rf.match_index.to_vec();
  233. let mid = matched.len() / 2 + 1;
  234. matched.sort_unstable();
  235. let new_commit_index = matched[mid];
  236. if new_commit_index > rf.commit_index
  237. && rf.log.at(new_commit_index).term == rf.current_term
  238. {
  239. log::info!(
  240. "{:?} moving leader commit index to {} in {:?}",
  241. rf.leader_id,
  242. new_commit_index,
  243. task_number
  244. );
  245. // COMMIT_INDEX_INVARIANT, SNAPSHOT_INDEX_INVARIANT:
  246. // Index new_commit_index exists in the log array,
  247. // which implies new_commit_index is in range
  248. // [log.start(), log.end()).
  249. rf.commit_index = new_commit_index;
  250. apply_command_signal.notify_one();
  251. }
  252. }
  253. // After each round of install snapshot, we must schedule
  254. // another round of append entries. The extra round must be run
  255. // even if match_index did not move after the snapshot is
  256. // installed.
  257. // For example,
  258. // 1. Leader committed index 10, received another request at
  259. // index 11.
  260. // 2. Leader sends append entries to all peers.
  261. // 3. Leader commits index 11. At this time, append entries to
  262. // peer X has not returned, while other append entries have.
  263. // 4. Leader snapshots index 11, received another request at
  264. // index 12.
  265. // 5. Leader needs to update peer X, but does not have the
  266. // commit at index 11 any more. Leader then sends install
  267. // snapshot to peer X at index 11.
  268. // 6. The original append entries request to peer X returns
  269. // successfully, moving match_index to 11.
  270. // 7. The install snapshot request returns successfully.
  271. //
  272. // The installed snapshot is at index 11, which is already sent
  273. // by the previous append entries request. Thus the match index
  274. // did not move. Still, we need the extra round of append
  275. // entries to peer X for log entry at index 12.
  276. if prev_log_index == match_index {
  277. // If we did not make any progress this time, try again.
  278. // This can only happen when installing snapshots.
  279. comms.rerun(peer);
  280. }
  281. }
  282. Ok(SyncLogEntriesResult::Archived(committed)) => {
  283. let rf = rf.lock();
  284. check_or_record!(
  285. prev_log_index < committed.index,
  286. ErrorKind::RefusedSnapshotAfterCommitted(
  287. prev_log_index,
  288. committed.index
  289. ),
  290. format!(
  291. "{:?} misbehaves: claimed log index {} is archived, \
  292. but commit index is at {:?}) which is before that",
  293. peer, prev_log_index, committed
  294. ),
  295. &rf
  296. );
  297. Self::check_committed(&rf, peer, &committed);
  298. // Next index moves towards the log end. This is the only place
  299. // where that happens. committed.index should be between log
  300. // start and end, guaranteed by check_committed() above.
  301. progress.record_success(committed.index + 1);
  302. comms.rerun(peer);
  303. }
  304. Ok(SyncLogEntriesResult::Diverged(committed)) => {
  305. let rf = rf.lock();
  306. check_or_record!(
  307. prev_log_index > committed.index,
  308. ErrorKind::DivergedBeforeCommitted(
  309. prev_log_index,
  310. committed.index
  311. ),
  312. format!(
  313. "{:?} claimed log index {} does not match, \
  314. but commit index is at {:?}) which is after that.",
  315. peer, prev_log_index, committed
  316. ),
  317. &rf
  318. );
  319. Self::check_committed(&rf, peer, &committed);
  320. progress.record_failure(committed.index);
  321. comms.rerun(peer);
  322. }
  323. // Do nothing, not our term anymore.
  324. Ok(SyncLogEntriesResult::TermElapsed(term)) => {
  325. RemoteContext::<Command>::term_marker().mark(term);
  326. }
  327. Err(_) => {
  328. tokio::time::sleep(HEARTBEAT_INTERVAL).await;
  329. comms.rerun(peer);
  330. }
  331. };
  332. }
  333. fn check_committed(
  334. rf: &RaftState<Command>,
  335. peer: Peer,
  336. committed: &IndexTerm,
  337. ) {
  338. if committed.index < rf.log.start() {
  339. return;
  340. }
  341. check_or_record!(
  342. committed.index < rf.log.end(),
  343. ErrorKind::CommittedBeyondEnd(committed.index),
  344. format!(
  345. "Follower {:?} committed a log entry {:?} that is
  346. beyond the end of the leader log at {:?}",
  347. peer,
  348. committed,
  349. rf.log.end(),
  350. ),
  351. rf
  352. );
  353. let local_term = rf.log.at(committed.index).term;
  354. check_or_record!(
  355. committed.term == local_term,
  356. ErrorKind::DivergedAtCommitted(committed.index),
  357. format!(
  358. "{:?} committed log diverged at {:?}: {:?} v.s. leader {:?}",
  359. peer, committed.index, committed.term, local_term
  360. ),
  361. rf
  362. );
  363. }
  364. fn build_sync_log_entries(
  365. rf: &Mutex<RaftState<Command>>,
  366. progress: &PeerProgress,
  367. task_number: TaskNumber,
  368. ) -> SyncLogEntriesOperation<Command> {
  369. let rf = rf.lock();
  370. if !rf.is_leader() {
  371. return SyncLogEntriesOperation::None;
  372. }
  373. let peer = progress.peer;
  374. // To send AppendEntries request, next_index must be strictly larger
  375. // than start(). Otherwise we won't be able to know the log term of the
  376. // entry right before next_index.
  377. let next_index = progress.next_index();
  378. if next_index > rf.log.start() {
  379. if next_index < rf.log.end() {
  380. log::debug!(
  381. "{:?} building append entries {:?} from {} to {:?}",
  382. rf.leader_id,
  383. task_number,
  384. next_index - 1,
  385. peer
  386. );
  387. SyncLogEntriesOperation::AppendEntries(
  388. Self::build_append_entries(&rf, next_index),
  389. )
  390. } else {
  391. log::debug!(
  392. "{:?} nothing in append entries {:?} to {:?}",
  393. rf.leader_id,
  394. task_number,
  395. peer
  396. );
  397. SyncLogEntriesOperation::None
  398. }
  399. } else {
  400. log::debug!(
  401. "{:?} installing snapshot {:?} at {} to {:?}",
  402. rf.leader_id,
  403. task_number,
  404. rf.log.first_index_term().index,
  405. peer,
  406. );
  407. SyncLogEntriesOperation::InstallSnapshot(
  408. Self::build_install_snapshot(&rf),
  409. )
  410. }
  411. }
  412. fn build_append_entries(
  413. rf: &RaftState<Command>,
  414. next_index: Index,
  415. ) -> AppendEntriesArgs<Command> {
  416. // It is guaranteed that next_index <= rf.log.end(). Panic otherwise.
  417. let prev_log_index = next_index - 1;
  418. let prev_log_term = rf.log.at(prev_log_index).term;
  419. AppendEntriesArgs {
  420. term: rf.current_term,
  421. leader_id: rf.leader_id,
  422. prev_log_index,
  423. prev_log_term,
  424. entries: rf.log.after(next_index).to_vec(),
  425. leader_commit: rf.commit_index,
  426. }
  427. }
  428. const APPEND_ENTRIES_RETRY: usize = 1;
  429. async fn append_entries(
  430. peer: Peer,
  431. args: AppendEntriesArgs<Command>,
  432. ) -> std::io::Result<SyncLogEntriesResult> {
  433. let beat_ticker = RemoteContext::<Command>::beat_ticker(peer);
  434. let rpc_client = RemoteContext::<Command>::rpc_client(peer);
  435. let term = args.term;
  436. let beat = beat_ticker.next_beat();
  437. let reply = retry_rpc(
  438. Self::APPEND_ENTRIES_RETRY,
  439. RPC_DEADLINE,
  440. move |_round| rpc_client.append_entries(args.clone()),
  441. )
  442. .await?;
  443. Ok(if reply.term == term {
  444. beat_ticker.tick(beat);
  445. if let Some(committed) = reply.committed {
  446. if reply.success {
  447. SyncLogEntriesResult::Archived(committed)
  448. } else {
  449. SyncLogEntriesResult::Diverged(committed)
  450. }
  451. } else {
  452. SyncLogEntriesResult::Success
  453. }
  454. } else {
  455. SyncLogEntriesResult::TermElapsed(reply.term)
  456. })
  457. }
  458. fn build_install_snapshot(rf: &RaftState<Command>) -> InstallSnapshotArgs {
  459. let (last, snapshot) = rf.log.snapshot();
  460. InstallSnapshotArgs {
  461. term: rf.current_term,
  462. leader_id: rf.leader_id,
  463. last_included_index: last.index,
  464. last_included_term: last.term,
  465. data: snapshot.to_owned(),
  466. offset: 0,
  467. done: true,
  468. }
  469. }
  470. const INSTALL_SNAPSHOT_RETRY: usize = 1;
  471. async fn install_snapshot(
  472. peer: Peer,
  473. args: InstallSnapshotArgs,
  474. ) -> std::io::Result<SyncLogEntriesResult> {
  475. let beat_ticker = RemoteContext::<Command>::beat_ticker(peer);
  476. let rpc_client = RemoteContext::<Command>::rpc_client(peer);
  477. let term = args.term;
  478. let beat = beat_ticker.next_beat();
  479. let reply = retry_rpc(
  480. Self::INSTALL_SNAPSHOT_RETRY,
  481. RPC_DEADLINE,
  482. move |_round| rpc_client.install_snapshot(args.clone()),
  483. )
  484. .await?;
  485. Ok(if reply.term == term {
  486. beat_ticker.tick(beat);
  487. if let Some(committed) = reply.committed {
  488. SyncLogEntriesResult::Archived(committed)
  489. } else {
  490. SyncLogEntriesResult::Success
  491. }
  492. } else {
  493. SyncLogEntriesResult::TermElapsed(reply.term)
  494. })
  495. }
  496. }