LCOV - code coverage report
Current view: top level - pageserver/src - walredo.rs (source / functions) Coverage Total Hit
Test: 7eb96e224e685167ad85f58f858387d8cf253f63.info Lines: 68.7 % 386 265
Test Date: 2024-09-23 21:23:07 Functions: 65.2 % 46 30

            Line data    Source code
       1              : //!
       2              : //! WAL redo. This service runs PostgreSQL in a special wal_redo mode
       3              : //! to apply given WAL records over an old page image and return new
       4              : //! page image.
       5              : //!
       6              : //! We rely on Postgres to perform WAL redo for us. We launch a
       7              : //! postgres process in special "wal redo" mode that's similar to
       8              : //! single-user mode. We then pass the previous page image, if any,
       9              : //! and all the WAL records we want to apply, to the postgres
      10              : //! process. Then we get the page image back. Communication with the
      11              : //! postgres process happens via stdin/stdout
      12              : //!
      13              : //! See pgxn/neon_walredo/walredoproc.c for the other side of
      14              : //! this communication.
      15              : //!
      16              : //! The Postgres process is assumed to be secure against malicious WAL
      17              : //! records. It achieves it by dropping privileges before replaying
      18              : //! any WAL records, so that even if an attacker hijacks the Postgres
      19              : //! process, he cannot escape out of it.
      20              : 
      21              : /// Process lifecycle and abstracction for the IPC protocol.
      22              : mod process;
      23              : 
      24              : /// Code to apply [`NeonWalRecord`]s.
      25              : pub(crate) mod apply_neon;
      26              : 
      27              : use crate::config::PageServerConf;
      28              : use crate::metrics::{
      29              :     WAL_REDO_BYTES_HISTOGRAM, WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM,
      30              :     WAL_REDO_RECORDS_HISTOGRAM, WAL_REDO_TIME,
      31              : };
      32              : use crate::repository::Key;
      33              : use crate::walrecord::NeonWalRecord;
      34              : use anyhow::Context;
      35              : use bytes::{Bytes, BytesMut};
      36              : use pageserver_api::models::{WalRedoManagerProcessStatus, WalRedoManagerStatus};
      37              : use pageserver_api::shard::TenantShardId;
      38              : use std::future::Future;
      39              : use std::sync::Arc;
      40              : use std::time::Duration;
      41              : use std::time::Instant;
      42              : use tracing::*;
      43              : use utils::lsn::Lsn;
      44              : use utils::sync::gate::GateError;
      45              : use utils::sync::heavier_once_cell;
      46              : 
      47              : /// The real implementation that uses a Postgres process to
      48              : /// perform WAL replay.
      49              : ///
      50              : /// Only one thread can use the process at a time, that is controlled by the
      51              : /// Mutex. In the future, we might want to launch a pool of processes to allow
      52              : /// concurrent replay of multiple records.
      53              : pub struct PostgresRedoManager {
      54              :     tenant_shard_id: TenantShardId,
      55              :     conf: &'static PageServerConf,
      56              :     last_redo_at: std::sync::Mutex<Option<Instant>>,
      57              :     /// We use [`heavier_once_cell`] for
      58              :     ///
      59              :     /// 1. coalescing the lazy spawning of walredo processes ([`ProcessOnceCell::Spawned`])
      60              :     /// 2. prevent new processes from being spawned on [`Self::shutdown`] (=> [`ProcessOnceCell::ManagerShutDown`]).
      61              :     ///
      62              :     /// # Spawning
      63              :     ///
      64              :     /// Redo requests use the once cell to coalesce onto one call to [`process::WalRedoProcess::launch`].
      65              :     ///
      66              :     /// Notably, requests don't use the [`heavier_once_cell::Guard`] to keep ahold of the
      67              :     /// their process object; we use [`Arc::clone`] for that.
      68              :     ///
      69              :     /// This is primarily because earlier implementations that didn't  use [`heavier_once_cell`]
      70              :     /// had that behavior; it's probably unnecessary.
      71              :     /// The only merit of it is that if one walredo process encounters an error,
      72              :     /// it can take it out of rotation (= using [`heavier_once_cell::Guard::take_and_deinit`].
      73              :     /// and retry redo, thereby starting the new process, while other redo tasks might
      74              :     /// still be using the old redo process. But, those other tasks will most likely
      75              :     /// encounter an error as well, and errors are an unexpected condition anyway.
      76              :     /// So, probably we could get rid of the `Arc` in the future.
      77              :     ///
      78              :     /// # Shutdown
      79              :     ///
      80              :     /// See [`Self::launched_processes`].
      81              :     redo_process: heavier_once_cell::OnceCell<ProcessOnceCell>,
      82              : 
      83              :     /// Gate that is entered when launching a walredo process and held open
      84              :     /// until the process has been `kill()`ed and `wait()`ed upon.
      85              :     ///
      86              :     /// Manager shutdown waits for this gate to close after setting the
      87              :     /// [`ProcessOnceCell::ManagerShutDown`] state in [`Self::redo_process`].
      88              :     ///
      89              :     /// This type of usage is a bit unusual because gates usually keep track of
      90              :     /// concurrent operations, e.g., every [`Self::request_redo`] that is inflight.
      91              :     /// But we use it here to keep track of the _processes_ that we have launched,
      92              :     /// which may outlive any individual redo request because
      93              :     /// - we keep walredo process around until its quiesced to amortize spawn cost and
      94              :     /// - the Arc may be held by multiple concurrent redo requests, so, just because
      95              :     ///   you replace the [`Self::redo_process`] cell's content doesn't mean the
      96              :     ///   process gets killed immediately.
      97              :     ///
      98              :     /// We could simplify this by getting rid of the [`Arc`].
      99              :     /// See the comment on [`Self::redo_process`] for more details.
     100              :     launched_processes: utils::sync::gate::Gate,
     101              : }
     102              : 
     103              : /// See [`PostgresRedoManager::redo_process`].
     104              : enum ProcessOnceCell {
     105              :     Spawned(Arc<Process>),
     106              :     ManagerShutDown,
     107              : }
     108              : 
     109              : struct Process {
     110              :     process: process::WalRedoProcess,
     111              :     /// This field is last in this struct so the guard gets dropped _after_ [`Self::process`].
     112              :     /// (Reminder: dropping [`Self::process`] synchronously sends SIGKILL and then `wait()`s for it to exit).
     113              :     _launched_processes_guard: utils::sync::gate::GateGuard,
     114              : }
     115              : 
     116              : impl std::ops::Deref for Process {
     117              :     type Target = process::WalRedoProcess;
     118              : 
     119           60 :     fn deref(&self) -> &Self::Target {
     120           60 :         &self.process
     121           60 :     }
     122              : }
     123              : 
     124            0 : #[derive(Debug, thiserror::Error)]
     125              : pub enum Error {
     126              :     #[error("cancelled")]
     127              :     Cancelled,
     128              :     #[error(transparent)]
     129              :     Other(#[from] anyhow::Error),
     130              : }
     131              : 
     132              : macro_rules! bail {
     133              :     ($($arg:tt)*) => {
     134              :         return Err($crate::walredo::Error::Other(::anyhow::anyhow!($($arg)*)));
     135              :     }
     136              : }
     137              : 
     138              : ///
     139              : /// Public interface of WAL redo manager
     140              : ///
     141              : impl PostgresRedoManager {
     142              :     ///
     143              :     /// Request the WAL redo manager to apply some WAL records
     144              :     ///
     145              :     /// The WAL redo is handled by a separate thread, so this just sends a request
     146              :     /// to the thread and waits for response.
     147              :     ///
     148              :     /// # Cancel-Safety
     149              :     ///
     150              :     /// This method is cancellation-safe.
     151           18 :     pub async fn request_redo(
     152           18 :         &self,
     153           18 :         key: Key,
     154           18 :         lsn: Lsn,
     155           18 :         base_img: Option<(Lsn, Bytes)>,
     156           18 :         records: Vec<(Lsn, NeonWalRecord)>,
     157           18 :         pg_version: u32,
     158           18 :     ) -> Result<Bytes, Error> {
     159           18 :         if records.is_empty() {
     160            0 :             bail!("invalid WAL redo request with no records");
     161           18 :         }
     162           18 : 
     163           18 :         let base_img_lsn = base_img.as_ref().map(|p| p.0).unwrap_or(Lsn::INVALID);
     164           18 :         let mut img = base_img.map(|p| p.1);
     165           18 :         let mut batch_neon = apply_neon::can_apply_in_neon(&records[0].1);
     166           18 :         let mut batch_start = 0;
     167           18 :         for (i, record) in records.iter().enumerate().skip(1) {
     168           18 :             let rec_neon = apply_neon::can_apply_in_neon(&record.1);
     169           18 : 
     170           18 :             if rec_neon != batch_neon {
     171            0 :                 let result = if batch_neon {
     172            0 :                     self.apply_batch_neon(key, lsn, img, &records[batch_start..i])
     173              :                 } else {
     174            0 :                     self.apply_batch_postgres(
     175            0 :                         key,
     176            0 :                         lsn,
     177            0 :                         img,
     178            0 :                         base_img_lsn,
     179            0 :                         &records[batch_start..i],
     180            0 :                         self.conf.wal_redo_timeout,
     181            0 :                         pg_version,
     182            0 :                     )
     183            0 :                     .await
     184              :                 };
     185            0 :                 img = Some(result?);
     186              : 
     187            0 :                 batch_neon = rec_neon;
     188            0 :                 batch_start = i;
     189           18 :             }
     190              :         }
     191              :         // last batch
     192           18 :         if batch_neon {
     193            0 :             self.apply_batch_neon(key, lsn, img, &records[batch_start..])
     194              :         } else {
     195           18 :             self.apply_batch_postgres(
     196           18 :                 key,
     197           18 :                 lsn,
     198           18 :                 img,
     199           18 :                 base_img_lsn,
     200           18 :                 &records[batch_start..],
     201           18 :                 self.conf.wal_redo_timeout,
     202           18 :                 pg_version,
     203           18 :             )
     204           48 :             .await
     205              :         }
     206           18 :     }
     207              : 
     208              :     /// Do a ping request-response roundtrip.
     209              :     ///
     210              :     /// Not used in production, but by Rust benchmarks.
     211              :     ///
     212              :     /// # Cancel-Safety
     213              :     ///
     214              :     /// This method is cancellation-safe.
     215            6 :     pub async fn ping(&self, pg_version: u32) -> Result<(), Error> {
     216            6 :         self.do_with_walredo_process(pg_version, |proc| async move {
     217            6 :             proc.ping(Duration::from_secs(1))
     218           12 :                 .await
     219            6 :                 .map_err(Error::Other)
     220            6 :         })
     221           12 :         .await
     222            6 :     }
     223              : 
     224            0 :     pub fn status(&self) -> WalRedoManagerStatus {
     225            0 :         WalRedoManagerStatus {
     226            0 :             last_redo_at: {
     227            0 :                 let at = *self.last_redo_at.lock().unwrap();
     228            0 :                 at.and_then(|at| {
     229            0 :                     let age = at.elapsed();
     230            0 :                     // map any chrono errors silently to None here
     231            0 :                     chrono::Utc::now().checked_sub_signed(chrono::Duration::from_std(age).ok()?)
     232            0 :                 })
     233            0 :             },
     234            0 :             process: self.redo_process.get().and_then(|p| match &*p {
     235            0 :                 ProcessOnceCell::Spawned(p) => Some(WalRedoManagerProcessStatus { pid: p.id() }),
     236            0 :                 ProcessOnceCell::ManagerShutDown => None,
     237            0 :             }),
     238            0 :         }
     239            0 :     }
     240              : }
     241              : 
     242              : impl PostgresRedoManager {
     243              :     ///
     244              :     /// Create a new PostgresRedoManager.
     245              :     ///
     246           24 :     pub fn new(
     247           24 :         conf: &'static PageServerConf,
     248           24 :         tenant_shard_id: TenantShardId,
     249           24 :     ) -> PostgresRedoManager {
     250           24 :         // The actual process is launched lazily, on first request.
     251           24 :         PostgresRedoManager {
     252           24 :             tenant_shard_id,
     253           24 :             conf,
     254           24 :             last_redo_at: std::sync::Mutex::default(),
     255           24 :             redo_process: heavier_once_cell::OnceCell::default(),
     256           24 :             launched_processes: utils::sync::gate::Gate::default(),
     257           24 :         }
     258           24 :     }
     259              : 
     260              :     /// Shut down the WAL redo manager.
     261              :     ///
     262              :     /// Returns `true` if this call was the one that initiated shutdown.
     263              :     /// `true` may be observed by no caller if the first caller stops polling.
     264              :     ///
     265              :     /// After this future completes
     266              :     /// - no redo process is running
     267              :     /// - no new redo process will be spawned
     268              :     /// - redo requests that need walredo process will fail with [`Error::Cancelled`]
     269              :     /// - [`apply_neon`]-only redo requests may still work, but this may change in the future
     270              :     ///
     271              :     /// # Cancel-Safety
     272              :     ///
     273              :     /// This method is cancellation-safe.
     274            0 :     pub async fn shutdown(&self) -> bool {
     275              :         // prevent new processes from being spawned
     276            0 :         let maybe_permit = match self.redo_process.get_or_init_detached().await {
     277            0 :             Ok(guard) => {
     278            0 :                 if matches!(&*guard, ProcessOnceCell::ManagerShutDown) {
     279            0 :                     None
     280              :                 } else {
     281            0 :                     let (proc, permit) = guard.take_and_deinit();
     282            0 :                     drop(proc); // this just drops the Arc, its refcount may not be zero yet
     283            0 :                     Some(permit)
     284              :                 }
     285              :             }
     286            0 :             Err(permit) => Some(permit),
     287              :         };
     288            0 :         let it_was_us = if let Some(permit) = maybe_permit {
     289            0 :             self.redo_process
     290            0 :                 .set(ProcessOnceCell::ManagerShutDown, permit);
     291            0 :             true
     292              :         } else {
     293            0 :             false
     294              :         };
     295              :         // wait for ongoing requests to drain and the refcounts of all Arc<WalRedoProcess> that
     296              :         // we ever launched to drop to zero, which when it happens synchronously kill()s & wait()s
     297              :         // for the underlying process.
     298            0 :         self.launched_processes.close().await;
     299            0 :         it_was_us
     300            0 :     }
     301              : 
     302              :     /// This type doesn't have its own background task to check for idleness: we
     303              :     /// rely on our owner calling this function periodically in its own housekeeping
     304              :     /// loops.
     305            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     306            0 :         if let Ok(g) = self.last_redo_at.try_lock() {
     307            0 :             if let Some(last_redo_at) = *g {
     308            0 :                 if last_redo_at.elapsed() >= idle_timeout {
     309            0 :                     drop(g);
     310            0 :                     drop(self.redo_process.get().map(|guard| guard.take_and_deinit()));
     311            0 :                 }
     312            0 :             }
     313            0 :         }
     314            0 :     }
     315              : 
     316              :     /// # Cancel-Safety
     317              :     ///
     318              :     /// This method is cancel-safe iff `closure` is cancel-safe.
     319           30 :     async fn do_with_walredo_process<
     320           30 :         F: FnOnce(Arc<Process>) -> Fut,
     321           30 :         Fut: Future<Output = Result<O, Error>>,
     322           30 :         O,
     323           30 :     >(
     324           30 :         &self,
     325           30 :         pg_version: u32,
     326           30 :         closure: F,
     327           30 :     ) -> Result<O, Error> {
     328           30 :         let proc: Arc<Process> = match self.redo_process.get_or_init_detached().await {
     329            0 :             Ok(guard) => match &*guard {
     330            0 :                 ProcessOnceCell::Spawned(proc) => Arc::clone(proc),
     331              :                 ProcessOnceCell::ManagerShutDown => {
     332            0 :                     return Err(Error::Cancelled);
     333              :                 }
     334              :             },
     335           30 :             Err(permit) => {
     336           30 :                 let start = Instant::now();
     337              :                 // acquire guard before spawning process, so that we don't spawn new processes
     338              :                 // if the gate is already closed.
     339           30 :                 let _launched_processes_guard = match self.launched_processes.enter() {
     340           30 :                     Ok(guard) => guard,
     341            0 :                     Err(GateError::GateClosed) => unreachable!(
     342            0 :                         "shutdown sets the once cell to `ManagerShutDown` state before closing the gate"
     343            0 :                     ),
     344              :                 };
     345           30 :                 let proc = Arc::new(Process {
     346           30 :                     process: process::WalRedoProcess::launch(
     347           30 :                         self.conf,
     348           30 :                         self.tenant_shard_id,
     349           30 :                         pg_version,
     350           30 :                     )
     351           30 :                     .context("launch walredo process")?,
     352           30 :                     _launched_processes_guard,
     353           30 :                 });
     354           30 :                 let duration = start.elapsed();
     355           30 :                 WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM.observe(duration.as_secs_f64());
     356           30 :                 info!(
     357            0 :                     elapsed_ms = duration.as_millis(),
     358            0 :                     pid = proc.id(),
     359            0 :                     "launched walredo process"
     360              :                 );
     361           30 :                 self.redo_process
     362           30 :                     .set(ProcessOnceCell::Spawned(Arc::clone(&proc)), permit);
     363           30 :                 proc
     364              :             }
     365              :         };
     366              : 
     367              :         // async closures are unstable, would support &Process
     368           60 :         let result = closure(proc.clone()).await;
     369              : 
     370           30 :         if result.is_err() {
     371              :             // Avoid concurrent callers hitting the same issue by taking `proc` out of the rotation.
     372              :             // Note that there may be other tasks concurrent with us that also hold `proc`.
     373              :             // We have to deal with that here.
     374              :             // Also read the doc comment on field `self.redo_process`.
     375              :             //
     376              :             // NB: there may still be other concurrent threads using `proc`.
     377              :             // The last one will send SIGKILL when the underlying Arc reaches refcount 0.
     378              :             //
     379              :             // NB: the drop impl blocks the dropping thread with a wait() system call for
     380              :             // the child process. In some ways the blocking is actually good: if we
     381              :             // deferred the waiting into the background / to tokio if we used `tokio::process`,
     382              :             // it could happen that if walredo always fails immediately, we spawn processes faster
     383              :             // than we can SIGKILL & `wait` for them to exit. By doing it the way we do here,
     384              :             // we limit this risk of run-away to at most $num_runtimes * $num_executor_threads.
     385              :             // This probably needs revisiting at some later point.
     386           12 :             match self.redo_process.get() {
     387            0 :                 None => (),
     388           12 :                 Some(guard) => {
     389           12 :                     match &*guard {
     390            0 :                         ProcessOnceCell::ManagerShutDown => {}
     391           12 :                         ProcessOnceCell::Spawned(guard_proc) => {
     392           12 :                             if Arc::ptr_eq(&proc, guard_proc) {
     393           12 :                                 // We're the first to observe an error from `proc`, it's our job to take it out of rotation.
     394           12 :                                 guard.take_and_deinit();
     395           12 :                             } else {
     396            0 :                                 // Another task already spawned another redo process (further up in this method)
     397            0 :                                 // and put it into `redo_process`. Do nothing, our view of the world is behind.
     398            0 :                             }
     399              :                         }
     400              :                     }
     401              :                 }
     402              :             }
     403              :             // The last task that does this `drop()` of `proc` will do a blocking `wait()` syscall.
     404           12 :             drop(proc);
     405           18 :         }
     406              : 
     407           30 :         result
     408           30 :     }
     409              : 
     410              :     ///
     411              :     /// Process one request for WAL redo using wal-redo postgres
     412              :     ///
     413              :     /// # Cancel-Safety
     414              :     ///
     415              :     /// Cancellation safe.
     416              :     #[allow(clippy::too_many_arguments)]
     417           18 :     async fn apply_batch_postgres(
     418           18 :         &self,
     419           18 :         key: Key,
     420           18 :         lsn: Lsn,
     421           18 :         base_img: Option<Bytes>,
     422           18 :         base_img_lsn: Lsn,
     423           18 :         records: &[(Lsn, NeonWalRecord)],
     424           18 :         wal_redo_timeout: Duration,
     425           18 :         pg_version: u32,
     426           18 :     ) -> Result<Bytes, Error> {
     427           18 :         *(self.last_redo_at.lock().unwrap()) = Some(Instant::now());
     428              : 
     429           18 :         let (rel, blknum) = key.to_rel_block().context("invalid record")?;
     430              :         const MAX_RETRY_ATTEMPTS: u32 = 1;
     431           18 :         let mut n_attempts = 0u32;
     432           24 :         loop {
     433           24 :             let base_img = &base_img;
     434           24 :             let closure = |proc: Arc<Process>| async move {
     435           24 :                 let started_at = std::time::Instant::now();
     436              : 
     437              :                 // Relational WAL records are applied using wal-redo-postgres
     438           24 :                 let result = proc
     439           24 :                     .apply_wal_records(rel, blknum, base_img, records, wal_redo_timeout)
     440           48 :                     .await
     441           24 :                     .context("apply_wal_records");
     442           24 : 
     443           24 :                 let duration = started_at.elapsed();
     444           24 : 
     445           24 :                 let len = records.len();
     446           48 :                 let nbytes = records.iter().fold(0, |acumulator, record| {
     447           48 :                     acumulator
     448           48 :                         + match &record.1 {
     449           48 :                             NeonWalRecord::Postgres { rec, .. } => rec.len(),
     450            0 :                             _ => unreachable!("Only PostgreSQL records are accepted in this batch"),
     451              :                         }
     452           48 :                 });
     453           24 : 
     454           24 :                 WAL_REDO_TIME.observe(duration.as_secs_f64());
     455           24 :                 WAL_REDO_RECORDS_HISTOGRAM.observe(len as f64);
     456           24 :                 WAL_REDO_BYTES_HISTOGRAM.observe(nbytes as f64);
     457           24 : 
     458           24 :                 debug!(
     459            0 :                     "postgres applied {} WAL records ({} bytes) in {} us to reconstruct page image at LSN {}",
     460            0 :                     len,
     461            0 :                     nbytes,
     462            0 :                     duration.as_micros(),
     463              :                     lsn
     464              :                 );
     465              : 
     466           24 :                 if let Err(e) = result.as_ref() {
     467           12 :                     error!(
     468            0 :                         "error applying {} WAL records {}..{} ({} bytes) to key {key}, from base image with LSN {} to reconstruct page image at LSN {} n_attempts={}: {:?}",
     469            0 :                         records.len(),
     470           12 :                         records.first().map(|p| p.0).unwrap_or(Lsn(0)),
     471           12 :                         records.last().map(|p| p.0).unwrap_or(Lsn(0)),
     472              :                         nbytes,
     473              :                         base_img_lsn,
     474              :                         lsn,
     475              :                         n_attempts,
     476              :                         e,
     477              :                     );
     478           12 :                 }
     479              : 
     480           24 :                 result.map_err(Error::Other)
     481           24 :             };
     482           48 :             let result = self.do_with_walredo_process(pg_version, closure).await;
     483              : 
     484           24 :             if result.is_ok() && n_attempts != 0 {
     485            0 :                 info!(n_attempts, "retried walredo succeeded");
     486           24 :             }
     487           24 :             n_attempts += 1;
     488           24 :             if n_attempts > MAX_RETRY_ATTEMPTS || result.is_ok() {
     489           18 :                 return result;
     490            6 :             }
     491              :         }
     492           18 :     }
     493              : 
     494              :     ///
     495              :     /// Process a batch of WAL records using bespoken Neon code.
     496              :     ///
     497            0 :     fn apply_batch_neon(
     498            0 :         &self,
     499            0 :         key: Key,
     500            0 :         lsn: Lsn,
     501            0 :         base_img: Option<Bytes>,
     502            0 :         records: &[(Lsn, NeonWalRecord)],
     503            0 :     ) -> Result<Bytes, Error> {
     504            0 :         let start_time = Instant::now();
     505            0 : 
     506            0 :         let mut page = BytesMut::new();
     507            0 :         if let Some(fpi) = base_img {
     508            0 :             // If full-page image is provided, then use it...
     509            0 :             page.extend_from_slice(&fpi[..]);
     510            0 :         } else {
     511              :             // All the current WAL record types that we can handle require a base image.
     512            0 :             bail!("invalid neon WAL redo request with no base image");
     513              :         }
     514              : 
     515              :         // Apply all the WAL records in the batch
     516            0 :         for (record_lsn, record) in records.iter() {
     517            0 :             self.apply_record_neon(key, &mut page, *record_lsn, record)?;
     518              :         }
     519              :         // Success!
     520            0 :         let duration = start_time.elapsed();
     521            0 :         // FIXME: using the same metric here creates a bimodal distribution by default, and because
     522            0 :         // there could be multiple batch sizes this would be N+1 modal.
     523            0 :         WAL_REDO_TIME.observe(duration.as_secs_f64());
     524            0 : 
     525            0 :         debug!(
     526            0 :             "neon applied {} WAL records in {} us to reconstruct page image at LSN {}",
     527            0 :             records.len(),
     528            0 :             duration.as_micros(),
     529              :             lsn
     530              :         );
     531              : 
     532            0 :         Ok(page.freeze())
     533            0 :     }
     534              : 
     535            0 :     fn apply_record_neon(
     536            0 :         &self,
     537            0 :         key: Key,
     538            0 :         page: &mut BytesMut,
     539            0 :         record_lsn: Lsn,
     540            0 :         record: &NeonWalRecord,
     541            0 :     ) -> anyhow::Result<()> {
     542            0 :         apply_neon::apply_in_neon(record, record_lsn, key, page)?;
     543              : 
     544            0 :         Ok(())
     545            0 :     }
     546              : }
     547              : 
     548              : #[cfg(test)]
     549              : mod tests {
     550              :     use super::PostgresRedoManager;
     551              :     use crate::repository::Key;
     552              :     use crate::{config::PageServerConf, walrecord::NeonWalRecord};
     553              :     use bytes::Bytes;
     554              :     use pageserver_api::shard::TenantShardId;
     555              :     use std::str::FromStr;
     556              :     use tracing::Instrument;
     557              :     use utils::{id::TenantId, lsn::Lsn};
     558              : 
     559              :     #[tokio::test]
     560            6 :     async fn test_ping() {
     561            6 :         let h = RedoHarness::new().unwrap();
     562            6 : 
     563            6 :         h.manager
     564            6 :             .ping(14)
     565            6 :             .instrument(h.span())
     566           12 :             .await
     567            6 :             .expect("ping should work");
     568            6 :     }
     569              : 
     570              :     #[tokio::test]
     571            6 :     async fn short_v14_redo() {
     572            6 :         let expected = std::fs::read("test_data/short_v14_redo.page").unwrap();
     573            6 : 
     574            6 :         let h = RedoHarness::new().unwrap();
     575            6 : 
     576            6 :         let page = h
     577            6 :             .manager
     578            6 :             .request_redo(
     579            6 :                 Key {
     580            6 :                     field1: 0,
     581            6 :                     field2: 1663,
     582            6 :                     field3: 13010,
     583            6 :                     field4: 1259,
     584            6 :                     field5: 0,
     585            6 :                     field6: 0,
     586            6 :                 },
     587            6 :                 Lsn::from_str("0/16E2408").unwrap(),
     588            6 :                 None,
     589            6 :                 short_records(),
     590            6 :                 14,
     591            6 :             )
     592            6 :             .instrument(h.span())
     593           12 :             .await
     594            6 :             .unwrap();
     595            6 : 
     596            6 :         assert_eq!(&expected, &*page);
     597            6 :     }
     598              : 
     599              :     #[tokio::test]
     600            6 :     async fn short_v14_fails_for_wrong_key_but_returns_zero_page() {
     601            6 :         let h = RedoHarness::new().unwrap();
     602            6 : 
     603            6 :         let page = h
     604            6 :             .manager
     605            6 :             .request_redo(
     606            6 :                 Key {
     607            6 :                     field1: 0,
     608            6 :                     field2: 1663,
     609            6 :                     // key should be 13010
     610            6 :                     field3: 13130,
     611            6 :                     field4: 1259,
     612            6 :                     field5: 0,
     613            6 :                     field6: 0,
     614            6 :                 },
     615            6 :                 Lsn::from_str("0/16E2408").unwrap(),
     616            6 :                 None,
     617            6 :                 short_records(),
     618            6 :                 14,
     619            6 :             )
     620            6 :             .instrument(h.span())
     621           12 :             .await
     622            6 :             .unwrap();
     623            6 : 
     624            6 :         // TODO: there will be some stderr printout, which is forwarded to tracing that could
     625            6 :         // perhaps be captured as long as it's in the same thread.
     626            6 :         assert_eq!(page, crate::ZERO_PAGE);
     627            6 :     }
     628              : 
     629              :     #[tokio::test]
     630            6 :     async fn test_stderr() {
     631            6 :         let h = RedoHarness::new().unwrap();
     632            6 :         h
     633            6 :             .manager
     634            6 :             .request_redo(
     635            6 :                 Key::from_i128(0),
     636            6 :                 Lsn::INVALID,
     637            6 :                 None,
     638            6 :                 short_records(),
     639            6 :                 16, /* 16 currently produces stderr output on startup, which adds a nice extra edge */
     640            6 :             )
     641            6 :             .instrument(h.span())
     642           24 :             .await
     643            6 :             .unwrap_err();
     644            6 :     }
     645              : 
     646              :     #[allow(clippy::octal_escapes)]
     647           18 :     fn short_records() -> Vec<(Lsn, NeonWalRecord)> {
     648           18 :         vec![
     649           18 :             (
     650           18 :                 Lsn::from_str("0/16A9388").unwrap(),
     651           18 :                 NeonWalRecord::Postgres {
     652           18 :                     will_init: true,
     653           18 :                     rec: Bytes::from_static(b"j\x03\0\0\0\x04\0\0\xe8\x7fj\x01\0\0\0\0\0\n\0\0\xd0\x16\x13Y\0\x10\0\04\x03\xd4\0\x05\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x03\0\0\0\0\x80\xeca\x01\0\0\x01\0\xd4\0\xa0\x1d\0 \x04 \0\0\0\0/\0\x01\0\xa0\x9dX\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\00\x9f\x9a\x01P\x9e\xb2\x01\0\x04\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x02\0!\0\x01\x08 \xff\xff\xff?\0\0\0\0\0\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\0\0\0\0\0\0\x80\xbf\0\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\0\0\0\0\x0c\x02\0\0\0\0\0\0\0\0\0\0\0\0\0\0/\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0\xdf\x04\0\0pg_type\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0G\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0\0\0\0\0\0\x0e\0\0\0\0@\x16D\x0e\0\0\0K\x10\0\0\x01\0pr \0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0[\x01\0\0\0\0\0\0\0\t\x04\0\0\x02\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0C\x01\0\0\x15\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0;\n\0\0pg_statistic\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0\xfd.\0\0\0\0\0\0\n\0\0\0\x02\0\0\0;\n\0\0\0\0\0\0\x13\0\0\0\0\0\xcbC\x13\0\0\0\x18\x0b\0\0\x01\0pr\x1f\0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0C\x01\0\0\0\0\0\0\0\t\x04\0\0\x01\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\x02\0\x01")
     654           18 :                 }
     655           18 :             ),
     656           18 :             (
     657           18 :                 Lsn::from_str("0/16D4080").unwrap(),
     658           18 :                 NeonWalRecord::Postgres {
     659           18 :                     will_init: false,
     660           18 :                     rec: Bytes::from_static(b"\xbc\0\0\0\0\0\0\0h?m\x01\0\0\0\0p\n\0\09\x08\xa3\xea\0 \x8c\0\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x02\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\x05\0\0\0\0@zD\x05\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\x02\0")
     661           18 :                 }
     662           18 :             )
     663           18 :         ]
     664           18 :     }
     665              : 
     666              :     struct RedoHarness {
     667              :         // underscored because unused, except for removal at drop
     668              :         _repo_dir: camino_tempfile::Utf8TempDir,
     669              :         manager: PostgresRedoManager,
     670              :         tenant_shard_id: TenantShardId,
     671              :     }
     672              : 
     673              :     impl RedoHarness {
     674           24 :         fn new() -> anyhow::Result<Self> {
     675           24 :             crate::tenant::harness::setup_logging();
     676              : 
     677           24 :             let repo_dir = camino_tempfile::tempdir()?;
     678           24 :             let conf = PageServerConf::dummy_conf(repo_dir.path().to_path_buf());
     679           24 :             let conf = Box::leak(Box::new(conf));
     680           24 :             let tenant_shard_id = TenantShardId::unsharded(TenantId::generate());
     681           24 : 
     682           24 :             let manager = PostgresRedoManager::new(conf, tenant_shard_id);
     683           24 : 
     684           24 :             Ok(RedoHarness {
     685           24 :                 _repo_dir: repo_dir,
     686           24 :                 manager,
     687           24 :                 tenant_shard_id,
     688           24 :             })
     689           24 :         }
     690           24 :         fn span(&self) -> tracing::Span {
     691           24 :             tracing::info_span!("RedoHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
     692           24 :         }
     693              :     }
     694              : }
        

Generated by: LCOV version 2.1-beta