lib.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. #![allow(unused)]
  2. extern crate bincode;
  3. extern crate futures;
  4. extern crate labrpc;
  5. extern crate rand;
  6. #[macro_use]
  7. extern crate serde_derive;
  8. extern crate tokio;
  9. use std::future::Future;
  10. use std::sync::atomic::AtomicBool;
  11. use std::sync::Arc;
  12. use std::time::Duration;
  13. use parking_lot::Mutex;
  14. use rand::{thread_rng, Rng};
  15. use crate::rpcs::RpcClient;
  16. use crate::utils::{retry_rpc, DropGuard};
  17. pub mod rpcs;
  18. mod utils;
  19. #[derive(Eq, PartialEq)]
  20. enum State {
  21. Follower,
  22. Candidate,
  23. // TODO: add PreVote
  24. Leader,
  25. }
  26. #[derive(
  27. Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize,
  28. )]
  29. struct Term(usize);
  30. #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
  31. struct Peer(usize);
  32. #[derive(Clone, Copy, Debug, Serialize, Deserialize)]
  33. struct Command(usize);
  34. // TODO: remove all of the defaults.
  35. impl Default for State {
  36. fn default() -> Self {
  37. Self::Leader
  38. }
  39. }
  40. impl Default for Term {
  41. fn default() -> Self {
  42. Self(0)
  43. }
  44. }
  45. impl Default for Peer {
  46. fn default() -> Self {
  47. Self(0)
  48. }
  49. }
  50. #[derive(Clone, Copy, Serialize, Deserialize)]
  51. struct LogEntry {
  52. term: Term,
  53. index: usize,
  54. // TODO: Allow sending of arbitrary information.
  55. command: Command,
  56. }
  57. #[derive(Default)]
  58. struct RaftState {
  59. current_term: Term,
  60. voted_for: Option<Peer>,
  61. log: Vec<LogEntry>,
  62. commit_index: usize,
  63. last_applied: usize,
  64. next_index: Vec<usize>,
  65. match_index: Vec<usize>,
  66. current_step: Vec<i64>,
  67. state: State,
  68. leader_id: Peer,
  69. // Current election cancel token, might be None if no election is running.
  70. election_cancel_token: Option<futures::channel::oneshot::Sender<Term>>,
  71. // Timer will be removed upon shutdown or elected.
  72. election_timer: Option<tokio::time::Delay>,
  73. }
  74. #[derive(Default)]
  75. struct Raft {
  76. inner_state: Arc<Mutex<RaftState>>,
  77. peers: Vec<RpcClient>,
  78. me: Peer,
  79. // new_log_entry: Sender<usize>,
  80. // new_log_entry: Receiver<usize>,
  81. // apply_command_cond: Condvar
  82. keep_running: AtomicBool,
  83. // applyCh: Sender<ApplyMsg>
  84. }
  85. #[derive(Clone, Serialize, Deserialize)]
  86. struct RequestVoteArgs {
  87. term: Term,
  88. candidate_id: Peer,
  89. last_log_index: usize,
  90. last_log_term: Term,
  91. }
  92. #[derive(Clone, Serialize, Deserialize)]
  93. struct RequestVoteReply {
  94. term: Term,
  95. vote_granted: bool,
  96. }
  97. #[derive(Clone, Serialize, Deserialize)]
  98. struct AppendEntriesArgs {
  99. term: Term,
  100. leader_id: Peer,
  101. prev_log_index: usize,
  102. prev_log_term: Term,
  103. entries: Vec<LogEntry>,
  104. leader_commit: usize,
  105. }
  106. #[derive(Clone, Serialize, Deserialize)]
  107. struct AppendEntriesReply {
  108. term: Term,
  109. success: bool,
  110. }
  111. impl Raft {
  112. pub fn new() -> Self {
  113. let raft = Self {
  114. ..Default::default()
  115. };
  116. raft.inner_state.lock().log.push(LogEntry {
  117. term: Default::default(),
  118. index: 0,
  119. command: Command(0),
  120. });
  121. raft
  122. }
  123. pub(crate) fn process_request_vote(
  124. &self,
  125. args: RequestVoteArgs,
  126. ) -> RequestVoteReply {
  127. let mut rf = self.inner_state.lock();
  128. let term = rf.current_term;
  129. if args.term < term {
  130. return RequestVoteReply {
  131. term,
  132. vote_granted: false,
  133. };
  134. } else if args.term > term {
  135. rf.current_term = args.term;
  136. rf.voted_for = None;
  137. rf.state = State::Follower;
  138. rf.reset_election_timer();
  139. rf.stop_current_election();
  140. rf.persist();
  141. }
  142. let voted_for = rf.voted_for;
  143. let (last_log_index, last_log_term) = rf.last_log_index_and_term();
  144. if (voted_for.is_none() || voted_for == Some(args.candidate_id))
  145. && (args.last_log_term > last_log_term
  146. || (args.last_log_term == last_log_term
  147. && args.last_log_index >= last_log_index))
  148. {
  149. rf.voted_for = Some(args.candidate_id);
  150. rf.reset_election_timer();
  151. // No need to stop the election. We are not a candidate.
  152. rf.persist();
  153. RequestVoteReply {
  154. term: args.term,
  155. vote_granted: true,
  156. }
  157. } else {
  158. RequestVoteReply {
  159. term: args.term,
  160. vote_granted: false,
  161. }
  162. }
  163. }
  164. pub(crate) fn process_append_entries(
  165. &self,
  166. args: AppendEntriesArgs,
  167. ) -> AppendEntriesReply {
  168. let mut rf = self.inner_state.lock();
  169. if rf.current_term > args.term {
  170. return AppendEntriesReply {
  171. term: rf.current_term,
  172. success: false,
  173. };
  174. }
  175. let _ = rf.deferred_persist();
  176. if rf.current_term < args.term {
  177. rf.current_term = args.term;
  178. rf.voted_for = None;
  179. }
  180. rf.state = State::Follower;
  181. rf.reset_election_timer();
  182. rf.stop_current_election();
  183. rf.leader_id = args.leader_id;
  184. if rf.log.len() <= args.prev_log_index
  185. || rf.log[args.prev_log_index].term != args.term
  186. {
  187. return AppendEntriesReply {
  188. term: args.term,
  189. success: false,
  190. };
  191. }
  192. for (i, entry) in args.entries.iter().enumerate() {
  193. let index = i + args.prev_log_index + 1;
  194. if rf.log.len() > index {
  195. if rf.log[index].term != entry.term {
  196. rf.log.truncate(index);
  197. rf.log.push(entry.clone());
  198. }
  199. } else {
  200. rf.log.push(entry.clone());
  201. }
  202. }
  203. if args.leader_commit > rf.commit_index {
  204. rf.commit_index = if args.leader_commit < rf.log.len() {
  205. args.leader_commit
  206. } else {
  207. rf.log.len() - 1
  208. };
  209. // TODO: apply commands.
  210. }
  211. AppendEntriesReply {
  212. term: args.term,
  213. success: true,
  214. }
  215. }
  216. fn run_election(&self) {
  217. let me = self.me;
  218. let (term, args, cancel_token) = {
  219. let mut rf = self.inner_state.lock();
  220. let (tx, rx) = futures::channel::oneshot::channel();
  221. rf.current_term.0 += 1;
  222. rf.voted_for = Some(me);
  223. rf.state = State::Candidate;
  224. rf.reset_election_timer();
  225. rf.stop_current_election();
  226. rf.election_cancel_token.replace(tx);
  227. rf.persist();
  228. let term = rf.current_term;
  229. let (last_log_index, last_log_term) = rf.last_log_index_and_term();
  230. (
  231. term,
  232. RequestVoteArgs {
  233. term,
  234. candidate_id: me,
  235. last_log_index,
  236. last_log_term,
  237. },
  238. rx,
  239. )
  240. };
  241. let mut votes = vec![];
  242. for (index, rpc_client) in self.peers.iter().enumerate() {
  243. if index != self.me.0 {
  244. // RpcClient must be cloned to avoid sending its reference
  245. // across threads.
  246. let rpc_client = rpc_client.clone();
  247. // RPCs are started right away.
  248. let one_vote =
  249. tokio::spawn(Self::request_vote(rpc_client, args.clone()));
  250. // Futures must be pinned so that they have Unpin, as required
  251. // by futures::future::select.
  252. votes.push(one_vote);
  253. }
  254. }
  255. tokio::spawn(Self::count_vote_util_cancelled(
  256. term,
  257. self.inner_state.clone(),
  258. votes,
  259. self.peers.len() / 2,
  260. cancel_token,
  261. ));
  262. }
  263. const REQUEST_VOTE_RETRY: usize = 4;
  264. async fn request_vote(
  265. rpc_client: RpcClient,
  266. args: RequestVoteArgs,
  267. ) -> Option<bool> {
  268. let term = args.term;
  269. let reply = retry_rpc(Self::REQUEST_VOTE_RETRY, move |_round| {
  270. rpc_client.clone().call_request_vote(args.clone())
  271. })
  272. .await;
  273. if let Ok(reply) = reply {
  274. return Some(reply.vote_granted && reply.term == term);
  275. }
  276. return None;
  277. }
  278. async fn count_vote_util_cancelled(
  279. term: Term,
  280. rf: Arc<Mutex<RaftState>>,
  281. votes: Vec<tokio::task::JoinHandle<Option<bool>>>,
  282. majority: usize,
  283. cancel_token: futures::channel::oneshot::Receiver<Term>,
  284. ) {
  285. let mut vote_count = 0;
  286. let mut against_count = 0;
  287. let mut cancel_token = cancel_token;
  288. let mut futures_vec = votes;
  289. while vote_count < majority && against_count <= majority {
  290. // Mixing tokio futures with futures-rs ones. Fingers crossed.
  291. let selected = futures::future::select(
  292. cancel_token,
  293. futures::future::select_all(futures_vec),
  294. )
  295. .await;
  296. let ((one_vote, _, rest), new_token) = match selected {
  297. futures::future::Either::Left(_) => break,
  298. futures::future::Either::Right(tuple) => tuple,
  299. };
  300. futures_vec = rest;
  301. cancel_token = new_token;
  302. if let Ok(Some(vote)) = one_vote {
  303. if vote {
  304. vote_count += 1
  305. } else {
  306. against_count += 1
  307. }
  308. }
  309. }
  310. if vote_count < majority {
  311. return;
  312. }
  313. let mut rf = rf.lock();
  314. if rf.current_term == term && rf.state == State::Candidate {
  315. rf.state = State::Leader;
  316. let log_len = rf.log.len();
  317. for item in rf.next_index.iter_mut() {
  318. *item = log_len;
  319. }
  320. for item in rf.match_index.iter_mut() {
  321. *item = 0;
  322. }
  323. // TODO: send heartbeats.
  324. // Drop the timer and cancel token.
  325. rf.election_cancel_token.take();
  326. rf.election_timer.take();
  327. rf.persist();
  328. }
  329. }
  330. fn schedule_heartbeats(&self, interval: Duration) {
  331. for (peer_index, rpc_client) in self.peers.iter().enumerate() {
  332. if peer_index != self.me.0 {
  333. // Interval and rf are now owned by the outer async function.
  334. let mut interval = tokio::time::interval(interval);
  335. let rf = self.inner_state.clone();
  336. // RPC client must be cloned into the outer async function.
  337. let rpc_client = rpc_client.clone();
  338. tokio::spawn(async move {
  339. loop {
  340. // TODO: shutdown signal or cancel token.
  341. interval.tick().await;
  342. if let Some(args) = Self::build_heartbeat(&rf) {
  343. tokio::spawn(Self::send_heartbeat(
  344. rpc_client.clone(),
  345. args,
  346. ));
  347. }
  348. }
  349. });
  350. }
  351. }
  352. }
  353. fn build_heartbeat(
  354. rf: &Arc<Mutex<RaftState>>,
  355. ) -> Option<AppendEntriesArgs> {
  356. let rf = rf.lock();
  357. if rf.state == State::Leader {
  358. return None;
  359. }
  360. let (last_log_index, last_log_term) = rf.last_log_index_and_term();
  361. let args = AppendEntriesArgs {
  362. term: rf.current_term,
  363. leader_id: rf.leader_id,
  364. prev_log_index: last_log_index,
  365. prev_log_term: last_log_term,
  366. entries: vec![],
  367. leader_commit: rf.commit_index,
  368. };
  369. Some(args)
  370. }
  371. const HEARTBEAT_RETRY: usize = 3;
  372. async fn send_heartbeat(
  373. rpc_client: RpcClient,
  374. args: AppendEntriesArgs,
  375. ) -> std::io::Result<()> {
  376. retry_rpc(Self::HEARTBEAT_RETRY, move |_round| {
  377. rpc_client.clone().call_append_entries(args.clone())
  378. })
  379. .await?;
  380. Ok(())
  381. }
  382. fn run_log_entry_daemon(
  383. &self,
  384. ) -> (
  385. std::thread::JoinHandle<()>,
  386. std::sync::mpsc::Sender<Option<Peer>>,
  387. ) {
  388. let (tx, rx) = std::sync::mpsc::channel::<Option<Peer>>();
  389. // Clone everything that the thread needs.
  390. let rerun = tx.clone();
  391. let peers = self.peers.clone();
  392. let rf = self.inner_state.clone();
  393. let me = self.me;
  394. let handle = std::thread::spawn(move || {
  395. while let Ok(peer) = rx.recv() {
  396. for (i, rpc_client) in peers.iter().enumerate() {
  397. if i != me.0 && peer.map(|p| p.0 == i).unwrap_or(true) {
  398. tokio::spawn(Self::sync_log_entry(
  399. rf.clone(),
  400. rpc_client.clone(),
  401. i,
  402. rerun.clone(),
  403. ));
  404. }
  405. }
  406. }
  407. });
  408. (handle, tx)
  409. }
  410. async fn sync_log_entry(
  411. rf: Arc<Mutex<RaftState>>,
  412. rpc_client: RpcClient,
  413. peer_index: usize,
  414. rerun: std::sync::mpsc::Sender<Option<Peer>>,
  415. ) {
  416. // TODO: cancel in flight changes?
  417. let args = Self::build_append_entries(&rf, peer_index);
  418. let term = args.term;
  419. let match_index = args.prev_log_index + args.entries.len();
  420. let succeeded = Self::append_entries(rpc_client, args).await;
  421. match succeeded {
  422. Ok(Some(succeeded)) => {
  423. if succeeded {
  424. let mut rf = rf.lock();
  425. rf.next_index[peer_index] = match_index + 1;
  426. if match_index > rf.match_index[peer_index] {
  427. rf.match_index[peer_index] = match_index;
  428. if rf.state == State::Leader && rf.current_term == term
  429. {
  430. let mut matched = rf.match_index.to_vec();
  431. let mid = matched.len() / 2 + 1;
  432. matched.sort();
  433. let new_commit_index = matched[mid];
  434. if new_commit_index > rf.commit_index
  435. && rf.log[new_commit_index].term
  436. == rf.current_term
  437. {
  438. rf.commit_index = new_commit_index;
  439. // TODO: apply command.
  440. }
  441. }
  442. }
  443. } else {
  444. let mut rf = rf.lock();
  445. let step = &mut rf.current_step[peer_index];
  446. *step += 1;
  447. let diff = (1 << 8) << *step;
  448. let next_index = &mut rf.next_index[peer_index];
  449. if diff >= *next_index {
  450. *next_index = 1usize;
  451. } else {
  452. *next_index -= diff;
  453. }
  454. rerun.send(Some(Peer(peer_index)));
  455. }
  456. }
  457. // Do nothing, not our term anymore.
  458. Ok(None) => {}
  459. Err(_) => {
  460. tokio::time::delay_for(Duration::from_millis(
  461. HEARTBEAT_INTERVAL_MILLIS,
  462. ))
  463. .await;
  464. rerun.send(Some(Peer(peer_index)));
  465. }
  466. };
  467. }
  468. fn build_append_entries(
  469. rf: &Arc<Mutex<RaftState>>,
  470. peer_index: usize,
  471. ) -> AppendEntriesArgs {
  472. let rf = rf.lock();
  473. let (prev_log_index, prev_log_term) = rf.last_log_index_and_term();
  474. AppendEntriesArgs {
  475. term: rf.current_term,
  476. leader_id: rf.leader_id,
  477. prev_log_index,
  478. prev_log_term,
  479. entries: rf.log[rf.next_index[peer_index]..].to_vec(),
  480. leader_commit: rf.commit_index,
  481. }
  482. }
  483. const APPEND_ENTRIES_RETRY: usize = 3;
  484. async fn append_entries(
  485. rpc_client: RpcClient,
  486. args: AppendEntriesArgs,
  487. ) -> std::io::Result<Option<bool>> {
  488. let term = args.term;
  489. let reply = retry_rpc(Self::APPEND_ENTRIES_RETRY, move |_round| {
  490. rpc_client.clone().call_append_entries(args.clone())
  491. })
  492. .await?;
  493. Ok(if reply.term == term {
  494. Some(reply.success)
  495. } else {
  496. None
  497. })
  498. }
  499. }
  500. const HEARTBEAT_INTERVAL_MILLIS: u64 = 150;
  501. const ELECTION_TIMEOUT_BASE_MILLIS: u64 = 150;
  502. const ELECTION_TIMEOUT_VAR_MILLIS: u64 = 250;
  503. impl RaftState {
  504. fn reset_election_timer(&mut self) {
  505. self.election_timer.as_mut().map(|timer| {
  506. timer.reset(
  507. (std::time::Instant::now() + Self::election_timeout()).into(),
  508. )
  509. });
  510. }
  511. fn election_timeout() -> Duration {
  512. Duration::from_millis(
  513. ELECTION_TIMEOUT_BASE_MILLIS
  514. + thread_rng().gen_range(0, ELECTION_TIMEOUT_VAR_MILLIS),
  515. )
  516. }
  517. fn stop_current_election(&mut self) {
  518. self.election_cancel_token
  519. .take()
  520. .map(|sender| sender.send(self.current_term));
  521. }
  522. fn persist(&self) {
  523. // TODO: implement
  524. }
  525. fn deferred_persist(&self) -> impl Drop + '_ {
  526. DropGuard::new(move || self.persist())
  527. }
  528. fn last_log_index_and_term(&self) -> (usize, Term) {
  529. let len = self.log.len();
  530. assert!(len > 0, "There should always be at least one entry in log");
  531. (len - 1, self.log.last().unwrap().term)
  532. }
  533. }