Skip to content

Add kernel, global, and timeout flags #334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
16 changes: 12 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ anyhow = "1.0.43"
cargo_metadata = "0.18"
clap = { version = "4.0.11", features = ["derive"] }
clap_complete = "4.0.2"
inferno = { version = "0.11.0", default_features = false, features = ["multithreaded", "nameattr"] }
humantime = "2.1.0"
inferno = { version = "0.11.21", default_features = false, features = ["multithreaded", "nameattr"] }
opener = "0.7.1"
shlex = "1.1.0"

Expand Down
21 changes: 15 additions & 6 deletions src/bin/flamegraph.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::path::PathBuf;

use anyhow::anyhow;
use anyhow::bail;
use clap::{CommandFactory, Parser};
use clap_complete::Shell;

Expand Down Expand Up @@ -46,11 +46,20 @@ fn main() -> anyhow::Result<()> {
let path = perf_file.to_str().unwrap();
Workload::ReadPerf(path.to_string())
} else {
match (opt.pid, opt.trailing_arguments.is_empty()) {
(Some(p), true) => Workload::Pid(p),
(None, false) => Workload::Command(opt.trailing_arguments.clone()),
(Some(_), false) => return Err(anyhow!("cannot pass in command with --pid")),
(None, true) => return Err(anyhow!("no workload given to generate a flamegraph for")),
match (
opt.pid,
opt.graph.global(),
opt.trailing_arguments.is_empty(),
) {
(Some(_), _, false) => bail!("cannot pass in command with --pid"),
(Some(_), true, _) => bail!("cannot specify both --global and --pid"),
(_, true, false) => bail!("cannot pass in command with --global"),

(Some(p), false, true) => Workload::Pid(p),
(None, false, false) => Workload::Command(opt.trailing_arguments.clone()),
(None, true, true) => Workload::Global,

(None, false, true) => bail!("no workload given to generate a flamegraph for"),
}
};
flamegraph::generate_flamegraph_for_workload(workload, opt.graph)
Expand Down
118 changes: 93 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use inferno::collapse::dtrace::{Folder, Options as CollapseOptions};
#[cfg(unix)]
use signal_hook::consts::{SIGINT, SIGTERM};

use anyhow::{anyhow, Context};
use anyhow::{anyhow, bail, Context};
use clap::{
builder::{PossibleValuesParser, TypedValueParser},
Args,
Expand All @@ -30,6 +30,7 @@ pub enum Workload {
Command(Vec<String>),
Pid(u32),
ReadPerf(String),
Global,
}

#[cfg(target_os = "linux")]
Expand All @@ -42,11 +43,13 @@ mod arch {
pub(crate) fn initial_command(
workload: Workload,
sudo: Option<Option<&str>>,
freq: u32,
custom_cmd: Option<String>,
verbose: bool,
ignore_status: bool,
opts: &Options,
) -> Option<String> {
let freq = opts.frequency();
let custom_cmd = opts.custom_cmd.clone();
let verbose = opts.verbose;
let ignore_status = opts.ignore_status;

let perf = if let Ok(path) = env::var("PERF") {
path
} else {
Expand Down Expand Up @@ -77,7 +80,16 @@ mod arch {
}
}

// This is checked earlier in Options::check
if opts.kernel {
unimplemented!("kernel sampling is not implemented using perf");
}

match workload {
Workload::Global => {
// This is also checked earlier in Options::check
unimplemented!("global sampling is not implemented using perf")
}
Workload::Command(c) => {
command.args(&c);
}
Expand Down Expand Up @@ -118,7 +130,7 @@ mod arch {

let output = command.output().context("unable to call perf script")?;
if !output.status.success() {
anyhow::bail!(format!(
bail!(format!(
"unable to run 'perf script': ({}) {}",
output.status,
std::str::from_utf8(&output.stderr)?
Expand Down Expand Up @@ -170,28 +182,60 @@ mod arch {
pub(crate) fn initial_command(
workload: Workload,
sudo: Option<Option<&str>>,
freq: u32,
custom_cmd: Option<String>,
verbose: bool,
ignore_status: bool,
opts: &Options,
) -> Option<String> {
let freq = opts.frequency();
let custom_cmd = opts.custom_cmd.clone();
let global = opts.global;
let kernel = opts.kernel;
let verbose = opts.verbose;
let ignore_status = opts.ignore_status;

let mut command = base_dtrace_command(sudo);

let stack = if kernel {
"stack(100),ustack(100)"
} else {
"ustack(100)"
};
let filter = if global { "" } else { "/pid == $target/" };

let timeout = if let Some(t) = opts.timeout {
format!("tick-{}ms {{ exit(0); }}", t.as_millis())
} else {
"".to_owned()
};

let dtrace_script = custom_cmd.unwrap_or(format!(
"profile-{freq} /pid == $target/ \
{{ @[ustack(100)] = count(); }}",
"profile-{freq} {filter} \
{{ @[{stack}] = count(); }} \
{timeout}",
));

command.arg("-x");
command.arg("ustackframes=100");

// Adjust the max number of saved process handles, to avoid having to
// constantly reload symbol tables.
#[cfg(target_os = "illumos")]
if global {
command.arg("-x");
command.arg("pgmax=1024");
}

if kernel {
command.arg("-x");
command.arg("stackframes=100");
}

command.arg("-n");
command.arg(&dtrace_script);

command.arg("-o");
command.arg("cargo-flamegraph.stacks");

match workload {
Workload::Global => (),
Workload::Command(c) => {
let mut escaped = String::new();
for (i, arg) in c.iter().enumerate() {
Expand Down Expand Up @@ -363,14 +407,7 @@ pub fn generate_flamegraph_for_workload(workload: Workload, opts: Options) -> an
let perf_output = if let Workload::ReadPerf(perf_file) = workload {
Some(perf_file)
} else {
arch::initial_command(
workload,
sudo,
opts.frequency(),
opts.custom_cmd,
opts.verbose,
opts.ignore_status,
)
arch::initial_command(workload, sudo, &opts)
};

#[cfg(unix)]
Expand Down Expand Up @@ -506,23 +543,54 @@ pub struct Options {
/// stdout.
#[clap(long)]
post_process: Option<String>,

/// Capture a trace of the entire system
#[clap(long)]
global: bool,

/// Include kernel stack frames
#[clap(long)]
kernel: bool,

/// Amount of time to sample for
#[clap(long)]
timeout: Option<humantime::Duration>,
}

impl Options {
pub fn check(&self) -> anyhow::Result<()> {
// Manually checking conflict because structopts `conflicts_with` leads
// to a panic in completion generation for zsh at the moment (see #158)
match self.frequency.is_some() && self.custom_cmd.is_some() {
true => Err(anyhow!(
"Cannot pass both a custom command and a frequency."
)),
false => Ok(()),
if self.custom_cmd.is_some() {
if self.frequency.is_some() {
bail!("Cannot pass both a custom command and a frequency.")
} else if self.global {
bail!("Cannot specify global tracing when a custom command is also provided");
} else if self.kernel {
bail!("Cannot specify kernel tracing when a custom command is also provided");
}
}

if cfg!(target_os = "linux") {
if self.global {
bail!("Global tracing is only supported using DTrace backend");
} else if self.kernel {
bail!("Kernel tracing is only supported using DTrace backend");
} else if self.timeout.is_some() {
bail!("Timeout is only supported using DTrace backend");
}
}

Ok(())
}

pub fn frequency(&self) -> u32 {
self.frequency.unwrap_or(997)
}

pub fn global(&self) -> bool {
self.global
}
}

#[derive(Debug, Args)]
Expand Down
Loading