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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
prelude! {}
mod watcher;
pub use watcher::Watcher;
pub struct FullFactory<'a> {
factory: alloc_data::mem::Factory<'a>,
data: sync::RwLockWriteGuard<'a, Data>,
}
impl<'a> std::ops::Deref for FullFactory<'a> {
type Target = alloc_data::mem::Factory<'a>;
fn deref(&self) -> &Self::Target {
&self.factory
}
}
impl<'a> std::ops::DerefMut for FullFactory<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.factory
}
}
impl<'a> FullFactory<'a> {
pub fn new(callstack_is_rev: bool) -> Self {
Self {
factory: alloc_data::mem::Factory::new(callstack_is_rev),
data: get_mut().unwrap(),
}
}
pub fn build_new(&mut self, alloc: alloc::Builder) -> Res<()> {
self.data.build_new(alloc)
}
pub fn add_new(&mut self, alloc: Alloc) -> Res<()> {
self.data.add_new(alloc)
}
pub fn add_dead(&mut self, timestamp: time::SinceStart, uid: uid::Alloc) -> Res<()> {
self.data.add_dead(timestamp, uid)
}
pub fn fill_stats(&mut self) -> Res<()> {
self.data.fill_stats()
}
pub fn mark_timestamp(&mut self, ts: time::SinceStart) {
self.data.mark_timestamp(ts)
}
}
pub fn start(target: impl AsRef<std::path::Path>) -> Res<()> {
Watcher::spawn(target, false);
Ok(())
}
lazy_static! {
static ref PROG: sync::RwLock<Option<LoadInfo>> = sync::RwLock::new(Some(LoadInfo::unknown()));
static ref DATA: sync::RwLock<Data> = sync::RwLock::new(Data::new());
static ref ERRORS: sync::RwLock<Vec<String>> = sync::RwLock::new(vec![]);
}
pub mod progress {
use super::*;
fn read<'a>() -> Res<sync::RwLockReadGuard<'a, Option<LoadInfo>>> {
PROG.read()
.map_err(|e| {
let e: err::Error = e.to_string().into();
e
})
.chain_err(|| "while reading the progress status")
}
fn write<'a>() -> Res<sync::RwLockWriteGuard<'a, Option<LoadInfo>>> {
PROG.write()
.map_err(|e| {
let e: err::Error = e.to_string().into();
e
})
.chain_err(|| "while writing the progress status")
}
pub fn set_unknown() -> Res<()> {
write().map(|mut prog| *prog = Some(LoadInfo::unknown()))
}
pub fn set_done() -> Res<()> {
*write()? = None;
Ok(())
}
pub fn set_total(total: usize) -> Res<()> {
let mut prog = write()?;
*prog = Some(LoadInfo { total, loaded: 0 });
Ok(())
}
pub fn set_loaded(loaded: usize) -> Res<()> {
let mut prog = write()?;
if let Some(prog) = prog.as_mut() {
prog.loaded = loaded;
}
Ok(())
}
pub fn inc_loaded() -> Res<()> {
if let Some(mut prog) = write()?.as_mut() {
prog.loaded += 1;
}
Ok(())
}
pub fn add_loaded(n: usize) -> Res<()> {
if let Some(mut prog) = write()?.as_mut() {
prog.loaded += n;
}
Ok(())
}
pub fn get() -> Res<Option<LoadInfo>> {
read().map(|info| info.clone())
}
}
pub fn get<'a>() -> Res<sync::RwLockReadGuard<'a, Data>> {
DATA.read()
.map_err(|e| {
let e: err::Error = e.to_string().into();
e
})
.chain_err(|| "while reading the global state")
}
pub fn alloc_count() -> Res<usize> {
get().map(|data| data.uid_map.len())
}
fn get_mut<'a>() -> Res<sync::RwLockWriteGuard<'a, Data>> {
DATA.write()
.map_err(|e| {
let e: err::Error = e.to_string().into();
e
})
.chain_err(|| "while reading the global state")
}
pub struct Data {
init: Option<alloc::Init>,
uid_map: uid::AllocMap<Alloc>,
tod_map: BTMap<time::SinceStart, BTSet<uid::Alloc>>,
current_time: time::SinceStart,
stats: Option<AllocStats>,
}
impl ops::Index<uid::Alloc> for Data {
type Output = Alloc;
fn index(&self, uid: uid::Alloc) -> &Alloc {
&self.uid_map[uid]
}
}
impl Data {
pub fn new() -> Self {
Self {
init: None,
uid_map: uid::AllocMap::new(),
tod_map: BTMap::new(),
current_time: time::SinceStart::zero(),
stats: None,
}
}
pub fn reserve(&mut self, capa: usize) {
self.uid_map.reserve(capa)
}
pub fn mark_timestamp(&mut self, ts: time::SinceStart) {
self.current_time = ts
}
pub fn init(&self) -> Option<&alloc::Init> {
self.init.as_ref()
}
pub fn has_init(&self) -> bool {
self.init().is_some()
}
pub fn alloc_count(&self) -> usize {
self.uid_map.len()
}
pub fn get_stats() -> Res<Option<AllocStats>> {
get().map(|data| data.stats())
}
pub fn stats(&self) -> Option<AllocStats> {
self.stats.clone()
}
pub fn current_time(&self) -> &time::SinceStart {
&self.current_time
}
pub fn start_time(&self) -> Res<time::Date> {
if let Some(init) = self.init.as_ref() {
Ok(init.start_time.clone())
} else {
bail!("cannot access start time")
}
}
pub fn get_alloc(&self, uid: uid::Alloc) -> Option<&Alloc> {
self.uid_map.get(uid)
}
pub fn iter_allocs(&self) -> impl Iterator<Item = &Alloc> {
self.uid_map.iter()
}
pub fn has_new_stuff_since(&self, time: Option<(uid::Alloc, time::SinceStart)>) -> bool {
if let Some((uid, tod)) = time {
self.uid_map[uid..].is_empty() || self.tod_map.keys().rev().next() != Some(&tod)
} else {
!self.uid_map.is_empty()
}
}
pub fn last_events(&self) -> Option<(uid::Alloc, time::SinceStart)> {
self.uid_map.last().map(|alloc| {
(
alloc.0,
self.tod_map
.keys()
.cloned()
.last()
.unwrap_or_else(time::SinceStart::zero),
)
})
}
pub fn iter_new_events<'me>(
&'me self,
since: Option<(uid::Alloc, time::SinceStart)>,
mut action: impl FnMut(Either<&'me Alloc, (time::SinceStart, &'me Alloc)>) -> Res<bool>,
) -> Res<()> {
let (mut new_iter, mut dead_iter) = if let Some((last_alloc, last_time)) = since {
let mut alloc_iter = self.uid_map[last_alloc..].iter();
let _alloc = alloc_iter.next();
debug_assert!(_alloc.unwrap().uid == last_alloc);
let last_time = last_time + time::SinceStart::from_nano_timestamp(0, 1);
(alloc_iter, self.tod_map.range(last_time..))
} else {
(
self.uid_map.iter(),
self.tod_map.range(time::SinceStart::zero()..),
)
};
let (mut next_new, mut next_dead) = (new_iter.next(), dead_iter.next());
let mut keep_going = true;
macro_rules! work {
(new: $alloc:expr) => {{
let cont = action(Either::Left($alloc))?;
if !cont {
keep_going = false
}
next_new = new_iter.next();
}};
(dead: $tod:expr, $uids:expr) => {{
for uid in $uids {
let alloc = &self.uid_map[*uid];
let cont = action(Either::Right(($tod, alloc)))?;
if !cont {
keep_going = false
}
}
next_dead = dead_iter.next();
}};
}
while keep_going {
match (next_new, next_dead) {
(Some(alloc), None) => {
work!(new: alloc);
next_dead = None;
}
(None, Some((tod, uids))) => {
work!(dead: *tod, uids);
next_new = None;
}
(Some(alloc), Some((tod, uids))) => {
if &alloc.toc <= tod {
work!(new: alloc);
next_dead = Some((tod, uids));
} else {
work!(dead: *tod, uids);
next_new = Some(alloc);
}
}
(None, None) => break,
}
}
Ok(())
}
}
impl Data {
fn tod_map_get_mut(&mut self, time: time::SinceStart) -> &mut AllocUidSet {
self.tod_map.entry(time).or_insert_with(AllocUidSet::new)
}
pub fn stats_do(&mut self, action: impl FnOnce(&mut AllocStats)) {
if let Some(stats) = self.stats.as_mut() {
action(stats)
}
}
pub fn fill_stats(&mut self) -> Res<()> {
let stats = self
.stats
.as_mut()
.ok_or_else(|| "[charts data] trying to fill stats of uninitialized data")?;
stats.alloc_count = self.uid_map.len();
stats.duration = self.current_time;
Ok(())
}
pub fn reset(&mut self, dump_dir: impl Into<std::path::PathBuf>, init: alloc::Init) {
self.stats = Some(AllocStats::new(dump_dir, init.start_time));
self.init = Some(init);
self.uid_map.clear();
self.tod_map.clear();
self.current_time = time::SinceStart::zero();
}
pub fn build_new(&mut self, alloc: alloc::Builder) -> Res<()> {
if self.current_time != alloc.toc {
self.current_time = alloc.toc.clone()
}
let uid = self.uid_map.next_index();
let alloc = alloc.build(
&self
.init
.as_ref()
.ok_or_else(|| "trying to build allocation without initialization")?
.sample_rate,
uid,
)?;
self.add_new(alloc)
}
pub fn add_new(&mut self, alloc: Alloc) -> Res<()> {
self.stats
.as_mut()
.ok_or_else(|| "trying to add allocation before initialization")?
.total_size += alloc.real_size as u64;
self.current_time = alloc.toc;
let uid = self.uid_map.next_index();
if uid != alloc.uid {
bail!(
"unexpected allocation index {}, expected {}",
alloc.uid,
uid
)
}
if let Some(tod) = alloc.tod.clone() {
self.add_dead(tod, uid.clone())?
}
let uid_check = self.uid_map.push(alloc);
debug_assert!(uid == uid_check);
Ok(())
}
pub fn add_dead(&mut self, timestamp: time::SinceStart, uid: uid::Alloc) -> Res<()> {
self.uid_map[uid].set_tod(timestamp)?;
self.current_time = timestamp;
let is_new = self.tod_map_get_mut(timestamp).insert(uid.clone());
if !is_new {
bail!(
"allocation UID collision (1): two allocations have UID #{}",
uid
)
}
Ok(())
}
pub fn add_diff(&mut self, diff: alloc::Diff) -> Res<()> {
self.current_time = diff.time;
if let Some(stats) = self.stats.as_mut() {
stats.alloc_count += diff.new.len();
stats.duration = diff.time;
} else {
if self.init.is_some() {
bail!("inconsistent state, adding diff to data with init but no statistics")
} else {
bail!("inconsistent state, adding diff to data with no init")
}
}
for alloc in diff.new {
self.build_new(alloc)?
}
for (uid, tod) in diff.dead {
self.add_dead(tod, uid)?
}
self.check_invariants().chain_err(|| "after adding diff")?;
Ok(())
}
#[cfg(not(debug_assertions))]
#[inline(always)]
fn check_invariants(&self) -> Res<()> {
Ok(())
}
#[cfg(debug_assertions)]
fn check_invariants(&self) -> Res<()> {
invariants::uid_order_is_toc_order(self)?;
Ok(())
}
}
pub fn add_diff(diff: alloc::Diff) -> Res<()> {
let mut data = get_mut().chain_err(|| "while registering a diff")?;
data.add_diff(diff)?;
Ok(())
}
pub mod invariants {
use super::*;
pub fn uid_order_is_toc_order(data: &Data) -> Res<()> {
let uid_map = &data.uid_map;
let mut prev_toc = None;
for alloc in uid_map.iter() {
if let Some(prev_toc) = prev_toc {
if prev_toc > &alloc.toc {
bail!("[data::invariants::uid_order_is_toc_order] invariant does not hold")
}
}
prev_toc = Some(&alloc.toc)
}
Ok(())
}
}