Skip to main content

rustorb_core/
trace.rs

1//! Trace output: what the ORB does, for finding interoperability and
2//! configuration problems (docs/tracing.md).
3//!
4//! The core reports its events through the [`tracing`] crate, with the
5//! module of each event as its target (`rustorb_core::connection`,
6//! `rustorb_core::server`, ...). An application that has set a global
7//! `tracing` subscriber receives every event and filters them itself.
8//! Without one, the events the [trace level](set_trace_level) selects are
9//! written to standard error, one line each, like omniORB's
10//! `-ORBtraceLevel`:
11//!
12//! | Level | `tracing` level | Events |
13//! | --- | --- | --- |
14//! | 0 | | none |
15//! | 1 (default) | `WARN` | servant and servant manager panics, failures the application should know of |
16//! | 5 | `INFO` | connections opened, accepted and closed; endpoints; `LOCATION_FORWARD` followed; POAs created and destroyed |
17//! | 10 | `DEBUG` | each request and its reply or system exception, client and server; objects activated and deactivated |
18//! | 25 | `TRACE` | each GIOP message sent and received: type, size and version |
19//!
20//! A level includes the events of the levels below it.
21
22use std::fmt;
23use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
24use std::time::{SystemTime, UNIX_EPOCH};
25
26pub use tracing::Level;
27
28/// The trace level of a `tracing` level: the lowest
29/// [trace level](set_trace_level) that selects it.
30pub const fn trace_level_of(level: Level) -> u32 {
31    match level {
32        Level::ERROR | Level::WARN => 1,
33        Level::INFO => 5,
34        Level::DEBUG => 10,
35        Level::TRACE => 25,
36    }
37}
38
39static LEVEL: AtomicU32 = AtomicU32::new(1);
40static TIME: AtomicBool = AtomicBool::new(false);
41
42/// Sets the trace level for the whole process (`-ORBtraceLevel N`; see
43/// the [module](self) for what each level selects). It decides what goes
44/// to standard error when no global `tracing` subscriber is set, and what
45/// the Python binding hands to `logging`; a subscriber of the application
46/// filters with its own settings.
47pub fn set_trace_level(level: u32) {
48    LEVEL.store(level, Ordering::Relaxed);
49}
50
51/// The trace level [`set_trace_level`] set; 1 at first.
52pub fn trace_level() -> u32 {
53    LEVEL.load(Ordering::Relaxed)
54}
55
56/// Whether trace lines on standard error start with the time, in UTC
57/// (`-ORBtraceTime 0|1`).
58pub fn set_trace_time(on: bool) {
59    TIME.store(on, Ordering::Relaxed);
60}
61
62/// Whether the trace level selects events of `level`.
63pub fn selects(level: Level) -> bool {
64    trace_level() >= trace_level_of(level)
65}
66
67/// Whether an event of `level` goes to standard error: the trace level
68/// selects it and no global subscriber is set.
69#[inline]
70pub(crate) fn to_stderr(level: Level) -> bool {
71    selects(level) && !tracing::dispatcher::has_been_set()
72}
73
74/// Writes one trace line to standard error.
75#[cold]
76pub(crate) fn write_stderr(level: Level, args: fmt::Arguments<'_>) {
77    eprintln!("{}", line(level, args, TIME.load(Ordering::Relaxed)));
78}
79
80/// The line for `message` that standard error would get:
81/// `rustorb: <level>: <message>`, after the time with
82/// [`set_trace_time`]. For bindings that write trace lines themselves.
83pub fn stderr_line(level: Level, message: &str) -> String {
84    line(
85        level,
86        format_args!("{message}"),
87        TIME.load(Ordering::Relaxed),
88    )
89}
90
91/// The text of a trace line: `rustorb: <level>: <message>`, after the time
92/// when `time` is set.
93fn line(level: Level, args: fmt::Arguments<'_>, time: bool) -> String {
94    let name = level_name(level);
95    if time {
96        format!("{} rustorb: {name}: {args}", utc_now())
97    } else {
98        format!("rustorb: {name}: {args}")
99    }
100}
101
102/// The name of `level` in trace lines (and in the Python binding).
103pub fn level_name(level: Level) -> &'static str {
104    match level {
105        Level::ERROR => "error",
106        Level::WARN => "warning",
107        Level::INFO => "info",
108        Level::DEBUG => "debug",
109        Level::TRACE => "trace",
110    }
111}
112
113/// The current time as `YYYY-MM-DD hh:mm:ss.uuuuuu`, UTC.
114fn utc_now() -> String {
115    let now = SystemTime::now()
116        .duration_since(UNIX_EPOCH)
117        .unwrap_or_default();
118    format_utc(now.as_secs(), now.subsec_micros())
119}
120
121fn format_utc(secs: u64, micros: u32) -> String {
122    let days = (secs / 86_400) as i64;
123    let rem = secs % 86_400;
124    let (y, m, d) = civil_from_days(days);
125    format!(
126        "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}.{micros:06}",
127        rem / 3600,
128        rem / 60 % 60,
129        rem % 60
130    )
131}
132
133/// The proleptic Gregorian date of a day count since 1970-01-01.
134fn civil_from_days(z: i64) -> (i64, u32, u32) {
135    let z = z + 719_468;
136    let era = z.div_euclid(146_097);
137    let doe = z.rem_euclid(146_097);
138    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
139    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
140    let mp = (5 * doy + 2) / 153;
141    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
142    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
143    let y = yoe + era * 400 + i64::from(m <= 2);
144    (y, m, d)
145}
146
147/// Reports an event: to the `tracing` subscriber, or to standard error
148/// when there is none and the trace level selects it. The arguments are
149/// evaluated only when the event goes somewhere.
150macro_rules! event {
151    ($level:ident, $($arg:tt)+) => {
152        if $crate::trace::to_stderr(::tracing::Level::$level) {
153            $crate::trace::write_stderr(::tracing::Level::$level, format_args!($($arg)+));
154        } else {
155            ::tracing::event!(::tracing::Level::$level, $($arg)+);
156        }
157    };
158}
159
160macro_rules! warning {
161    ($($arg:tt)+) => { $crate::trace::event!(WARN, $($arg)+) };
162}
163
164macro_rules! info {
165    ($($arg:tt)+) => { $crate::trace::event!(INFO, $($arg)+) };
166}
167
168macro_rules! debug {
169    ($($arg:tt)+) => { $crate::trace::event!(DEBUG, $($arg)+) };
170}
171
172macro_rules! trace {
173    ($($arg:tt)+) => { $crate::trace::event!(TRACE, $($arg)+) };
174}
175
176pub(crate) use {debug, event, info, trace, warning};
177
178/// The name of a GIOP message type in trace lines, from the type octet of
179/// its header.
180pub(crate) fn message_type_name(octet: u8) -> &'static str {
181    match octet {
182        0 => "Request",
183        1 => "Reply",
184        2 => "CancelRequest",
185        3 => "LocateRequest",
186        4 => "LocateReply",
187        5 => "CloseConnection",
188        6 => "MessageError",
189        7 => "Fragment",
190        _ => "unknown",
191    }
192}
193
194/// The type, version and size of a whole message (header included), for
195/// trace lines: `Request (GIOP 1.2, 120 bytes)`.
196pub(crate) struct MessageSummary<'a>(pub(crate) &'a [u8], pub(crate) usize);
197
198impl fmt::Display for MessageSummary<'_> {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        let MessageSummary(head, len) = *self;
201        match head {
202            [b'G', b'I', b'O', b'P', major, minor, _, kind, ..] => write!(
203                f,
204                "{} (GIOP {major}.{minor}, {len} bytes)",
205                message_type_name(*kind)
206            ),
207            _ => write!(f, "a message of {len} bytes"),
208        }
209    }
210}
211
212/// An object reference in trace lines: its type and first IIOP address,
213/// `IDL:Echo:1.0 at host:port`.
214pub(crate) struct IorSummary<'a>(pub(crate) &'a rustorb_giop::Ior);
215
216impl fmt::Display for IorSummary<'_> {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        let ior = self.0;
219        if ior.is_nil() {
220            return f.write_str("a nil reference");
221        }
222        let id = if ior.type_id.is_empty() {
223            "an object"
224        } else {
225            &ior.type_id
226        };
227        let first = ior
228            .profiles
229            .iter()
230            .filter(|p| p.tag == rustorb_giop::TAG_INTERNET_IOP)
231            .find_map(|p| p.iiop().ok());
232        match first {
233            Some(iiop) => write!(f, "{id} at {}:{}", iiop.host, iiop.port),
234            None => write!(f, "{id} (no IIOP profile)"),
235        }
236    }
237}
238
239/// An ObjectId in trace lines: as text when it is printable ASCII, else
240/// in hex.
241pub(crate) struct IdSummary<'a>(pub(crate) &'a [u8]);
242
243impl fmt::Display for IdSummary<'_> {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        let id = self.0;
246        if !id.is_empty() && id.iter().all(|b| b.is_ascii_graphic() || *b == b' ') {
247            write!(f, "{:?}", String::from_utf8_lossy(id))
248        } else {
249            f.write_str("0x")?;
250            id.iter().try_for_each(|b| write!(f, "{b:02x}"))
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn utc_dates() {
261        assert_eq!(format_utc(0, 0), "1970-01-01 00:00:00.000000");
262        assert_eq!(format_utc(951_782_400, 5), "2000-02-29 00:00:00.000005");
263        assert_eq!(
264            format_utc(1_793_569_356, 123_456),
265            "2026-11-01 21:42:36.123456"
266        );
267    }
268
269    #[test]
270    fn lines() {
271        assert_eq!(
272            line(Level::WARN, format_args!("x {}", 1), false),
273            "rustorb: warning: x 1"
274        );
275        assert!(line(Level::INFO, format_args!("y"), true).ends_with(" rustorb: info: y"));
276    }
277
278    #[test]
279    fn levels() {
280        assert_eq!(trace_level_of(Level::WARN), 1);
281        assert_eq!(trace_level_of(Level::TRACE), 25);
282        let msg = b"GIOP\x01\x02\x01\x00\x00\x00\x00\x00";
283        assert_eq!(IdSummary(b"Echo").to_string(), "\"Echo\"");
284        assert_eq!(IdSummary(&[0, 0xab]).to_string(), "0x00ab");
285        assert_eq!(
286            MessageSummary(msg, 12).to_string(),
287            "Request (GIOP 1.2, 12 bytes)"
288        );
289    }
290}