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

Generated by: LCOV version 2.1-beta