LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - walproposer_api.rs (source / functions) Coverage Total Hit
Test: f08493f498dc56383410c7d22f77751c183f1590.info Lines: 97.0 % 498 483
Test Date: 2024-02-22 21:37:45 Functions: 80.5 % 246 198

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

Generated by: LCOV version 2.1-beta