LCOV - code coverage report
Current view: top level - safekeeper/tests/walproposer_sim - safekeeper.rs (source / functions) Coverage Total Hit
Test: b837401fb09d2d9818b70e630fdb67e9799b7b0d.info Lines: 93.0 % 285 265
Test Date: 2024-04-18 15:32:49 Functions: 79.4 % 63 50

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

Generated by: LCOV version 2.1-beta