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

Generated by: LCOV version 2.1-beta