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
1 change: 1 addition & 0 deletions package-lock.json

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

123 changes: 121 additions & 2 deletions src/data/common/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::{Error, Result};
use anyhow::{bail, Error, Result};
use log::error;
use regex::Regex;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fs;
use std::fs::File;
Expand Down Expand Up @@ -119,6 +120,33 @@ pub fn copy_graph_and_update_graph_data(
}
}

/// Returns the name of the first file in dir whose name matches the pattern regex but does
/// not match the optional exclude regex.
pub fn find_file(dir: &PathBuf, pattern: &str, exclude_pattern: Option<&str>) -> Result<String> {
let regex = Regex::new(pattern)?;
let exclude_regex = exclude_pattern.map(Regex::new).transpose()?;
for entry in fs::read_dir(dir)? {
let filename = entry?.file_name().into_string().unwrap();
if regex.is_match(&filename)
&& !exclude_regex
.as_ref()
.is_some_and(|ex| ex.is_match(&filename))
{
return Ok(filename);
}
}
match exclude_pattern {
Some(exclude_pattern) => bail!(
"Could not find any file matching /{pattern}/ (excluding /{exclude_pattern}/) in {}",
dir.display()
),
None => bail!(
"Could not find any file matching /{pattern}/ in {}",
dir.display()
),
}
}

/// Collects the paths of all files in a dir and returns a map from file names to file paths,
/// if the file system read was successful
pub fn collect_file_paths_in_dir(dir: &PathBuf) -> Result<HashMap<String, PathBuf>> {
Expand Down Expand Up @@ -230,7 +258,98 @@ pub fn combine_value_ranges(value_ranges: Vec<(u64, u64)>) -> (u64, u64) {

#[cfg(test)]
mod utils_test {
use super::{combine_value_ranges, topological_sort};
use super::{combine_value_ranges, find_file, topological_sort};
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

#[test]
fn test_find_file_prefix_match() {
let dir = TempDir::new().unwrap();
for f in &[
"cpu_utilization.bin",
"other_cpu_utilization.bin",
"noise.txt",
] {
fs::File::create(dir.path().join(f)).unwrap();
}
let path = PathBuf::from(dir.path());
// Anchored at the start with `^`.
assert_eq!(
find_file(&path, "^cpu_utilization", None).unwrap(),
"cpu_utilization.bin",
);
// No match returns Err.
assert!(find_file(&path, "^missing", None).is_err());
}

#[test]
fn test_find_file_suffix_match() {
let dir = TempDir::new().unwrap();
for f in &["data.bin", "data.bin.bak", "noise.txt"] {
fs::File::create(dir.path().join(f)).unwrap();
}
let path = PathBuf::from(dir.path());
// Anchored at the end with `$` (".bin" mid-name in "data.bin.bak" doesn't match).
assert_eq!(find_file(&path, r"\.bin$", None).unwrap(), "data.bin");
// No match returns Err.
assert!(find_file(&path, r"\.missing$", None).is_err());
}

#[test]
fn test_find_file_excludes_substring_collision() {
// Regression test: the forward flamegraph lookup must not pick up
// `reverse-flamegraph.svg`, whose name also ends in `flamegraph.svg`. Create the files
// in both orders to defeat any reliance on directory read ordering.
for order in [
["flamegraph.svg", "reverse-flamegraph.svg"],
["reverse-flamegraph.svg", "flamegraph.svg"],
] {
let dir = TempDir::new().unwrap();
for f in order {
fs::File::create(dir.path().join(f)).unwrap();
}
let path = PathBuf::from(dir.path());
// Forward: match `flamegraph.svg` but exclude the reverse variant.
assert_eq!(
find_file(
&path,
r"flamegraph\.svg$",
Some(r"reverse-flamegraph\.svg$")
)
.unwrap(),
"flamegraph.svg",
);
// Reverse: matches only the reverse variant.
assert_eq!(
find_file(&path, r"reverse-flamegraph\.svg$", None).unwrap(),
"reverse-flamegraph.svg",
);
}
}

#[test]
fn test_find_file_excludes_legacy_run_prefixed_names() {
// The same disambiguation must hold for the legacy `<run>-flamegraph.svg` naming.
let dir = TempDir::new().unwrap();
for f in &["myrun-flamegraph.svg", "myrun-reverse-flamegraph.svg"] {
fs::File::create(dir.path().join(f)).unwrap();
}
let path = PathBuf::from(dir.path());
assert_eq!(
find_file(
&path,
r"flamegraph\.svg$",
Some(r"reverse-flamegraph\.svg$")
)
.unwrap(),
"myrun-flamegraph.svg",
);
assert_eq!(
find_file(&path, r"reverse-flamegraph\.svg$", None).unwrap(),
"myrun-reverse-flamegraph.svg",
);
}

#[test]
fn test_topological_sort_fixed_result() {
Expand Down
94 changes: 46 additions & 48 deletions src/data/java_profile.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use crate::data::common::data_formats::{
AperfData, GraphData, GraphGroup, Profiler, ProfilingData,
};
use crate::data::common::utils::copy_graph_and_update_graph_data;
#[cfg(target_os = "linux")]
use crate::data::common::utils::get_data_name_from_type;
use crate::data::common::utils::{copy_graph_and_update_graph_data, find_file};
use crate::data::{Data, ProcessData};
use crate::profiling::{jfr, Profile};
use crate::visualizer::ReportParams;
Expand All @@ -15,6 +13,7 @@ use std::collections::HashMap;
use std::fs;
#[cfg(target_os = "linux")]
use {
crate::data::common::utils::get_data_name_from_type,
crate::data::{CollectData, CollectorParams},
crate::PDError,
log::debug,
Expand All @@ -32,6 +31,10 @@ lazy_static! {
pub static ref ASPROF_CHILDREN: Mutex<Vec<Child>> = Mutex::new(Vec::new());
}

fn java_profiler_data_filename(pid: &str) -> String {
format!("java_profiler_data_{}.json", pid)
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct JavaProfileRaw {
process_map: HashMap<String, Vec<String>>,
Expand Down Expand Up @@ -300,10 +303,7 @@ impl CollectData for JavaProfileRaw {

// Generate heatmaps for each profiling type
for metric in PROFILE_METRICS {
let html_path = data_dir.join(format!(
"{}-java-profile-{}-{}.html",
params.run_name, key, metric
));
let html_path = data_dir.join(format!("java-profile-{}-{}.html", key, metric));

match Command::new("jfrconv")
.args([
Expand Down Expand Up @@ -340,12 +340,6 @@ impl CollectData for JavaProfileRaw {
}
}

// Generate Profiler from JFR
let profiler_data_path = params.data_dir.join(format!(
"{}-java-profile-{}-profiler-data.json",
params.run_name, key
));

let event_out_path_buf =
params.data_dir.join(format!("parsed_jfr_events_{key}.out"));
let events_out_path = if params.save_profile_events {
Expand All @@ -358,11 +352,16 @@ impl CollectData for JavaProfileRaw {
// so that the new flow is only executed in tests. Remove the guardrail
// after the feature is ready to launch.
if params.save_profile_events {
// Generate Profiler from JFR
match jfr::build_java_profiler_data(&jfr_path, events_out_path) {
Ok(mut profiler) => {
profiler.metadata = jfr::parse_jfr_metadata(&metadata_json);
if let Ok(json) = serde_json::to_string(&profiler) {
fs::write(&profiler_data_path, json).ok();
fs::write(
params.data_dir.join(java_profiler_data_filename(key)),
json,
)
.ok();
}
}
Err(e) => {
Expand All @@ -371,17 +370,12 @@ impl CollectData for JavaProfileRaw {
}
}

let jfr_dest =
data_dir.join(format!("{}-java-profile-{}.jfr", params.run_name, key));
let jfr_dest = data_dir.join(format!("java-profile-{}.jfr", key));
fs::copy(&jfr_path, jfr_dest).ok();
}
}

let mut jps_map = File::create(
data_dir
.clone()
.join(format!("{}-jps-map.json", params.run_name)),
)?;
let mut jps_map = File::create(data_dir.clone().join("jps-map.json"))?;
write!(jps_map, "{}", serde_json::to_string(&self.process_map)?)?;

Ok(())
Expand Down Expand Up @@ -411,11 +405,17 @@ impl ProcessData for JavaProfile {
// For backward compatibility
let mut graph_data = GraphData::default();

let processes_loc = params
.data_dir
.join(format!("{}-jps-map.json", params.run_name));
let processes_json =
fs::read_to_string(processes_loc.to_str().unwrap()).unwrap_or_default();
// Look up the jps map by suffix to support both the current `jps-map.json` and the
// legacy `<run_name>-jps-map.json` naming.
let processes_json = match find_file(&params.data_dir, r"jps-map\.json$", None) {
Ok(processes_json_path) => {
fs::read_to_string(params.data_dir.join(processes_json_path)).unwrap_or_default()
}
Err(e) => {
error!("{e}");
String::default()
}
};
let process_map: HashMap<String, Vec<String>> =
serde_json::from_str(&processes_json).unwrap_or_default();

Expand Down Expand Up @@ -446,34 +446,32 @@ impl ProcessData for JavaProfile {
// Copy jfrconv-generated HTML graphs for this process to the report data dir
// and build the GraphData (backward compatibility).
for &metric in &profile_metrics {
let filename = if metric == "legacy" {
let filename_suffix = if metric == "legacy" {
// backward compatibility - previous versions generated a single flamegraph
format!("{}-java-flamegraph-{}.html", params.run_name, process)
format!("java-flamegraph-{}.html", process)
} else {
format!(
"{}-java-profile-{}-{}.html",
params.run_name, process, metric
)
format!("java-profile-{}-{}.html", process, metric)
};
copy_graph_and_update_graph_data(
&params.data_dir,
&params.report_dir,
&filename,
metric,
&deduped_name,
format!("({}) JVM: {}", metric, deduped_name),
&mut graph_data,
);
let filename_pattern = format!("{}$", regex::escape(&filename_suffix));
if let Ok(filename) = find_file(&params.data_dir, &filename_pattern, None) {
copy_graph_and_update_graph_data(
&params.data_dir,
&params.report_dir,
&filename,
metric,
&deduped_name,
format!("({}) JVM: {}", metric, deduped_name),
&mut graph_data,
);
}
}

// Deserialize the ProfilerData generated at the end of recording.
let profiler_data_path = params.data_dir.join(format!(
"{}-java-profile-{}-profiler-data.json",
params.run_name, process
));
let mut profiler = match fs::read_to_string(&profiler_data_path)
.ok()
.and_then(|json| serde_json::from_str::<Profiler>(&json).ok())
let mut profiler = match fs::read_to_string(
params.data_dir.join(java_profiler_data_filename(process)),
)
.ok()
.and_then(|json| serde_json::from_str::<Profiler>(&json).ok())
{
Some(profiler) => profiler,
None => continue,
Expand Down
Loading
Loading