LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - safekeeper.rs (source / functions) Coverage Total Hit
Test: d5cbf29d97fdd23f6bda3d96cc57e517a06c5084.info Lines: 94.8 % 290 275
Test Date: 2025-03-18 14:05:41 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         9444 :     fn new(disk: Arc<SafekeeperDisk>, conf: SafeKeeperConf) -> Result<Self> {
      46         9444 :         let mut timelines = HashMap::new();
      47              : 
      48         9444 :         for (&ttid, disk) in disk.timelines.lock().iter() {
      49         7006 :             debug!("loading timeline {}", ttid);
      50         7006 :             let state = disk.state.lock().clone();
      51         7006 : 
      52         7006 :             if state.server.wal_seg_size == 0 {
      53            0 :                 bail!(TimelineError::UninitializedWalSegSize(ttid));
      54         7006 :             }
      55         7006 : 
      56         7006 :             if state.server.pg_version == UNKNOWN_SERVER_VERSION {
      57            0 :                 bail!(TimelineError::UninitialinzedPgVersion(ttid));
      58         7006 :             }
      59         7006 : 
      60         7006 :             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         7006 :             }
      67         7006 : 
      68         7006 :             let control_store = DiskStateStorage::new(disk.clone());
      69         7006 :             let wal_store = DiskWALStorage::new(disk.clone(), &control_store)?;
      70              : 
      71         7006 :             let sk = SafeKeeper::new(TimelineState::new(control_store), wal_store, conf.my_id)?;
      72         7006 :             timelines.insert(
      73         7006 :                 ttid,
      74         7006 :                 SharedState {
      75         7006 :                     sk,
      76         7006 :                     disk: disk.clone(),
      77         7006 :                 },
      78         7006 :             );
      79              :         }
      80              : 
      81         9444 :         Ok(Self {
      82         9444 :             timelines,
      83         9444 :             conf,
      84         9444 :             disk,
      85         9444 :         })
      86         9444 :     }
      87              : 
      88         1452 :     fn create(&mut self, ttid: TenantTimelineId, server_info: ServerInfo) -> Result<()> {
      89         1452 :         if self.timelines.contains_key(&ttid) {
      90            0 :             bail!("timeline {} already exists", ttid);
      91         1452 :         }
      92         1452 : 
      93         1452 :         debug!("creating new timeline {}", ttid);
      94              : 
      95         1452 :         let commit_lsn = Lsn::INVALID;
      96         1452 :         let local_start_lsn = Lsn::INVALID;
      97              : 
      98         1452 :         let state = TimelinePersistentState::new(
      99         1452 :             &ttid,
     100         1452 :             Configuration::empty(),
     101         1452 :             server_info,
     102         1452 :             commit_lsn,
     103         1452 :             local_start_lsn,
     104         1452 :         )?;
     105              : 
     106         1452 :         let disk_timeline = self.disk.put_state(&ttid, state);
     107         1452 :         let control_store = DiskStateStorage::new(disk_timeline.clone());
     108         1452 :         let wal_store = DiskWALStorage::new(disk_timeline.clone(), &control_store)?;
     109              : 
     110         1452 :         let sk = SafeKeeper::new(
     111         1452 :             TimelineState::new(control_store),
     112         1452 :             wal_store,
     113         1452 :             self.conf.my_id,
     114         1452 :         )?;
     115              : 
     116         1452 :         self.timelines.insert(
     117         1452 :             ttid,
     118         1452 :             SharedState {
     119         1452 :                 sk,
     120         1452 :                 disk: disk_timeline,
     121         1452 :             },
     122         1452 :         );
     123         1452 :         Ok(())
     124         1452 :     }
     125              : 
     126        27957 :     fn get(&mut self, ttid: &TenantTimelineId) -> &mut SharedState {
     127        27957 :         self.timelines.get_mut(ttid).expect("timeline must exist")
     128        27957 :     }
     129              : 
     130        18615 :     fn has_tli(&self, ttid: &TenantTimelineId) -> bool {
     131        18615 :         self.timelines.contains_key(ttid)
     132        18615 :     }
     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         9444 : pub fn run_server(os: NodeOs, disk: Arc<SafekeeperDisk>) -> Result<()> {
     147         9444 :     let _enter = info_span!("safekeeper", id = os.id()).entered();
     148         9444 :     debug!("started server");
     149         9444 :     os.log_event("started;safekeeper".to_owned());
     150         9444 :     let conf = SafeKeeperConf {
     151         9444 :         workdir: Utf8PathBuf::from("."),
     152         9444 :         my_id: NodeId(os.id() as u64),
     153         9444 :         listen_pg_addr: String::new(),
     154         9444 :         listen_http_addr: String::new(),
     155         9444 :         listen_https_addr: None,
     156         9444 :         no_sync: false,
     157         9444 :         broker_endpoint: "/".parse::<Uri>().unwrap(),
     158         9444 :         broker_keepalive_interval: Duration::from_secs(0),
     159         9444 :         heartbeat_timeout: Duration::from_secs(0),
     160         9444 :         remote_storage: None,
     161         9444 :         max_offloader_lag_bytes: 0,
     162         9444 :         wal_backup_enabled: false,
     163         9444 :         listen_pg_addr_tenant_only: None,
     164         9444 :         advertise_pg_addr: None,
     165         9444 :         availability_zone: None,
     166         9444 :         peer_recovery_enabled: false,
     167         9444 :         backup_parallel_jobs: 0,
     168         9444 :         pg_auth: None,
     169         9444 :         pg_tenant_only_auth: None,
     170         9444 :         http_auth: None,
     171         9444 :         sk_auth_token: None,
     172         9444 :         current_thread_runtime: false,
     173         9444 :         walsenders_keep_horizon: false,
     174         9444 :         partial_backup_timeout: Duration::from_secs(0),
     175         9444 :         disable_periodic_broker_push: false,
     176         9444 :         enable_offload: false,
     177         9444 :         delete_offloaded_wal: false,
     178         9444 :         control_file_save_interval: Duration::from_secs(1),
     179         9444 :         partial_backup_concurrency: 1,
     180         9444 :         eviction_min_resident: Duration::ZERO,
     181         9444 :         wal_reader_fanout: false,
     182         9444 :         max_delta_for_fanout: None,
     183         9444 :         ssl_key_file: Utf8PathBuf::from(""),
     184         9444 :         ssl_cert_file: Utf8PathBuf::from(""),
     185         9444 :         ssl_ca_cert: None,
     186         9444 :     };
     187              : 
     188         9444 :     let mut global = GlobalMap::new(disk, conf.clone())?;
     189         9444 :     let mut conns: HashMap<usize, ConnState> = HashMap::new();
     190              : 
     191         9444 :     for (&_ttid, shared_state) in global.timelines.iter_mut() {
     192         7006 :         let flush_lsn = shared_state.sk.wal_store.flush_lsn();
     193         7006 :         let commit_lsn = shared_state.sk.state.commit_lsn;
     194         7006 :         os.log_event(format!("tli_loaded;{};{}", flush_lsn.0, commit_lsn.0));
     195         7006 :     }
     196              : 
     197         9444 :     let node_events = os.node_events();
     198         9444 :     let mut epoll_vec: Vec<Box<dyn PollSome>> = vec![];
     199         9444 :     let mut epoll_idx: Vec<usize> = vec![];
     200              : 
     201              :     // TODO: batch events processing (multiple events per tick)
     202              :     loop {
     203        71492 :         epoll_vec.clear();
     204        71492 :         epoll_idx.clear();
     205        71492 : 
     206        71492 :         // node events channel
     207        71492 :         epoll_vec.push(Box::new(node_events.clone()));
     208        71492 :         epoll_idx.push(0);
     209              : 
     210              :         // tcp connections
     211       260870 :         for conn in conns.values() {
     212       260870 :             epoll_vec.push(Box::new(conn.tcp.recv_chan()));
     213       260870 :             epoll_idx.push(conn.tcp.connection_id());
     214       260870 :         }
     215              : 
     216              :         // waiting for the next message
     217        71492 :         let index = executor::epoll_chans(&epoll_vec, -1).unwrap();
     218        71492 : 
     219        71492 :         if index == 0 {
     220              :             // got a new connection
     221        23847 :             match node_events.must_recv() {
     222        23847 :                 NodeEvent::Accept(tcp) => {
     223        23847 :                     conns.insert(
     224        23847 :                         tcp.connection_id(),
     225        23847 :                         ConnState {
     226        23847 :                             tcp,
     227        23847 :                             greeting: false,
     228        23847 :                             ttid: TenantTimelineId::empty(),
     229        23847 :                             flush_pending: false,
     230        23847 :                             runtime: tokio::runtime::Builder::new_current_thread().build()?,
     231              :                         },
     232              :                     );
     233              :                 }
     234            0 :                 NodeEvent::Internal(_) => unreachable!(),
     235              :             }
     236        23847 :             continue;
     237        47645 :         }
     238        47645 : 
     239        47645 :         let connection_id = epoll_idx[index];
     240        47645 :         let conn = conns.get_mut(&connection_id).unwrap();
     241        47645 :         let mut next_event = Some(conn.tcp.recv_chan().must_recv());
     242              : 
     243              :         loop {
     244        86597 :             let event = match next_event {
     245        48600 :                 Some(event) => event,
     246        37997 :                 None => break,
     247              :             };
     248              : 
     249        48600 :             match event {
     250        34847 :                 NetEvent::Message(msg) => {
     251        34847 :                     let res = conn.process_any(msg, &mut global);
     252        34847 :                     if res.is_err() {
     253         9648 :                         let e = res.unwrap_err();
     254         9648 :                         let estr = e.to_string();
     255         9648 :                         if !estr.contains("finished processing START_REPLICATION") {
     256         9444 :                             warn!("conn {:?} error: {:?}", connection_id, e);
     257            0 :                             panic!("unexpected error at safekeeper: {:#}", e);
     258          204 :                         }
     259          204 :                         conns.remove(&connection_id);
     260          204 :                         break;
     261        25199 :                     }
     262              :                 }
     263        13753 :                 NetEvent::Closed => {
     264        13753 :                     // TODO: remove from conns?
     265        13753 :                 }
     266              :             }
     267              : 
     268        38952 :             next_event = conn.tcp.recv_chan().try_recv();
     269              :         }
     270              : 
     271       170766 :         conns.retain(|_, conn| {
     272       170766 :             let res = conn.flush(&mut global);
     273       170766 :             if res.is_err() {
     274            0 :                 debug!("conn {:?} error: {:?}", conn.tcp, res);
     275       170766 :             }
     276       170766 :             res.is_ok()
     277       170766 :         });
     278              :     }
     279            0 : }
     280              : 
     281              : impl ConnState {
     282              :     /// Process a message from the network. It can be START_REPLICATION request or a valid ProposerAcceptorMessage message.
     283        25403 :     fn process_any(&mut self, any: AnyMessage, global: &mut GlobalMap) -> Result<()> {
     284        25403 :         if let AnyMessage::Bytes(copy_data) = any {
     285        25403 :             let repl_prefix = b"START_REPLICATION ";
     286        25403 :             if !self.greeting && copy_data.starts_with(repl_prefix) {
     287          204 :                 self.process_start_replication(copy_data.slice(repl_prefix.len()..), global)?;
     288          204 :                 bail!("finished processing START_REPLICATION")
     289        25199 :             }
     290              : 
     291        25199 :             let msg = ProposerAcceptorMessage::parse(copy_data, SK_PROTO_VERSION_3)?;
     292        25199 :             debug!("got msg: {:?}", msg);
     293        25199 :             self.process(msg, global)
     294              :         } else {
     295            0 :             bail!("unexpected message, expected AnyMessage::Bytes");
     296              :         }
     297        25403 :     }
     298              : 
     299              :     /// Process START_REPLICATION request.
     300          204 :     fn process_start_replication(
     301          204 :         &mut self,
     302          204 :         copy_data: Bytes,
     303          204 :         global: &mut GlobalMap,
     304          204 :     ) -> Result<()> {
     305              :         // format is "<tenant_id> <timeline_id> <start_lsn> <end_lsn>"
     306          204 :         let str = String::from_utf8(copy_data.to_vec())?;
     307              : 
     308          204 :         let mut parts = str.split(' ');
     309          204 :         let tenant_id = parts.next().unwrap().parse::<TenantId>()?;
     310          204 :         let timeline_id = parts.next().unwrap().parse::<TimelineId>()?;
     311          204 :         let start_lsn = parts.next().unwrap().parse::<u64>()?;
     312          204 :         let end_lsn = parts.next().unwrap().parse::<u64>()?;
     313              : 
     314          204 :         let ttid = TenantTimelineId::new(tenant_id, timeline_id);
     315          204 :         let shared_state = global.get(&ttid);
     316          204 : 
     317          204 :         // read bytes from start_lsn to end_lsn
     318          204 :         let mut buf = vec![0; (end_lsn - start_lsn) as usize];
     319          204 :         shared_state.disk.wal.lock().read(start_lsn, &mut buf);
     320          204 : 
     321          204 :         // send bytes to the client
     322          204 :         self.tcp.send(AnyMessage::Bytes(Bytes::from(buf)));
     323          204 :         Ok(())
     324          204 :     }
     325              : 
     326              :     /// Get or create a timeline.
     327        18615 :     fn init_timeline(
     328        18615 :         &mut self,
     329        18615 :         ttid: TenantTimelineId,
     330        18615 :         server_info: ServerInfo,
     331        18615 :         global: &mut GlobalMap,
     332        18615 :     ) -> Result<()> {
     333        18615 :         self.ttid = ttid;
     334        18615 :         if global.has_tli(&ttid) {
     335        17163 :             return Ok(());
     336         1452 :         }
     337         1452 : 
     338         1452 :         global.create(ttid, server_info)
     339        18615 :     }
     340              : 
     341              :     /// Process a ProposerAcceptorMessage.
     342        25199 :     fn process(&mut self, msg: ProposerAcceptorMessage, global: &mut GlobalMap) -> Result<()> {
     343        25199 :         if !self.greeting {
     344        18615 :             self.greeting = true;
     345        18615 : 
     346        18615 :             match msg {
     347        18615 :                 ProposerAcceptorMessage::Greeting(ref greeting) => {
     348        18615 :                     tracing::info!(
     349            0 :                         "start handshake with walproposer {:?} {:?}",
     350              :                         self.tcp,
     351              :                         greeting
     352              :                     );
     353        18615 :                     let server_info = ServerInfo {
     354        18615 :                         pg_version: greeting.pg_version,
     355        18615 :                         system_id: greeting.system_id,
     356        18615 :                         wal_seg_size: greeting.wal_seg_size,
     357        18615 :                     };
     358        18615 :                     let ttid = TenantTimelineId::new(greeting.tenant_id, greeting.timeline_id);
     359        18615 :                     self.init_timeline(ttid, server_info, global)?
     360              :                 }
     361              :                 _ => {
     362            0 :                     bail!("unexpected message {msg:?} instead of greeting");
     363              :                 }
     364              :             }
     365         6584 :         }
     366              : 
     367        25199 :         let tli = global.get(&self.ttid);
     368        25199 : 
     369        25199 :         match msg {
     370         3074 :             ProposerAcceptorMessage::AppendRequest(append_request) => {
     371         3074 :                 self.flush_pending = true;
     372         3074 :                 self.process_sk_msg(
     373         3074 :                     tli,
     374         3074 :                     &ProposerAcceptorMessage::NoFlushAppendRequest(append_request),
     375         3074 :                 )?;
     376              :             }
     377        22125 :             other => {
     378        22125 :                 self.process_sk_msg(tli, &other)?;
     379              :             }
     380              :         }
     381              : 
     382        25199 :         Ok(())
     383        25199 :     }
     384              : 
     385              :     /// Process FlushWAL if needed.
     386       170766 :     fn flush(&mut self, global: &mut GlobalMap) -> Result<()> {
     387       170766 :         // TODO: try to add extra flushes in simulation, to verify that extra flushes don't break anything
     388       170766 :         if !self.flush_pending {
     389       168212 :             return Ok(());
     390         2554 :         }
     391         2554 :         self.flush_pending = false;
     392         2554 :         let shared_state = global.get(&self.ttid);
     393         2554 :         self.process_sk_msg(shared_state, &ProposerAcceptorMessage::FlushWAL)
     394       170766 :     }
     395              : 
     396              :     /// Make safekeeper process a message and send a reply to the TCP
     397        27753 :     fn process_sk_msg(
     398        27753 :         &mut self,
     399        27753 :         shared_state: &mut SharedState,
     400        27753 :         msg: &ProposerAcceptorMessage,
     401        27753 :     ) -> Result<()> {
     402        27753 :         let mut reply = self.runtime.block_on(shared_state.sk.process_msg(msg))?;
     403        27753 :         if let Some(reply) = &mut reply {
     404              :             // TODO: if this is AppendResponse, fill in proper hot standby feedback and disk consistent lsn
     405              : 
     406        23931 :             let mut buf = BytesMut::with_capacity(128);
     407        23931 :             reply.serialize(&mut buf, SK_PROTO_VERSION_3)?;
     408              : 
     409        23931 :             self.tcp.send(AnyMessage::Bytes(buf.into()));
     410         3822 :         }
     411        27753 :         Ok(())
     412        27753 :     }
     413              : }
     414              : 
     415              : impl Drop for ConnState {
     416        23819 :     fn drop(&mut self) {
     417        23819 :         debug!("dropping conn: {:?}", self.tcp);
     418        23819 :         if !std::thread::panicking() {
     419          204 :             self.tcp.close();
     420        23615 :         }
     421              :         // TODO: clean up non-fsynced WAL
     422        23819 :     }
     423              : }
        

Generated by: LCOV version 2.1-beta