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

Generated by: LCOV version 2.1-beta