Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 56 additions & 18 deletions aqpbm-cli/src/benchmark_external_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@ use aqpbm_core::harness::protocol::{
use aqpbm_core::harness::run_directory::RunDirectory;
use clap::{Parser, Subcommand};
use system_bench::engines_external::clickhouse_server::{ClickHouseEngine, ClickHouseServer};
use system_bench::engines_external::victoriametrics_server::{
VictoriaMetricsEngine, VictoriaMetricsServer,
};

/// The engines this binary can run.
pub const ENGINES: [&str; 2] = ["fake", "clickhouse"];
pub const ENGINES: [&str; 3] = ["fake", "clickhouse", "victoriametrics"];

#[derive(Parser, Debug)]
pub struct BenchmarkExternalArgs {
Expand All @@ -30,7 +33,7 @@ pub struct BenchmarkExternalArgs {
#[derive(Subcommand, Debug)]
pub enum BenchmarkExternalCmd {
/// Run every (workload, variant) cell of the run directory on one engine.
Run(RunArgs),
Run(Box<RunArgs>),
/// Join every engine run's cells into summary.csv, summary.md and accuracy.csv.
Report(ReportArgs),
}
Expand All @@ -40,15 +43,17 @@ pub struct RunArgs {
/// The run directory: workloads/, plans/<variant>/, results/.
#[arg(long)]
pub run_directory: PathBuf,
/// The engine: `fake` (the harness's own fake engine) or `clickhouse`.
/// The engine: `fake` (the harness's own fake engine), `clickhouse` or
/// `victoriametrics`.
#[arg(long)]
pub engine: String,
/// The ClickHouse server's HTTP interface, e.g. `http://10.0.0.1:8123`
/// (engine `clickhouse`).
#[arg(long)]
pub clickhouse_url: Option<String>,
/// The server's cgroup v2 directory, e.g.
/// `/sys/fs/cgroup/system.slice/docker-<id>.scope` (engine `clickhouse`).
/// `/sys/fs/cgroup/system.slice/docker-<id>.scope` (engines `clickhouse`
/// and `victoriametrics`).
#[arg(long)]
pub server_cgroup_directory: Option<PathBuf>,
/// The SSH destination of the server host, e.g. `bench@10.0.0.2`; the
Expand All @@ -64,6 +69,14 @@ pub struct RunArgs {
/// How long one ClickHouse statement may run, in seconds.
#[arg(long, default_value_t = 600)]
pub clickhouse_statement_timeout_seconds: u64,
/// The VictoriaMetrics server's HTTP interface, e.g. `http://10.0.0.1:8428`
/// (engine `victoriametrics`).
#[arg(long)]
pub victoriametrics_url: Option<String>,
/// The server's `-streamAggr.config` file on the server host, replaced
/// for each arm (engine `victoriametrics`).
#[arg(long)]
pub victoriametrics_stream_aggregation_config: Option<PathBuf>,
/// Only these variants (repeatable); every variant under plans/ by default.
#[arg(long = "variant")]
pub variants: Vec<String>,
Expand Down Expand Up @@ -92,7 +105,7 @@ pub struct ReportArgs {

pub fn run(args: BenchmarkExternalArgs) -> Result<()> {
match args.command {
BenchmarkExternalCmd::Run(args) => run_engine_cmd(args),
BenchmarkExternalCmd::Run(args) => run_engine_cmd(*args),
BenchmarkExternalCmd::Report(args) => report_cmd(args),
}
}
Expand All @@ -101,30 +114,22 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> {
let engine: Box<dyn EngineUnderTest> = match args.engine.as_str() {
"fake" => {
if args.clickhouse_url.is_some()
|| args.victoriametrics_url.is_some()
|| args.victoriametrics_stream_aggregation_config.is_some()
|| args.server_cgroup_directory.is_some()
|| args.server_ssh_host.is_some()
{
bail!(
"--clickhouse-url, --server-cgroup-directory and --server-ssh-host are for engine clickhouse only"
"--clickhouse-url, --victoriametrics-url, --victoriametrics-stream-aggregation-config, --server-cgroup-directory and --server-ssh-host are for engines clickhouse and victoriametrics only"
);
}
Box::new(FakeEngine::default())
}
"clickhouse" => {
let (Some(url), Some(cgroup_directory)) = (
args.clickhouse_url.clone(),
args.server_cgroup_directory.clone(),
) else {
let (Some(url), Some(cgroup)) = (args.clickhouse_url.clone(), server_cgroup(&args))
else {
bail!("engine clickhouse needs --clickhouse-url and --server-cgroup-directory");
};
let cgroup = match args.server_ssh_host.clone() {
Some(host) => CgroupSource::Remote {
ssh_program: args.ssh_program.clone(),
host,
cgroup_directory,
},
None => CgroupSource::Local(cgroup_directory),
};
Box::new(ClickHouseEngine::new(ClickHouseServer {
url,
cgroup,
Expand All @@ -134,6 +139,27 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> {
),
})?)
}
"victoriametrics" => {
let (Some(url), Some(cgroup), Some(stream_aggregation_config)) = (
args.victoriametrics_url.clone(),
server_cgroup(&args),
args.victoriametrics_stream_aggregation_config.clone(),
) else {
bail!(
"engine victoriametrics needs --victoriametrics-url, --server-cgroup-directory and --victoriametrics-stream-aggregation-config"
);
};
// Wall-clock data runs one arm at a time.
if args.warmup != 0 || args.runs != 1 {
bail!("engine victoriametrics runs one arm at a time: pass --warmup 0 --runs 1");
}
Box::new(VictoriaMetricsEngine::new(VictoriaMetricsServer {
url,
cgroup,
stream_aggregation_config,
request_timeout: std::time::Duration::from_secs(600),
})?)
}
other => bail!(
"unknown engine '{other}'; known engines: {}",
ENGINES.join(", ")
Expand Down Expand Up @@ -168,6 +194,18 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> {
Ok(())
}

fn server_cgroup(args: &RunArgs) -> Option<CgroupSource> {
let cgroup_directory = args.server_cgroup_directory.clone()?;
Some(match args.server_ssh_host.clone() {
Some(host) => CgroupSource::Remote {
ssh_program: args.ssh_program.clone(),
host,
cgroup_directory,
},
None => CgroupSource::Local(cgroup_directory),
})
}

fn report_cmd(args: ReportArgs) -> Result<()> {
let (engine, variant) = args
.truth
Expand Down
34 changes: 34 additions & 0 deletions aqpbm-cli/tests/benchmark_external_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,37 @@ fn the_clickhouse_engine_needs_its_server() {
);
let _ = std::fs::remove_dir_all(run.parent().unwrap());
}

/// X4: engine `victoriametrics` needs its server, cgroup directory and
/// config file, and runs one arm at a time (wall-clock data): only with
/// `--warmup 0 --runs 1`.
#[test]
fn the_victoriametrics_engine_needs_its_server_and_one_run() {
let run = fixture("x4");
let base = [
"benchmark-external",
"run",
"--run-directory",
run.to_str().unwrap(),
"--engine",
"victoriametrics",
];
let out = approxbench(&base);
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("--victoriametrics-url"), "{stderr}");
let mut with_server = base.to_vec();
with_server.extend([
"--victoriametrics-url",
"http://127.0.0.1:1",
"--server-cgroup-directory",
"/sys/fs/cgroup/system.slice/docker-1.scope",
"--victoriametrics-stream-aggregation-config",
"/data/victoriametrics/config/stream-aggregation.yaml",
]);
let out = approxbench(&with_server);
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("--warmup 0 --runs 1"), "{stderr}");
let _ = std::fs::remove_dir_all(run.parent().unwrap());
}
92 changes: 92 additions & 0 deletions aqpbm-core/src/harness/cgroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ impl CgroupSource {
}
}

pub fn replace_file_on_server_host(&self, path: &Path, text: &str) -> Result<(), CgroupError> {
match self {
CgroupSource::Local(_) => replace_local_file(path, text),
CgroupSource::Remote {
ssh_program, host, ..
} => ssh_replace(ssh_program, host, path, text),
}
}

/// `cpu.stat` read once.
pub fn cpu(&self) -> Result<CgroupCpu, CgroupError> {
CgroupCpu::parse(&self.read("cpu.stat")?)
Expand Down Expand Up @@ -243,6 +252,87 @@ fn ssh_read(ssh_program: &str, host: &str, path: &Path) -> Result<String, Cgroup
}
}

fn temporary_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(".tmp");
PathBuf::from(name)
}

fn replace_local_file(path: &Path, text: &str) -> Result<(), CgroupError> {
use std::io::Write;
let temporary = temporary_path(path);
let written = std::fs::remove_file(&temporary)
.or_else(|error| match error.kind() {
std::io::ErrorKind::NotFound => Ok(()),
_ => Err(error),
})
.and_then(|()| {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
})
.and_then(|mut file| file.write_all(text.as_bytes()))
.and_then(|()| std::fs::rename(&temporary, path));
written.map_err(|error| {
let _ = std::fs::remove_file(&temporary);
CgroupError::Write {
file: path.display().to_string(),
message: error.to_string(),
}
})
}

fn ssh_replace(ssh_program: &str, host: &str, path: &Path, text: &str) -> Result<(), CgroupError> {
use std::io::Write;
let quoted = shell_quoted(&path.to_string_lossy());
let temporary = shell_quoted(&temporary_path(path).to_string_lossy());
let length = text.len();
let mut child = Command::new(ssh_program)
.args(SSH_OPTIONS)
.arg("--")
.arg(host)
.arg(format!(
"rm -f -- {temporary} && set -C && cat > {temporary} && \
[ \"$(wc -c < {temporary})\" -eq {length} ] && exec mv -f -- {temporary} {quoted}; \
status=$?; rm -f -- {temporary}; exit $status"
))
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| CgroupError::Remote {
host: host.into(),
message: format!("cannot start {ssh_program}: {error}"),
})?;
let written = child
.stdin
.take()
.expect("stdin is piped")
.write_all(text.as_bytes());
let output = child
.wait_with_output()
.map_err(|error| CgroupError::Remote {
host: host.into(),
message: error.to_string(),
})?;
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
match (output.status.code(), written) {
(Some(0), Ok(())) => Ok(()),
(Some(255) | None, _) => Err(CgroupError::Remote {
host: host.into(),
message: stderr,
}),
(_, written) => Err(CgroupError::Write {
file: format!("{host}:{}", path.display()),
message: match written {
Err(error) if stderr.is_empty() => error.to_string(),
_ => stderr,
},
}),
}
}

/// `text` in single quotes for the server host's shell, each `'` as `'\''`.
fn shell_quoted(text: &str) -> String {
format!("'{}'", text.replace('\'', r"'\''"))
Expand All @@ -255,6 +345,8 @@ pub enum CgroupError {
Read { file: String, message: String },
#[error("{file} has no '{field}' line")]
MissingField { file: String, field: String },
#[error("cannot write {file}: {message}")]
Write { file: String, message: String },
#[error("cannot parse {file}: {message}")]
Parse { file: String, message: String },
#[error("SSH to {host}: {message}")]
Expand Down
53 changes: 53 additions & 0 deletions aqpbm-core/tests/harness_cgroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,56 @@ fn a_group_with_a_foreign_process_is_not_the_server_cpu() {
.unwrap();
assert_eq!(shared.cpu_source(), "schedstat");
}

#[cfg(unix)]
#[test]
fn a_file_on_the_server_host_is_replaced_locally_and_over_ssh() {
let temp = TempDir::new("replace-'quoted'");
let config = temp.0.join("stream-aggregation.yaml");
std::fs::write(&config, "[]\n").unwrap();
let local = CgroupSource::Local(temp.0.clone());
local
.replace_file_on_server_host(&config, "- interval: 10s\n")
.unwrap();
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
"- interval: 10s\n"
);
let remote = CgroupSource::Remote {
ssh_program: fake_ssh(&temp.0),
host: "bench@192.0.2.1".into(),
cgroup_directory: temp.0.clone(),
};
remote
.replace_file_on_server_host(&config, "- interval: 20s\n")
.unwrap();
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
"- interval: 20s\n"
);
assert!(!temp.0.join("stream-aggregation.yaml.tmp").exists());
#[cfg(unix)]
{
let target = temp.0.join("not-the-config");
std::fs::write(&target, "kept").unwrap();
std::os::unix::fs::symlink(&target, temp.0.join("stream-aggregation.yaml.tmp")).unwrap();
local
.replace_file_on_server_host(&config, "- interval: 30s\n")
.unwrap();
assert_eq!(std::fs::read_to_string(&target).unwrap(), "kept");
std::os::unix::fs::symlink(&target, temp.0.join("stream-aggregation.yaml.tmp")).unwrap();
remote
.replace_file_on_server_host(&config, "- interval: 40s\n")
.unwrap();
assert_eq!(std::fs::read_to_string(&target).unwrap(), "kept");
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
"- interval: 40s\n"
);
}
let missing = temp.0.join("no-such-directory").join("config.yaml");
assert!(matches!(
remote.replace_file_on_server_host(&missing, "x"),
Err(CgroupError::Write { .. })
));
}
Loading
Loading