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

Generated by: LCOV version 2.1-beta