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
#![feature(decl_macro)]

#[macro_use] extern crate serde_derive;
#[macro_use] extern crate lazy_static;

use time::precise_time_ns;
use deflate::{
    Compression,
    write::GzEncoder,
};
use std::{
    borrow::Cow,
    time::Duration,
    fs::{remove_file, OpenOptions},
    io::{BufWriter, Write},
    thread::{spawn, sleep, JoinHandle},
    sync::mpsc::{channel, Sender},
    sync::atomic::{AtomicUsize, Ordering},
};

mod scope;
mod local;
mod global;
mod trace;
pub mod colors;

pub use self::scope::ScopeComplete;
pub use self::local::{Local, LOCAL};
pub use self::global::{Global, GLOBAL};
pub use self::trace::{Event, Base, Instant, Async, Args, Flow};

pub const ENABLED: bool = cfg!(feature = "trace");
pub const TRACE_LOC: bool = cfg!(feature = "trace_location");

pub fn generate_id() -> usize {
    static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
    NEXT_ID.fetch_add(1, Ordering::Relaxed)
}

use log::{Log, Metadata, Record};

pub struct Logger;

impl Log for Logger {
    fn enabled(&self, _metadata: &Metadata) -> bool {
        //metadata.level() <= Level::Info
        true
    }

    fn log(&self, record: &Record) {
        let ts = precise_time_ns();
        if self.enabled(record.metadata()) {
            LOCAL.with(|profiler| match *profiler.borrow() {
                Some(ref profiler) => profiler.log(ts, record),
                None => println!("ERROR: push_log on unregistered thread!"),
            });
        }
    }

    fn flush(&self) {}
}

pub struct AppendWorker {
    handle: Option<JoinHandle<()>>,
    tx: Sender<()>,
}

impl AppendWorker {
    pub fn new(filename: &str, duration: Duration) -> Self {
        let _ = remove_file(filename);
        let w = OpenOptions::new()
            .create_new(true)
            .append(true)
            .open(filename)
            .unwrap();

        let (tx, rx) = channel();
        let handle = spawn(move || {
            let encoder = GzEncoder::new(w, Compression::Default);
            let mut buf = BufWriter::new(encoder);
            buf.write(b"[\n").ok();

            loop {
                sleep(duration);
                GLOBAL.lock().unwrap().write_profile(&mut buf);
                buf.flush().ok();
                if rx.try_recv().is_ok() {
                    break;
                }
            }

            write_global_instant(&mut buf, "EOF");

            buf.write(b"]\n").ok();
            buf.flush().ok();
        });

        Self { handle: Some(handle), tx }
    }

    pub fn end(&mut self) {
        self.tx.send(()).unwrap();
        self.handle.take().unwrap().join().unwrap();
    }
}

fn write_global_instant<W: Write>(w: &mut W, name: &'static str) {
    let ts = precise_time_ns();
    serde_json::to_writer(w, &Event::Instant {
        s: "g",
        ts: ts / 1000,
        base: Base {
            name: name.into(),
            cat: None,
            pid: 0,
            tid: 0,
            args: Args::Empty,
            cname: Some(colors::WHITE),
        },
    }).ok();
}

/// Registers the current thread with the global profiler.
pub fn register_thread(pid: Option<usize>, sort_index: Option<usize>) {
    GLOBAL.lock().unwrap().register_thread(pid.unwrap_or(0), sort_index);
}

pub macro location() {
    if $crate::TRACE_LOC {
        $crate::Args::Location { module: module_path!(), file: file!(), line: line!() }
    } else {
        $crate::Args::Empty
    }
}

pub macro instant {
    (json $name:expr, $value:expr) => {
        if $crate::ENABLED {
            $crate::instant_thread($name, "", $crate::Args::Custom {
                value: $value,
            });
        }
    },
    ($name:expr) => {
        $crate::instant!($name => "");
    },
    ([ $($cat:ident)+ ] $name:expr) => {
        $crate::instant!($name => stringify!($($cat,)+));
    },
    ($cat:expr => $name:expr) => {
        if $crate::ENABLED {
            $crate::instant_thread($name, $cat, $crate::location!());
        }
    }
}

pub macro scope($($name:tt)+) {
    let _profile_scope = if $crate::ENABLED {
        Some($crate::ScopeComplete::new(stringify!($($name)+), location!()))
    } else {
        None
    };
}

#[doc(hidden)]
pub fn instant_thread(name: &'static str, cat: &'static str, args: Args) {
    let ts = precise_time_ns();
    LOCAL.with(|profiler| match *profiler.borrow() {
        Some(ref profiler) => profiler.instant_thread(ts, name, cat, args),
        None => println!("ERROR: instant_thread on unregistered thread!"),
    });
}

pub macro async_event {
    ($kind:ident, $name:expr, $cat:expr, $id:expr, $cname:expr) => {
        if $crate::ENABLED {
            let cat: Option<&'static str> = $cat;
            $crate::push_async($id, $name, $cat, $crate::Async::$kind, location!(), $cname);
        }
    }
}

pub macro async_start {
    ($name:expr, $cat:expr, $id:expr) =>              { $crate::async_event!(Start, $name, $cat, $id, None); },
    ($name:expr, $cat:expr, $id:expr, $cname:expr) => { $crate::async_event!(Start, $name, $cat, $id, Some($cname)); }
}

pub macro async_instant {
    ($name:expr, $cat:expr, $id:expr) =>              { $crate::async_event!(Start, $name, $cat, $id, None); },
    ($name:expr, $cat:expr, $id:expr, $cname:expr) => { $crate::async_event!(Start, $name, $cat, $id, Some($cname)); }
}

pub macro async_end {
    ($name:expr, $cat:expr, $id:expr) =>              { $crate::async_event!(Start, $name, $cat, $id, None); },
    ($name:expr, $cat:expr, $id:expr, $cname:expr) => { $crate::async_event!(Start, $name, $cat, $id, Some($cname)); }
}

#[doc(hidden)]
pub fn push_async<N, C>(
    id: usize,
    name: N,
    cat: Option<C>,
    kind: Async,
    args: Args,
    cname: Option<&'static str>,
)
    where
        N: Into<Cow<'static, str>>,
        C: Into<Cow<'static, str>>,
{
    let ts = precise_time_ns();
    LOCAL.with(|profiler| match *profiler.borrow() {
        Some(ref profiler) => profiler.async_event(kind, ts, id, name.into(), cat.map(Into::into), None, args, cname),
        None => println!("ERROR: push_async on unregistered thread!"),
    });
}

pub macro flow_event {
    ($kind:ident, $name:expr, $cat:expr, $id:expr, $cname:expr) => {
        if $crate::ENABLED {
            let cat: Option<&'static str> = $cat;
            $crate::push_flow($id, $name, cat, $crate::Flow::$kind, location!(), $cname);
        }
    }
}

pub macro flow_start {
    ($name:expr, $id:expr) =>              { $crate::flow_event!(Start, $name, None, $id, None); },
    ($name:expr, $id:expr, $cname:expr) => { $crate::flow_event!(Start, $name, None, $id, Some($cname)); }
}

pub macro flow_step {
    ($name:expr, $id:expr) =>              { $crate::flow_event!(Step, $name, None, $id, None); },
    ($name:expr, $id:expr, $cname:expr) => { $crate::flow_event!(Step, $name, None, $id, Some($cname)); }
}

pub macro flow_end {
    ($name:expr, $id:expr) =>              { $crate::flow_event!(End, $name, None, $id, None); },
    ($name:expr, $id:expr, $cname:expr) => { $crate::flow_event!(End, $name, None, $id, Some($cname)); }
}

#[doc(hidden)]
pub fn push_flow<N, C>(
    id: usize,
    name: N,
    cat: Option<C>,
    kind: Flow,
    args: Args,
    cname: Option<&'static str>,
)
    where
        N: Into<Cow<'static, str>>,
        C: Into<Cow<'static, str>>,
{
    let ts = precise_time_ns();
    LOCAL.with(|profiler| match *profiler.borrow() {
        Some(ref profiler) => profiler.flow_event(kind, ts, id, name.into(), cat.map(Into::into), args, cname),
        None => println!("ERROR: push_flow on unregistered thread!"),
    });
}