risingwave_common_heap_profiling/
profiler.rs1use std::ffi::CString;
16use std::fs;
17use std::path::Path;
18
19use parking_lot::Once;
20use risingwave_common::config::HeapProfilingConfig;
21use risingwave_common::util::resource_util;
22use tikv_jemalloc_ctl::{opt as jemalloc_opt, prof as jemalloc_prof};
23use tokio::time::{self, Duration};
24
25use super::AUTO_DUMP_SUFFIX;
26
27pub struct HeapProfiler {
31 config: HeapProfilingConfig,
32 threshold_auto_dump_heap_profile: usize,
33 jemalloc_dump_mib: jemalloc_prof::dump_mib,
34 opt_prof: bool,
36}
37
38impl HeapProfiler {
39 pub fn new(total_memory: usize, config: HeapProfilingConfig) -> Self {
45 let threshold_auto_dump_heap_profile =
46 (total_memory as f64 * config.threshold_auto as f64) as usize;
47 let jemalloc_dump_mib = jemalloc_prof::dump::mib().unwrap();
48 let opt_prof = jemalloc_opt::prof::read().unwrap();
49
50 Self {
51 config,
52 threshold_auto_dump_heap_profile,
53 jemalloc_dump_mib,
54 opt_prof,
55 }
56 }
57
58 fn auto_dump_heap_prof(&self) {
59 let time_prefix = chrono::Local::now().format("%Y-%m-%d-%H-%M-%S");
60 let file_name = format!("{}.{}", time_prefix, AUTO_DUMP_SUFFIX);
61
62 let file_path = Path::new(&self.config.dir)
63 .join(&file_name)
64 .to_str()
65 .expect("file path is not valid utf8")
66 .to_owned();
67 let file_path_c = CString::new(file_path).expect("0 byte in file path");
68
69 if let Err(e) = self
71 .jemalloc_dump_mib
72 .write(unsafe { &*(file_path_c.as_c_str() as *const _) })
73 {
74 tracing::warn!("Auto Jemalloc dump heap file failed! {:?}", e);
75 } else {
76 tracing::info!("Successfully dumped heap profile to {}", file_name);
77 }
78 }
79
80 pub fn start(self) {
82 if !self.config.enable_auto || !self.opt_prof {
83 tracing::info!("Auto memory dump is disabled.");
84 return;
85 }
86
87 static START: Once = Once::new();
88 START.call_once(|| {
89 fs::create_dir_all(&self.config.dir).unwrap();
90 tokio::spawn(async move {
91 let mut interval = time::interval(Duration::from_millis(500));
92 let mut prev_used_memory_bytes = 0;
93 loop {
94 interval.tick().await;
95 let cur_used_memory_bytes = resource_util::memory::total_memory_used_bytes();
96
97 if cur_used_memory_bytes > self.threshold_auto_dump_heap_profile
99 && prev_used_memory_bytes <= self.threshold_auto_dump_heap_profile
100 {
101 self.auto_dump_heap_prof();
102 }
103 prev_used_memory_bytes = cur_used_memory_bytes;
104 }
105 });
106 })
107 }
108}