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

Generated by: LCOV version 2.1-beta