Line data Source code
1 : use std::cell::{RefCell, RefMut, UnsafeCell};
2 : use std::ffi::CStr;
3 : use std::sync::Arc;
4 :
5 : use bytes::Bytes;
6 : use desim::executor::{self, PollSome};
7 : use desim::network::TCP;
8 : use desim::node_os::NodeOs;
9 : use desim::proto::{AnyMessage, NetEvent, NodeEvent};
10 : use desim::world::NodeId;
11 : use tracing::debug;
12 : use utils::lsn::Lsn;
13 : use walproposer::api_bindings::Level;
14 : use walproposer::bindings::{
15 : NeonWALReadResult, SafekeeperStateDesiredEvents, WL_SOCKET_READABLE, WL_SOCKET_WRITEABLE,
16 : };
17 : use walproposer::walproposer::{ApiImpl, Config};
18 :
19 : use super::walproposer_disk::DiskWalProposer;
20 :
21 : /// Special state for each wp->sk connection.
22 : struct SafekeeperConn {
23 : host: String,
24 : port: String,
25 : node_id: NodeId,
26 : // socket is Some(..) equals to connection is established
27 : socket: Option<TCP>,
28 : // connection is in progress
29 : is_connecting: bool,
30 : // START_WAL_PUSH is in progress
31 : is_start_wal_push: bool,
32 : // pointer to Safekeeper in walproposer for callbacks
33 : raw_ptr: *mut walproposer::bindings::Safekeeper,
34 : }
35 :
36 : impl SafekeeperConn {
37 27027 : pub fn new(host: String, port: String) -> Self {
38 : // port number is the same as NodeId
39 27027 : let port_num = port.parse::<u32>().unwrap();
40 27027 : Self {
41 27027 : host,
42 27027 : port,
43 27027 : node_id: port_num,
44 27027 : socket: None,
45 27027 : is_connecting: false,
46 27027 : is_start_wal_push: false,
47 27027 : raw_ptr: std::ptr::null_mut(),
48 27027 : }
49 27027 : }
50 : }
51 :
52 : /// Simulation version of a postgres WaitEventSet. At pos 0 there is always
53 : /// a special NodeEvents channel, which is used as a latch.
54 : struct EventSet {
55 : os: NodeOs,
56 : // all pollable channels, 0 is always NodeEvent channel
57 : chans: Vec<Box<dyn PollSome>>,
58 : // 0 is always nullptr
59 : sk_ptrs: Vec<*mut walproposer::bindings::Safekeeper>,
60 : // event mask for each channel
61 : masks: Vec<u32>,
62 : }
63 :
64 : impl EventSet {
65 9009 : pub fn new(os: NodeOs) -> Self {
66 9009 : let node_events = os.node_events();
67 9009 : Self {
68 9009 : os,
69 9009 : chans: vec![Box::new(node_events)],
70 9009 : sk_ptrs: vec![std::ptr::null_mut()],
71 9009 : masks: vec![WL_SOCKET_READABLE],
72 9009 : }
73 9009 : }
74 :
75 : /// Leaves all readable channels at the beginning of the array.
76 27085 : fn sort_readable(&mut self) -> usize {
77 27085 : let mut cnt = 1;
78 62825 : for i in 1..self.chans.len() {
79 62825 : if self.masks[i] & WL_SOCKET_READABLE != 0 {
80 62825 : self.chans.swap(i, cnt);
81 62825 : self.sk_ptrs.swap(i, cnt);
82 62825 : self.masks.swap(i, cnt);
83 62825 : cnt += 1;
84 62825 : }
85 : }
86 27085 : cnt
87 27085 : }
88 :
89 65210 : fn update_event_set(&mut self, conn: &SafekeeperConn, event_mask: u32) {
90 65210 : let index = self
91 65210 : .sk_ptrs
92 65210 : .iter()
93 247351 : .position(|&ptr| ptr == conn.raw_ptr)
94 65210 : .expect("safekeeper should exist in event set");
95 65210 : self.masks[index] = event_mask;
96 65210 : }
97 :
98 60536 : fn add_safekeeper(&mut self, sk: &SafekeeperConn, event_mask: u32) {
99 146298 : for ptr in self.sk_ptrs.iter() {
100 146298 : assert!(*ptr != sk.raw_ptr);
101 : }
102 :
103 60536 : self.chans.push(Box::new(
104 60536 : sk.socket
105 60536 : .as_ref()
106 60536 : .expect("socket should not be closed")
107 60536 : .recv_chan(),
108 60536 : ));
109 60536 : self.sk_ptrs.push(sk.raw_ptr);
110 60536 : self.masks.push(event_mask);
111 60536 : }
112 :
113 38831 : fn remove_safekeeper(&mut self, sk: &SafekeeperConn) {
114 82516 : let index = self.sk_ptrs.iter().position(|&ptr| ptr == sk.raw_ptr);
115 38831 : if index.is_none() {
116 5 : debug!("remove_safekeeper: sk={:?} not found", sk.raw_ptr);
117 5 : return;
118 38826 : }
119 38826 : let index = index.unwrap();
120 :
121 38826 : self.chans.remove(index);
122 38826 : self.sk_ptrs.remove(index);
123 38826 : self.masks.remove(index);
124 :
125 : // to simulate the actual behaviour
126 38826 : self.refresh_event_set();
127 38831 : }
128 :
129 : /// Updates all masks to match the result of a SafekeeperStateDesiredEvents.
130 43408 : fn refresh_event_set(&mut self) {
131 121662 : for (i, mask) in self.masks.iter_mut().enumerate() {
132 121662 : if i == 0 {
133 43408 : continue;
134 78254 : }
135 :
136 78254 : let mut mask_sk: u32 = 0;
137 78254 : let mut mask_nwr: u32 = 0;
138 78254 : unsafe { SafekeeperStateDesiredEvents(self.sk_ptrs[i], &mut mask_sk, &mut mask_nwr) };
139 :
140 78254 : if mask_sk != *mask {
141 0 : debug!(
142 0 : "refresh_event_set: sk={:?}, old_mask={:#b}, new_mask={:#b}",
143 0 : self.sk_ptrs[i], *mask, mask_sk
144 : );
145 0 : *mask = mask_sk;
146 78254 : }
147 : }
148 43408 : }
149 :
150 : /// Wait for events on all channels.
151 27085 : fn wait(&mut self, timeout_millis: i64) -> walproposer::walproposer::WaitResult {
152 : // all channels are always writeable
153 89910 : for (i, mask) in self.masks.iter().enumerate() {
154 89910 : if *mask & WL_SOCKET_WRITEABLE != 0 {
155 0 : return walproposer::walproposer::WaitResult::Network(
156 0 : self.sk_ptrs[i],
157 0 : WL_SOCKET_WRITEABLE,
158 0 : );
159 89910 : }
160 : }
161 :
162 27085 : let cnt = self.sort_readable();
163 :
164 27085 : let slice = &self.chans[0..cnt];
165 27085 : match executor::epoll_chans(slice, timeout_millis) {
166 11413 : None => walproposer::walproposer::WaitResult::Timeout,
167 : Some(0) => {
168 410 : let msg = self.os.node_events().must_recv();
169 410 : match msg {
170 410 : NodeEvent::Internal(AnyMessage::Just32(0)) => {
171 410 : // got a notification about new WAL available
172 410 : }
173 0 : NodeEvent::Internal(_) => unreachable!(),
174 0 : NodeEvent::Accept(_) => unreachable!(),
175 : }
176 410 : walproposer::walproposer::WaitResult::Latch
177 : }
178 15262 : Some(index) => walproposer::walproposer::WaitResult::Network(
179 15262 : self.sk_ptrs[index],
180 15262 : WL_SOCKET_READABLE,
181 15262 : ),
182 : }
183 27085 : }
184 : }
185 :
186 : /// This struct handles all calls from walproposer into walproposer_api.
187 : pub struct SimulationApi {
188 : os: NodeOs,
189 : safekeepers: RefCell<Vec<SafekeeperConn>>,
190 : disk: Arc<DiskWalProposer>,
191 : redo_start_lsn: Option<Lsn>,
192 : last_logged_commit_lsn: u64,
193 : shmem: UnsafeCell<walproposer::bindings::WalproposerShmemState>,
194 : config: Config,
195 : event_set: RefCell<Option<EventSet>>,
196 : }
197 :
198 : pub struct Args {
199 : pub os: NodeOs,
200 : pub config: Config,
201 : pub disk: Arc<DiskWalProposer>,
202 : pub redo_start_lsn: Option<Lsn>,
203 : }
204 :
205 : impl SimulationApi {
206 9009 : pub fn new(args: Args) -> Self {
207 : // initialize connection state for each safekeeper
208 9009 : let sk_conns = args
209 9009 : .config
210 9009 : .safekeepers_list
211 9009 : .iter()
212 27027 : .map(|s| {
213 27027 : SafekeeperConn::new(
214 27027 : s.split(':').next().unwrap().to_string(),
215 27027 : s.split(':').nth(1).unwrap().to_string(),
216 : )
217 27027 : })
218 9009 : .collect::<Vec<_>>();
219 :
220 9009 : Self {
221 9009 : os: args.os,
222 9009 : safekeepers: RefCell::new(sk_conns),
223 9009 : disk: args.disk,
224 9009 : redo_start_lsn: args.redo_start_lsn,
225 9009 : last_logged_commit_lsn: 0,
226 9009 : shmem: UnsafeCell::new(walproposer::api_bindings::empty_shmem()),
227 9009 : config: args.config,
228 9009 : event_set: RefCell::new(None),
229 9009 : }
230 9009 : }
231 :
232 : /// Get SafekeeperConn for the given Safekeeper.
233 294058 : fn get_conn(&self, sk: &mut walproposer::bindings::Safekeeper) -> RefMut<'_, SafekeeperConn> {
234 294058 : let sk_port = unsafe { CStr::from_ptr(sk.port).to_str().unwrap() };
235 294058 : let state = self.safekeepers.borrow_mut();
236 294058 : RefMut::map(state, |v| {
237 294058 : v.iter_mut()
238 587914 : .find(|conn| conn.port == sk_port)
239 294058 : .expect("safekeeper conn not found by port")
240 294058 : })
241 294058 : }
242 : }
243 :
244 : impl ApiImpl for SimulationApi {
245 313932 : fn get_current_timestamp(&self) -> i64 {
246 313932 : debug!("get_current_timestamp");
247 : // PG TimestampTZ is microseconds, but simulation unit is assumed to be
248 : // milliseconds, so add 10^3
249 313932 : self.os.now() as i64 * 1000
250 313932 : }
251 :
252 584 : fn update_donor(&self, donor: &mut walproposer::bindings::Safekeeper, donor_lsn: u64) {
253 584 : let mut shmem = unsafe { *self.get_shmem_state() };
254 584 : shmem.propEpochStartLsn.value = donor_lsn;
255 584 : shmem.donor_conninfo = donor.conninfo;
256 584 : }
257 :
258 33599 : fn conn_status(
259 33599 : &self,
260 33599 : _: &mut walproposer::bindings::Safekeeper,
261 33599 : ) -> walproposer::bindings::WalProposerConnStatusType {
262 33599 : debug!("conn_status");
263 : // break the connection with a 10% chance
264 33599 : if self.os.random(100) < 10 {
265 3331 : walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_BAD
266 : } else {
267 30268 : walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_OK
268 : }
269 33599 : }
270 :
271 33599 : fn conn_connect_start(&self, sk: &mut walproposer::bindings::Safekeeper) {
272 33599 : debug!("conn_connect_start");
273 33599 : let mut conn = self.get_conn(sk);
274 :
275 33599 : assert!(conn.socket.is_none());
276 33599 : let socket = self.os.open_tcp(conn.node_id);
277 33599 : conn.socket = Some(socket);
278 33599 : conn.raw_ptr = sk;
279 33599 : conn.is_connecting = true;
280 33599 : }
281 :
282 30268 : fn conn_connect_poll(
283 30268 : &self,
284 30268 : _: &mut walproposer::bindings::Safekeeper,
285 30268 : ) -> walproposer::bindings::WalProposerConnectPollStatusType {
286 30268 : debug!("conn_connect_poll");
287 : // TODO: break the connection here
288 30268 : walproposer::bindings::WalProposerConnectPollStatusType_WP_CONN_POLLING_OK
289 30268 : }
290 :
291 30268 : fn conn_send_query(&self, sk: &mut walproposer::bindings::Safekeeper, query: &str) -> bool {
292 30268 : debug!("conn_send_query: {}", query);
293 30268 : self.get_conn(sk).is_start_wal_push = true;
294 30268 : true
295 30268 : }
296 :
297 30268 : fn conn_get_query_result(
298 30268 : &self,
299 30268 : _: &mut walproposer::bindings::Safekeeper,
300 30268 : ) -> walproposer::bindings::WalProposerExecStatusType {
301 30268 : debug!("conn_get_query_result");
302 : // TODO: break the connection here
303 30268 : walproposer::bindings::WalProposerExecStatusType_WP_EXEC_SUCCESS_COPYBOTH
304 30268 : }
305 :
306 16672 : fn conn_async_read(
307 16672 : &self,
308 16672 : sk: &mut walproposer::bindings::Safekeeper,
309 16672 : vec: &mut Vec<u8>,
310 16672 : ) -> walproposer::bindings::PGAsyncReadResult {
311 16672 : debug!("conn_async_read");
312 16672 : let mut conn = self.get_conn(sk);
313 :
314 16672 : let socket = if let Some(socket) = conn.socket.as_mut() {
315 16672 : socket
316 : } else {
317 : // socket is already closed
318 0 : return walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL;
319 : };
320 :
321 16672 : let msg = socket.recv_chan().try_recv();
322 :
323 15065 : match msg {
324 : None => {
325 : // no message is ready
326 1607 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_TRY_AGAIN
327 : }
328 : Some(NetEvent::Closed) => {
329 : // connection is closed
330 8235 : debug!("conn_async_read: connection is closed");
331 8235 : conn.socket = None;
332 8235 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL
333 : }
334 6830 : Some(NetEvent::Message(msg)) => {
335 : // got a message
336 6830 : let b = match msg {
337 6830 : desim::proto::AnyMessage::Bytes(b) => b,
338 0 : _ => unreachable!(),
339 : };
340 6830 : vec.extend_from_slice(&b);
341 6830 : walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_SUCCESS
342 : }
343 : }
344 16672 : }
345 :
346 33258 : fn conn_blocking_write(&self, sk: &mut walproposer::bindings::Safekeeper, buf: &[u8]) -> bool {
347 33258 : let mut conn = self.get_conn(sk);
348 33258 : debug!("conn_blocking_write to {}: {:?}", conn.node_id, buf);
349 33258 : let socket = conn.socket.as_mut().unwrap();
350 33258 : socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
351 33258 : true
352 33258 : }
353 :
354 3579 : fn conn_async_write(
355 3579 : &self,
356 3579 : sk: &mut walproposer::bindings::Safekeeper,
357 3579 : buf: &[u8],
358 3579 : ) -> walproposer::bindings::PGAsyncWriteResult {
359 3579 : let mut conn = self.get_conn(sk);
360 3579 : debug!("conn_async_write to {}: {:?}", conn.node_id, buf);
361 3579 : if let Some(socket) = conn.socket.as_mut() {
362 3579 : socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
363 3579 : } else {
364 : // connection is already closed
365 0 : debug!("conn_async_write: writing to a closed socket!");
366 : // TODO: maybe we should return error here?
367 : }
368 3579 : walproposer::bindings::PGAsyncWriteResult_PG_ASYNC_WRITE_SUCCESS
369 3579 : }
370 :
371 604 : fn wal_reader_allocate(&self, _: &mut walproposer::bindings::Safekeeper) -> NeonWALReadResult {
372 604 : debug!("wal_reader_allocate");
373 604 : walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
374 604 : }
375 :
376 941 : fn wal_read(
377 941 : &self,
378 941 : _sk: &mut walproposer::bindings::Safekeeper,
379 941 : buf: &mut [u8],
380 941 : startpos: u64,
381 941 : ) -> NeonWALReadResult {
382 941 : self.disk.lock().read(startpos, buf);
383 941 : walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
384 941 : }
385 :
386 9009 : fn init_event_set(&self, _: &mut walproposer::bindings::WalProposer) {
387 9009 : debug!("init_event_set");
388 9009 : let new_event_set = EventSet::new(self.os.clone());
389 9009 : let old_event_set = self.event_set.replace(Some(new_event_set));
390 9009 : assert!(old_event_set.is_none());
391 9009 : }
392 :
393 65210 : fn update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper, event_mask: u32) {
394 65210 : debug!(
395 0 : "update_event_set, sk={:?}, events_mask={:#b}",
396 0 : sk as *mut walproposer::bindings::Safekeeper, event_mask
397 : );
398 65210 : let conn = self.get_conn(sk);
399 :
400 65210 : self.event_set
401 65210 : .borrow_mut()
402 65210 : .as_mut()
403 65210 : .unwrap()
404 65210 : .update_event_set(&conn, event_mask);
405 65210 : }
406 :
407 60536 : fn add_safekeeper_event_set(
408 60536 : &self,
409 60536 : sk: &mut walproposer::bindings::Safekeeper,
410 60536 : event_mask: u32,
411 60536 : ) {
412 60536 : debug!(
413 0 : "add_safekeeper_event_set, sk={:?}, events_mask={:#b}",
414 0 : sk as *mut walproposer::bindings::Safekeeper, event_mask
415 : );
416 :
417 60536 : self.event_set
418 60536 : .borrow_mut()
419 60536 : .as_mut()
420 60536 : .unwrap()
421 60536 : .add_safekeeper(&self.get_conn(sk), event_mask);
422 60536 : }
423 :
424 38831 : fn rm_safekeeper_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
425 38831 : debug!(
426 0 : "rm_safekeeper_event_set, sk={:?}",
427 0 : sk as *mut walproposer::bindings::Safekeeper,
428 : );
429 :
430 38831 : self.event_set
431 38831 : .borrow_mut()
432 38831 : .as_mut()
433 38831 : .unwrap()
434 38831 : .remove_safekeeper(&self.get_conn(sk));
435 38831 : }
436 :
437 4582 : fn active_state_update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
438 4582 : debug!("active_state_update_event_set");
439 :
440 4582 : assert!(sk.state == walproposer::bindings::SafekeeperState_SS_ACTIVE);
441 4582 : self.event_set
442 4582 : .borrow_mut()
443 4582 : .as_mut()
444 4582 : .unwrap()
445 4582 : .refresh_event_set();
446 4582 : }
447 :
448 14227 : fn wal_reader_events(&self, _sk: &mut walproposer::bindings::Safekeeper) -> u32 {
449 14227 : 0
450 14227 : }
451 :
452 87621 : fn wait_event_set(
453 87621 : &self,
454 87621 : _: &mut walproposer::bindings::WalProposer,
455 87621 : timeout_millis: i64,
456 87621 : ) -> walproposer::walproposer::WaitResult {
457 : // TODO: handle multiple stages as part of the simulation (e.g. connect, start_wal_push, etc)
458 87621 : let mut conns = self.safekeepers.borrow_mut();
459 202279 : for conn in conns.iter_mut() {
460 202279 : if conn.socket.is_some() && conn.is_connecting {
461 30268 : conn.is_connecting = false;
462 30268 : debug!("wait_event_set, connecting to {}:{}", conn.host, conn.port);
463 30268 : return walproposer::walproposer::WaitResult::Network(
464 30268 : conn.raw_ptr,
465 30268 : WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE,
466 30268 : );
467 172011 : }
468 172011 : if conn.socket.is_some() && conn.is_start_wal_push {
469 30268 : conn.is_start_wal_push = false;
470 30268 : debug!(
471 0 : "wait_event_set, start wal push to {}:{}",
472 : conn.host, conn.port
473 : );
474 30268 : return walproposer::walproposer::WaitResult::Network(
475 30268 : conn.raw_ptr,
476 30268 : WL_SOCKET_READABLE,
477 30268 : );
478 141743 : }
479 : }
480 27085 : drop(conns);
481 :
482 27085 : let res = self
483 27085 : .event_set
484 27085 : .borrow_mut()
485 27085 : .as_mut()
486 27085 : .unwrap()
487 27085 : .wait(timeout_millis);
488 :
489 27085 : debug!(
490 0 : "wait_event_set, timeout_millis={}, res={:?}",
491 : timeout_millis, res,
492 : );
493 27085 : res
494 87621 : }
495 :
496 0 : fn strong_random(&self, buf: &mut [u8]) -> bool {
497 0 : debug!("strong_random");
498 0 : buf.fill(0);
499 0 : true
500 0 : }
501 :
502 242 : fn finish_sync_safekeepers(&self, lsn: u64) -> ! {
503 242 : debug!("finish_sync_safekeepers, lsn={}", lsn);
504 242 : executor::exit(0, Lsn(lsn).to_string());
505 : }
506 :
507 146839 : fn log_internal(&self, _wp: &mut walproposer::bindings::WalProposer, level: Level, msg: &str) {
508 146839 : debug!("wp_log[{}] {}", level, msg);
509 146839 : if level == Level::Fatal || level == Level::Panic {
510 64 : if msg.contains("rejects our connection request with term") {
511 : // collected quorum with lower term, then got rejected by next connected safekeeper
512 40 : executor::exit(1, msg.to_owned());
513 24 : }
514 24 : if msg.contains("collected propTermStartLsn") && msg.contains(", but basebackup LSN ") {
515 : // sync-safekeepers collected wrong quorum, walproposer collected another quorum
516 3 : executor::exit(1, msg.to_owned());
517 21 : }
518 21 : if msg.contains("failed to download WAL for logical replicaiton") {
519 : // Recovery connection broken and recovery was failed
520 21 : executor::exit(1, msg.to_owned());
521 0 : }
522 0 : if msg.contains("missing majority of votes, collected") {
523 : // Voting bug when safekeeper disconnects after voting
524 0 : executor::exit(1, msg.to_owned());
525 0 : }
526 0 : panic!("unknown FATAL error from walproposer: {msg}");
527 146775 : }
528 146775 : }
529 :
530 367 : fn after_election(&self, wp: &mut walproposer::bindings::WalProposer) {
531 367 : let prop_lsn = wp.propTermStartLsn;
532 367 : let prop_term = wp.propTerm;
533 :
534 367 : let mut prev_lsn: u64 = 0;
535 367 : let mut prev_term: u64 = 0;
536 :
537 : unsafe {
538 367 : let history = wp.propTermHistory.entries;
539 367 : let len = wp.propTermHistory.n_entries as usize;
540 367 : if len > 1 {
541 317 : let entry = *history.wrapping_add(len - 2);
542 317 : prev_lsn = entry.lsn;
543 317 : prev_term = entry.term;
544 317 : }
545 : }
546 :
547 367 : let msg = format!("prop_elected;{prop_lsn};{prop_term};{prev_lsn};{prev_term}");
548 :
549 367 : debug!(msg);
550 367 : self.os.log_event(msg);
551 367 : }
552 :
553 151 : fn get_redo_start_lsn(&self) -> u64 {
554 151 : debug!("get_redo_start_lsn -> {:?}", self.redo_start_lsn);
555 151 : self.redo_start_lsn.expect("redo_start_lsn is not set").0
556 151 : }
557 :
558 1324 : fn get_shmem_state(&self) -> *mut walproposer::bindings::WalproposerShmemState {
559 1324 : self.shmem.get()
560 1324 : }
561 :
562 88 : fn start_streaming(
563 88 : &self,
564 88 : startpos: u64,
565 88 : callback: &walproposer::walproposer::StreamingCallback,
566 88 : ) {
567 88 : let disk = &self.disk;
568 88 : let disk_lsn = disk.lock().flush_rec_ptr().0;
569 88 : debug!("start_streaming at {} (disk_lsn={})", startpos, disk_lsn);
570 88 : if startpos < disk_lsn {
571 34 : debug!(
572 0 : "startpos < disk_lsn, it means we wrote some transaction even before streaming started"
573 : );
574 54 : }
575 88 : assert!(startpos <= disk_lsn);
576 88 : let mut broadcasted = Lsn(startpos);
577 :
578 : loop {
579 370 : let available = disk.lock().flush_rec_ptr();
580 370 : assert!(available >= broadcasted);
581 282 : callback.broadcast(broadcasted, available);
582 282 : broadcasted = available;
583 282 : callback.poll();
584 : }
585 : }
586 :
587 1758 : fn process_safekeeper_feedback(
588 1758 : &mut self,
589 1758 : wp: &mut walproposer::bindings::WalProposer,
590 1758 : _sk: &mut walproposer::bindings::Safekeeper,
591 1758 : ) {
592 1758 : debug!("process_safekeeper_feedback, commit_lsn={}", wp.commitLsn);
593 1758 : if wp.commitLsn > self.last_logged_commit_lsn {
594 346 : self.os.log_event(format!("commit_lsn;{}", wp.commitLsn));
595 346 : self.last_logged_commit_lsn = wp.commitLsn;
596 1412 : }
597 1758 : }
598 :
599 68 : fn get_flush_rec_ptr(&self) -> u64 {
600 68 : let lsn = self.disk.lock().flush_rec_ptr();
601 68 : debug!("get_flush_rec_ptr: {}", lsn);
602 68 : lsn.0
603 68 : }
604 :
605 367 : fn recovery_download(
606 367 : &self,
607 367 : wp: &mut walproposer::bindings::WalProposer,
608 367 : sk: &mut walproposer::bindings::Safekeeper,
609 367 : ) -> bool {
610 367 : let mut startpos = wp.truncateLsn;
611 367 : let endpos = wp.propTermStartLsn;
612 :
613 367 : if startpos == endpos {
614 156 : debug!("recovery_download: nothing to download");
615 156 : return true;
616 211 : }
617 :
618 211 : debug!("recovery_download from {} to {}", startpos, endpos,);
619 :
620 211 : let replication_prompt = format!(
621 211 : "START_REPLICATION {} {} {} {}",
622 : self.config.ttid.tenant_id, self.config.ttid.timeline_id, startpos, endpos,
623 : );
624 211 : let async_conn = self.get_conn(sk);
625 :
626 211 : let conn = self.os.open_tcp(async_conn.node_id);
627 211 : conn.send(desim::proto::AnyMessage::Bytes(replication_prompt.into()));
628 :
629 211 : let chan = conn.recv_chan();
630 342 : while startpos < endpos {
631 211 : let event = chan.recv();
632 190 : match event {
633 : NetEvent::Closed => {
634 21 : debug!("connection closed in recovery");
635 21 : break;
636 : }
637 131 : NetEvent::Message(AnyMessage::Bytes(b)) => {
638 131 : debug!("got recovery bytes from safekeeper");
639 131 : self.disk.lock().write(startpos, &b);
640 131 : startpos += b.len() as u64;
641 : }
642 59 : NetEvent::Message(_) => unreachable!(),
643 : }
644 : }
645 :
646 152 : debug!("recovery finished at {}", startpos);
647 :
648 152 : startpos == endpos
649 308 : }
650 :
651 11894 : fn conn_finish(&self, sk: &mut walproposer::bindings::Safekeeper) {
652 11894 : let mut conn = self.get_conn(sk);
653 11894 : debug!("conn_finish to {}", conn.node_id);
654 11894 : if let Some(socket) = conn.socket.as_mut() {
655 3654 : socket.close();
656 8240 : } else {
657 8240 : // connection is already closed
658 8240 : }
659 11894 : conn.socket = None;
660 11894 : }
661 :
662 11566 : fn conn_error_message(&self, _sk: &mut walproposer::bindings::Safekeeper) -> String {
663 11566 : "connection is closed, probably".into()
664 11566 : }
665 : }
|