Line data Source code
1 : use std::cell::Cell;
2 : use std::str::FromStr;
3 : use std::sync::Arc;
4 :
5 : use desim::executor::{self, ExternalHandle};
6 : use desim::node_os::NodeOs;
7 : use desim::options::{Delay, NetworkOptions};
8 : use desim::proto::{AnyMessage, NodeEvent};
9 : use desim::world::{Node, World};
10 : use rand::{Rng, SeedableRng};
11 : use tracing::{debug, info_span, warn};
12 : use utils::id::TenantTimelineId;
13 : use utils::lsn::Lsn;
14 : use walproposer::walproposer::{Config, Wrapper};
15 :
16 : use super::log::SimClock;
17 : use super::safekeeper_disk::SafekeeperDisk;
18 : use super::walproposer_api;
19 : use super::walproposer_disk::DiskWalProposer;
20 : use crate::walproposer_sim::safekeeper::run_server;
21 : use crate::walproposer_sim::walproposer_api::SimulationApi;
22 :
23 : /// Simulated safekeeper node.
24 : pub struct SafekeeperNode {
25 : pub node: Arc<Node>,
26 : pub id: u32,
27 : pub disk: Arc<SafekeeperDisk>,
28 : pub thread: Cell<ExternalHandle>,
29 : }
30 :
31 : impl SafekeeperNode {
32 : /// Create and start a safekeeper at the specified Node.
33 1524 : pub fn new(node: Arc<Node>) -> Self {
34 1524 : let disk = Arc::new(SafekeeperDisk::new());
35 1524 : let thread = Cell::new(SafekeeperNode::launch(disk.clone(), node.clone()));
36 1524 :
37 1524 : Self {
38 1524 : id: node.id,
39 1524 : node,
40 1524 : disk,
41 1524 : thread,
42 1524 : }
43 1524 : }
44 :
45 9900 : fn launch(disk: Arc<SafekeeperDisk>, node: Arc<Node>) -> ExternalHandle {
46 9900 : // start the server thread
47 9900 : node.launch(move |os| {
48 9741 : run_server(os, disk).expect("server should finish without errors");
49 9900 : })
50 9900 : }
51 :
52 : /// Restart the safekeeper.
53 8376 : pub fn restart(&self) {
54 8376 : let new_thread = SafekeeperNode::launch(self.disk.clone(), self.node.clone());
55 8376 : let old_thread = self.thread.replace(new_thread);
56 8376 : old_thread.crash_stop();
57 8376 : }
58 : }
59 :
60 : /// Simulated walproposer node.
61 : pub struct WalProposer {
62 : thread: ExternalHandle,
63 : node: Arc<Node>,
64 : disk: Arc<DiskWalProposer>,
65 : sync_safekeepers: bool,
66 : }
67 :
68 : impl WalProposer {
69 : /// Generic start function for both modes.
70 9140 : fn start(
71 9140 : os: NodeOs,
72 9140 : disk: Arc<DiskWalProposer>,
73 9140 : ttid: TenantTimelineId,
74 9140 : addrs: Vec<String>,
75 9140 : lsn: Option<Lsn>,
76 9140 : ) {
77 9140 : let sync_safekeepers = lsn.is_none();
78 :
79 9140 : let _enter = if sync_safekeepers {
80 8787 : info_span!("sync", started = executor::now()).entered()
81 : } else {
82 353 : info_span!("walproposer", started = executor::now()).entered()
83 : };
84 :
85 9140 : os.log_event(format!("started;walproposer;{}", sync_safekeepers as i32));
86 9140 :
87 9140 : let config = Config {
88 9140 : ttid,
89 9140 : safekeepers_list: addrs,
90 9140 : safekeeper_reconnect_timeout: 1000,
91 9140 : safekeeper_connection_timeout: 5000,
92 9140 : sync_safekeepers,
93 9140 : };
94 9140 : let args = walproposer_api::Args {
95 9140 : os,
96 9140 : config: config.clone(),
97 9140 : disk,
98 9140 : redo_start_lsn: lsn,
99 9140 : };
100 9140 : let api = SimulationApi::new(args);
101 9140 : let wp = Wrapper::new(Box::new(api), config);
102 9140 : wp.start();
103 9140 : }
104 :
105 : /// Start walproposer in a sync_safekeepers mode.
106 8985 : pub fn launch_sync(ttid: TenantTimelineId, addrs: Vec<String>, node: Arc<Node>) -> Self {
107 8985 : debug!("sync_safekeepers started at node {}", node.id);
108 8985 : let disk = DiskWalProposer::new();
109 8985 : let disk_wp = disk.clone();
110 8985 :
111 8985 : // start the client thread
112 8985 : let handle = node.launch(move |os| {
113 8787 : WalProposer::start(os, disk_wp, ttid, addrs, None);
114 8985 : });
115 8985 :
116 8985 : Self {
117 8985 : thread: handle,
118 8985 : node,
119 8985 : disk,
120 8985 : sync_safekeepers: true,
121 8985 : }
122 8985 : }
123 :
124 : /// Start walproposer in a normal mode.
125 353 : pub fn launch_walproposer(
126 353 : ttid: TenantTimelineId,
127 353 : addrs: Vec<String>,
128 353 : node: Arc<Node>,
129 353 : lsn: Lsn,
130 353 : ) -> Self {
131 353 : debug!("walproposer started at node {}", node.id);
132 353 : let disk = DiskWalProposer::new();
133 353 : disk.lock().reset_to(lsn);
134 353 : let disk_wp = disk.clone();
135 353 :
136 353 : // start the client thread
137 353 : let handle = node.launch(move |os| {
138 353 : WalProposer::start(os, disk_wp, ttid, addrs, Some(lsn));
139 353 : });
140 353 :
141 353 : Self {
142 353 : thread: handle,
143 353 : node,
144 353 : disk,
145 353 : sync_safekeepers: false,
146 353 : }
147 353 : }
148 :
149 579 : pub fn write_tx(&mut self, cnt: usize) {
150 579 : let start_lsn = self.disk.lock().flush_rec_ptr();
151 579 :
152 11729 : for _ in 0..cnt {
153 11729 : self.disk
154 11729 : .lock()
155 11729 : .insert_logical_message(c"prefix", b"message");
156 11729 : }
157 :
158 579 : let end_lsn = self.disk.lock().flush_rec_ptr();
159 579 :
160 579 : // log event
161 579 : self.node
162 579 : .log_event(format!("write_wal;{};{};{}", start_lsn.0, end_lsn.0, cnt));
163 579 :
164 579 : // now we need to set "Latch" in walproposer
165 579 : self.node
166 579 : .node_events()
167 579 : .send(NodeEvent::Internal(AnyMessage::Just32(0)));
168 579 : }
169 :
170 8405 : pub fn stop(&self) {
171 8405 : self.thread.crash_stop();
172 8405 : }
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 8985 : pub fn launch_sync_safekeepers(&self) -> WalProposer {
265 8985 : WalProposer::launch_sync(self.ttid, self.sk_list.clone(), self.world.new_node())
266 8985 : }
267 :
268 : /// Spawn a new walproposer thread.
269 353 : pub fn launch_walproposer(&self, lsn: Lsn) -> WalProposer {
270 353 : let lsn = if lsn.0 == 0 {
271 : // usual LSN after basebackup
272 191 : Lsn(21623024)
273 : } else {
274 162 : lsn
275 : };
276 :
277 353 : WalProposer::launch_walproposer(self.ttid, self.sk_list.clone(), self.world.new_node(), lsn)
278 353 : }
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 25755 : for (time, _) in schedule {
294 25251 : if *time < now {
295 0 : continue;
296 25251 : }
297 25251 : 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 26197 : if wp.sync_safekeepers && wp.thread.is_finished() {
310 421 : let res = wp.thread.result();
311 421 : if res.0 != 0 {
312 71 : warn!("sync non-zero exitcode: {:?}", res);
313 71 : debug!("restarting sync_safekeepers");
314 : // restart the sync_safekeepers
315 71 : wp = self.launch_sync_safekeepers();
316 71 : continue;
317 350 : }
318 350 : let lsn = Lsn::from_str(&res.1)?;
319 350 : debug!("sync_safekeepers finished at LSN {}", lsn);
320 350 : wp = self.launch_walproposer(lsn);
321 350 : debug!("walproposer started at thread {}", wp.thread.id());
322 25776 : }
323 :
324 26126 : let now = self.world.now();
325 51377 : while schedule_ptr < schedule.len() && schedule[schedule_ptr].0 <= now {
326 25251 : if now != schedule[schedule_ptr].0 {
327 0 : warn!("skipped event {:?} at {}", schedule[schedule_ptr], now);
328 25251 : }
329 :
330 25251 : let action = &schedule[schedule_ptr].1;
331 25251 : match action {
332 8472 : TestAction::WriteTx(size) => {
333 8472 : if !wp.sync_safekeepers && !wp.thread.is_finished() {
334 477 : started_tx += *size;
335 477 : wp.write_tx(*size);
336 477 : debug!("written {} transactions", size);
337 : } else {
338 7995 : skipped_tx += size;
339 7995 : debug!("skipped {} transactions", size);
340 : }
341 : }
342 8375 : TestAction::RestartSafekeeper(id) => {
343 8375 : debug!("restarting safekeeper {}", id);
344 8375 : self.servers[*id].restart();
345 : }
346 : TestAction::RestartWalProposer => {
347 8404 : debug!("restarting sync_safekeepers");
348 8404 : wp.stop();
349 8404 : wp = self.launch_sync_safekeepers();
350 : }
351 : }
352 25251 : schedule_ptr += 1;
353 : }
354 :
355 26126 : if schedule_ptr == schedule.len() {
356 504 : break;
357 25622 : }
358 25622 : let next_event_time = schedule[schedule_ptr].0;
359 25622 :
360 25622 : // poll until the next event
361 25622 : if wp.thread.is_finished() {
362 31 : while self.world.step() && self.world.now() < next_event_time {}
363 : } else {
364 406841 : while self.world.step()
365 406841 : && self.world.now() < next_event_time
366 381651 : && !wp.thread.is_finished()
367 381225 : {}
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 25136 : time += rng.gen_range(0..500);
400 25136 : let action = match rng.gen_range(0..3) {
401 8365 : 0 => TestAction::WriteTx(rng.gen_range(1..10)),
402 8369 : 1 => TestAction::RestartSafekeeper(rng.gen_range(0..3)),
403 8402 : 2 => TestAction::RestartWalProposer,
404 0 : _ => unreachable!(),
405 : };
406 25136 : 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 : }
|