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

Generated by: LCOV version 2.1-beta