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
use crate::absolute_time;
use parking_lot::Mutex;
use serde::Serialize;
use std::sync::atomic::{AtomicU32, Ordering};
use std::{
env,
fs::{self, File},
io::{self, Write as _},
path::PathBuf,
process,
time::{Duration, Instant},
};
const LOGS_ROTATION: Duration = Duration::from_secs(30);
pub fn is_enabled() -> bool {
*LOGGING_ENABLED
}
pub fn log_poll(
task_name: &str,
task_id: u64,
start: Instant,
end: Instant,
first_time: bool,
last_time: bool,
) {
if !is_enabled() {
return;
}
let tid = current_thread_id();
let start_ts = absolute_time::elapsed_since_abs_time(start) / 1_000;
let end_ts = absolute_time::elapsed_since_abs_time(end) / 1_000;
let cname = None;
write_record(&Record {
cat: "polling",
name: task_name,
ph: "B",
pid: 0,
tid,
ts: start_ts,
dur: None,
bp: None,
id: None,
arg: None,
cname,
});
if !(first_time && last_time) {
write_record(&Record {
cat: "polling",
name: task_name,
ph: if first_time {
"s"
} else if last_time {
"f"
} else {
"t"
},
pid: 0,
tid,
ts: if first_time { end_ts } else { start_ts },
dur: None,
bp: Some("e"),
id: Some(task_id),
arg: None,
cname: None,
});
}
write_record(&Record {
cat: "polling",
name: task_name,
ph: "E",
pid: 0,
tid,
ts: end_ts,
dur: None,
bp: None,
id: None,
arg: None,
cname,
});
}
pub fn log_wake_up(task_name: &str, _task_id: u64) {
if !is_enabled() {
return;
}
write_record(&Record {
cat: "wakeup",
name: task_name,
ph: "i",
pid: 0,
tid: current_thread_id(),
ts: absolute_time::now_since_abs_time() / 1_000,
dur: None,
id: None,
bp: None,
arg: None,
cname: None,
});
}
fn current_thread_id() -> u32 {
lazy_static::lazy_static! {
static ref NEXT_THREAD_ID: AtomicU32 = AtomicU32::new(0);
}
thread_local! {
static THREAD_ID: u32 = NEXT_THREAD_ID.fetch_add(1, Ordering::Relaxed);
}
THREAD_ID.with(|id| *id)
}
fn write_record(record: &Record) {
let mut serialized = serde_json::to_vec(&record).unwrap();
serialized.extend_from_slice(b",\n");
let mut output = OUTPUT.lock();
let output = match output.as_mut() {
Some(o) => o,
None => return,
};
if output.next_rotation <= Instant::now() {
output.file.sync_all().unwrap();
let source_path = output.out_directory.join("profile.json");
fs::rename(
&source_path,
output
.out_directory
.join(format!("profile.{}.{}.json", process::id(), output.next_filename_suffix)),
)
.unwrap();
output.file = File::create(&source_path).unwrap();
output.file.write_all(b"[\n").unwrap();
output.next_filename_suffix += 1;
output.next_rotation += LOGS_ROTATION;
}
output.file.write_all(&serialized).unwrap();
}
lazy_static::lazy_static! {
static ref LOGGING_ENABLED: bool = env::var_os("PROFILE_DIR").is_some();
static ref OUTPUT: Mutex<Option<OutputState>> = {
let out_directory = if let Some(v) = env::var_os("PROFILE_DIR") {
PathBuf::from(v)
} else {
return Mutex::new(None)
};
match fs::create_dir(&out_directory) {
Ok(()) => {}
Err(ref err) if err.kind() == io::ErrorKind::AlreadyExists => {},
Err(err) => panic!("{:?}", err),
};
let mut file = File::create(out_directory.join("profile.json")).unwrap();
file.write_all(b"[\n").unwrap();
Mutex::new(Some(OutputState {
file,
out_directory,
next_filename_suffix: 0,
next_rotation: Instant::now() + LOGS_ROTATION,
}))
};
}
struct OutputState {
file: File,
out_directory: PathBuf,
next_filename_suffix: u32,
next_rotation: Instant,
}
#[derive(Serialize)]
struct Record<'a> {
cat: &'a str,
name: &'a str,
ph: &'static str,
pid: u32,
tid: u32,
ts: u64,
#[serde(skip_serializing_if = "Option::is_none")]
dur: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
bp: Option<&'a str>,
arg: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
cname: Option<&'a str>,
}