LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - walproposer_api.rs (source / functions) Coverage Total Hit
Test: 8549b42bca720d24c422725f040bd1efc90a86da.info Lines: 92.9 % 453 421
Test Date: 2025-07-26 19:05:24 Functions: 96.4 % 138 133

            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        27906 :     pub fn new(host: String, port: String) -> Self {
      38              :         // port number is the same as NodeId
      39        27906 :         let port_num = port.parse::<u32>().unwrap();
      40        27906 :         Self {
      41        27906 :             host,
      42        27906 :             port,
      43        27906 :             node_id: port_num,
      44        27906 :             socket: None,
      45        27906 :             is_connecting: false,
      46        27906 :             is_start_wal_push: false,
      47        27906 :             raw_ptr: std::ptr::null_mut(),
      48        27906 :         }
      49        27906 :     }
      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         9302 :     pub fn new(os: NodeOs) -> Self {
      66         9302 :         let node_events = os.node_events();
      67         9302 :         Self {
      68         9302 :             os,
      69         9302 :             chans: vec![Box::new(node_events)],
      70         9302 :             sk_ptrs: vec![std::ptr::null_mut()],
      71         9302 :             masks: vec![WL_SOCKET_READABLE],
      72         9302 :         }
      73         9302 :     }
      74              : 
      75              :     /// Leaves all readable channels at the beginning of the array.
      76        30489 :     fn sort_readable(&mut self) -> usize {
      77        30489 :         let mut cnt = 1;
      78        73607 :         for i in 1..self.chans.len() {
      79        73607 :             if self.masks[i] & WL_SOCKET_READABLE != 0 {
      80        73607 :                 self.chans.swap(i, cnt);
      81        73607 :                 self.sk_ptrs.swap(i, cnt);
      82        73607 :                 self.masks.swap(i, cnt);
      83        73607 :                 cnt += 1;
      84        73607 :             }
      85              :         }
      86        30489 :         cnt
      87        30489 :     }
      88              : 
      89        68221 :     fn update_event_set(&mut self, conn: &SafekeeperConn, event_mask: u32) {
      90        68221 :         let index = self
      91        68221 :             .sk_ptrs
      92        68221 :             .iter()
      93       257170 :             .position(|&ptr| ptr == conn.raw_ptr)
      94        68221 :             .expect("safekeeper should exist in event set");
      95        68221 :         self.masks[index] = event_mask;
      96        68221 :     }
      97              : 
      98        61704 :     fn add_safekeeper(&mut self, sk: &SafekeeperConn, event_mask: u32) {
      99       149065 :         for ptr in self.sk_ptrs.iter() {
     100       149065 :             assert!(*ptr != sk.raw_ptr);
     101              :         }
     102              : 
     103        61704 :         self.chans.push(Box::new(
     104        61704 :             sk.socket
     105        61704 :                 .as_ref()
     106        61704 :                 .expect("socket should not be closed")
     107        61704 :                 .recv_chan(),
     108        61704 :         ));
     109        61704 :         self.sk_ptrs.push(sk.raw_ptr);
     110        61704 :         self.masks.push(event_mask);
     111        61704 :     }
     112              : 
     113        39005 :     fn remove_safekeeper(&mut self, sk: &SafekeeperConn) {
     114        83097 :         let index = self.sk_ptrs.iter().position(|&ptr| ptr == sk.raw_ptr);
     115        39005 :         if index.is_none() {
     116            1 :             debug!("remove_safekeeper: sk={:?} not found", sk.raw_ptr);
     117            1 :             return;
     118        39004 :         }
     119        39004 :         let index = index.unwrap();
     120              : 
     121        39004 :         self.chans.remove(index);
     122        39004 :         self.sk_ptrs.remove(index);
     123        39004 :         self.masks.remove(index);
     124              : 
     125              :         // to simulate the actual behaviour
     126        39004 :         self.refresh_event_set();
     127        39005 :     }
     128              : 
     129              :     /// Updates all masks to match the result of a SafekeeperStateDesiredEvents.
     130        46913 :     fn refresh_event_set(&mut self) {
     131       135786 :         for (i, mask) in self.masks.iter_mut().enumerate() {
     132       135786 :             if i == 0 {
     133        46913 :                 continue;
     134        88873 :             }
     135              : 
     136        88873 :             let mut mask_sk: u32 = 0;
     137        88873 :             let mut mask_nwr: u32 = 0;
     138        88873 :             unsafe { SafekeeperStateDesiredEvents(self.sk_ptrs[i], &mut mask_sk, &mut mask_nwr) };
     139              : 
     140        88873 :             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        88873 :             }
     147              :         }
     148        46913 :     }
     149              : 
     150              :     /// Wait for events on all channels.
     151        30489 :     fn wait(&mut self, timeout_millis: i64) -> walproposer::walproposer::WaitResult {
     152              :         // all channels are always writeable
     153       104096 :         for (i, mask) in self.masks.iter().enumerate() {
     154       104096 :             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       104096 :             }
     160              :         }
     161              : 
     162        30489 :         let cnt = self.sort_readable();
     163              : 
     164        30489 :         let slice = &self.chans[0..cnt];
     165        30489 :         match executor::epoll_chans(slice, timeout_millis) {
     166        11436 :             None => walproposer::walproposer::WaitResult::Timeout,
     167              :             Some(0) => {
     168          608 :                 let msg = self.os.node_events().must_recv();
     169          608 :                 match msg {
     170          608 :                     NodeEvent::Internal(AnyMessage::Just32(0)) => {
     171          608 :                         // got a notification about new WAL available
     172          608 :                     }
     173            0 :                     NodeEvent::Internal(_) => unreachable!(),
     174            0 :                     NodeEvent::Accept(_) => unreachable!(),
     175              :                 }
     176          608 :                 walproposer::walproposer::WaitResult::Latch
     177              :             }
     178        18445 :             Some(index) => walproposer::walproposer::WaitResult::Network(
     179        18445 :                 self.sk_ptrs[index],
     180        18445 :                 WL_SOCKET_READABLE,
     181        18445 :             ),
     182              :         }
     183        30489 :     }
     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         9302 :     pub fn new(args: Args) -> Self {
     207              :         // initialize connection state for each safekeeper
     208         9302 :         let sk_conns = args
     209         9302 :             .config
     210         9302 :             .safekeepers_list
     211         9302 :             .iter()
     212        27906 :             .map(|s| {
     213        27906 :                 SafekeeperConn::new(
     214        27906 :                     s.split(':').next().unwrap().to_string(),
     215        27906 :                     s.split(':').nth(1).unwrap().to_string(),
     216              :                 )
     217        27906 :             })
     218         9302 :             .collect::<Vec<_>>();
     219              : 
     220         9302 :         Self {
     221         9302 :             os: args.os,
     222         9302 :             safekeepers: RefCell::new(sk_conns),
     223         9302 :             disk: args.disk,
     224         9302 :             redo_start_lsn: args.redo_start_lsn,
     225         9302 :             last_logged_commit_lsn: 0,
     226         9302 :             shmem: UnsafeCell::new(walproposer::api_bindings::empty_shmem()),
     227         9302 :             config: args.config,
     228         9302 :             event_set: RefCell::new(None),
     229         9302 :         }
     230         9302 :     }
     231              : 
     232              :     /// Get SafekeeperConn for the given Safekeeper.
     233       308734 :     fn get_conn(&self, sk: &mut walproposer::bindings::Safekeeper) -> RefMut<'_, SafekeeperConn> {
     234       308734 :         let sk_port = unsafe { CStr::from_ptr(sk.port).to_str().unwrap() };
     235       308734 :         let state = self.safekeepers.borrow_mut();
     236       308734 :         RefMut::map(state, |v| {
     237       308734 :             v.iter_mut()
     238       617275 :                 .find(|conn| conn.port == sk_port)
     239       308734 :                 .expect("safekeeper conn not found by port")
     240       308734 :         })
     241       308734 :     }
     242              : }
     243              : 
     244              : impl ApiImpl for SimulationApi {
     245       331157 :     fn get_current_timestamp(&self) -> i64 {
     246       331157 :         debug!("get_current_timestamp");
     247              :         // PG TimestampTZ is microseconds, but simulation unit is assumed to be
     248              :         // milliseconds, so add 10^3
     249       331157 :         self.os.now() as i64 * 1000
     250       331157 :     }
     251              : 
     252         1225 :     fn update_donor(&self, donor: &mut walproposer::bindings::Safekeeper, donor_lsn: u64) {
     253         1225 :         let mut shmem = unsafe { *self.get_shmem_state() };
     254         1225 :         shmem.propEpochStartLsn.value = donor_lsn;
     255         1225 :         shmem.donor_conninfo = donor.conninfo;
     256         1225 :     }
     257              : 
     258        34319 :     fn conn_status(
     259        34319 :         &self,
     260        34319 :         _: &mut walproposer::bindings::Safekeeper,
     261        34319 :     ) -> walproposer::bindings::WalProposerConnStatusType {
     262        34319 :         debug!("conn_status");
     263              :         // break the connection with a 10% chance
     264        34319 :         if self.os.random(100) < 10 {
     265         3467 :             walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_BAD
     266              :         } else {
     267        30852 :             walproposer::bindings::WalProposerConnStatusType_WP_CONNECTION_OK
     268              :         }
     269        34319 :     }
     270              : 
     271        34319 :     fn conn_connect_start(&self, sk: &mut walproposer::bindings::Safekeeper) {
     272        34319 :         debug!("conn_connect_start");
     273        34319 :         let mut conn = self.get_conn(sk);
     274              : 
     275        34319 :         assert!(conn.socket.is_none());
     276        34319 :         let socket = self.os.open_tcp(conn.node_id);
     277        34319 :         conn.socket = Some(socket);
     278        34319 :         conn.raw_ptr = sk;
     279        34319 :         conn.is_connecting = true;
     280        34319 :     }
     281              : 
     282        30852 :     fn conn_connect_poll(
     283        30852 :         &self,
     284        30852 :         _: &mut walproposer::bindings::Safekeeper,
     285        30852 :     ) -> walproposer::bindings::WalProposerConnectPollStatusType {
     286        30852 :         debug!("conn_connect_poll");
     287              :         // TODO: break the connection here
     288        30852 :         walproposer::bindings::WalProposerConnectPollStatusType_WP_CONN_POLLING_OK
     289        30852 :     }
     290              : 
     291        30852 :     fn conn_send_query(&self, sk: &mut walproposer::bindings::Safekeeper, query: &str) -> bool {
     292        30852 :         debug!("conn_send_query: {}", query);
     293        30852 :         self.get_conn(sk).is_start_wal_push = true;
     294        30852 :         true
     295        30852 :     }
     296              : 
     297        30852 :     fn conn_get_query_result(
     298        30852 :         &self,
     299        30852 :         _: &mut walproposer::bindings::Safekeeper,
     300        30852 :     ) -> walproposer::bindings::WalProposerExecStatusType {
     301        30852 :         debug!("conn_get_query_result");
     302              :         // TODO: break the connection here
     303        30852 :         walproposer::bindings::WalProposerExecStatusType_WP_EXEC_SUCCESS_COPYBOTH
     304        30852 :     }
     305              : 
     306        21023 :     fn conn_async_read(
     307        21023 :         &self,
     308        21023 :         sk: &mut walproposer::bindings::Safekeeper,
     309        21023 :         vec: &mut Vec<u8>,
     310        21023 :     ) -> walproposer::bindings::PGAsyncReadResult {
     311        21023 :         debug!("conn_async_read");
     312        21023 :         let mut conn = self.get_conn(sk);
     313              : 
     314        21023 :         let socket = if let Some(socket) = conn.socket.as_mut() {
     315        21023 :             socket
     316              :         } else {
     317              :             // socket is already closed
     318            0 :             return walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL;
     319              :         };
     320              : 
     321        21023 :         let msg = socket.recv_chan().try_recv();
     322              : 
     323        18264 :         match msg {
     324              :             None => {
     325              :                 // no message is ready
     326         2759 :                 walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_TRY_AGAIN
     327              :             }
     328              :             Some(NetEvent::Closed) => {
     329              :                 // connection is closed
     330         7813 :                 debug!("conn_async_read: connection is closed");
     331         7813 :                 conn.socket = None;
     332         7813 :                 walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_FAIL
     333              :             }
     334        10451 :             Some(NetEvent::Message(msg)) => {
     335              :                 // got a message
     336        10451 :                 let b = match msg {
     337        10451 :                     desim::proto::AnyMessage::Bytes(b) => b,
     338            0 :                     _ => unreachable!(),
     339              :                 };
     340        10451 :                 vec.extend_from_slice(&b);
     341        10451 :                 walproposer::bindings::PGAsyncReadResult_PG_ASYNC_READ_SUCCESS
     342              :             }
     343              :         }
     344        21023 :     }
     345              : 
     346        35211 :     fn conn_blocking_write(&self, sk: &mut walproposer::bindings::Safekeeper, buf: &[u8]) -> bool {
     347        35211 :         let mut conn = self.get_conn(sk);
     348        35211 :         debug!("conn_blocking_write to {}: {:?}", conn.node_id, buf);
     349        35211 :         let socket = conn.socket.as_mut().unwrap();
     350        35211 :         socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
     351        35211 :         true
     352        35211 :     }
     353              : 
     354         6393 :     fn conn_async_write(
     355         6393 :         &self,
     356         6393 :         sk: &mut walproposer::bindings::Safekeeper,
     357         6393 :         buf: &[u8],
     358         6393 :     ) -> walproposer::bindings::PGAsyncWriteResult {
     359         6393 :         let mut conn = self.get_conn(sk);
     360         6393 :         debug!("conn_async_write to {}: {:?}", conn.node_id, buf);
     361         6393 :         if let Some(socket) = conn.socket.as_mut() {
     362         6393 :             socket.send(desim::proto::AnyMessage::Bytes(Bytes::copy_from_slice(buf)));
     363         6393 :         } 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         6393 :         walproposer::bindings::PGAsyncWriteResult_PG_ASYNC_WRITE_SUCCESS
     369         6393 :     }
     370              : 
     371         1243 :     fn wal_reader_allocate(&self, _: &mut walproposer::bindings::Safekeeper) -> NeonWALReadResult {
     372         1243 :         debug!("wal_reader_allocate");
     373         1243 :         walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
     374         1243 :     }
     375              : 
     376         1236 :     fn wal_read(
     377         1236 :         &self,
     378         1236 :         _sk: &mut walproposer::bindings::Safekeeper,
     379         1236 :         buf: &mut [u8],
     380         1236 :         startpos: u64,
     381         1236 :     ) -> NeonWALReadResult {
     382         1236 :         self.disk.lock().read(startpos, buf);
     383         1236 :         walproposer::bindings::NeonWALReadResult_NEON_WALREAD_SUCCESS
     384         1236 :     }
     385              : 
     386         9302 :     fn init_event_set(&self, _: &mut walproposer::bindings::WalProposer) {
     387         9302 :         debug!("init_event_set");
     388         9302 :         let new_event_set = EventSet::new(self.os.clone());
     389         9302 :         let old_event_set = self.event_set.replace(Some(new_event_set));
     390         9302 :         assert!(old_event_set.is_none());
     391         9302 :     }
     392              : 
     393        68221 :     fn update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper, event_mask: u32) {
     394        68221 :         debug!(
     395            0 :             "update_event_set, sk={:?}, events_mask={:#b}",
     396            0 :             sk as *mut walproposer::bindings::Safekeeper, event_mask
     397              :         );
     398        68221 :         let conn = self.get_conn(sk);
     399              : 
     400        68221 :         self.event_set
     401        68221 :             .borrow_mut()
     402        68221 :             .as_mut()
     403        68221 :             .unwrap()
     404        68221 :             .update_event_set(&conn, event_mask);
     405        68221 :     }
     406              : 
     407        61704 :     fn add_safekeeper_event_set(
     408        61704 :         &self,
     409        61704 :         sk: &mut walproposer::bindings::Safekeeper,
     410        61704 :         event_mask: u32,
     411        61704 :     ) {
     412        61704 :         debug!(
     413            0 :             "add_safekeeper_event_set, sk={:?}, events_mask={:#b}",
     414            0 :             sk as *mut walproposer::bindings::Safekeeper, event_mask
     415              :         );
     416              : 
     417        61704 :         self.event_set
     418        61704 :             .borrow_mut()
     419        61704 :             .as_mut()
     420        61704 :             .unwrap()
     421        61704 :             .add_safekeeper(&self.get_conn(sk), event_mask);
     422        61704 :     }
     423              : 
     424        39005 :     fn rm_safekeeper_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
     425        39005 :         debug!(
     426            0 :             "rm_safekeeper_event_set, sk={:?}",
     427            0 :             sk as *mut walproposer::bindings::Safekeeper,
     428              :         );
     429              : 
     430        39005 :         self.event_set
     431        39005 :             .borrow_mut()
     432        39005 :             .as_mut()
     433        39005 :             .unwrap()
     434        39005 :             .remove_safekeeper(&self.get_conn(sk));
     435        39005 :     }
     436              : 
     437         7909 :     fn active_state_update_event_set(&self, sk: &mut walproposer::bindings::Safekeeper) {
     438         7909 :         debug!("active_state_update_event_set");
     439              : 
     440         7909 :         assert!(sk.state == walproposer::bindings::SafekeeperState_SS_ACTIVE);
     441         7909 :         self.event_set
     442         7909 :             .borrow_mut()
     443         7909 :             .as_mut()
     444         7909 :             .unwrap()
     445         7909 :             .refresh_event_set();
     446         7909 :     }
     447              : 
     448        24188 :     fn wal_reader_events(&self, _sk: &mut walproposer::bindings::Safekeeper) -> u32 {
     449        24188 :         0
     450        24188 :     }
     451              : 
     452        92193 :     fn wait_event_set(
     453        92193 :         &self,
     454        92193 :         _: &mut walproposer::bindings::WalProposer,
     455        92193 :         timeout_millis: i64,
     456        92193 :     ) -> walproposer::walproposer::WaitResult {
     457              :         // TODO: handle multiple stages as part of the simulation (e.g. connect, start_wal_push, etc)
     458        92193 :         let mut conns = self.safekeepers.borrow_mut();
     459       214925 :         for conn in conns.iter_mut() {
     460       214925 :             if conn.socket.is_some() && conn.is_connecting {
     461        30852 :                 conn.is_connecting = false;
     462        30852 :                 debug!("wait_event_set, connecting to {}:{}", conn.host, conn.port);
     463        30852 :                 return walproposer::walproposer::WaitResult::Network(
     464        30852 :                     conn.raw_ptr,
     465        30852 :                     WL_SOCKET_READABLE | WL_SOCKET_WRITEABLE,
     466        30852 :                 );
     467       184073 :             }
     468       184073 :             if conn.socket.is_some() && conn.is_start_wal_push {
     469        30852 :                 conn.is_start_wal_push = false;
     470        30852 :                 debug!(
     471            0 :                     "wait_event_set, start wal push to {}:{}",
     472              :                     conn.host, conn.port
     473              :                 );
     474        30852 :                 return walproposer::walproposer::WaitResult::Network(
     475        30852 :                     conn.raw_ptr,
     476        30852 :                     WL_SOCKET_READABLE,
     477        30852 :                 );
     478       153221 :             }
     479              :         }
     480        30489 :         drop(conns);
     481              : 
     482        30489 :         let res = self
     483        30489 :             .event_set
     484        30489 :             .borrow_mut()
     485        30489 :             .as_mut()
     486        30489 :             .unwrap()
     487        30489 :             .wait(timeout_millis);
     488              : 
     489        30489 :         debug!(
     490            0 :             "wait_event_set, timeout_millis={}, res={:?}",
     491              :             timeout_millis, res,
     492              :         );
     493        30489 :         res
     494        92193 :     }
     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          393 :     fn finish_sync_safekeepers(&self, lsn: u64) -> ! {
     503          393 :         debug!("finish_sync_safekeepers, lsn={}", lsn);
     504          393 :         executor::exit(0, Lsn(lsn).to_string());
     505              :     }
     506              : 
     507       158808 :     fn log_internal(&self, _wp: &mut walproposer::bindings::WalProposer, level: Level, msg: &str) {
     508       158808 :         debug!("wp_log[{}] {}", level, msg);
     509       158808 :         if level == Level::Fatal || level == Level::Panic {
     510          110 :             if msg.contains("rejects our connection request with term") {
     511              :                 // collected quorum with lower term, then got rejected by next connected safekeeper
     512           67 :                 executor::exit(1, msg.to_owned());
     513           43 :             }
     514           43 :             if msg.contains("collected propTermStartLsn") && msg.contains(", but basebackup LSN ") {
     515              :                 // sync-safekeepers collected wrong quorum, walproposer collected another quorum
     516            6 :                 executor::exit(1, msg.to_owned());
     517           37 :             }
     518           37 :             if msg.contains("failed to download WAL for logical replicaiton") {
     519              :                 // Recovery connection broken and recovery was failed
     520           37 :                 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       158698 :         }
     528       158698 :     }
     529              : 
     530          697 :     fn after_election(&self, wp: &mut walproposer::bindings::WalProposer) {
     531          697 :         let prop_lsn = wp.propTermStartLsn;
     532          697 :         let prop_term = wp.propTerm;
     533              : 
     534          697 :         let mut prev_lsn: u64 = 0;
     535          697 :         let mut prev_term: u64 = 0;
     536              : 
     537              :         unsafe {
     538          697 :             let history = wp.propTermHistory.entries;
     539          697 :             let len = wp.propTermHistory.n_entries as usize;
     540          697 :             if len > 1 {
     541          630 :                 let entry = *history.wrapping_add(len - 2);
     542          630 :                 prev_lsn = entry.lsn;
     543          630 :                 prev_term = entry.term;
     544          630 :             }
     545              :         }
     546              : 
     547          697 :         let msg = format!("prop_elected;{prop_lsn};{prop_term};{prev_lsn};{prev_term}");
     548              : 
     549          697 :         debug!(msg);
     550          697 :         self.os.log_event(msg);
     551          697 :     }
     552              : 
     553          287 :     fn get_redo_start_lsn(&self) -> u64 {
     554          287 :         debug!("get_redo_start_lsn -> {:?}", self.redo_start_lsn);
     555          287 :         self.redo_start_lsn.expect("redo_start_lsn is not set").0
     556          287 :     }
     557              : 
     558         2631 :     fn get_shmem_state(&self) -> *mut walproposer::bindings::WalproposerShmemState {
     559         2631 :         self.shmem.get()
     560         2631 :     }
     561              : 
     562          198 :     fn start_streaming(
     563          198 :         &self,
     564          198 :         startpos: u64,
     565          198 :         callback: &walproposer::walproposer::StreamingCallback,
     566          198 :     ) {
     567          198 :         let disk = &self.disk;
     568          198 :         let disk_lsn = disk.lock().flush_rec_ptr().0;
     569          198 :         debug!("start_streaming at {} (disk_lsn={})", startpos, disk_lsn);
     570          198 :         if startpos < disk_lsn {
     571           63 :             debug!(
     572            0 :                 "startpos < disk_lsn, it means we wrote some transaction even before streaming started"
     573              :             );
     574          135 :         }
     575          198 :         assert!(startpos <= disk_lsn);
     576          198 :         let mut broadcasted = Lsn(startpos);
     577              : 
     578              :         loop {
     579          570 :             let available = disk.lock().flush_rec_ptr();
     580          570 :             assert!(available >= broadcasted);
     581          372 :             callback.broadcast(broadcasted, available);
     582          372 :             broadcasted = available;
     583          372 :             callback.poll();
     584              :         }
     585              :     }
     586              : 
     587         3001 :     fn process_safekeeper_feedback(
     588         3001 :         &mut self,
     589         3001 :         wp: &mut walproposer::bindings::WalProposer,
     590         3001 :         _sk: &mut walproposer::bindings::Safekeeper,
     591         3001 :     ) {
     592         3001 :         debug!("process_safekeeper_feedback, commit_lsn={}", wp.commitLsn);
     593         3001 :         if wp.commitLsn > self.last_logged_commit_lsn {
     594          590 :             self.os.log_event(format!("commit_lsn;{}", wp.commitLsn));
     595          590 :             self.last_logged_commit_lsn = wp.commitLsn;
     596         2411 :         }
     597         3001 :     }
     598              : 
     599          102 :     fn get_flush_rec_ptr(&self) -> u64 {
     600          102 :         let lsn = self.disk.lock().flush_rec_ptr();
     601          102 :         debug!("get_flush_rec_ptr: {}", lsn);
     602          102 :         lsn.0
     603          102 :     }
     604              : 
     605          697 :     fn recovery_download(
     606          697 :         &self,
     607          697 :         wp: &mut walproposer::bindings::WalProposer,
     608          697 :         sk: &mut walproposer::bindings::Safekeeper,
     609          697 :     ) -> bool {
     610          697 :         let mut startpos = wp.truncateLsn;
     611          697 :         let endpos = wp.propTermStartLsn;
     612              : 
     613          697 :         if startpos == endpos {
     614          311 :             debug!("recovery_download: nothing to download");
     615          311 :             return true;
     616          386 :         }
     617              : 
     618          386 :         debug!("recovery_download from {} to {}", startpos, endpos,);
     619              : 
     620          386 :         let replication_prompt = format!(
     621          386 :             "START_REPLICATION {} {} {} {}",
     622              :             self.config.ttid.tenant_id, self.config.ttid.timeline_id, startpos, endpos,
     623              :         );
     624          386 :         let async_conn = self.get_conn(sk);
     625              : 
     626          386 :         let conn = self.os.open_tcp(async_conn.node_id);
     627          386 :         conn.send(desim::proto::AnyMessage::Bytes(replication_prompt.into()));
     628              : 
     629          386 :         let chan = conn.recv_chan();
     630          649 :         while startpos < endpos {
     631          386 :             let event = chan.recv();
     632          349 :             match event {
     633              :                 NetEvent::Closed => {
     634           37 :                     debug!("connection closed in recovery");
     635           37 :                     break;
     636              :                 }
     637          263 :                 NetEvent::Message(AnyMessage::Bytes(b)) => {
     638          263 :                     debug!("got recovery bytes from safekeeper");
     639          263 :                     self.disk.lock().write(startpos, &b);
     640          263 :                     startpos += b.len() as u64;
     641              :                 }
     642           86 :                 NetEvent::Message(_) => unreachable!(),
     643              :             }
     644              :         }
     645              : 
     646          300 :         debug!("recovery finished at {}", startpos);
     647              : 
     648          300 :         startpos == endpos
     649          611 :     }
     650              : 
     651        11620 :     fn conn_finish(&self, sk: &mut walproposer::bindings::Safekeeper) {
     652        11620 :         let mut conn = self.get_conn(sk);
     653        11620 :         debug!("conn_finish to {}", conn.node_id);
     654        11620 :         if let Some(socket) = conn.socket.as_mut() {
     655         3806 :             socket.close();
     656         7814 :         } else {
     657         7814 :             // connection is already closed
     658         7814 :         }
     659        11620 :         conn.socket = None;
     660        11620 :     }
     661              : 
     662        11280 :     fn conn_error_message(&self, _sk: &mut walproposer::bindings::Safekeeper) -> String {
     663        11280 :         "connection is closed, probably".into()
     664        11280 :     }
     665              : }
        

Generated by: LCOV version 2.1-beta