LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - safekeeper.rs (source / functions) Coverage Total Hit
Test: 04c8e12da19d1932a32b89117fc3b8bb24fc4824.info Lines: 94.8 % 286 271
Test Date: 2025-03-14 12:19:16 Functions: 94.9 % 39 37

            Line data    Source code
       1              : //! Safekeeper communication endpoint to WAL proposer (compute node).
       2              : //! Gets messages from the network, passes them down to consensus module and
       3              : //! sends replies back.
       4              : 
       5              : use std::collections::HashMap;
       6              : use std::sync::Arc;
       7              : use std::time::Duration;
       8              : 
       9              : use anyhow::{Result, bail};
      10              : use bytes::{Bytes, BytesMut};
      11              : use camino::Utf8PathBuf;
      12              : use desim::executor::{self, PollSome};
      13              : use desim::network::TCP;
      14              : use desim::node_os::NodeOs;
      15              : use desim::proto::{AnyMessage, NetEvent, NodeEvent};
      16              : use http::Uri;
      17              : use safekeeper::SafeKeeperConf;
      18              : use safekeeper::safekeeper::{
      19              :     ProposerAcceptorMessage, SK_PROTO_VERSION_3, SafeKeeper, UNKNOWN_SERVER_VERSION,
      20              : };
      21              : use safekeeper::state::{TimelinePersistentState, TimelineState};
      22              : use safekeeper::timeline::TimelineError;
      23              : use safekeeper::wal_storage::Storage;
      24              : use safekeeper_api::ServerInfo;
      25              : use safekeeper_api::membership::Configuration;
      26              : use tracing::{debug, info_span, warn};
      27              : use utils::id::{NodeId, TenantId, TenantTimelineId, TimelineId};
      28              : use utils::lsn::Lsn;
      29              : 
      30              : use super::safekeeper_disk::{DiskStateStorage, DiskWALStorage, SafekeeperDisk, TimelineDisk};
      31              : 
      32              : struct SharedState {
      33              :     sk: SafeKeeper<DiskStateStorage, DiskWALStorage>,
      34              :     disk: Arc<TimelineDisk>,
      35              : }
      36              : 
      37              : struct GlobalMap {
      38              :     timelines: HashMap<TenantTimelineId, SharedState>,
      39              :     conf: SafeKeeperConf,
      40              :     disk: Arc<SafekeeperDisk>,
      41              : }
      42              : 
      43              : impl GlobalMap {
      44              :     /// Restores global state from disk.
      45        10085 :     fn new(disk: Arc<SafekeeperDisk>, conf: SafeKeeperConf) -> Result<Self> {
      46        10085 :         let mut timelines = HashMap::new();
      47              : 
      48        10085 :         for (&ttid, disk) in disk.timelines.lock().iter() {
      49         7681 :             debug!("loading timeline {}", ttid);
      50         7681 :             let state = disk.state.lock().clone();
      51         7681 : 
      52         7681 :             if state.server.wal_seg_size == 0 {
      53            0 :                 bail!(TimelineError::UninitializedWalSegSize(ttid));
      54         7681 :             }
      55         7681 : 
      56         7681 :             if state.server.pg_version == UNKNOWN_SERVER_VERSION {
      57            0 :                 bail!(TimelineError::UninitialinzedPgVersion(ttid));
      58         7681 :             }
      59         7681 : 
      60         7681 :             if state.commit_lsn < state.local_start_lsn {
      61            0 :                 bail!(
      62            0 :                     "commit_lsn {} is smaller than local_start_lsn {}",
      63            0 :                     state.commit_lsn,
      64            0 :                     state.local_start_lsn
      65            0 :                 );
      66         7681 :             }
      67         7681 : 
      68         7681 :             let control_store = DiskStateStorage::new(disk.clone());
      69         7681 :             let wal_store = DiskWALStorage::new(disk.clone(), &control_store)?;
      70              : 
      71         7681 :             let sk = SafeKeeper::new(TimelineState::new(control_store), wal_store, conf.my_id)?;
      72         7681 :             timelines.insert(
      73         7681 :                 ttid,
      74         7681 :                 SharedState {
      75         7681 :                     sk,
      76         7681 :                     disk: disk.clone(),
      77         7681 :                 },
      78         7681 :             );
      79              :         }
      80              : 
      81        10085 :         Ok(Self {
      82        10085 :             timelines,
      83        10085 :             conf,
      84        10085 :             disk,
      85        10085 :         })
      86        10085 :     }
      87              : 
      88         1447 :     fn create(&mut self, ttid: TenantTimelineId, server_info: ServerInfo) -> Result<()> {
      89         1447 :         if self.timelines.contains_key(&ttid) {
      90            0 :             bail!("timeline {} already exists", ttid);
      91         1447 :         }
      92         1447 : 
      93         1447 :         debug!("creating new timeline {}", ttid);
      94              : 
      95         1447 :         let commit_lsn = Lsn::INVALID;
      96         1447 :         let local_start_lsn = Lsn::INVALID;
      97              : 
      98         1447 :         let state = TimelinePersistentState::new(
      99         1447 :             &ttid,
     100         1447 :             Configuration::empty(),
     101         1447 :             server_info,
     102         1447 :             commit_lsn,
     103         1447 :             local_start_lsn,
     104         1447 :         )?;
     105              : 
     106         1447 :         let disk_timeline = self.disk.put_state(&ttid, state);
     107         1447 :         let control_store = DiskStateStorage::new(disk_timeline.clone());
     108         1447 :         let wal_store = DiskWALStorage::new(disk_timeline.clone(), &control_store)?;
     109              : 
     110         1447 :         let sk = SafeKeeper::new(
     111         1447 :             TimelineState::new(control_store),
     112         1447 :             wal_store,
     113         1447 :             self.conf.my_id,
     114         1447 :         )?;
     115              : 
     116         1447 :         self.timelines.insert(
     117         1447 :             ttid,
     118         1447 :             SharedState {
     119         1447 :                 sk,
     120         1447 :                 disk: disk_timeline,
     121         1447 :             },
     122         1447 :         );
     123         1447 :         Ok(())
     124         1447 :     }
     125              : 
     126        33561 :     fn get(&mut self, ttid: &TenantTimelineId) -> &mut SharedState {
     127        33561 :         self.timelines.get_mut(ttid).expect("timeline must exist")
     128        33561 :     }
     129              : 
     130        19855 :     fn has_tli(&self, ttid: &TenantTimelineId) -> bool {
     131        19855 :         self.timelines.contains_key(ttid)
     132        19855 :     }
     133              : }
     134              : 
     135              : /// State of a single connection to walproposer.
     136              : struct ConnState {
     137              :     tcp: TCP,
     138              : 
     139              :     greeting: bool,
     140              :     ttid: TenantTimelineId,
     141              :     flush_pending: bool,
     142              : 
     143              :     runtime: tokio::runtime::Runtime,
     144              : }
     145              : 
     146        10085 : pub fn run_server(os: NodeOs, disk: Arc<SafekeeperDisk>) -> Result<()> {
     147        10085 :     let _enter = info_span!("safekeeper", id = os.id()).entered();
     148        10085 :     debug!("started server");
     149        10085 :     os.log_event("started;safekeeper".to_owned());
     150        10085 :     let conf = SafeKeeperConf {
     151        10085 :         workdir: Utf8PathBuf::from("."),
     152        10085 :         my_id: NodeId(os.id() as u64),
     153        10085 :         listen_pg_addr: String::new(),
     154        10085 :         listen_http_addr: String::new(),
     155        10085 :         no_sync: false,
     156        10085 :         broker_endpoint: "/".parse::<Uri>().unwrap(),
     157        10085 :         broker_keepalive_interval: Duration::from_secs(0),
     158        10085 :         heartbeat_timeout: Duration::from_secs(0),
     159        10085 :         remote_storage: None,
     160        10085 :         max_offloader_lag_bytes: 0,
     161        10085 :         wal_backup_enabled: false,
     162        10085 :         listen_pg_addr_tenant_only: None,
     163        10085 :         advertise_pg_addr: None,
     164        10085 :         availability_zone: None,
     165        10085 :         peer_recovery_enabled: false,
     166        10085 :         backup_parallel_jobs: 0,
     167        10085 :         pg_auth: None,
     168        10085 :         pg_tenant_only_auth: None,
     169        10085 :         http_auth: None,
     170        10085 :         sk_auth_token: None,
     171        10085 :         current_thread_runtime: false,
     172        10085 :         walsenders_keep_horizon: false,
     173        10085 :         partial_backup_timeout: Duration::from_secs(0),
     174        10085 :         disable_periodic_broker_push: false,
     175        10085 :         enable_offload: false,
     176        10085 :         delete_offloaded_wal: false,
     177        10085 :         control_file_save_interval: Duration::from_secs(1),
     178        10085 :         partial_backup_concurrency: 1,
     179        10085 :         eviction_min_resident: Duration::ZERO,
     180        10085 :         wal_reader_fanout: false,
     181        10085 :         max_delta_for_fanout: None,
     182        10085 :     };
     183              : 
     184        10085 :     let mut global = GlobalMap::new(disk, conf.clone())?;
     185        10085 :     let mut conns: HashMap<usize, ConnState> = HashMap::new();
     186              : 
     187        10085 :     for (&_ttid, shared_state) in global.timelines.iter_mut() {
     188         7681 :         let flush_lsn = shared_state.sk.wal_store.flush_lsn();
     189         7681 :         let commit_lsn = shared_state.sk.state.commit_lsn;
     190         7681 :         os.log_event(format!("tli_loaded;{};{}", flush_lsn.0, commit_lsn.0));
     191         7681 :     }
     192              : 
     193        10085 :     let node_events = os.node_events();
     194        10085 :     let mut epoll_vec: Vec<Box<dyn PollSome>> = vec![];
     195        10085 :     let mut epoll_idx: Vec<usize> = vec![];
     196              : 
     197              :     // TODO: batch events processing (multiple events per tick)
     198              :     loop {
     199        78515 :         epoll_vec.clear();
     200        78515 :         epoll_idx.clear();
     201        78515 : 
     202        78515 :         // node events channel
     203        78515 :         epoll_vec.push(Box::new(node_events.clone()));
     204        78515 :         epoll_idx.push(0);
     205              : 
     206              :         // tcp connections
     207       280225 :         for conn in conns.values() {
     208       280225 :             epoll_vec.push(Box::new(conn.tcp.recv_chan()));
     209       280225 :             epoll_idx.push(conn.tcp.connection_id());
     210       280225 :         }
     211              : 
     212              :         // waiting for the next message
     213        78515 :         let index = executor::epoll_chans(&epoll_vec, -1).unwrap();
     214        78515 : 
     215        78515 :         if index == 0 {
     216              :             // got a new connection
     217        25526 :             match node_events.must_recv() {
     218        25526 :                 NodeEvent::Accept(tcp) => {
     219        25526 :                     conns.insert(
     220        25526 :                         tcp.connection_id(),
     221        25526 :                         ConnState {
     222        25526 :                             tcp,
     223        25526 :                             greeting: false,
     224        25526 :                             ttid: TenantTimelineId::empty(),
     225        25526 :                             flush_pending: false,
     226        25526 :                             runtime: tokio::runtime::Builder::new_current_thread().build()?,
     227              :                         },
     228              :                     );
     229              :                 }
     230            0 :                 NodeEvent::Internal(_) => unreachable!(),
     231              :             }
     232        25526 :             continue;
     233        52989 :         }
     234        52989 : 
     235        52989 :         let connection_id = epoll_idx[index];
     236        52989 :         let conn = conns.get_mut(&connection_id).unwrap();
     237        52989 :         let mut next_event = Some(conn.tcp.recv_chan().must_recv());
     238              : 
     239              :         loop {
     240        97022 :             let event = match next_event {
     241        54448 :                 Some(event) => event,
     242        42574 :                 None => break,
     243              :             };
     244              : 
     245        54448 :             match event {
     246        39845 :                 NetEvent::Message(msg) => {
     247        39845 :                     let res = conn.process_any(msg, &mut global);
     248        39845 :                     if res.is_err() {
     249        10415 :                         let e = res.unwrap_err();
     250        10415 :                         let estr = e.to_string();
     251        10415 :                         if !estr.contains("finished processing START_REPLICATION") {
     252        10085 :                             warn!("conn {:?} error: {:?}", connection_id, e);
     253            0 :                             panic!("unexpected error at safekeeper: {:#}", e);
     254          330 :                         }
     255          330 :                         conns.remove(&connection_id);
     256          330 :                         break;
     257        29430 :                     }
     258              :                 }
     259        14603 :                 NetEvent::Closed => {
     260        14603 :                     // TODO: remove from conns?
     261        14603 :                 }
     262              :             }
     263              : 
     264        44033 :             next_event = conn.tcp.recv_chan().try_recv();
     265              :         }
     266              : 
     267       186450 :         conns.retain(|_, conn| {
     268       186450 :             let res = conn.flush(&mut global);
     269       186450 :             if res.is_err() {
     270            0 :                 debug!("conn {:?} error: {:?}", conn.tcp, res);
     271       186450 :             }
     272       186450 :             res.is_ok()
     273       186450 :         });
     274              :     }
     275            0 : }
     276              : 
     277              : impl ConnState {
     278              :     /// Process a message from the network. It can be START_REPLICATION request or a valid ProposerAcceptorMessage message.
     279        29760 :     fn process_any(&mut self, any: AnyMessage, global: &mut GlobalMap) -> Result<()> {
     280        29760 :         if let AnyMessage::Bytes(copy_data) = any {
     281        29760 :             let repl_prefix = b"START_REPLICATION ";
     282        29760 :             if !self.greeting && copy_data.starts_with(repl_prefix) {
     283          330 :                 self.process_start_replication(copy_data.slice(repl_prefix.len()..), global)?;
     284          330 :                 bail!("finished processing START_REPLICATION")
     285        29430 :             }
     286              : 
     287        29430 :             let msg = ProposerAcceptorMessage::parse(copy_data, SK_PROTO_VERSION_3)?;
     288        29430 :             debug!("got msg: {:?}", msg);
     289        29430 :             self.process(msg, global)
     290              :         } else {
     291            0 :             bail!("unexpected message, expected AnyMessage::Bytes");
     292              :         }
     293        29760 :     }
     294              : 
     295              :     /// Process START_REPLICATION request.
     296          330 :     fn process_start_replication(
     297          330 :         &mut self,
     298          330 :         copy_data: Bytes,
     299          330 :         global: &mut GlobalMap,
     300          330 :     ) -> Result<()> {
     301              :         // format is "<tenant_id> <timeline_id> <start_lsn> <end_lsn>"
     302          330 :         let str = String::from_utf8(copy_data.to_vec())?;
     303              : 
     304          330 :         let mut parts = str.split(' ');
     305          330 :         let tenant_id = parts.next().unwrap().parse::<TenantId>()?;
     306          330 :         let timeline_id = parts.next().unwrap().parse::<TimelineId>()?;
     307          330 :         let start_lsn = parts.next().unwrap().parse::<u64>()?;
     308          330 :         let end_lsn = parts.next().unwrap().parse::<u64>()?;
     309              : 
     310          330 :         let ttid = TenantTimelineId::new(tenant_id, timeline_id);
     311          330 :         let shared_state = global.get(&ttid);
     312          330 : 
     313          330 :         // read bytes from start_lsn to end_lsn
     314          330 :         let mut buf = vec![0; (end_lsn - start_lsn) as usize];
     315          330 :         shared_state.disk.wal.lock().read(start_lsn, &mut buf);
     316          330 : 
     317          330 :         // send bytes to the client
     318          330 :         self.tcp.send(AnyMessage::Bytes(Bytes::from(buf)));
     319          330 :         Ok(())
     320          330 :     }
     321              : 
     322              :     /// Get or create a timeline.
     323        19855 :     fn init_timeline(
     324        19855 :         &mut self,
     325        19855 :         ttid: TenantTimelineId,
     326        19855 :         server_info: ServerInfo,
     327        19855 :         global: &mut GlobalMap,
     328        19855 :     ) -> Result<()> {
     329        19855 :         self.ttid = ttid;
     330        19855 :         if global.has_tli(&ttid) {
     331        18408 :             return Ok(());
     332         1447 :         }
     333         1447 : 
     334         1447 :         global.create(ttid, server_info)
     335        19855 :     }
     336              : 
     337              :     /// Process a ProposerAcceptorMessage.
     338        29430 :     fn process(&mut self, msg: ProposerAcceptorMessage, global: &mut GlobalMap) -> Result<()> {
     339        29430 :         if !self.greeting {
     340        19855 :             self.greeting = true;
     341        19855 : 
     342        19855 :             match msg {
     343        19855 :                 ProposerAcceptorMessage::Greeting(ref greeting) => {
     344        19855 :                     tracing::info!(
     345            0 :                         "start handshake with walproposer {:?} {:?}",
     346              :                         self.tcp,
     347              :                         greeting
     348              :                     );
     349        19855 :                     let server_info = ServerInfo {
     350        19855 :                         pg_version: greeting.pg_version,
     351        19855 :                         system_id: greeting.system_id,
     352        19855 :                         wal_seg_size: greeting.wal_seg_size,
     353        19855 :                     };
     354        19855 :                     let ttid = TenantTimelineId::new(greeting.tenant_id, greeting.timeline_id);
     355        19855 :                     self.init_timeline(ttid, server_info, global)?
     356              :                 }
     357              :                 _ => {
     358            0 :                     bail!("unexpected message {msg:?} instead of greeting");
     359              :                 }
     360              :             }
     361         9575 :         }
     362              : 
     363        29430 :         let tli = global.get(&self.ttid);
     364        29430 : 
     365        29430 :         match msg {
     366         4613 :             ProposerAcceptorMessage::AppendRequest(append_request) => {
     367         4613 :                 self.flush_pending = true;
     368         4613 :                 self.process_sk_msg(
     369         4613 :                     tli,
     370         4613 :                     &ProposerAcceptorMessage::NoFlushAppendRequest(append_request),
     371         4613 :                 )?;
     372              :             }
     373        24817 :             other => {
     374        24817 :                 self.process_sk_msg(tli, &other)?;
     375              :             }
     376              :         }
     377              : 
     378        29430 :         Ok(())
     379        29430 :     }
     380              : 
     381              :     /// Process FlushWAL if needed.
     382       186450 :     fn flush(&mut self, global: &mut GlobalMap) -> Result<()> {
     383       186450 :         // TODO: try to add extra flushes in simulation, to verify that extra flushes don't break anything
     384       186450 :         if !self.flush_pending {
     385       182649 :             return Ok(());
     386         3801 :         }
     387         3801 :         self.flush_pending = false;
     388         3801 :         let shared_state = global.get(&self.ttid);
     389         3801 :         self.process_sk_msg(shared_state, &ProposerAcceptorMessage::FlushWAL)
     390       186450 :     }
     391              : 
     392              :     /// Make safekeeper process a message and send a reply to the TCP
     393        33231 :     fn process_sk_msg(
     394        33231 :         &mut self,
     395        33231 :         shared_state: &mut SharedState,
     396        33231 :         msg: &ProposerAcceptorMessage,
     397        33231 :     ) -> Result<()> {
     398        33231 :         let mut reply = self.runtime.block_on(shared_state.sk.process_msg(msg))?;
     399        33231 :         if let Some(reply) = &mut reply {
     400              :             // TODO: if this is AppendResponse, fill in proper hot standby feedback and disk consistent lsn
     401              : 
     402        27384 :             let mut buf = BytesMut::with_capacity(128);
     403        27384 :             reply.serialize(&mut buf, SK_PROTO_VERSION_3)?;
     404              : 
     405        27384 :             self.tcp.send(AnyMessage::Bytes(buf.into()));
     406         5847 :         }
     407        33231 :         Ok(())
     408        33231 :     }
     409              : }
     410              : 
     411              : impl Drop for ConnState {
     412        25498 :     fn drop(&mut self) {
     413        25498 :         debug!("dropping conn: {:?}", self.tcp);
     414        25498 :         if !std::thread::panicking() {
     415          330 :             self.tcp.close();
     416        25168 :         }
     417              :         // TODO: clean up non-fsynced WAL
     418        25498 :     }
     419              : }
        

Generated by: LCOV version 2.1-beta