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

Generated by: LCOV version 2.1-beta