Skip to content

crimson/os/seastore/cache/LRU: account the empty extent when adding it to LRU - #62969

Merged
cyx1231st merged 1 commit into
ceph:mainfrom
zhscn:fix-cache-lru-size-metric
May 12, 2025
Merged

cyx1231st merged 1 commit into
ceph:mainfrom
zhscn:fix-cache-lru-size-metric

Conversation

@zhscn

@zhscn zhscn commented Apr 25, 2025 •

Copy link
Copy Markdown
Member

Don't update num_extents when a partial extent is already in LRU.

Fixes: https://tracker.ceph.com/issues/69986

Contribution Guidelines

  • To sign and title your commits, please refer to Submitting Patches to Ceph.

  • If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.

  • When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an x between the brackets: [x]. Spaces and capitalization matter when checking off items this way.

Checklist

  • Tracker (select at least one)
    • References tracker ticket
    • Very recent bug; references commit where it was introduced
    • New feature (ticket optional)
    • Doc update (no ticket needed)
    • Code cleanup (no ticket needed)
  • Component impact
    • Affects Dashboard, opened tracker ticket
    • Affects Orchestrator, opened tracker ticket
    • No impact that needs to be tracked
  • Documentation (select at least one)
    • Updates relevant documentation
    • No doc update is appropriate
  • Tests (select at least one)
Show available Jenkins commands

@zhscn
zhscn requested a review from a team as a code owner April 25, 2025 08:59
@zhscn
zhscn force-pushed the fix-cache-lru-size-metric branch from 86b2e9a to ee388c3 Compare April 25, 2025 09:00

@cyx1231st cyx1231st left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! LGTM.

@zhscn

zhscn commented Apr 25, 2025

Copy link
Copy Markdown
Member Author

Tested with

rbd-concurrent-io-snap-test -s 1 -c 1 -r 120 -d .
rbd-concurrent-io-snap-test
[package]
name = "rbd-concurrent-io-snap-test"
version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = { version = "1.0.86", features = ["backtrace"] }
clap = { version = "4.5.16", features = ["derive"] }
rand = "0.8.5"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
use std::{
    cmp::max,
    collections::BTreeMap,
    process::Command,
    sync::{atomic::AtomicBool, Arc, Mutex},
    thread::{self, sleep},
    time::Duration,
};

use anyhow::{bail, Result};
use clap::Parser;
use rand::seq::SliceRandom;
use tracing::info;
use tracing_subscriber::fmt::SubscriberBuilder;

#[derive(Parser, Debug)]
struct Cli {
    #[clap(short, long, default_value = "15")]
    /// The size of image in GiB
    size: String,
    #[clap(short, long, default_value = "3")]
    /// The number of cycles to run
    cycle: usize,
    #[clap(short, long, default_value = "5")]
    /// The maximum number of snapshots to keep
    max_snaps: usize,
    #[clap(short, long, default_value = "5")]
    /// The number of fio rand runs during one cycle
    fio_count: usize,
    #[clap(short, long, default_value = "300")]
    /// The number of seconds to run the fio rand test
    rand_runtime: usize,
    #[clap(short, long, default_value = "rbd")]
    /// Pool name
    pool: String,
    #[clap(short, long, default_value = "test")]
    /// Test image name
    image: String,
    #[clap(short, long, default_value = "false")]
    /// Verifies the checksum of the snapshot
    verify: bool,
    #[clap(short, long, required = true)]
    directory: String,
}

fn run_command(cmd: &str, args: &[&str]) -> Result<()> {
    let mut child = Command::new(cmd).args(args).spawn()?;
    info!("Running command: {} {} {:?}", child.id(), cmd, args);
    let res = child.wait()?;
    if !res.success() {
        bail!("command {} {:?} failed: {:?}", cmd, args, res);
    }
    Ok(())
}

fn run_fio_seq(pool: &str, image: &str) -> Result<()> {
    run_command(
        "fio",
        &[
            "--name=seq",
            "--ioengine=rbd",
            "--clientname=admin",
            &format!("--pool={}", pool),
            &format!("--rbdname={}", image),
            "--direct=1",
            "--sync=1",
            "--rw=write",
            "--bs=2M",
            "--numjobs=1",
            "--iodepth=64",
        ],
    )
}

fn run_fio_rand(pool: &str, image: &str, seconds: usize) -> Result<()> {
    run_command(
        "fio",
        &[
            "--name=rand",
            "--ioengine=rbd",
            "--clientname=admin",
            &format!("--pool={}", pool),
            &format!("--rbdname={}", image),
            "--direct=1",
            "--sync=1",
            "--time_based=1",
            &format!("--runtime={}", seconds),
            "--randrepeat=0",
            "--rw=randwrite",
            "--bsrange=4K-1024K",
            "--numjobs=1",
            "--iodepth=768",
        ],
    )?;
    info!("fio rand finish");
    Ok(())
}

fn run_rbd_snap_command(op: &str, pool: &str, image: &str, id: usize) -> Result<()> {
    run_command("rbd", &["snap", op, &format!("{}/{}@{}", pool, image, id)])
}

fn run_rbd_snap_create(pool: &str, image: &str, id: usize) -> Result<()> {
    run_rbd_snap_command("create", pool, image, id)
}

fn run_rbd_snap_rm(pool: &str, image: &str, id: usize) -> Result<()> {
    run_rbd_snap_command("rm", pool, image, id)
}

fn run_rbd_snap_rollback(pool: &str, image: &str, id: usize) -> Result<()> {
    run_rbd_snap_command("rollback", pool, image, id)
}

fn export_and_calc_checksum(
    pool: &str,
    image: &str,
    id: Option<usize>,
    dir: &str,
    mv: bool,
) -> Result<(String, String)> {
    let (rbd_name, output_name) = if let Some(id) = id {
        (
            format!("{}/{}@{}", pool, image, id),
            format!("{}@{}", image, id),
        )
    } else {
        (format!("{}/{}", pool, image), image.to_string())
    };
    let _ = run_command("rm", &["-f", &output_name]);
    run_command("rbd", &["export", &rbd_name, &output_name])?;
    info!("Running command: md5sum {}", &output_name);
    let output = Command::new("md5sum").arg(&output_name).output()?;
    let checksum = String::from_utf8(output.stdout)?;
    if mv {
        run_command("mv", &[&output_name, &format!("{}/", dir)])?;
    }
    let checksum = checksum.split_whitespace().next().unwrap().to_string();
    info!("{:?} checksum {}", id, checksum);
    Ok((checksum, output_name))
}

fn verify_checksum(
    pool: &str,
    image: &str,
    id: Option<usize>,
    checksum: &str,
    dir: &str,
) -> Result<()> {
    let (current_checksum, output_name) = export_and_calc_checksum(pool, image, id, dir, false)?;
    if current_checksum != checksum {
        run_command(
            "mv",
            &[&output_name, &format!("{}/{}_error", dir, output_name)],
        )?;
        anyhow::bail!(
            "Current {}/{}:{} checksum mismatchs with pervious: {} != {}",
            pool,
            image,
            id.map_or_else(|| "head".to_string(), |i| i.to_string()),
            current_checksum,
            checksum
        );
    } else {
        run_command("mv", &[&output_name, &format!("{}/", dir)])?;
    }
    Ok(())
}

struct SnapManager {
    args: Cli,
    min_snap_count: usize,
    current_snap_id: usize,
    snaps_checksum: BTreeMap<usize, String>,
    stop: bool,
}

impl SnapManager {
    fn new(args: Cli) -> Self {
        let min_snap_count = max(1, args.max_snaps / 2);
        Self {
            args,
            min_snap_count,
            current_snap_id: 1,
            snaps_checksum: BTreeMap::new(),
            stop: false,
        }
    }
    fn next_snap_id(&mut self) -> usize {
        let ret = self.current_snap_id;
        self.current_snap_id += 1;
        ret
    }
    fn get_snap_ids(&self) -> Vec<usize> {
        self.snaps_checksum.keys().cloned().collect()
    }
    fn create_snap(&mut self) -> Result<()> {
        let snap_id = self.next_snap_id();
        run_rbd_snap_create(&self.args.pool, &self.args.image, snap_id)?;
        let checksum = if self.args.verify {
            export_and_calc_checksum(
                &self.args.pool,
                &self.args.image,
                Some(snap_id),
                &self.args.directory,
                true,
            )?
            .0
        } else {
            "".to_string()
        };
        self.snaps_checksum.insert(snap_id, checksum);
        Ok(())
    }
    fn remove_snap(&mut self, snap_id: usize) -> Result<()> {
        run_rbd_snap_rm(&self.args.pool, &self.args.image, snap_id)?;
        self.snaps_checksum.remove(&snap_id);
        run_command(
            "rm",
            &[
                "-f",
                &format!("{}/{}@{}", self.args.directory, self.args.image, snap_id),
            ],
        )?;
        Ok(())
    }
    fn rollback_snap(&self, snap_id: usize) -> Result<()> {
        run_rbd_snap_rollback(&self.args.pool, &self.args.image, snap_id)
    }
    fn validate_all_snapshots(&self) -> Result<()> {
        for (snap_id, checksum) in &self.snaps_checksum {
            verify_checksum(
                &self.args.pool,
                &self.args.image,
                Some(*snap_id),
                checksum,
                &self.args.directory,
            )?;
        }
        Ok(())
    }
    fn select_random_snap_id(&self) -> usize {
        assert!(!self.snaps_checksum.is_empty());
        let snap_count = self.snaps_checksum.len();
        let snap_id = rand::random::<usize>() % snap_count;
        *self.snaps_checksum.keys().nth(snap_id).unwrap()
    }
}

fn run_snap(snap_manager: Arc<Mutex<SnapManager>>) -> Result<()> {
    info!("snap thread");

    loop {
        sleep(Duration::from_secs(1));
        let mut snap_manager = snap_manager.lock().unwrap();
        if snap_manager.stop {
            break;
        }

        let create_snap = {
            let snap_count = snap_manager.snaps_checksum.len();
            if snap_count < snap_manager.min_snap_count {
                true
            } else if snap_count > snap_manager.args.max_snaps {
                false
            } else {
                rand::random::<bool>()
            }
        };
        if create_snap {
	   info!("create snap");
            snap_manager.create_snap()?;
        } else {
            let snap_id = snap_manager.select_random_snap_id();
	   info!("remove snap {}", snap_id);
            snap_manager.remove_snap(snap_id)?;
        }
    }
    Ok(())
}

fn run_io_impl(snap_manager: Arc<Mutex<SnapManager>>) -> Result<()> {
    info!("io thread");
    let (cycle, fio_count, rand_runtime, pool, image) = {
        let snap_manager = snap_manager.lock().unwrap();
        let args = &snap_manager.args;
        (
            args.cycle,
            args.fio_count,
            args.rand_runtime,
            args.pool.clone(),
            args.image.clone(),
        )
    };
    for c in 0..cycle {
        info!("Cycle {}", c);
        for _ in 0..fio_count {
            run_fio_rand(&pool, &image, rand_runtime)?;

            let mut snap_manager = snap_manager.lock().unwrap();
            snap_manager.create_snap()?;
        }
        let mut snap_manager = snap_manager.lock().unwrap();

        let mut snap_ids = snap_manager.get_snap_ids();

        snap_ids.shuffle(&mut rand::thread_rng());
        for snap_id in snap_ids.iter() {
            snap_manager.rollback_snap(*snap_id)?;
            if snap_manager.args.verify {
                let checksum = snap_manager.snaps_checksum.get(snap_id).unwrap();
                verify_checksum(&pool, &image, None, checksum, &snap_manager.args.directory)?;
            }
        }
        snap_manager.validate_all_snapshots()?;

        snap_ids.shuffle(&mut rand::thread_rng());
        for snap_id in snap_ids.iter() {
            snap_manager.remove_snap(*snap_id)?;
            if snap_manager.args.verify {
                snap_manager.validate_all_snapshots()?;
            }
        }
    }
    Ok(())
}

fn run_io(snap_manager: Arc<Mutex<SnapManager>>) -> Result<()> {
    let res = run_io_impl(snap_manager.clone());
    snap_manager.lock().unwrap().stop = true;
    res
}

fn main() {
    SubscriberBuilder::default()
        .with_ansi(false)
        .with_target(false)
        .with_thread_ids(true)
        .init();

    let args = Cli::parse();
    info!("{:?}", args);
    let _ = run_command("ceph", &["osd", "pool", "create", &args.pool]);
    run_command(
        "rbd",
        &[
            "create",
            &format!("--size={}G", args.size),
            &format!("{}/{}", args.pool, args.image),
        ],
    )
    .unwrap();
    run_fio_seq(&args.pool, &args.image).unwrap();
    let snap_manager = Arc::new(Mutex::new(SnapManager::new(args)));
    let success = Arc::new(AtomicBool::new(true));
    let io_thread = {
        let snap_manager = snap_manager.clone();
        let success = success.clone();
        thread::spawn(move || {
            if let Err(err) = run_io(snap_manager) {
                tracing::error!("{:?}", err);
                success.store(false, std::sync::atomic::Ordering::SeqCst);
            }
        })
    };
    let snap_thread = {
        let snap_manager = snap_manager.clone();
        let success = success.clone();
        thread::spawn(move || {
            if let Err(err) = run_snap(snap_manager) {
                tracing::error!("{:?}", err);
                success.store(false, std::sync::atomic::Ordering::SeqCst);
            }
        })
    };
    io_thread.join().unwrap();
    snap_thread.join().unwrap();
    if success.load(std::sync::atomic::Ordering::SeqCst) {
        info!("success");
    } else {
        info!("failed");
    }
}

@Matan-B

Matan-B commented Apr 27, 2025

Copy link
Copy Markdown
Contributor

jenkins test make check arm64

@Matan-B
Matan-B requested a review from liu-chunmei April 27, 2025 08:14
@Matan-B

Matan-B commented Apr 27, 2025

Copy link
Copy Markdown
Contributor

@zhscn, Thanks for finding that!
Can you please open a tracker.ceph account so we could update the "Assignee" in the tracker when issues are wip?

@zhscn

zhscn commented Apr 27, 2025 •

Copy link
Copy Markdown
Member Author

@zhscn, Thanks for finding that! Can you please open a tracker.ceph account so we could update the "Assignee" in the tracker when issues are wip?

My tracker id is ZhangSong https://tracker.ceph.com/users/13609

@Matan-B

Matan-B commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

My tracker id is ZhangSong https://tracker.ceph.com/users/13609

Ack, requesting to add to the relevant groups so it will be possible to mark you as assignee :)

@athanatos
athanatos self-requested a review May 9, 2025 02:12

@athanatos athanatos left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just hit the same bug and came to the same conclusion -- looks right to me!

@Matan-B Matan-B moved this from Needs QA to Tested in Crimson May 11, 2025
@cyx1231st
cyx1231st merged commit 1f4b9fd into ceph:main May 12, 2025
@zhscn
zhscn deleted the fix-cache-lru-size-metric branch May 12, 2025 02:50
@Matan-B Matan-B moved this from Tested to Merged (Main) in Crimson May 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Merged (Pre Umbrella cutoff)

Development

Successfully merging this pull request may close these issues.

4 participants