1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use super::error::{ProfError, ProfResult};
use crate::AllocStats;
use libc::{self, c_char, c_void};
use std::collections::HashMap;
use std::{ptr, slice, sync::Mutex, thread};
use tikv_jemalloc_ctl::{epoch, stats, Error};
use tikv_jemalloc_sys::malloc_stats_print;
pub type Allocator = tikv_jemallocator::Jemalloc;
pub const fn allocator() -> Allocator {
tikv_jemallocator::Jemalloc
}
lazy_static! {
static ref THREAD_MEMORY_MAP: Mutex<HashMap<ThreadId, MemoryStatsAccessor>> =
Mutex::new(HashMap::new());
}
struct MemoryStatsAccessor {
thread_name: String,
}
pub fn add_thread_memory_accessor() {
let mut thread_memory_map = THREAD_MEMORY_MAP.lock().unwrap();
thread_memory_map.insert(
thread::current().id(),
MemoryStatsAccessor {
thread_name: thread::current().name().unwrap().to_string(),
},
);
}
pub fn remove_thread_memory_accessor() {
let mut thread_memory_map = THREAD_MEMORY_MAP.lock().unwrap();
thread_memory_map.remove(&thread::current().id());
}
pub use self::profiling::{activate_prof, deactivate_prof, dump_prof};
use std::thread::ThreadId;
pub fn dump_stats() -> String {
let mut buf = Vec::with_capacity(1024);
unsafe {
malloc_stats_print(
Some(write_cb),
&mut buf as *mut Vec<u8> as *mut c_void,
ptr::null(),
);
}
let mut memory_stats = format!(
"Memory stats summary: {}\n",
String::from_utf8_lossy(&buf).into_owned()
);
memory_stats.push_str("Memory stats by thread:\n");
let thread_memory_map = THREAD_MEMORY_MAP.lock().unwrap();
for (_, accessor) in thread_memory_map.iter() {
memory_stats.push_str(format!("Thread [{}]: \n", accessor.thread_name).as_str());
}
memory_stats
}
pub fn fetch_stats() -> Result<Option<AllocStats>, Error> {
epoch::advance()?;
Ok(Some(vec![
("allocated", stats::allocated::read()?),
("active", stats::active::read()?),
("metadata", stats::metadata::read()?),
("resident", stats::resident::read()?),
("mapped", stats::mapped::read()?),
("retained", stats::retained::read()?),
(
"dirty",
stats::resident::read()? - stats::active::read()? - stats::metadata::read()?,
),
(
"fragmentation",
stats::active::read()? - stats::allocated::read()?,
),
]))
}
#[allow(clippy::cast_ptr_alignment)]
extern "C" fn write_cb(printer: *mut c_void, msg: *const c_char) {
unsafe {
let buf = &mut *(printer as *mut Vec<u8>);
let len = libc::strlen(msg);
let bytes = slice::from_raw_parts(msg as *const u8, len);
buf.extend_from_slice(bytes);
}
}
#[cfg(test)]
mod tests {
#[test]
fn dump_stats() {
assert_ne!(super::dump_stats().len(), 0);
}
}
#[cfg(feature = "mem-profiling")]
mod profiling {
use std::ffi::CString;
use libc::c_char;
use super::{ProfError, ProfResult};
const PROF_ACTIVE: &[u8] = b"prof.active\0";
const PROF_DUMP: &[u8] = b"prof.dump\0";
pub fn activate_prof() -> ProfResult<()> {
info!("start profiler");
unsafe {
if let Err(e) = tikv_jemalloc_ctl::raw::update(PROF_ACTIVE, true) {
error!("failed to activate profiling: {}", e);
return Err(ProfError::JemallocError(format!(
"failed to activate profiling: {}",
e
)));
}
}
Ok(())
}
pub fn deactivate_prof() -> ProfResult<()> {
info!("stop profiler");
unsafe {
if let Err(e) = tikv_jemalloc_ctl::raw::update(PROF_ACTIVE, false) {
error!("failed to deactivate profiling: {}", e);
return Err(ProfError::JemallocError(format!(
"failed to deactivate profiling: {}",
e
)));
}
}
Ok(())
}
pub fn dump_prof(path: &str) -> ProfResult<()> {
let mut bytes = CString::new(path)?.into_bytes_with_nul();
let ptr = bytes.as_mut_ptr() as *mut c_char;
let res = unsafe { tikv_jemalloc_ctl::raw::write(PROF_DUMP, ptr) };
match res {
Err(e) => {
error!("failed to dump the profile to {:?}: {}", path, e);
Err(ProfError::JemallocError(format!(
"failed to dump the profile to {:?}: {}",
path, e
)))
}
Ok(_) => {
info!("dump profile to {}", path);
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::Builder;
const OPT_PROF: &[u8] = b"opt.prof\0";
fn is_profiling_on() -> bool {
match unsafe { tikv_jemalloc_ctl::raw::read(OPT_PROF) } {
Err(e) => {
panic!("is_profiling_on: {:?}", e);
}
Ok(prof) => prof,
}
}
#[test]
#[ignore]
fn test_profiling_memory() {
assert!(is_profiling_on(), r#"Set MALLOC_CONF="prof:true""#);
let dir = Builder::new()
.prefix("test_profiling_memory")
.tempdir()
.unwrap();
let os_path = dir.path().to_path_buf().join("test1.dump").into_os_string();
let path = os_path.into_string().unwrap();
super::dump_prof(&path).unwrap();
let os_path = dir.path().to_path_buf().join("test2.dump").into_os_string();
let path = os_path.into_string().unwrap();
super::dump_prof(&path).unwrap();
let files = fs::read_dir(dir.path()).unwrap().count();
assert_eq!(files, 2);
let mut prof_count = 0;
for file_entry in fs::read_dir(dir.path()).unwrap() {
let file_entry = file_entry.unwrap();
let path = file_entry.path().to_str().unwrap().to_owned();
if path.contains("test1.dump") || path.contains("test2.dump") {
let metadata = file_entry.metadata().unwrap();
let file_len = metadata.len();
assert!(file_len > 10);
prof_count += 1
}
}
assert_eq!(prof_count, 2);
}
}
}
#[cfg(not(feature = "mem-profiling"))]
mod profiling {
use super::{ProfError, ProfResult};
pub fn dump_prof(_path: &str) -> ProfResult<()> {
Err(ProfError::MemProfilingNotEnabled)
}
pub fn activate_prof() -> ProfResult<()> {
Err(ProfError::MemProfilingNotEnabled)
}
pub fn deactivate_prof() -> ProfResult<()> {
Err(ProfError::MemProfilingNotEnabled)
}
}