LCOV - code coverage report
Current view: top level - libs/postgres_ffi/wal_craft/src - xlog_utils_test.rs (source / functions) Coverage Total Hit
Test: 8ac049b474321fdc72ddcb56d7165153a1a900e8.info Lines: 98.2 % 169 166
Test Date: 2023-09-06 10:18:01 Functions: 100.0 % 50 50

            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            6 : fn init_logging() {
      14            6 :     let _ = env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(
      15            6 :         format!("crate=info,postgres_ffi::{PG_MAJORVERSION}::xlog_utils=trace"),
      16            6 :     ))
      17            6 :     .is_test(true)
      18            6 :     .try_init();
      19            6 : }
      20              : 
      21            6 : fn test_end_of_wal<C: crate::Crafter>(test_name: &str) {
      22            6 :     use crate::*;
      23            6 : 
      24            6 :     let pg_version = PG_MAJORVERSION[1..3].parse::<u32>().unwrap();
      25            6 : 
      26            6 :     // Craft some WAL
      27            6 :     let top_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
      28            6 :         .join("..")
      29            6 :         .join("..")
      30            6 :         .join("..");
      31            6 :     let cfg = Conf {
      32            6 :         pg_version,
      33            6 :         pg_distrib_dir: top_path.join("pg_install"),
      34            6 :         datadir: top_path.join(format!("test_output/{}-{PG_MAJORVERSION}", test_name)),
      35            6 :     };
      36            6 :     if cfg.datadir.exists() {
      37            0 :         fs::remove_dir_all(&cfg.datadir).unwrap();
      38            6 :     }
      39            6 :     cfg.initdb().unwrap();
      40            6 :     let srv = cfg.start_server().unwrap();
      41            6 :     let (intermediate_lsns, expected_end_of_wal_partial) =
      42            6 :         C::craft(&mut srv.connect_with_timeout().unwrap()).unwrap();
      43            6 :     let intermediate_lsns: Vec<Lsn> = intermediate_lsns
      44            6 :         .iter()
      45            8 :         .map(|&lsn| u64::from(lsn).into())
      46            6 :         .collect();
      47            6 :     let expected_end_of_wal: Lsn = u64::from(expected_end_of_wal_partial).into();
      48            6 :     srv.kill();
      49            6 : 
      50            6 :     // Check find_end_of_wal on the initial WAL
      51            6 :     let last_segment = cfg
      52            6 :         .wal_dir()
      53            6 :         .read_dir()
      54            6 :         .unwrap()
      55           16 :         .map(|f| f.unwrap().file_name().into_string().unwrap())
      56           16 :         .filter(|fname| IsXLogFileName(fname))
      57            6 :         .max()
      58            6 :         .unwrap();
      59            6 :     check_pg_waldump_end_of_wal(&cfg, &last_segment, expected_end_of_wal);
      60           14 :     for start_lsn in intermediate_lsns
      61            6 :         .iter()
      62            6 :         .chain(std::iter::once(&expected_end_of_wal))
      63              :     {
      64              :         // Erase all WAL before `start_lsn` to ensure it's not used by `find_end_of_wal`.
      65              :         // We assume that `start_lsn` is non-decreasing.
      66           14 :         info!(
      67           14 :             "Checking with start_lsn={}, erasing WAL before it",
      68              :             start_lsn
      69              :         );
      70           38 :         for file in fs::read_dir(cfg.wal_dir()).unwrap().flatten() {
      71           38 :             let fname = file.file_name().into_string().unwrap();
      72           38 :             if !IsXLogFileName(&fname) {
      73           14 :                 continue;
      74           24 :             }
      75           24 :             let (segno, _) = XLogFromFileName(&fname, WAL_SEGMENT_SIZE);
      76           24 :             let seg_start_lsn = XLogSegNoOffsetToRecPtr(segno, 0, WAL_SEGMENT_SIZE);
      77           24 :             if seg_start_lsn > u64::from(*start_lsn) {
      78            4 :                 continue;
      79           20 :             }
      80           20 :             let mut f = File::options().write(true).open(file.path()).unwrap();
      81           20 :             const ZEROS: [u8; WAL_SEGMENT_SIZE] = [0u8; WAL_SEGMENT_SIZE];
      82           20 :             f.write_all(
      83           20 :                 &ZEROS[0..min(
      84           20 :                     WAL_SEGMENT_SIZE,
      85           20 :                     (u64::from(*start_lsn) - seg_start_lsn) as usize,
      86           20 :                 )],
      87           20 :             )
      88           20 :             .unwrap();
      89              :         }
      90           14 :         check_end_of_wal(&cfg, &last_segment, *start_lsn, expected_end_of_wal);
      91              :     }
      92            6 : }
      93              : 
      94            6 : fn check_pg_waldump_end_of_wal(
      95            6 :     cfg: &crate::Conf,
      96            6 :     last_segment: &str,
      97            6 :     expected_end_of_wal: Lsn,
      98            6 : ) {
      99            6 :     // Get the actual end of WAL by pg_waldump
     100            6 :     let waldump_output = cfg
     101            6 :         .pg_waldump("000000010000000000000001", last_segment)
     102            6 :         .unwrap()
     103            6 :         .stderr;
     104            6 :     let waldump_output = std::str::from_utf8(&waldump_output).unwrap();
     105            6 :     let caps = match Regex::new(r"invalid record length at (.+):")
     106            6 :         .unwrap()
     107            6 :         .captures(waldump_output)
     108              :     {
     109            6 :         Some(caps) => caps,
     110              :         None => {
     111            0 :             error!("Unable to parse pg_waldump's stderr:\n{}", waldump_output);
     112            0 :             panic!();
     113              :         }
     114              :     };
     115            6 :     let waldump_wal_end = Lsn::from_str(caps.get(1).unwrap().as_str()).unwrap();
     116            6 :     info!(
     117            6 :         "waldump erred on {}, expected wal end at {}",
     118              :         waldump_wal_end, expected_end_of_wal
     119              :     );
     120            6 :     assert_eq!(waldump_wal_end, expected_end_of_wal);
     121            6 : }
     122              : 
     123           14 : fn check_end_of_wal(
     124           14 :     cfg: &crate::Conf,
     125           14 :     last_segment: &str,
     126           14 :     start_lsn: Lsn,
     127           14 :     expected_end_of_wal: Lsn,
     128           14 : ) {
     129           14 :     // Check end_of_wal on non-partial WAL segment (we treat it as fully populated)
     130           14 :     // let wal_end = find_end_of_wal(&cfg.wal_dir(), WAL_SEGMENT_SIZE, start_lsn).unwrap();
     131           14 :     // info!(
     132           14 :     //     "find_end_of_wal returned wal_end={} with non-partial WAL segment",
     133           14 :     //     wal_end
     134           14 :     // );
     135           14 :     // assert_eq!(wal_end, expected_end_of_wal_non_partial);
     136           14 : 
     137           14 :     // Rename file to partial to actually find last valid lsn, then rename it back.
     138           14 :     fs::rename(
     139           14 :         cfg.wal_dir().join(last_segment),
     140           14 :         cfg.wal_dir().join(format!("{}.partial", last_segment)),
     141           14 :     )
     142           14 :     .unwrap();
     143           14 :     let wal_end = find_end_of_wal(&cfg.wal_dir(), WAL_SEGMENT_SIZE, start_lsn).unwrap();
     144           14 :     info!(
     145           14 :         "find_end_of_wal returned wal_end={} with partial WAL segment",
     146              :         wal_end
     147              :     );
     148           14 :     assert_eq!(wal_end, expected_end_of_wal);
     149           14 :     fs::rename(
     150           14 :         cfg.wal_dir().join(format!("{}.partial", last_segment)),
     151           14 :         cfg.wal_dir().join(last_segment),
     152           14 :     )
     153           14 :     .unwrap();
     154           14 : }
     155              : 
     156              : const_assert!(WAL_SEGMENT_SIZE == 16 * 1024 * 1024);
     157              : 
     158            2 : #[test]
     159            2 : pub fn test_find_end_of_wal_simple() {
     160            2 :     init_logging();
     161            2 :     test_end_of_wal::<crate::Simple>("test_find_end_of_wal_simple");
     162            2 : }
     163              : 
     164            2 : #[test]
     165            2 : pub fn test_find_end_of_wal_crossing_segment_followed_by_small_one() {
     166            2 :     init_logging();
     167            2 :     test_end_of_wal::<crate::WalRecordCrossingSegmentFollowedBySmallOne>(
     168            2 :         "test_find_end_of_wal_crossing_segment_followed_by_small_one",
     169            2 :     );
     170            2 : }
     171              : 
     172            2 : #[test]
     173            2 : pub fn test_find_end_of_wal_last_crossing_segment() {
     174            2 :     init_logging();
     175            2 :     test_end_of_wal::<crate::LastWalRecordCrossingSegment>(
     176            2 :         "test_find_end_of_wal_last_crossing_segment",
     177            2 :     );
     178            2 : }
     179              : 
     180              : /// Check the math in update_next_xid
     181              : ///
     182              : /// NOTE: These checks are sensitive to the value of XID_CHECKPOINT_INTERVAL,
     183              : /// currently 1024.
     184            2 : #[test]
     185            2 : pub fn test_update_next_xid() {
     186            2 :     let checkpoint_buf = [0u8; std::mem::size_of::<CheckPoint>()];
     187            2 :     let mut checkpoint = CheckPoint::decode(&checkpoint_buf).unwrap();
     188            2 : 
     189            2 :     checkpoint.nextXid = FullTransactionId { value: 10 };
     190            2 :     assert_eq!(checkpoint.nextXid.value, 10);
     191              : 
     192              :     // The input XID gets rounded up to the next XID_CHECKPOINT_INTERVAL
     193              :     // boundary
     194            2 :     checkpoint.update_next_xid(100);
     195            2 :     assert_eq!(checkpoint.nextXid.value, 1024);
     196              : 
     197              :     // No change
     198            2 :     checkpoint.update_next_xid(500);
     199            2 :     assert_eq!(checkpoint.nextXid.value, 1024);
     200            2 :     checkpoint.update_next_xid(1023);
     201            2 :     assert_eq!(checkpoint.nextXid.value, 1024);
     202              : 
     203              :     // The function returns the *next* XID, given the highest XID seen so
     204              :     // far. So when we pass 1024, the nextXid gets bumped up to the next
     205              :     // XID_CHECKPOINT_INTERVAL boundary.
     206            2 :     checkpoint.update_next_xid(1024);
     207            2 :     assert_eq!(checkpoint.nextXid.value, 2048);
     208            2 : }
     209              : 
     210            2 : #[test]
     211            2 : pub fn test_encode_logical_message() {
     212            2 :     let expected = [
     213            2 :         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,
     214            2 :         38, 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,
     215            2 :         101, 102, 105, 120, 0, 109, 101, 115, 115, 97, 103, 101,
     216            2 :     ];
     217            2 :     let actual = encode_logical_message("prefix", "message");
     218            2 :     assert_eq!(expected, actual[..]);
     219            2 : }
        

Generated by: LCOV version 2.1-beta