LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - simulation.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 97.7 % 300 293
Test Date: 2024-10-22 22:13:45 Functions: 88.9 % 63 56

            Line data    Source code
       1              : use std::{cell::Cell, str::FromStr, sync::Arc};
       2              : 
       3              : use crate::walproposer_sim::{safekeeper::run_server, walproposer_api::SimulationApi};
       4              : use desim::{
       5              :     executor::{self, ExternalHandle},
       6              :     node_os::NodeOs,
       7              :     options::{Delay, NetworkOptions},
       8              :     proto::{AnyMessage, NodeEvent},
       9              :     world::Node,
      10              :     world::World,
      11              : };
      12              : use rand::{Rng, SeedableRng};
      13              : use tracing::{debug, info_span, warn};
      14              : use utils::{id::TenantTimelineId, lsn::Lsn};
      15              : use walproposer::walproposer::{Config, Wrapper};
      16              : 
      17              : use super::{
      18              :     log::SimClock, safekeeper_disk::SafekeeperDisk, walproposer_api,
      19              :     walproposer_disk::DiskWalProposer,
      20              : };
      21              : 
      22              : /// Simulated safekeeper node.
      23              : pub struct SafekeeperNode {
      24              :     pub node: Arc<Node>,
      25              :     pub id: u32,
      26              :     pub disk: Arc<SafekeeperDisk>,
      27              :     pub thread: Cell<ExternalHandle>,
      28              : }
      29              : 
      30              : impl SafekeeperNode {
      31              :     /// Create and start a safekeeper at the specified Node.
      32         1524 :     pub fn new(node: Arc<Node>) -> Self {
      33         1524 :         let disk = Arc::new(SafekeeperDisk::new());
      34         1524 :         let thread = Cell::new(SafekeeperNode::launch(disk.clone(), node.clone()));
      35         1524 : 
      36         1524 :         Self {
      37         1524 :             id: node.id,
      38         1524 :             node,
      39         1524 :             disk,
      40         1524 :             thread,
      41         1524 :         }
      42         1524 :     }
      43              : 
      44         9904 :     fn launch(disk: Arc<SafekeeperDisk>, node: Arc<Node>) -> ExternalHandle {
      45         9904 :         // start the server thread
      46         9904 :         node.launch(move |os| {
      47         9727 :             run_server(os, disk).expect("server should finish without errors");
      48         9904 :         })
      49         9904 :     }
      50              : 
      51              :     /// Restart the safekeeper.
      52         8380 :     pub fn restart(&self) {
      53         8380 :         let new_thread = SafekeeperNode::launch(self.disk.clone(), self.node.clone());
      54         8380 :         let old_thread = self.thread.replace(new_thread);
      55         8380 :         old_thread.crash_stop();
      56         8380 :     }
      57              : }
      58              : 
      59              : /// Simulated walproposer node.
      60              : pub struct WalProposer {
      61              :     thread: ExternalHandle,
      62              :     node: Arc<Node>,
      63              :     disk: Arc<DiskWalProposer>,
      64              :     sync_safekeepers: bool,
      65              : }
      66              : 
      67              : impl WalProposer {
      68              :     /// Generic start function for both modes.
      69         9177 :     fn start(
      70         9177 :         os: NodeOs,
      71         9177 :         disk: Arc<DiskWalProposer>,
      72         9177 :         ttid: TenantTimelineId,
      73         9177 :         addrs: Vec<String>,
      74         9177 :         lsn: Option<Lsn>,
      75         9177 :     ) {
      76         9177 :         let sync_safekeepers = lsn.is_none();
      77              : 
      78         9177 :         let _enter = if sync_safekeepers {
      79         8810 :             info_span!("sync", started = executor::now()).entered()
      80              :         } else {
      81          367 :             info_span!("walproposer", started = executor::now()).entered()
      82              :         };
      83              : 
      84         9177 :         os.log_event(format!("started;walproposer;{}", sync_safekeepers as i32));
      85         9177 : 
      86         9177 :         let config = Config {
      87         9177 :             ttid,
      88         9177 :             safekeepers_list: addrs,
      89         9177 :             safekeeper_reconnect_timeout: 1000,
      90         9177 :             safekeeper_connection_timeout: 5000,
      91         9177 :             sync_safekeepers,
      92         9177 :         };
      93         9177 :         let args = walproposer_api::Args {
      94         9177 :             os,
      95         9177 :             config: config.clone(),
      96         9177 :             disk,
      97         9177 :             redo_start_lsn: lsn,
      98         9177 :         };
      99         9177 :         let api = SimulationApi::new(args);
     100         9177 :         let wp = Wrapper::new(Box::new(api), config);
     101         9177 :         wp.start();
     102         9177 :     }
     103              : 
     104              :     /// Start walproposer in a sync_safekeepers mode.
     105         9003 :     pub fn launch_sync(ttid: TenantTimelineId, addrs: Vec<String>, node: Arc<Node>) -> Self {
     106         9003 :         debug!("sync_safekeepers started at node {}", node.id);
     107         9003 :         let disk = DiskWalProposer::new();
     108         9003 :         let disk_wp = disk.clone();
     109         9003 : 
     110         9003 :         // start the client thread
     111         9003 :         let handle = node.launch(move |os| {
     112         8810 :             WalProposer::start(os, disk_wp, ttid, addrs, None);
     113         9003 :         });
     114         9003 : 
     115         9003 :         Self {
     116         9003 :             thread: handle,
     117         9003 :             node,
     118         9003 :             disk,
     119         9003 :             sync_safekeepers: true,
     120         9003 :         }
     121         9003 :     }
     122              : 
     123              :     /// Start walproposer in a normal mode.
     124          367 :     pub fn launch_walproposer(
     125          367 :         ttid: TenantTimelineId,
     126          367 :         addrs: Vec<String>,
     127          367 :         node: Arc<Node>,
     128          367 :         lsn: Lsn,
     129          367 :     ) -> Self {
     130          367 :         debug!("walproposer started at node {}", node.id);
     131          367 :         let disk = DiskWalProposer::new();
     132          367 :         disk.lock().reset_to(lsn);
     133          367 :         let disk_wp = disk.clone();
     134          367 : 
     135          367 :         // start the client thread
     136          367 :         let handle = node.launch(move |os| {
     137          367 :             WalProposer::start(os, disk_wp, ttid, addrs, Some(lsn));
     138          367 :         });
     139          367 : 
     140          367 :         Self {
     141          367 :             thread: handle,
     142          367 :             node,
     143          367 :             disk,
     144          367 :             sync_safekeepers: false,
     145          367 :         }
     146          367 :     }
     147              : 
     148          553 :     pub fn write_tx(&mut self, cnt: usize) {
     149          553 :         let start_lsn = self.disk.lock().flush_rec_ptr();
     150          553 : 
     151        11679 :         for _ in 0..cnt {
     152        11679 :             self.disk
     153        11679 :                 .lock()
     154        11679 :                 .insert_logical_message("prefix", b"message")
     155        11679 :                 .expect("failed to generate logical message");
     156        11679 :         }
     157              : 
     158          553 :         let end_lsn = self.disk.lock().flush_rec_ptr();
     159          553 : 
     160          553 :         // log event
     161          553 :         self.node
     162          553 :             .log_event(format!("write_wal;{};{};{}", start_lsn.0, end_lsn.0, cnt));
     163          553 : 
     164          553 :         // now we need to set "Latch" in walproposer
     165          553 :         self.node
     166          553 :             .node_events()
     167          553 :             .send(NodeEvent::Internal(AnyMessage::Just32(0)));
     168          553 :     }
     169              : 
     170         8442 :     pub fn stop(&self) {
     171         8442 :         self.thread.crash_stop();
     172         8442 :     }
     173              : }
     174              : 
     175              : /// Holds basic simulation settings, such as network options.
     176              : pub struct TestConfig {
     177              :     pub network: NetworkOptions,
     178              :     pub timeout: u64,
     179              :     pub clock: Option<SimClock>,
     180              : }
     181              : 
     182              : impl TestConfig {
     183              :     /// Create a new TestConfig with default settings.
     184            9 :     pub fn new(clock: Option<SimClock>) -> Self {
     185            9 :         Self {
     186            9 :             network: NetworkOptions {
     187            9 :                 keepalive_timeout: Some(2000),
     188            9 :                 connect_delay: Delay {
     189            9 :                     min: 1,
     190            9 :                     max: 5,
     191            9 :                     fail_prob: 0.0,
     192            9 :                 },
     193            9 :                 send_delay: Delay {
     194            9 :                     min: 1,
     195            9 :                     max: 5,
     196            9 :                     fail_prob: 0.0,
     197            9 :                 },
     198            9 :             },
     199            9 :             timeout: 1_000 * 10,
     200            9 :             clock,
     201            9 :         }
     202            9 :     }
     203              : 
     204              :     /// Start a new simulation with the specified seed.
     205          508 :     pub fn start(&self, seed: u64) -> Test {
     206          508 :         let world = Arc::new(World::new(seed, Arc::new(self.network.clone())));
     207              : 
     208          508 :         if let Some(clock) = &self.clock {
     209          508 :             clock.set_clock(world.clock());
     210          508 :         }
     211              : 
     212          508 :         let servers = [
     213          508 :             SafekeeperNode::new(world.new_node()),
     214          508 :             SafekeeperNode::new(world.new_node()),
     215          508 :             SafekeeperNode::new(world.new_node()),
     216          508 :         ];
     217          508 : 
     218          508 :         let server_ids = [servers[0].id, servers[1].id, servers[2].id];
     219         1524 :         let safekeepers_addrs = server_ids.map(|id| format!("node:{}", id)).to_vec();
     220          508 : 
     221          508 :         let ttid = TenantTimelineId::generate();
     222          508 : 
     223          508 :         Test {
     224          508 :             world,
     225          508 :             servers,
     226          508 :             sk_list: safekeepers_addrs,
     227          508 :             ttid,
     228          508 :             timeout: self.timeout,
     229          508 :         }
     230          508 :     }
     231              : }
     232              : 
     233              : /// Holds simulation state.
     234              : pub struct Test {
     235              :     pub world: Arc<World>,
     236              :     pub servers: [SafekeeperNode; 3],
     237              :     pub sk_list: Vec<String>,
     238              :     pub ttid: TenantTimelineId,
     239              :     pub timeout: u64,
     240              : }
     241              : 
     242              : impl Test {
     243              :     /// Start a sync_safekeepers thread and wait for it to finish.
     244            6 :     pub fn sync_safekeepers(&self) -> anyhow::Result<Lsn> {
     245            6 :         let wp = self.launch_sync_safekeepers();
     246            6 : 
     247            6 :         // poll until exit or timeout
     248            6 :         let time_limit = self.timeout;
     249          230 :         while self.world.step() && self.world.now() < time_limit && !wp.thread.is_finished() {}
     250              : 
     251            6 :         if !wp.thread.is_finished() {
     252            0 :             anyhow::bail!("timeout or idle stuck");
     253            6 :         }
     254            6 : 
     255            6 :         let res = wp.thread.result();
     256            6 :         if res.0 != 0 {
     257            0 :             anyhow::bail!("non-zero exitcode: {:?}", res);
     258            6 :         }
     259            6 :         let lsn = Lsn::from_str(&res.1)?;
     260            6 :         Ok(lsn)
     261            6 :     }
     262              : 
     263              :     /// Spawn a new sync_safekeepers thread.
     264         9003 :     pub fn launch_sync_safekeepers(&self) -> WalProposer {
     265         9003 :         WalProposer::launch_sync(self.ttid, self.sk_list.clone(), self.world.new_node())
     266         9003 :     }
     267              : 
     268              :     /// Spawn a new walproposer thread.
     269          367 :     pub fn launch_walproposer(&self, lsn: Lsn) -> WalProposer {
     270          367 :         let lsn = if lsn.0 == 0 {
     271              :             // usual LSN after basebackup
     272          172 :             Lsn(21623024)
     273              :         } else {
     274          195 :             lsn
     275              :         };
     276              : 
     277          367 :         WalProposer::launch_walproposer(self.ttid, self.sk_list.clone(), self.world.new_node(), lsn)
     278          367 :     }
     279              : 
     280              :     /// Execute the simulation for the specified duration.
     281          105 :     pub fn poll_for_duration(&self, duration: u64) {
     282          105 :         let time_limit = std::cmp::min(self.world.now() + duration, self.timeout);
     283         1762 :         while self.world.step() && self.world.now() < time_limit {}
     284          105 :     }
     285              : 
     286              :     /// Execute the simulation together with events defined in some schedule.
     287          504 :     pub fn run_schedule(&self, schedule: &Schedule) -> anyhow::Result<()> {
     288          504 :         // scheduling empty events so that world will stop in those points
     289          504 :         {
     290          504 :             let clock = self.world.clock();
     291          504 : 
     292          504 :             let now = self.world.now();
     293        25793 :             for (time, _) in schedule {
     294        25289 :                 if *time < now {
     295            0 :                     continue;
     296        25289 :                 }
     297        25289 :                 clock.schedule_fake(*time - now);
     298              :             }
     299              :         }
     300              : 
     301          504 :         let mut wp = self.launch_sync_safekeepers();
     302          504 : 
     303          504 :         let mut skipped_tx = 0;
     304          504 :         let mut started_tx = 0;
     305          504 : 
     306          504 :         let mut schedule_ptr = 0;
     307              : 
     308              :         loop {
     309        26207 :             if wp.sync_safekeepers && wp.thread.is_finished() {
     310          416 :                 let res = wp.thread.result();
     311          416 :                 if res.0 != 0 {
     312           52 :                     warn!("sync non-zero exitcode: {:?}", res);
     313           52 :                     debug!("restarting sync_safekeepers");
     314              :                     // restart the sync_safekeepers
     315           52 :                     wp = self.launch_sync_safekeepers();
     316           52 :                     continue;
     317          364 :                 }
     318          364 :                 let lsn = Lsn::from_str(&res.1)?;
     319          364 :                 debug!("sync_safekeepers finished at LSN {}", lsn);
     320          364 :                 wp = self.launch_walproposer(lsn);
     321          364 :                 debug!("walproposer started at thread {}", wp.thread.id());
     322        25791 :             }
     323              : 
     324        26155 :             let now = self.world.now();
     325        51444 :             while schedule_ptr < schedule.len() && schedule[schedule_ptr].0 <= now {
     326        25289 :                 if now != schedule[schedule_ptr].0 {
     327            0 :                     warn!("skipped event {:?} at {}", schedule[schedule_ptr], now);
     328        25289 :                 }
     329              : 
     330        25289 :                 let action = &schedule[schedule_ptr].1;
     331        25289 :                 match action {
     332         8469 :                     TestAction::WriteTx(size) => {
     333         8469 :                         if !wp.sync_safekeepers && !wp.thread.is_finished() {
     334          451 :                             started_tx += *size;
     335          451 :                             wp.write_tx(*size);
     336          451 :                             debug!("written {} transactions", size);
     337              :                         } else {
     338         8018 :                             skipped_tx += size;
     339         8018 :                             debug!("skipped {} transactions", size);
     340              :                         }
     341              :                     }
     342         8379 :                     TestAction::RestartSafekeeper(id) => {
     343         8379 :                         debug!("restarting safekeeper {}", id);
     344         8379 :                         self.servers[*id].restart();
     345              :                     }
     346              :                     TestAction::RestartWalProposer => {
     347         8441 :                         debug!("restarting sync_safekeepers");
     348         8441 :                         wp.stop();
     349         8441 :                         wp = self.launch_sync_safekeepers();
     350              :                     }
     351              :                 }
     352        25289 :                 schedule_ptr += 1;
     353              :             }
     354              : 
     355        26155 :             if schedule_ptr == schedule.len() {
     356          504 :                 break;
     357        25651 :             }
     358        25651 :             let next_event_time = schedule[schedule_ptr].0;
     359        25651 : 
     360        25651 :             // poll until the next event
     361        25651 :             if wp.thread.is_finished() {
     362          239 :                 while self.world.step() && self.world.now() < next_event_time {}
     363              :             } else {
     364       402111 :                 while self.world.step()
     365       402111 :                     && self.world.now() < next_event_time
     366       376902 :                     && !wp.thread.is_finished()
     367       376478 :                 {}
     368              :             }
     369              :         }
     370              : 
     371          504 :         debug!(
     372            0 :             "finished schedule, total steps: {}",
     373            0 :             self.world.get_thread_step_count()
     374              :         );
     375          504 :         debug!("skipped_tx: {}", skipped_tx);
     376          504 :         debug!("started_tx: {}", started_tx);
     377              : 
     378          504 :         Ok(())
     379          504 :     }
     380              : }
     381              : 
     382              : #[derive(Debug, Clone)]
     383              : pub enum TestAction {
     384              :     WriteTx(usize),
     385              :     RestartSafekeeper(usize),
     386              :     RestartWalProposer,
     387              : }
     388              : 
     389              : pub type Schedule = Vec<(u64, TestAction)>;
     390              : 
     391          502 : pub fn generate_schedule(seed: u64) -> Schedule {
     392          502 :     let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
     393          502 :     let mut schedule = Vec::new();
     394          502 :     let mut time = 0;
     395          502 : 
     396          502 :     let cnt = rng.gen_range(1..100);
     397          502 : 
     398          502 :     for _ in 0..cnt {
     399        25174 :         time += rng.gen_range(0..500);
     400        25174 :         let action = match rng.gen_range(0..3) {
     401         8362 :             0 => TestAction::WriteTx(rng.gen_range(1..10)),
     402         8373 :             1 => TestAction::RestartSafekeeper(rng.gen_range(0..3)),
     403         8439 :             2 => TestAction::RestartWalProposer,
     404            0 :             _ => unreachable!(),
     405              :         };
     406        25174 :         schedule.push((time, action));
     407              :     }
     408              : 
     409          502 :     schedule
     410          502 : }
     411              : 
     412          502 : pub fn generate_network_opts(seed: u64) -> NetworkOptions {
     413          502 :     let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
     414          502 : 
     415          502 :     let timeout = rng.gen_range(100..2000);
     416          502 :     let max_delay = rng.gen_range(1..2 * timeout);
     417          502 :     let min_delay = rng.gen_range(1..=max_delay);
     418          502 : 
     419          502 :     let max_fail_prob = rng.gen_range(0.0..0.9);
     420          502 :     let connect_fail_prob = rng.gen_range(0.0..max_fail_prob);
     421          502 :     let send_fail_prob = rng.gen_range(0.0..connect_fail_prob);
     422          502 : 
     423          502 :     NetworkOptions {
     424          502 :         keepalive_timeout: Some(timeout),
     425          502 :         connect_delay: Delay {
     426          502 :             min: min_delay,
     427          502 :             max: max_delay,
     428          502 :             fail_prob: connect_fail_prob,
     429          502 :         },
     430          502 :         send_delay: Delay {
     431          502 :             min: min_delay,
     432          502 :             max: max_delay,
     433          502 :             fail_prob: send_fail_prob,
     434          502 :         },
     435          502 :     }
     436          502 : }
        

Generated by: LCOV version 2.1-beta