LCOV - code coverage report
Current view: top level - libs/postgres_ffi/wal_craft/src - xlog_utils_test.rs (source / functions) Coverage Total Hit
Test: a43a77853355b937a79c57b07a8f05607cf29e6c.info Lines: 98.4 % 188 185
Test Date: 2024-09-19 12:04:32 Functions: 100.0 % 84 84

            Line data    Source code
       1              : //! Tests for postgres_ffi xlog_utils module. Put it here to break cyclic dependency.
       2              : 
       3              : use super::*;
       4              : use crate::{error, info};
       5              : use regex::Regex;
       6              : use std::cmp::min;
       7              : use std::fs::{self, File};
       8              : use std::io::Write;
       9              : use std::{env, str::FromStr};
      10              : use utils::const_assert;
      11              : use utils::lsn::Lsn;
      12              : 
      13           12 : fn init_logging() {
      14           12 :     let _ = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(format!(
      15           12 :         "crate=info,postgres_ffi::{PG_MAJORVERSION}::xlog_utils=trace"
      16           12 :     )))
      17           12 :     .is_test(true)
      18           12 :     .try_init();
      19           12 : }
      20              : 
      21              : /// Test that find_end_of_wal returns the same results as pg_dump on various
      22              : /// WALs created by Crafter.
      23           12 : fn test_end_of_wal<C: crate::Crafter>(test_name: &str) {
      24              :     use crate::*;
      25              : 
      26           12 :     let pg_version = PG_MAJORVERSION[1..3].parse::<u32>().unwrap();
      27           12 : 
      28           12 :     // Craft some WAL
      29           12 :     let top_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
      30           12 :         .join("..")
      31           12 :         .join("..")
      32           12 :         .join("..");
      33           12 :     let cfg = Conf {
      34           12 :         pg_version,
      35           12 :         pg_distrib_dir: top_path.join("pg_install"),
      36           12 :         datadir: top_path.join(format!("test_output/{}-{PG_MAJORVERSION}", test_name)),
      37           12 :     };
      38           12 :     if cfg.datadir.exists() {
      39            0 :         fs::remove_dir_all(&cfg.datadir).unwrap();
      40           12 :     }
      41           12 :     cfg.initdb().unwrap();
      42           12 :     let srv = cfg.start_server().unwrap();
      43           12 :     let intermediate_lsns = C::craft(&mut srv.connect_with_timeout().unwrap()).unwrap();
      44           12 :     let intermediate_lsns: Vec<Lsn> = intermediate_lsns
      45           12 :         .iter()
      46           20 :         .map(|&lsn| u64::from(lsn).into())
      47           12 :         .collect();
      48           12 :     // Kill postgres. Note that it might have inserted to WAL something after
      49           12 :     // 'craft' did its job.
      50           12 :     srv.kill();
      51           12 : 
      52           12 :     // Check find_end_of_wal on the initial WAL
      53           12 :     let last_segment = cfg
      54           12 :         .wal_dir()
      55           12 :         .read_dir()
      56           12 :         .unwrap()
      57           35 :         .map(|f| f.unwrap().file_name().into_string().unwrap())
      58           35 :         .filter(|fname| IsXLogFileName(fname))
      59           12 :         .max()
      60           12 :         .unwrap();
      61           12 :     let expected_end_of_wal = find_pg_waldump_end_of_wal(&cfg, &last_segment);
      62           32 :     for start_lsn in intermediate_lsns
      63           12 :         .iter()
      64           12 :         .chain(std::iter::once(&expected_end_of_wal))
      65              :     {
      66              :         // Erase all WAL before `start_lsn` to ensure it's not used by `find_end_of_wal`.
      67              :         // We assume that `start_lsn` is non-decreasing.
      68           32 :         info!(
      69           32 :             "Checking with start_lsn={}, erasing WAL before it",
      70              :             start_lsn
      71              :         );
      72           96 :         for file in fs::read_dir(cfg.wal_dir()).unwrap().flatten() {
      73           96 :             let fname = file.file_name().into_string().unwrap();
      74           96 :             if !IsXLogFileName(&fname) {
      75           40 :                 continue;
      76           56 :             }
      77           56 :             let (segno, _) = XLogFromFileName(&fname, WAL_SEGMENT_SIZE);
      78           56 :             let seg_start_lsn = XLogSegNoOffsetToRecPtr(segno, 0, WAL_SEGMENT_SIZE);
      79           56 :             if seg_start_lsn > u64::from(*start_lsn) {
      80            8 :                 continue;
      81           48 :             }
      82           48 :             let mut f = File::options().write(true).open(file.path()).unwrap();
      83           48 :             const ZEROS: [u8; WAL_SEGMENT_SIZE] = [0u8; WAL_SEGMENT_SIZE];
      84           48 :             f.write_all(
      85           48 :                 &ZEROS[0..min(
      86           48 :                     WAL_SEGMENT_SIZE,
      87           48 :                     (u64::from(*start_lsn) - seg_start_lsn) as usize,
      88           48 :                 )],
      89           48 :             )
      90           48 :             .unwrap();
      91           48 :         }
      92           32 :         check_end_of_wal(&cfg, &last_segment, *start_lsn, expected_end_of_wal);
      93              :     }
      94           12 : }
      95              : 
      96           12 : fn find_pg_waldump_end_of_wal(cfg: &crate::Conf, last_segment: &str) -> Lsn {
      97           12 :     // Get the actual end of WAL by pg_waldump
      98           12 :     let waldump_output = cfg
      99           12 :         .pg_waldump("000000010000000000000001", last_segment)
     100           12 :         .unwrap()
     101           12 :         .stderr;
     102           12 :     let waldump_output = std::str::from_utf8(&waldump_output).unwrap();
     103           12 :     let caps = match Regex::new(r"invalid record length at (.+):")
     104           12 :         .unwrap()
     105           12 :         .captures(waldump_output)
     106              :     {
     107           12 :         Some(caps) => caps,
     108              :         None => {
     109            0 :             error!("Unable to parse pg_waldump's stderr:\n{}", waldump_output);
     110            0 :             panic!();
     111              :         }
     112              :     };
     113           12 :     let waldump_wal_end = Lsn::from_str(caps.get(1).unwrap().as_str()).unwrap();
     114           12 :     info!("waldump erred on {}", waldump_wal_end);
     115           12 :     waldump_wal_end
     116           12 : }
     117              : 
     118           32 : fn check_end_of_wal(
     119           32 :     cfg: &crate::Conf,
     120           32 :     last_segment: &str,
     121           32 :     start_lsn: Lsn,
     122           32 :     expected_end_of_wal: Lsn,
     123           32 : ) {
     124           32 :     // Check end_of_wal on non-partial WAL segment (we treat it as fully populated)
     125           32 :     // let wal_end = find_end_of_wal(&cfg.wal_dir(), WAL_SEGMENT_SIZE, start_lsn).unwrap();
     126           32 :     // info!(
     127           32 :     //     "find_end_of_wal returned wal_end={} with non-partial WAL segment",
     128           32 :     //     wal_end
     129           32 :     // );
     130           32 :     // assert_eq!(wal_end, expected_end_of_wal_non_partial);
     131           32 : 
     132           32 :     // Rename file to partial to actually find last valid lsn, then rename it back.
     133           32 :     fs::rename(
     134           32 :         cfg.wal_dir().join(last_segment),
     135           32 :         cfg.wal_dir().join(format!("{}.partial", last_segment)),
     136           32 :     )
     137           32 :     .unwrap();
     138           32 :     let wal_end = find_end_of_wal(&cfg.wal_dir(), WAL_SEGMENT_SIZE, start_lsn).unwrap();
     139           32 :     info!(
     140           32 :         "find_end_of_wal returned wal_end={} with partial WAL segment",
     141              :         wal_end
     142              :     );
     143           32 :     assert_eq!(wal_end, expected_end_of_wal);
     144           32 :     fs::rename(
     145           32 :         cfg.wal_dir().join(format!("{}.partial", last_segment)),
     146           32 :         cfg.wal_dir().join(last_segment),
     147           32 :     )
     148           32 :     .unwrap();
     149           32 : }
     150              : 
     151              : const_assert!(WAL_SEGMENT_SIZE == 16 * 1024 * 1024);
     152              : 
     153              : #[test]
     154            4 : pub fn test_find_end_of_wal_simple() {
     155            4 :     init_logging();
     156            4 :     test_end_of_wal::<crate::Simple>("test_find_end_of_wal_simple");
     157            4 : }
     158              : 
     159              : #[test]
     160            4 : pub fn test_find_end_of_wal_crossing_segment_followed_by_small_one() {
     161            4 :     init_logging();
     162            4 :     test_end_of_wal::<crate::WalRecordCrossingSegmentFollowedBySmallOne>(
     163            4 :         "test_find_end_of_wal_crossing_segment_followed_by_small_one",
     164            4 :     );
     165            4 : }
     166              : 
     167              : #[test]
     168            4 : pub fn test_find_end_of_wal_last_crossing_segment() {
     169            4 :     init_logging();
     170            4 :     test_end_of_wal::<crate::LastWalRecordCrossingSegment>(
     171            4 :         "test_find_end_of_wal_last_crossing_segment",
     172            4 :     );
     173            4 : }
     174              : 
     175              : /// Check the math in update_next_xid
     176              : ///
     177              : /// NOTE: These checks are sensitive to the value of XID_CHECKPOINT_INTERVAL,
     178              : /// currently 1024.
     179              : #[test]
     180            4 : pub fn test_update_next_xid() {
     181            4 :     let checkpoint_buf = [0u8; size_of::<CheckPoint>()];
     182            4 :     let mut checkpoint = CheckPoint::decode(&checkpoint_buf).unwrap();
     183            4 : 
     184            4 :     checkpoint.nextXid = FullTransactionId { value: 10 };
     185            4 :     assert_eq!(checkpoint.nextXid.value, 10);
     186              : 
     187              :     // The input XID gets rounded up to the next XID_CHECKPOINT_INTERVAL
     188              :     // boundary
     189            4 :     checkpoint.update_next_xid(100);
     190            4 :     assert_eq!(checkpoint.nextXid.value, 1024);
     191              : 
     192              :     // No change
     193            4 :     checkpoint.update_next_xid(500);
     194            4 :     assert_eq!(checkpoint.nextXid.value, 1024);
     195            4 :     checkpoint.update_next_xid(1023);
     196            4 :     assert_eq!(checkpoint.nextXid.value, 1024);
     197              : 
     198              :     // The function returns the *next* XID, given the highest XID seen so
     199              :     // far. So when we pass 1024, the nextXid gets bumped up to the next
     200              :     // XID_CHECKPOINT_INTERVAL boundary.
     201            4 :     checkpoint.update_next_xid(1024);
     202            4 :     assert_eq!(checkpoint.nextXid.value, 2048);
     203            4 : }
     204              : 
     205              : #[test]
     206            4 : pub fn test_update_next_multixid() {
     207            4 :     let checkpoint_buf = [0u8; size_of::<CheckPoint>()];
     208            4 :     let mut checkpoint = CheckPoint::decode(&checkpoint_buf).unwrap();
     209            4 : 
     210            4 :     // simple case
     211            4 :     checkpoint.nextMulti = 20;
     212            4 :     checkpoint.nextMultiOffset = 20;
     213            4 :     checkpoint.update_next_multixid(1000, 2000);
     214            4 :     assert_eq!(checkpoint.nextMulti, 1000);
     215            4 :     assert_eq!(checkpoint.nextMultiOffset, 2000);
     216              : 
     217              :     // No change
     218            4 :     checkpoint.update_next_multixid(500, 900);
     219            4 :     assert_eq!(checkpoint.nextMulti, 1000);
     220            4 :     assert_eq!(checkpoint.nextMultiOffset, 2000);
     221              : 
     222              :     // Close to wraparound, but not wrapped around yet
     223            4 :     checkpoint.nextMulti = 0xffff0000;
     224            4 :     checkpoint.nextMultiOffset = 0xfffe0000;
     225            4 :     checkpoint.update_next_multixid(0xffff00ff, 0xfffe00ff);
     226            4 :     assert_eq!(checkpoint.nextMulti, 0xffff00ff);
     227            4 :     assert_eq!(checkpoint.nextMultiOffset, 0xfffe00ff);
     228              : 
     229              :     // Wraparound
     230            4 :     checkpoint.update_next_multixid(1, 900);
     231            4 :     assert_eq!(checkpoint.nextMulti, 1);
     232            4 :     assert_eq!(checkpoint.nextMultiOffset, 900);
     233              : 
     234              :     // Wraparound nextMulti to 0.
     235              :     //
     236              :     // It's a bit surprising that nextMulti can be 0, because that's a special value
     237              :     // (InvalidMultiXactId). However, that's how Postgres does it at multi-xid wraparound:
     238              :     // nextMulti wraps around to 0, but then when the next multi-xid is assigned, it skips
     239              :     // the 0 and the next multi-xid actually assigned is 1.
     240            4 :     checkpoint.nextMulti = 0xffff0000;
     241            4 :     checkpoint.nextMultiOffset = 0xfffe0000;
     242            4 :     checkpoint.update_next_multixid(0, 0xfffe00ff);
     243            4 :     assert_eq!(checkpoint.nextMulti, 0);
     244            4 :     assert_eq!(checkpoint.nextMultiOffset, 0xfffe00ff);
     245              : 
     246              :     // Wraparound nextMultiOffset to 0
     247            4 :     checkpoint.update_next_multixid(0, 0);
     248            4 :     assert_eq!(checkpoint.nextMulti, 0);
     249            4 :     assert_eq!(checkpoint.nextMultiOffset, 0);
     250            4 : }
     251              : 
     252              : #[test]
     253            4 : pub fn test_encode_logical_message() {
     254            4 :     let expected = [
     255            4 :         64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 170, 34, 166, 227, 255, 38,
     256            4 :         0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 112, 114, 101, 102,
     257            4 :         105, 120, 0, 109, 101, 115, 115, 97, 103, 101,
     258            4 :     ];
     259            4 :     let actual = encode_logical_message("prefix", "message");
     260            4 :     assert_eq!(expected, actual[..]);
     261            4 : }
        

Generated by: LCOV version 2.1-beta