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

Generated by: LCOV version 2.1-beta