Skip to content

Commit

Permalink
fix: panic when perf counter could not be initialized
Browse files Browse the repository at this point in the history
As reported in iopsystems#14, the CPU CPI sampler will panic if the cycles or
instructions perf counters cannot be initialized.

This PR fixes the bug by returning a Nop sampler if there are
exceptions during initialization.
  • Loading branch information
brayniac committed May 9, 2023
1 parent 8634df2 commit d063ad7
Showing 1 changed file with 43 additions and 20 deletions.
63 changes: 43 additions & 20 deletions src/samplers/cpu/cpi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,49 @@ impl Cpi {
pub fn new(_config: &Config) -> Self {
let now = Instant::now();

let mut group = Group::new().expect("couldn't init perf group");
let counters = vec![
(
Counter::new(&CPU_CYCLES, None),
Builder::new()
.group(&mut group)
.kind(Hardware::CPU_CYCLES)
.build()
.expect("failed to init cycles counter"),
),
(
Counter::new(&CPU_INSTRUCTIONS, None),
Builder::new()
.group(&mut group)
.kind(Hardware::INSTRUCTIONS)
.build()
.expect("failed to init instructions counter"),
),
];
group.enable().expect("couldn't enable perf counters");
// initialize a group for the perf counters
let mut group = match Group::new() {
Ok(g) => g,
Err(_) => {
error!("couldn't init perf group");
return Nop { };
}
}

// initialize the counters
let mut counters = vec![];

match Builder::new()
.group(&mut group)
.kind(Hardware::CPU_CYCLES)
.build() {
Ok(counter) => {
counters.push((Counter::new(&CPU_CYCLES, None), counter));
}
Err(_) => {
error!("failed to initialize cpu cycles perf counter");
return Nop { };
}
}

match Builder::new()
.group(&mut group)
.kind(Hardware::INSTRUCTIONS)
.build() {
Ok(counter) => {
counters.push((Counter::new(&CPU_INSTRUCTIONS, None), counter));
}
Err(_) => {
error!("failed to initialize cpu instructions perf counter");
return Nop { };
}
}

// enable the counters in the group
if group.enable().is_err() {
error!("couldn't enable perf counter group");
return Nop { };
}

Self {
prev: now,
Expand Down

0 comments on commit d063ad7

Please sign in to comment.