bootstrap/utils/
tracing.rs

1//! Wrapper macros for `tracing` macros to avoid having to write `cfg(feature = "tracing")`-gated
2//! `debug!`/`trace!` everytime, e.g.
3//!
4//! ```rust,ignore (example)
5//! #[cfg(feature = "tracing")]
6//! trace!("...");
7//! ```
8//!
9//! When `feature = "tracing"` is inactive, these macros expand to nothing.
10
11#[macro_export]
12macro_rules! trace {
13    ($($tokens:tt)*) => {
14        #[cfg(feature = "tracing")]
15        ::tracing::trace!($($tokens)*)
16    }
17}
18
19#[macro_export]
20macro_rules! debug {
21    ($($tokens:tt)*) => {
22        #[cfg(feature = "tracing")]
23        ::tracing::debug!($($tokens)*)
24    }
25}
26
27#[macro_export]
28macro_rules! warn {
29    ($($tokens:tt)*) => {
30        #[cfg(feature = "tracing")]
31        ::tracing::warn!($($tokens)*)
32    }
33}
34
35#[macro_export]
36macro_rules! info {
37    ($($tokens:tt)*) => {
38        #[cfg(feature = "tracing")]
39        ::tracing::info!($($tokens)*)
40    }
41}
42
43#[macro_export]
44macro_rules! error {
45    ($($tokens:tt)*) => {
46        #[cfg(feature = "tracing")]
47        ::tracing::error!($($tokens)*)
48    }
49}
50
51#[cfg(feature = "tracing")]
52pub const IO_SPAN_TARGET: &str = "IO";
53
54/// Create a tracing span around an I/O operation, if tracing is enabled.
55/// Note that at least one tracing value field has to be passed to this macro, otherwise it will not
56/// compile.
57#[macro_export]
58macro_rules! trace_io {
59    ($name:expr, $($args:tt)*) => {
60        ::tracing::trace_span!(
61            target: $crate::utils::tracing::IO_SPAN_TARGET,
62            $name,
63            $($args)*,
64            location = $crate::utils::tracing::format_location(*::std::panic::Location::caller())
65        ).entered()
66    }
67}
68
69#[cfg(feature = "tracing")]
70pub fn format_location(location: std::panic::Location<'static>) -> String {
71    format!("{}:{}", location.file(), location.line())
72}
73
74#[cfg(feature = "tracing")]
75const COMMAND_SPAN_TARGET: &str = "COMMAND";
76
77#[cfg(feature = "tracing")]
78pub fn trace_cmd(command: &crate::BootstrapCommand) -> tracing::span::EnteredSpan {
79    let fingerprint = command.fingerprint();
80    let location = command.get_created_location();
81    let location = format_location(location);
82
83    tracing::span!(
84        target: COMMAND_SPAN_TARGET,
85        tracing::Level::TRACE,
86        "cmd",
87        cmd_name = fingerprint.program_name().to_string(),
88        cmd = fingerprint.format_short_cmd(),
89        full_cmd = ?command,
90        location
91    )
92    .entered()
93}
94
95// # Note on `tracing` usage in bootstrap
96//
97// Due to the conditional compilation via the `tracing` cargo feature, this means that `tracing`
98// usages in bootstrap need to be also gated behind the `tracing` feature:
99//
100// - `tracing` macros with log levels (`trace!`, `debug!`, `warn!`, `info`, `error`) should not be
101//   used *directly*. You should use the wrapped `tracing` macros which gate the actual invocations
102//   behind `feature = "tracing"`.
103// - `tracing`'s `#[instrument(..)]` macro will need to be gated like `#![cfg_attr(feature =
104//   "tracing", instrument(..))]`.
105#[cfg(feature = "tracing")]
106mod inner {
107    use std::fmt::Debug;
108    use std::fs::File;
109    use std::io::Write;
110    use std::path::{Path, PathBuf};
111    use std::sync::atomic::Ordering;
112
113    use chrono::{DateTime, Utc};
114    use tracing::field::{Field, Visit};
115    use tracing::{Event, Id, Level, Subscriber};
116    use tracing_subscriber::layer::{Context, SubscriberExt};
117    use tracing_subscriber::registry::{LookupSpan, SpanRef};
118    use tracing_subscriber::{EnvFilter, Layer};
119
120    use super::{COMMAND_SPAN_TARGET, IO_SPAN_TARGET};
121    use crate::STEP_SPAN_TARGET;
122
123    pub fn setup_tracing(env_name: &str) -> TracingGuard {
124        let filter = EnvFilter::from_env(env_name);
125
126        let registry = tracing_subscriber::registry().with(filter).with(TracingPrinter::default());
127
128        // When we're creating this layer, we do not yet know the location of the tracing output
129        // directory, because it is stored in the output directory determined after Config is parsed,
130        // but we already want to make tracing calls during (and before) config parsing.
131        // So we store the output into a temporary file, and then move it to the tracing directory
132        // before bootstrap ends.
133        let tempdir = tempfile::TempDir::new().expect("Cannot create temporary directory");
134        let chrome_tracing_path = tempdir.path().join("bootstrap-trace.json");
135        let file = std::io::BufWriter::new(File::create(&chrome_tracing_path).unwrap());
136
137        let chrome_layer = tracing_chrome::ChromeLayerBuilder::new()
138            .writer(file)
139            .include_args(true)
140            .name_fn(Box::new(|event_or_span| match event_or_span {
141                tracing_chrome::EventOrSpan::Event(e) => e.metadata().name().to_string(),
142                tracing_chrome::EventOrSpan::Span(s) => {
143                    if s.metadata().target() == STEP_SPAN_TARGET
144                        && let Some(extension) = s.extensions().get::<StepNameExtension>()
145                    {
146                        extension.0.clone()
147                    } else if s.metadata().target() == COMMAND_SPAN_TARGET
148                        && let Some(extension) = s.extensions().get::<CommandNameExtension>()
149                    {
150                        extension.0.clone()
151                    } else {
152                        s.metadata().name().to_string()
153                    }
154                }
155            }));
156        let (chrome_layer, guard) = chrome_layer.build();
157
158        tracing::subscriber::set_global_default(registry.with(chrome_layer)).unwrap();
159        TracingGuard { guard, _tempdir: tempdir, chrome_tracing_path }
160    }
161
162    pub struct TracingGuard {
163        guard: tracing_chrome::FlushGuard,
164        _tempdir: tempfile::TempDir,
165        chrome_tracing_path: std::path::PathBuf,
166    }
167
168    impl TracingGuard {
169        pub fn copy_to_dir(self, dir: &std::path::Path) {
170            drop(self.guard);
171            std::fs::rename(&self.chrome_tracing_path, dir.join("chrome-trace.json")).unwrap();
172        }
173    }
174
175    /// Visitor that extracts both known and unknown field values from events and spans.
176    #[derive(Default)]
177    struct FieldValues {
178        /// Main event message
179        message: Option<String>,
180        /// Name of a recorded psna
181        step_name: Option<String>,
182        /// Short name of an executed command
183        cmd_name: Option<String>,
184        /// The rest of arbitrary event/span fields
185        fields: Vec<(&'static str, String)>,
186    }
187
188    impl Visit for FieldValues {
189        /// Record fields if possible using `record_str`, to avoid rendering simple strings with
190        /// their `Debug` representation, which adds extra quotes.
191        fn record_str(&mut self, field: &Field, value: &str) {
192            match field.name() {
193                "step_name" => {
194                    self.step_name = Some(value.to_string());
195                }
196                "cmd_name" => {
197                    self.cmd_name = Some(value.to_string());
198                }
199                name => {
200                    self.fields.push((name, value.to_string()));
201                }
202            }
203        }
204
205        fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
206            let formatted = format!("{value:?}");
207            match field.name() {
208                "message" => {
209                    self.message = Some(formatted);
210                }
211                name => {
212                    self.fields.push((name, formatted));
213                }
214            }
215        }
216    }
217
218    #[derive(Copy, Clone)]
219    enum SpanAction {
220        Enter,
221    }
222
223    /// Holds the name of a step span, stored in `tracing_subscriber`'s extensions.
224    struct StepNameExtension(String);
225
226    /// Holds the name of a command span, stored in `tracing_subscriber`'s extensions.
227    struct CommandNameExtension(String);
228
229    #[derive(Default)]
230    struct TracingPrinter {
231        indent: std::sync::atomic::AtomicU32,
232        span_values: std::sync::Mutex<std::collections::HashMap<tracing::Id, FieldValues>>,
233    }
234
235    impl TracingPrinter {
236        fn format_header<W: Write>(
237            &self,
238            writer: &mut W,
239            time: DateTime<Utc>,
240            level: &Level,
241        ) -> std::io::Result<()> {
242            // Use a fixed-width timestamp without date, that shouldn't be very important
243            let timestamp = time.format("%H:%M:%S.%3f");
244            write!(writer, "{timestamp} ")?;
245            // Make sure that levels are aligned to the same number of characters, in order not to
246            // break the layout
247            write!(writer, "{level:>5} ")?;
248            write!(writer, "{}", " ".repeat(self.indent.load(Ordering::Relaxed) as usize))
249        }
250
251        fn write_event<W: Write>(&self, writer: &mut W, event: &Event<'_>) -> std::io::Result<()> {
252            let now = Utc::now();
253
254            self.format_header(writer, now, event.metadata().level())?;
255
256            let mut field_values = FieldValues::default();
257            event.record(&mut field_values);
258
259            if let Some(msg) = &field_values.message {
260                write!(writer, "{msg}")?;
261            }
262
263            if !field_values.fields.is_empty() {
264                if field_values.message.is_some() {
265                    write!(writer, " ")?;
266                }
267                write!(writer, "[")?;
268                for (index, (name, value)) in field_values.fields.iter().enumerate() {
269                    write!(writer, "{name} = {value}")?;
270                    if index < field_values.fields.len() - 1 {
271                        write!(writer, ", ")?;
272                    }
273                }
274                write!(writer, "]")?;
275            }
276            write_location(writer, event.metadata())?;
277            writeln!(writer)?;
278            Ok(())
279        }
280
281        fn write_span<W: Write, S>(
282            &self,
283            writer: &mut W,
284            span: SpanRef<'_, S>,
285            field_values: Option<&FieldValues>,
286            action: SpanAction,
287        ) -> std::io::Result<()>
288        where
289            S: for<'lookup> LookupSpan<'lookup>,
290        {
291            let now = Utc::now();
292
293            self.format_header(writer, now, span.metadata().level())?;
294            match action {
295                SpanAction::Enter => {
296                    write!(writer, "> ")?;
297                }
298            }
299
300            fn write_fields<'a, I: IntoIterator<Item = &'a (&'a str, String)>, W: Write>(
301                writer: &mut W,
302                iter: I,
303            ) -> std::io::Result<()> {
304                let items = iter.into_iter().collect::<Vec<_>>();
305                if !items.is_empty() {
306                    write!(writer, " [")?;
307                    for (index, (name, value)) in items.iter().enumerate() {
308                        write!(writer, "{name} = {value}")?;
309                        if index < items.len() - 1 {
310                            write!(writer, ", ")?;
311                        }
312                    }
313                    write!(writer, "]")?;
314                }
315                Ok(())
316            }
317
318            // Write fields while treating the "location" field specially, and assuming that it
319            // contains the source file location relevant to the span.
320            let write_with_location = |writer: &mut W| -> std::io::Result<()> {
321                if let Some(values) = field_values {
322                    write_fields(
323                        writer,
324                        values.fields.iter().filter(|(name, _)| *name != "location"),
325                    )?;
326                    let location =
327                        &values.fields.iter().find(|(name, _)| *name == "location").unwrap().1;
328                    let (filename, line) = location.rsplit_once(':').unwrap();
329                    let filename = shorten_filename(filename);
330                    write!(writer, " ({filename}:{line})",)?;
331                }
332                Ok(())
333            };
334
335            // We handle steps specially. We instrument them dynamically in `Builder::ensure`,
336            // and we want to have custom name for each step span. But tracing doesn't allow setting
337            // dynamic span names. So we detect step spans here and override their name.
338            match span.metadata().target() {
339                // Executed step
340                STEP_SPAN_TARGET => {
341                    let name =
342                        field_values.and_then(|v| v.step_name.as_deref()).unwrap_or(span.name());
343                    write!(writer, "{name}")?;
344
345                    // There should be only one more field called `args`
346                    if let Some(values) = field_values {
347                        let field = &values.fields[0];
348                        write!(writer, " {{{}}}", field.1)?;
349                    }
350                    write_location(writer, span.metadata())?;
351                }
352                // Executed command
353                COMMAND_SPAN_TARGET => {
354                    write!(writer, "{}", span.name())?;
355                    write_with_location(writer)?;
356                }
357                IO_SPAN_TARGET => {
358                    write!(writer, "{}", span.name())?;
359                    write_with_location(writer)?;
360                }
361                // Other span
362                _ => {
363                    write!(writer, "{}", span.name())?;
364                    if let Some(values) = field_values {
365                        write_fields(writer, values.fields.iter())?;
366                    }
367                    write_location(writer, span.metadata())?;
368                }
369            }
370
371            writeln!(writer)?;
372            Ok(())
373        }
374    }
375
376    fn write_location<W: Write>(
377        writer: &mut W,
378        metadata: &'static tracing::Metadata<'static>,
379    ) -> std::io::Result<()> {
380        if let Some(filename) = metadata.file() {
381            let filename = shorten_filename(filename);
382
383            write!(writer, " ({filename}")?;
384            if let Some(line) = metadata.line() {
385                write!(writer, ":{line}")?;
386            }
387            write!(writer, ")")?;
388        }
389        Ok(())
390    }
391
392    /// Keep only the module name and file name to make it shorter
393    fn shorten_filename(filename: &str) -> String {
394        Path::new(filename)
395            .components()
396            // Take last two path components
397            .rev()
398            .take(2)
399            .collect::<Vec<_>>()
400            .into_iter()
401            .rev()
402            .collect::<PathBuf>()
403            .display()
404            .to_string()
405    }
406
407    impl<S> Layer<S> for TracingPrinter
408    where
409        S: Subscriber,
410        S: for<'lookup> LookupSpan<'lookup>,
411    {
412        fn on_new_span(&self, attrs: &tracing::span::Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
413            // Record value of span fields
414            // Note that we do not implement changing values of span fields after they are created.
415            // For that we would also need to implement the `on_record` method
416            let mut field_values = FieldValues::default();
417            attrs.record(&mut field_values);
418
419            // We need to propagate the actual name of the span to the Chrome layer below, because
420            // it cannot access field values. We do that through extensions.
421            if attrs.metadata().target() == STEP_SPAN_TARGET
422                && let Some(step_name) = field_values.step_name.clone()
423            {
424                ctx.span(id).unwrap().extensions_mut().insert(StepNameExtension(step_name));
425            } else if attrs.metadata().target() == COMMAND_SPAN_TARGET
426                && let Some(cmd_name) = field_values.cmd_name.clone()
427            {
428                ctx.span(id).unwrap().extensions_mut().insert(CommandNameExtension(cmd_name));
429            }
430            self.span_values.lock().unwrap().insert(id.clone(), field_values);
431        }
432
433        fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
434            let mut writer = std::io::stderr().lock();
435            self.write_event(&mut writer, event).unwrap();
436        }
437
438        fn on_enter(&self, id: &Id, ctx: Context<'_, S>) {
439            if let Some(span) = ctx.span(id) {
440                let mut writer = std::io::stderr().lock();
441                let values = self.span_values.lock().unwrap();
442                let values = values.get(id);
443                self.write_span(&mut writer, span, values, SpanAction::Enter).unwrap();
444            }
445            self.indent.fetch_add(1, Ordering::Relaxed);
446        }
447
448        fn on_exit(&self, _id: &Id, _ctx: Context<'_, S>) {
449            self.indent.fetch_sub(1, Ordering::Relaxed);
450        }
451    }
452}
453
454#[cfg(feature = "tracing")]
455pub use inner::setup_tracing;