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

Generated by: LCOV version 2.1-beta