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

Generated by: LCOV version 2.1-beta