stratus/infra/tracing/
tracing_config.rs

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
use std::collections::HashMap;
use std::io::stdout;
use std::io::IsTerminal;
use std::net::SocketAddr;
use std::str::FromStr;

use anyhow::anyhow;
use clap::Parser;
use console_subscriber::ConsoleLayer;
use display_json::DebugAsJson;
use itertools::Itertools;
use opentelemetry::KeyValue;
use opentelemetry_otlp::Protocol;
use opentelemetry_otlp::SpanExporterBuilder;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::runtime;
use opentelemetry_sdk::trace;
use opentelemetry_sdk::trace::BatchConfigBuilder;
use opentelemetry_sdk::trace::Tracer as SdkTracer;
use opentelemetry_sdk::Resource as SdkResource;
use tonic::metadata::MetadataKey;
use tonic::metadata::MetadataMap;
use tracing_subscriber::fmt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::Layer;

use crate::ext::spawn_named;
use crate::infra::build_info;
use crate::infra::sentry::SentryConfig;
use crate::infra::tracing::TracingContextLayer;
use crate::infra::tracing::TracingJsonFormatter;
use crate::infra::tracing::TracingMinimalTimer;

// -----------------------------------------------------------------------------
// Config
// -----------------------------------------------------------------------------

#[derive(DebugAsJson, Clone, Parser, serde::Serialize)]
pub struct TracingConfig {
    /// OpenTelemetry server URL.
    #[arg(long = "tracing-url", alias = "tracing-collector-url", env = "TRACING_URL")]
    pub tracing_url: Option<String>,

    /// OpenTelemetry server communication protocol.
    #[arg(long = "tracing-protocol", env = "TRACING_PROTOCOL", default_value = "grpc")]
    pub tracing_protocol: TracingProtocol,

    /// OpenTelemetry additional HTTP headers or GRPC metadata.
    #[arg(long = "tracing-headers", env = "TRACING_HEADERS", value_delimiter = ',')]
    pub tracing_headers: Vec<String>,

    /// How tracing events will be formatted when displayed in stdout.
    #[arg(long = "tracing-log-format", env = "TRACING_LOG_FORMAT", default_value = "normal")]
    pub tracing_log_format: TracingLogFormat,

    // Tokio Console GRPC server binding address.
    #[arg(long = "tokio-console-address", env = "TRACING_TOKIO_CONSOLE_ADDRESS")]
    pub tracing_tokio_console_address: Option<SocketAddr>,
}

impl TracingConfig {
    /// Inits application global tracing registry.
    ///
    /// Uses println! to have information available in stdout before tracing is initialized.
    pub fn init(&self, sentry_config: &Option<SentryConfig>) -> anyhow::Result<()> {
        match self.create_subscriber(sentry_config).try_init() {
            Ok(()) => Ok(()),
            Err(e) => {
                println!("failed to create tracing registry | reason={e:?}");
                Err(e.into())
            }
        }
    }
    pub fn create_subscriber(&self, sentry_config: &Option<SentryConfig>) -> impl SubscriberInitExt {
        println!("creating tracing registry");

        // configure tracing context layer
        println!("tracing registry: enabling tracing context recorder");
        let tracing_context_layer = TracingContextLayer.with_filter(EnvFilter::from_default_env());

        // configure stdout log layer
        let enable_ansi = stdout().is_terminal();
        println!(
            "tracing registry: enabling console logs | format={} ansi={}",
            self.tracing_log_format, enable_ansi
        );
        let stdout_layer = match self.tracing_log_format {
            TracingLogFormat::Json => fmt::Layer::default()
                .event_format(TracingJsonFormatter)
                .with_filter(EnvFilter::from_default_env())
                .boxed(),
            TracingLogFormat::Minimal => fmt::Layer::default()
                .with_thread_ids(false)
                .with_thread_names(false)
                .with_target(false)
                .with_ansi(enable_ansi)
                .with_timer(TracingMinimalTimer)
                .with_filter(EnvFilter::from_default_env())
                .boxed(),
            TracingLogFormat::Normal => fmt::Layer::default().with_ansi(enable_ansi).with_filter(EnvFilter::from_default_env()).boxed(),
            TracingLogFormat::Verbose => fmt::Layer::default()
                .with_ansi(enable_ansi)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_filter(EnvFilter::from_default_env())
                .boxed(),
        };

        // configure opentelemetry layer
        let opentelemetry_layer = match &self.tracing_url {
            Some(url) => {
                let tracer = opentelemetry_tracer(url, self.tracing_protocol, &self.tracing_headers);
                let layer = tracing_opentelemetry::layer()
                    .with_tracked_inactivity(false)
                    .with_tracer(tracer)
                    .with_filter(EnvFilter::from_default_env());
                Some(layer)
            }
            None => {
                println!("tracing registry: skipping opentelemetry exporter");
                None
            }
        };

        // configure sentry layer
        let sentry_layer = match &sentry_config {
            Some(sentry_config) => {
                println!("tracing registry: enabling sentry exporter | url={}", sentry_config.sentry_url);
                let layer = sentry_tracing::layer().with_filter(EnvFilter::from_default_env());
                Some(layer)
            }
            None => {
                println!("tracing registry: skipping sentry exporter");
                None
            }
        };

        // configure tokio-console layer
        let tokio_console_layer = match self.tracing_tokio_console_address {
            Some(tokio_console_address) => {
                println!("tracing registry: enabling tokio console exporter | address={tokio_console_address}");

                let (console_layer, console_server) = ConsoleLayer::builder().with_default_env().server_addr(tokio_console_address).build();
                spawn_named("console::grpc-server", async move {
                    if let Err(e) = console_server.serve().await {
                        tracing::error!(reason = ?e, address = %tokio_console_address, "failed to create tokio-console server");
                    };
                });
                Some(console_layer)
            }
            None => {
                println!("tracing registry: skipping tokio-console exporter");
                None
            }
        };

        tracing_subscriber::registry()
            .with(tracing_context_layer)
            .with(stdout_layer)
            .with(opentelemetry_layer)
            .with(sentry_layer)
            .with(tokio_console_layer)
    }
}

fn opentelemetry_tracer(url: &str, protocol: TracingProtocol, headers: &[String]) -> SdkTracer {
    println!(
        "tracing registry: enabling opentelemetry exporter | url={} protocol={} headers={} service={}",
        url,
        protocol,
        headers.len(),
        build_info::service_name()
    );

    // configure headers
    let headers = headers
        .iter()
        .map(|header| {
            let mut parts = header.splitn(2, '=');
            let key = parts.next().unwrap();
            let value = parts.next().unwrap_or_default();
            (key, value)
        })
        .collect_vec();

    // configure tracer
    let tracer_exporter: SpanExporterBuilder = match protocol {
        TracingProtocol::Grpc => {
            let mut protocol_metadata = MetadataMap::new();
            for (key, value) in headers {
                protocol_metadata.insert(MetadataKey::from_str(key).unwrap(), value.parse().unwrap());
            }

            opentelemetry_otlp::new_exporter()
                .tonic()
                .with_protocol(Protocol::Grpc)
                .with_endpoint(url)
                .with_metadata(protocol_metadata)
                .into()
        }
        TracingProtocol::HttpBinary | TracingProtocol::HttpJson => {
            let mut protocol_headers = HashMap::new();
            for (key, value) in headers {
                protocol_headers.insert(key.to_owned(), value.to_owned());
            }

            opentelemetry_otlp::new_exporter()
                .http()
                .with_protocol(protocol.into())
                .with_endpoint(url)
                .with_headers(protocol_headers)
                .into()
        }
    };

    let tracer_config = trace::config().with_resource(SdkResource::new(vec![KeyValue::new("service.name", build_info::service_name())]));

    // configure pipeline
    let batch_config = BatchConfigBuilder::default().with_max_queue_size(u16::MAX as usize).build();
    opentelemetry_otlp::new_pipeline()
        .tracing()
        .with_exporter(tracer_exporter)
        .with_trace_config(tracer_config)
        .with_batch_config(batch_config)
        .install_batch(runtime::Tokio)
        .unwrap()
}

// -----------------------------------------------------------------------------
// Protocol
// -----------------------------------------------------------------------------

#[derive(DebugAsJson, strum::Display, Clone, Copy, Eq, PartialEq, serde::Serialize)]
pub enum TracingProtocol {
    #[serde(rename = "grpc")]
    #[strum(to_string = "grpc")]
    Grpc,

    #[serde(rename = "http-binary")]
    #[strum(to_string = "http-binary")]
    HttpBinary,

    #[serde(rename = "http-json")]
    #[strum(to_string = "http-json")]
    HttpJson,
}

impl FromStr for TracingProtocol {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> anyhow::Result<Self, Self::Err> {
        match s.to_lowercase().trim() {
            "grpc" => Ok(Self::Grpc),
            "http-binary" => Ok(Self::HttpBinary),
            "http-json" => Ok(Self::HttpJson),
            s => Err(anyhow!("unknown tracing protocol: {}", s)),
        }
    }
}

impl From<TracingProtocol> for Protocol {
    fn from(value: TracingProtocol) -> Self {
        match value {
            TracingProtocol::Grpc => Self::Grpc,
            TracingProtocol::HttpBinary => Self::HttpBinary,
            TracingProtocol::HttpJson => Self::HttpJson,
        }
    }
}

// -----------------------------------------------------------------------------
// LogFormat
// -----------------------------------------------------------------------------

/// Tracing event log format.
#[derive(DebugAsJson, strum::Display, Clone, Copy, Eq, PartialEq, serde::Serialize)]
pub enum TracingLogFormat {
    /// Minimal format: Time (no date), level, and message.
    #[serde(rename = "minimal")]
    #[strum(to_string = "minimal")]
    Minimal,

    /// Normal format: Default `tracing` crate configuration.
    #[serde(rename = "normal")]
    #[strum(to_string = "normal")]
    Normal,

    /// Verbose format: Full datetime, level, thread, target, and message.
    #[serde(rename = "verbose")]
    #[strum(to_string = "verbose")]
    Verbose,

    /// JSON format: Verbose information formatted as JSON.
    #[serde(rename = "json")]
    #[strum(to_string = "json")]
    Json,
}

impl FromStr for TracingLogFormat {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> anyhow::Result<Self, Self::Err> {
        match s.to_lowercase().trim() {
            "json" => Ok(Self::Json),
            "minimal" => Ok(Self::Minimal),
            "normal" => Ok(Self::Normal),
            "verbose" | "full" => Ok(Self::Verbose),
            s => Err(anyhow!("unknown log format: {}", s)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tracing_config_with_json_format() {
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Json,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&None);
    }

    #[test]
    fn test_tracing_config_with_minimal_format() {
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Minimal,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&None);
    }

    #[test]
    fn test_tracing_config_with_normal_format() {
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Normal,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&None);
    }

    #[test]
    fn test_tracing_config_with_verbose_format() {
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Verbose,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&None);
    }

    #[tokio::test]
    async fn test_tracing_config_with_opentelemetry() {
        let config = TracingConfig {
            tracing_url: Some("http://localhost:4317".to_string()),
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Normal,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&None);
    }

    #[test]
    fn test_tracing_config_with_sentry() {
        let sentry_config = SentryConfig {
            sentry_url: "http://localhost:1234".to_string(),
        };
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Normal,
            tracing_tokio_console_address: None,
        };
        config.create_subscriber(&Some(sentry_config));
    }

    #[tokio::test]
    async fn test_tracing_config_with_tokio_console() {
        let config = TracingConfig {
            tracing_url: None,
            tracing_protocol: TracingProtocol::Grpc,
            tracing_headers: vec![],
            tracing_log_format: TracingLogFormat::Normal,
            tracing_tokio_console_address: Some("127.0.0.1:6669".parse().unwrap()),
        };
        config.create_subscriber(&None);
    }

    #[test]
    fn test_tracing_protocol_from_str() {
        assert_eq!(TracingProtocol::from_str("grpc").unwrap(), TracingProtocol::Grpc);
        assert_eq!(TracingProtocol::from_str("http-binary").unwrap(), TracingProtocol::HttpBinary);
        assert_eq!(TracingProtocol::from_str("http-json").unwrap(), TracingProtocol::HttpJson);
        assert!(TracingProtocol::from_str("invalid").is_err());
    }

    #[test]
    fn test_tracing_protocol_display() {
        assert_eq!(TracingProtocol::Grpc.to_string(), "grpc");
        assert_eq!(TracingProtocol::HttpBinary.to_string(), "http-binary");
        assert_eq!(TracingProtocol::HttpJson.to_string(), "http-json");
    }

    #[test]
    fn test_tracing_protocol_into_protocol() {
        assert_eq!(Protocol::from(TracingProtocol::Grpc), Protocol::Grpc);
        assert_eq!(Protocol::from(TracingProtocol::HttpBinary), Protocol::HttpBinary);
        assert_eq!(Protocol::from(TracingProtocol::HttpJson), Protocol::HttpJson);
    }
}