LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - walproposer_api.rs (source / functions) Coverage Total Hit
Test: f8d8f5b90fa487a9e82c42da223f012f5d4fece7.info Lines: 95.5 % 486 464
Test Date: 2024-09-19 20:36:02 Functions: 99.3 % 138 137

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

Generated by: LCOV version 2.1-beta