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 anyhow::Context;
33 : use bytes::{Bytes, BytesMut};
34 : use pageserver_api::key::Key;
35 : use pageserver_api::models::{WalRedoManagerProcessStatus, WalRedoManagerStatus};
36 : use pageserver_api::record::NeonWalRecord;
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 40 : fn deref(&self) -> &Self::Target {
120 40 : &self.process
121 40 : }
122 : }
123 :
124 : #[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 12 : pub async fn request_redo(
152 12 : &self,
153 12 : key: Key,
154 12 : lsn: Lsn,
155 12 : base_img: Option<(Lsn, Bytes)>,
156 12 : records: Vec<(Lsn, NeonWalRecord)>,
157 12 : pg_version: u32,
158 12 : ) -> Result<Bytes, Error> {
159 12 : if records.is_empty() {
160 0 : bail!("invalid WAL redo request with no records");
161 12 : }
162 12 :
163 12 : let base_img_lsn = base_img.as_ref().map(|p| p.0).unwrap_or(Lsn::INVALID);
164 12 : let mut img = base_img.map(|p| p.1);
165 12 : let mut batch_neon = apply_neon::can_apply_in_neon(&records[0].1);
166 12 : let mut batch_start = 0;
167 12 : for (i, record) in records.iter().enumerate().skip(1) {
168 12 : let rec_neon = apply_neon::can_apply_in_neon(&record.1);
169 12 :
170 12 : 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 12 : }
190 : }
191 : // last batch
192 12 : if batch_neon {
193 0 : self.apply_batch_neon(key, lsn, img, &records[batch_start..])
194 : } else {
195 12 : self.apply_batch_postgres(
196 12 : key,
197 12 : lsn,
198 12 : img,
199 12 : base_img_lsn,
200 12 : &records[batch_start..],
201 12 : self.conf.wal_redo_timeout,
202 12 : pg_version,
203 12 : )
204 12 : .await
205 : }
206 12 : }
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 4 : pub async fn ping(&self, pg_version: u32) -> Result<(), Error> {
216 4 : self.do_with_walredo_process(pg_version, |proc| async move {
217 4 : proc.ping(Duration::from_secs(1))
218 4 : .await
219 4 : .map_err(Error::Other)
220 4 : })
221 4 : .await
222 4 : }
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 16 : pub fn new(
247 16 : conf: &'static PageServerConf,
248 16 : tenant_shard_id: TenantShardId,
249 16 : ) -> PostgresRedoManager {
250 16 : // The actual process is launched lazily, on first request.
251 16 : PostgresRedoManager {
252 16 : tenant_shard_id,
253 16 : conf,
254 16 : last_redo_at: std::sync::Mutex::default(),
255 16 : redo_process: heavier_once_cell::OnceCell::default(),
256 16 : launched_processes: utils::sync::gate::Gate::default(),
257 16 : }
258 16 : }
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 20 : async fn do_with_walredo_process<
320 20 : F: FnOnce(Arc<Process>) -> Fut,
321 20 : Fut: Future<Output = Result<O, Error>>,
322 20 : O,
323 20 : >(
324 20 : &self,
325 20 : pg_version: u32,
326 20 : closure: F,
327 20 : ) -> Result<O, Error> {
328 20 : 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 20 : Err(permit) => {
336 20 : 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 20 : let _launched_processes_guard = match self.launched_processes.enter() {
340 20 : 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 20 : let proc = Arc::new(Process {
346 20 : process: process::WalRedoProcess::launch(
347 20 : self.conf,
348 20 : self.tenant_shard_id,
349 20 : pg_version,
350 20 : )
351 20 : .context("launch walredo process")?,
352 20 : _launched_processes_guard,
353 20 : });
354 20 : let duration = start.elapsed();
355 20 : WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM.observe(duration.as_secs_f64());
356 20 : info!(
357 0 : elapsed_ms = duration.as_millis(),
358 0 : pid = proc.id(),
359 0 : "launched walredo process"
360 : );
361 20 : self.redo_process
362 20 : .set(ProcessOnceCell::Spawned(Arc::clone(&proc)), permit);
363 20 : proc
364 : }
365 : };
366 :
367 : // async closures are unstable, would support &Process
368 20 : let result = closure(proc.clone()).await;
369 :
370 20 : 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 8 : match self.redo_process.get() {
387 0 : None => (),
388 8 : Some(guard) => {
389 8 : match &*guard {
390 0 : ProcessOnceCell::ManagerShutDown => {}
391 8 : ProcessOnceCell::Spawned(guard_proc) => {
392 8 : if Arc::ptr_eq(&proc, guard_proc) {
393 8 : // We're the first to observe an error from `proc`, it's our job to take it out of rotation.
394 8 : guard.take_and_deinit();
395 8 : } 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 8 : drop(proc);
405 12 : }
406 :
407 20 : result
408 20 : }
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 12 : async fn apply_batch_postgres(
418 12 : &self,
419 12 : key: Key,
420 12 : lsn: Lsn,
421 12 : base_img: Option<Bytes>,
422 12 : base_img_lsn: Lsn,
423 12 : records: &[(Lsn, NeonWalRecord)],
424 12 : wal_redo_timeout: Duration,
425 12 : pg_version: u32,
426 12 : ) -> Result<Bytes, Error> {
427 12 : *(self.last_redo_at.lock().unwrap()) = Some(Instant::now());
428 :
429 12 : let (rel, blknum) = key.to_rel_block().context("invalid record")?;
430 : const MAX_RETRY_ATTEMPTS: u32 = 1;
431 12 : let mut n_attempts = 0u32;
432 16 : loop {
433 16 : let base_img = &base_img;
434 16 : let closure = |proc: Arc<Process>| async move {
435 16 : let started_at = std::time::Instant::now();
436 :
437 : // Relational WAL records are applied using wal-redo-postgres
438 16 : let result = proc
439 16 : .apply_wal_records(rel, blknum, base_img, records, wal_redo_timeout)
440 16 : .await
441 16 : .context("apply_wal_records");
442 16 :
443 16 : let duration = started_at.elapsed();
444 16 :
445 16 : let len = records.len();
446 32 : let nbytes = records.iter().fold(0, |acumulator, record| {
447 32 : acumulator
448 32 : + match &record.1 {
449 32 : NeonWalRecord::Postgres { rec, .. } => rec.len(),
450 0 : _ => unreachable!("Only PostgreSQL records are accepted in this batch"),
451 : }
452 32 : });
453 16 :
454 16 : WAL_REDO_TIME.observe(duration.as_secs_f64());
455 16 : WAL_REDO_RECORDS_HISTOGRAM.observe(len as f64);
456 16 : WAL_REDO_BYTES_HISTOGRAM.observe(nbytes as f64);
457 16 :
458 16 : 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 16 : if let Err(e) = result.as_ref() {
467 8 : 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 8 : records.first().map(|p| p.0).unwrap_or(Lsn(0)),
471 8 : 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 8 : }
479 :
480 16 : result.map_err(Error::Other)
481 16 : };
482 16 : let result = self.do_with_walredo_process(pg_version, closure).await;
483 :
484 16 : if result.is_ok() && n_attempts != 0 {
485 0 : info!(n_attempts, "retried walredo succeeded");
486 16 : }
487 16 : n_attempts += 1;
488 16 : if n_attempts > MAX_RETRY_ATTEMPTS || result.is_ok() {
489 12 : return result;
490 4 : }
491 : }
492 12 : }
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::config::PageServerConf;
552 : use bytes::Bytes;
553 : use pageserver_api::key::Key;
554 : use pageserver_api::record::NeonWalRecord;
555 : use pageserver_api::shard::TenantShardId;
556 : use std::str::FromStr;
557 : use tracing::Instrument;
558 : use utils::{id::TenantId, lsn::Lsn};
559 :
560 : #[tokio::test]
561 4 : async fn test_ping() {
562 4 : let h = RedoHarness::new().unwrap();
563 4 :
564 4 : h.manager
565 4 : .ping(14)
566 4 : .instrument(h.span())
567 4 : .await
568 4 : .expect("ping should work");
569 4 : }
570 :
571 : #[tokio::test]
572 4 : async fn short_v14_redo() {
573 4 : let expected = std::fs::read("test_data/short_v14_redo.page").unwrap();
574 4 :
575 4 : let h = RedoHarness::new().unwrap();
576 4 :
577 4 : let page = h
578 4 : .manager
579 4 : .request_redo(
580 4 : Key {
581 4 : field1: 0,
582 4 : field2: 1663,
583 4 : field3: 13010,
584 4 : field4: 1259,
585 4 : field5: 0,
586 4 : field6: 0,
587 4 : },
588 4 : Lsn::from_str("0/16E2408").unwrap(),
589 4 : None,
590 4 : short_records(),
591 4 : 14,
592 4 : )
593 4 : .instrument(h.span())
594 4 : .await
595 4 : .unwrap();
596 4 :
597 4 : assert_eq!(&expected, &*page);
598 4 : }
599 :
600 : #[tokio::test]
601 4 : async fn short_v14_fails_for_wrong_key_but_returns_zero_page() {
602 4 : let h = RedoHarness::new().unwrap();
603 4 :
604 4 : let page = h
605 4 : .manager
606 4 : .request_redo(
607 4 : Key {
608 4 : field1: 0,
609 4 : field2: 1663,
610 4 : // key should be 13010
611 4 : field3: 13130,
612 4 : field4: 1259,
613 4 : field5: 0,
614 4 : field6: 0,
615 4 : },
616 4 : Lsn::from_str("0/16E2408").unwrap(),
617 4 : None,
618 4 : short_records(),
619 4 : 14,
620 4 : )
621 4 : .instrument(h.span())
622 4 : .await
623 4 : .unwrap();
624 4 :
625 4 : // TODO: there will be some stderr printout, which is forwarded to tracing that could
626 4 : // perhaps be captured as long as it's in the same thread.
627 4 : assert_eq!(page, crate::ZERO_PAGE);
628 4 : }
629 :
630 : #[tokio::test]
631 4 : async fn test_stderr() {
632 4 : let h = RedoHarness::new().unwrap();
633 4 : h
634 4 : .manager
635 4 : .request_redo(
636 4 : Key::from_i128(0),
637 4 : Lsn::INVALID,
638 4 : None,
639 4 : short_records(),
640 4 : 16, /* 16 currently produces stderr output on startup, which adds a nice extra edge */
641 4 : )
642 4 : .instrument(h.span())
643 4 : .await
644 4 : .unwrap_err();
645 4 : }
646 :
647 : #[allow(clippy::octal_escapes)]
648 12 : fn short_records() -> Vec<(Lsn, NeonWalRecord)> {
649 12 : vec![
650 12 : (
651 12 : Lsn::from_str("0/16A9388").unwrap(),
652 12 : NeonWalRecord::Postgres {
653 12 : will_init: true,
654 12 : 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")
655 12 : }
656 12 : ),
657 12 : (
658 12 : Lsn::from_str("0/16D4080").unwrap(),
659 12 : NeonWalRecord::Postgres {
660 12 : will_init: false,
661 12 : 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")
662 12 : }
663 12 : )
664 12 : ]
665 12 : }
666 :
667 : struct RedoHarness {
668 : // underscored because unused, except for removal at drop
669 : _repo_dir: camino_tempfile::Utf8TempDir,
670 : manager: PostgresRedoManager,
671 : tenant_shard_id: TenantShardId,
672 : }
673 :
674 : impl RedoHarness {
675 16 : fn new() -> anyhow::Result<Self> {
676 16 : crate::tenant::harness::setup_logging();
677 :
678 16 : let repo_dir = camino_tempfile::tempdir()?;
679 16 : let conf = PageServerConf::dummy_conf(repo_dir.path().to_path_buf());
680 16 : let conf = Box::leak(Box::new(conf));
681 16 : let tenant_shard_id = TenantShardId::unsharded(TenantId::generate());
682 16 :
683 16 : let manager = PostgresRedoManager::new(conf, tenant_shard_id);
684 16 :
685 16 : Ok(RedoHarness {
686 16 : _repo_dir: repo_dir,
687 16 : manager,
688 16 : tenant_shard_id,
689 16 : })
690 16 : }
691 16 : fn span(&self) -> tracing::Span {
692 16 : tracing::info_span!("RedoHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
693 16 : }
694 : }
695 : }
|