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

Generated by: LCOV version 2.1-beta