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 6024 : pub fn new(node: Arc<Node>) -> Self {
33 6024 : let disk = Arc::new(SafekeeperDisk::new());
34 6024 : let thread = Cell::new(SafekeeperNode::launch(disk.clone(), node.clone()));
35 6024 :
36 6024 : Self {
37 6024 : id: node.id,
38 6024 : node,
39 6024 : disk,
40 6024 : thread,
41 6024 : }
42 6024 : }
43 :
44 39689 : fn launch(disk: Arc<SafekeeperDisk>, node: Arc<Node>) -> ExternalHandle {
45 39689 : // start the server thread
46 39689 : node.launch(move |os| {
47 39015 : run_server(os, disk).expect("server should finish without errors");
48 39689 : })
49 39689 : }
50 :
51 : /// Restart the safekeeper.
52 33665 : pub fn restart(&self) {
53 33665 : let new_thread = SafekeeperNode::launch(self.disk.clone(), self.node.clone());
54 33665 : let old_thread = self.thread.replace(new_thread);
55 33665 : old_thread.crash_stop();
56 33665 : }
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 36263 : fn start(
70 36263 : os: NodeOs,
71 36263 : disk: Arc<DiskWalProposer>,
72 36263 : ttid: TenantTimelineId,
73 36263 : addrs: Vec<String>,
74 36263 : lsn: Option<Lsn>,
75 36263 : ) {
76 36263 : let sync_safekeepers = lsn.is_none();
77 :
78 36263 : let _enter = if sync_safekeepers {
79 34811 : info_span!("sync", started = executor::now()).entered()
80 : } else {
81 1452 : info_span!("walproposer", started = executor::now()).entered()
82 : };
83 :
84 36263 : os.log_event(format!("started;walproposer;{}", sync_safekeepers as i32));
85 36263 :
86 36263 : let config = Config {
87 36263 : ttid,
88 36263 : safekeepers_list: addrs,
89 36263 : safekeeper_reconnect_timeout: 1000,
90 36263 : safekeeper_connection_timeout: 5000,
91 36263 : sync_safekeepers,
92 36263 : };
93 36263 : let args = walproposer_api::Args {
94 36263 : os,
95 36263 : config: config.clone(),
96 36263 : disk,
97 36263 : redo_start_lsn: lsn,
98 36263 : };
99 36263 : let api = SimulationApi::new(args);
100 36263 : let wp = Wrapper::new(Box::new(api), config);
101 36263 : wp.start();
102 36263 : }
103 :
104 : /// Start walproposer in a sync_safekeepers mode.
105 35523 : pub fn launch_sync(ttid: TenantTimelineId, addrs: Vec<String>, node: Arc<Node>) -> Self {
106 35523 : debug!("sync_safekeepers started at node {}", node.id);
107 35523 : let disk = DiskWalProposer::new();
108 35523 : let disk_wp = disk.clone();
109 35523 :
110 35523 : // start the client thread
111 35523 : let handle = node.launch(move |os| {
112 34811 : WalProposer::start(os, disk_wp, ttid, addrs, None);
113 35523 : });
114 35523 :
115 35523 : Self {
116 35523 : thread: handle,
117 35523 : node,
118 35523 : disk,
119 35523 : sync_safekeepers: true,
120 35523 : }
121 35523 : }
122 :
123 : /// Start walproposer in a normal mode.
124 1452 : pub fn launch_walproposer(
125 1452 : ttid: TenantTimelineId,
126 1452 : addrs: Vec<String>,
127 1452 : node: Arc<Node>,
128 1452 : lsn: Lsn,
129 1452 : ) -> Self {
130 1452 : debug!("walproposer started at node {}", node.id);
131 1452 : let disk = DiskWalProposer::new();
132 1452 : disk.lock().reset_to(lsn);
133 1452 : let disk_wp = disk.clone();
134 1452 :
135 1452 : // start the client thread
136 1452 : let handle = node.launch(move |os| {
137 1452 : WalProposer::start(os, disk_wp, ttid, addrs, Some(lsn));
138 1452 : });
139 1452 :
140 1452 : Self {
141 1452 : thread: handle,
142 1452 : node,
143 1452 : disk,
144 1452 : sync_safekeepers: false,
145 1452 : }
146 1452 : }
147 :
148 1574 : pub fn write_tx(&mut self, cnt: usize) {
149 1574 : let start_lsn = self.disk.lock().flush_rec_ptr();
150 1574 :
151 16708 : for _ in 0..cnt {
152 16708 : self.disk
153 16708 : .lock()
154 16708 : .insert_logical_message("prefix", b"message")
155 16708 : .expect("failed to generate logical message");
156 16708 : }
157 :
158 1574 : let end_lsn = self.disk.lock().flush_rec_ptr();
159 1574 :
160 1574 : // log event
161 1574 : self.node
162 1574 : .log_event(format!("write_wal;{};{};{}", start_lsn.0, end_lsn.0, cnt));
163 1574 :
164 1574 : // now we need to set "Latch" in walproposer
165 1574 : self.node
166 1574 : .node_events()
167 1574 : .send(NodeEvent::Internal(AnyMessage::Just32(0)));
168 1574 : }
169 :
170 33293 : pub fn stop(&self) {
171 33293 : self.thread.crash_stop();
172 33293 : }
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 2008 : pub fn start(&self, seed: u64) -> Test {
206 2008 : let world = Arc::new(World::new(seed, Arc::new(self.network.clone())));
207 :
208 2008 : if let Some(clock) = &self.clock {
209 2008 : clock.set_clock(world.clock());
210 2008 : }
211 :
212 2008 : let servers = [
213 2008 : SafekeeperNode::new(world.new_node()),
214 2008 : SafekeeperNode::new(world.new_node()),
215 2008 : SafekeeperNode::new(world.new_node()),
216 2008 : ];
217 2008 :
218 2008 : let server_ids = [servers[0].id, servers[1].id, servers[2].id];
219 6024 : let safekeepers_addrs = server_ids.map(|id| format!("node:{}", id)).to_vec();
220 2008 :
221 2008 : let ttid = TenantTimelineId::generate();
222 2008 :
223 2008 : Test {
224 2008 : world,
225 2008 : servers,
226 2008 : sk_list: safekeepers_addrs,
227 2008 : ttid,
228 2008 : timeout: self.timeout,
229 2008 : }
230 2008 : }
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 35523 : pub fn launch_sync_safekeepers(&self) -> WalProposer {
265 35523 : WalProposer::launch_sync(self.ttid, self.sk_list.clone(), self.world.new_node())
266 35523 : }
267 :
268 : /// Spawn a new walproposer thread.
269 1452 : pub fn launch_walproposer(&self, lsn: Lsn) -> WalProposer {
270 1452 : let lsn = if lsn.0 == 0 {
271 : // usual LSN after basebackup
272 715 : Lsn(21623024)
273 : } else {
274 737 : lsn
275 : };
276 :
277 1452 : WalProposer::launch_walproposer(self.ttid, self.sk_list.clone(), self.world.new_node(), lsn)
278 1452 : }
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 2004 : pub fn run_schedule(&self, schedule: &Schedule) -> anyhow::Result<()> {
288 2004 : // scheduling empty events so that world will stop in those points
289 2004 : {
290 2004 : let clock = self.world.clock();
291 2004 :
292 2004 : let now = self.world.now();
293 102592 : for (time, _) in schedule {
294 100588 : if *time < now {
295 0 : continue;
296 100588 : }
297 100588 : clock.schedule_fake(*time - now);
298 : }
299 : }
300 :
301 2004 : let mut wp = self.launch_sync_safekeepers();
302 2004 :
303 2004 : let mut skipped_tx = 0;
304 2004 : let mut started_tx = 0;
305 2004 :
306 2004 : let mut schedule_ptr = 0;
307 :
308 : loop {
309 104333 : if wp.sync_safekeepers && wp.thread.is_finished() {
310 1670 : let res = wp.thread.result();
311 1670 : if res.0 != 0 {
312 221 : warn!("sync non-zero exitcode: {:?}", res);
313 221 : debug!("restarting sync_safekeepers");
314 : // restart the sync_safekeepers
315 221 : wp = self.launch_sync_safekeepers();
316 221 : continue;
317 1449 : }
318 1449 : let lsn = Lsn::from_str(&res.1)?;
319 1449 : debug!("sync_safekeepers finished at LSN {}", lsn);
320 1449 : wp = self.launch_walproposer(lsn);
321 1449 : debug!("walproposer started at thread {}", wp.thread.id());
322 102663 : }
323 :
324 104112 : let now = self.world.now();
325 204700 : while schedule_ptr < schedule.len() && schedule[schedule_ptr].0 <= now {
326 100588 : if now != schedule[schedule_ptr].0 {
327 0 : warn!("skipped event {:?} at {}", schedule[schedule_ptr], now);
328 100588 : }
329 :
330 100588 : let action = &schedule[schedule_ptr].1;
331 100588 : match action {
332 33632 : TestAction::WriteTx(size) => {
333 33632 : if !wp.sync_safekeepers && !wp.thread.is_finished() {
334 1472 : started_tx += *size;
335 1472 : wp.write_tx(*size);
336 1472 : debug!("written {} transactions", size);
337 : } else {
338 32160 : skipped_tx += size;
339 32160 : debug!("skipped {} transactions", size);
340 : }
341 : }
342 33664 : TestAction::RestartSafekeeper(id) => {
343 33664 : debug!("restarting safekeeper {}", id);
344 33664 : self.servers[*id].restart();
345 : }
346 : TestAction::RestartWalProposer => {
347 33292 : debug!("restarting sync_safekeepers");
348 33292 : wp.stop();
349 33292 : wp = self.launch_sync_safekeepers();
350 : }
351 : }
352 100588 : schedule_ptr += 1;
353 : }
354 :
355 104112 : if schedule_ptr == schedule.len() {
356 2004 : break;
357 102108 : }
358 102108 : let next_event_time = schedule[schedule_ptr].0;
359 102108 :
360 102108 : // poll until the next event
361 102108 : if wp.thread.is_finished() {
362 1543 : while self.world.step() && self.world.now() < next_event_time {}
363 : } else {
364 1595163 : while self.world.step()
365 1595163 : && self.world.now() < next_event_time
366 1494931 : && !wp.thread.is_finished()
367 1493206 : {}
368 : }
369 : }
370 :
371 2004 : debug!(
372 0 : "finished schedule, total steps: {}",
373 0 : self.world.get_thread_step_count()
374 : );
375 2004 : debug!("skipped_tx: {}", skipped_tx);
376 2004 : debug!("started_tx: {}", started_tx);
377 :
378 2004 : Ok(())
379 2004 : }
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 2002 : pub fn generate_schedule(seed: u64) -> Schedule {
392 2002 : let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
393 2002 : let mut schedule = Vec::new();
394 2002 : let mut time = 0;
395 2002 :
396 2002 : let cnt = rng.gen_range(1..100);
397 2002 :
398 2002 : for _ in 0..cnt {
399 100473 : time += rng.gen_range(0..500);
400 100473 : let action = match rng.gen_range(0..3) {
401 33525 : 0 => TestAction::WriteTx(rng.gen_range(1..10)),
402 33658 : 1 => TestAction::RestartSafekeeper(rng.gen_range(0..3)),
403 33290 : 2 => TestAction::RestartWalProposer,
404 0 : _ => unreachable!(),
405 : };
406 100473 : schedule.push((time, action));
407 : }
408 :
409 2002 : schedule
410 2002 : }
411 :
412 2002 : pub fn generate_network_opts(seed: u64) -> NetworkOptions {
413 2002 : let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
414 2002 :
415 2002 : let timeout = rng.gen_range(100..2000);
416 2002 : let max_delay = rng.gen_range(1..2 * timeout);
417 2002 : let min_delay = rng.gen_range(1..=max_delay);
418 2002 :
419 2002 : let max_fail_prob = rng.gen_range(0.0..0.9);
420 2002 : let connect_fail_prob = rng.gen_range(0.0..max_fail_prob);
421 2002 : let send_fail_prob = rng.gen_range(0.0..connect_fail_prob);
422 2002 :
423 2002 : NetworkOptions {
424 2002 : keepalive_timeout: Some(timeout),
425 2002 : connect_delay: Delay {
426 2002 : min: min_delay,
427 2002 : max: max_delay,
428 2002 : fail_prob: connect_fail_prob,
429 2002 : },
430 2002 : send_delay: Delay {
431 2002 : min: min_delay,
432 2002 : max: max_delay,
433 2002 : fail_prob: send_fail_prob,
434 2002 : },
435 2002 : }
436 2002 : }
|