1#![allow(
7 unsafe_code,
8 missing_docs,
9 clippy::missing_errors_doc,
10 clippy::new_without_default
11)]
12
13#[cfg(not(target_arch = "wasm32"))]
15pub mod api_key_decorator;
16#[cfg(not(target_arch = "wasm32"))]
17pub mod composite_event_sink;
18#[cfg(not(target_arch = "wasm32"))]
19mod env_config;
20#[cfg(not(target_arch = "wasm32"))]
21pub mod http_event_sink;
22#[cfg(not(target_arch = "wasm32"))]
23pub mod local_event_sink;
24#[cfg(not(target_arch = "wasm32"))]
25pub mod log_interop;
26#[cfg(not(target_arch = "wasm32"))]
27pub mod oidc_client_credentials_decorator;
28#[cfg(not(target_arch = "wasm32"))]
29pub mod request_decorator;
30#[cfg(not(target_arch = "wasm32"))]
31pub mod stream_block;
32#[cfg(not(target_arch = "wasm32"))]
33pub mod stream_info;
34#[cfg(not(target_arch = "wasm32"))]
35pub mod system_monitor;
36#[cfg(not(target_arch = "wasm32"))]
37pub mod tracing_interop;
38
39#[cfg(feature = "jemalloc")]
44pub mod jemalloc_conf;
45
46#[cfg(target_arch = "wasm32")]
48mod console_event_sink;
49#[cfg(target_arch = "wasm32")]
50pub use console_event_sink::*;
51
52#[cfg(not(target_arch = "wasm32"))]
54mod native {
55 use std::any::TypeId;
56 use std::collections::HashMap;
57 use std::str::FromStr;
58 use std::sync::{Arc, Mutex, Weak};
59
60 use crate::env_config::{env_override, resolve};
61 use crate::log_interop::install_log_interop;
62 use crate::request_decorator::RequestDecorator;
63 use crate::tracing_interop::install_tracing_interop;
64 use micromegas_telemetry::property_names::RESERVED_PROPERTY_PREFIX;
65 use micromegas_tracing::event::BoxedEventSink;
66 use micromegas_tracing::info;
67 use micromegas_tracing::{
68 event::EventSink,
69 guards::{TracingSystemGuard, TracingThreadGuard},
70 prelude::*,
71 };
72
73 use crate::composite_event_sink::CompositeSink;
74 use crate::http_event_sink::{HttpEventSink, HttpSinkConfig};
75 use crate::local_event_sink::LocalEventSink;
76 use crate::system_monitor::spawn_system_monitor;
77
78 pub mod tokio_retry {
79 pub use tokio_retry2::*;
80 }
81
82 pub mod reqwest {
83 pub use reqwest::*;
84 }
85
86 pub const PROCESS_PROPERTIES_ENV_VAR: &str = "MICROMEGAS_PROCESS_PROPERTIES";
90
91 pub const LOCAL_SINK_MAX_LEVEL_ENV_VAR: &str = "MICROMEGAS_LOCAL_SINK_MAX_LEVEL";
99
100 pub const ENABLE_CPU_TRACING_ENV_VAR: &str = "MICROMEGAS_ENABLE_CPU_TRACING";
105
106 pub fn resolve_cpu_tracing_enabled(explicit: Option<bool>, env_value: Option<&str>) -> bool {
109 explicit.unwrap_or_else(|| env_value == Some("true"))
110 }
111
112 pub const TELEMETRY_SINK_MAX_LEVEL_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_SINK_MAX_LEVEL";
119
120 pub const DEFAULT_LOCAL_SINK_MAX_LEVEL: LevelFilter = LevelFilter::Info;
123
124 pub const DEFAULT_TELEMETRY_SINK_MAX_LEVEL: LevelFilter = LevelFilter::Debug;
127
128 const MAX_QUEUE_BYTES_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_MAX_QUEUE_BYTES";
129 const HARD_QUEUE_BYTES_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_HARD_QUEUE_BYTES";
130 const MAX_IN_FLIGHT_REQUESTS_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_MAX_IN_FLIGHT_REQUESTS";
131 const REQUEST_TIMEOUT_SECS_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_REQUEST_TIMEOUT_SECS";
132
133 pub fn merge_process_properties(
153 properties: &mut HashMap<String, String>,
154 raw: &str,
155 ) -> anyhow::Result<()> {
156 use anyhow::Context;
157
158 let mut parsed = Vec::new();
159 for entry in raw.split(',').map(str::trim).filter(|e| !e.is_empty()) {
160 let (key, value) = entry.split_once('=').with_context(|| {
161 format!("invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: expected key=value")
162 })?;
163 let (key, value) = (key.trim(), value.trim());
164 if key.is_empty() {
165 anyhow::bail!("invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: empty key");
166 }
167 if key.starts_with(RESERVED_PROPERTY_PREFIX) {
168 anyhow::bail!(
169 "invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: the \
170 {RESERVED_PROPERTY_PREFIX} namespace is server-written only and \
171 would be stripped on ingestion"
172 );
173 }
174 parsed.push((key.to_string(), value.to_string()));
175 }
176 for (key, value) in parsed {
177 properties.entry(key).or_insert(value);
178 }
179 Ok(())
180 }
181
182 pub struct TelemetryGuardBuilder {
183 logs_buffer_size: usize,
184 metrics_buffer_size: usize,
185 threads_buffer_size: usize,
186 target_max_levels: HashMap<String, String>,
187 max_level_override: Option<LevelFilter>,
188 interop_max_level_override: Option<LevelFilter>,
189 install_log_capture: bool,
190 install_tracing_capture: bool,
191 local_sink_enabled: bool,
192 local_sink_max_level: Option<LevelFilter>,
193 cpu_tracing_enabled: Option<bool>,
194 telemetry_sink_url: Option<String>,
195 telemetry_sink_max_level: Option<LevelFilter>,
196 telemetry_max_queue_bytes: Option<usize>,
197 telemetry_hard_queue_bytes: Option<usize>,
198 telemetry_max_in_flight_requests: Option<usize>,
199 telemetry_request_timeout: Option<std::time::Duration>,
200 telemetry_retry_by_priority:
201 Option<[core::iter::Take<tokio_retry::strategy::ExponentialBackoff>; 4]>,
202 telemetry_make_request_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
203 extra_sinks: HashMap<TypeId, (LevelFilter, BoxedEventSink)>,
204 system_metrics_enabled: bool,
205 default_system_properties_enabled: bool,
206 process_properties: HashMap<String, String>,
207 }
208
209 impl Default for TelemetryGuardBuilder {
210 fn default() -> Self {
211 Self {
212 logs_buffer_size: 10 * 1024 * 1024,
213 metrics_buffer_size: 1024 * 1024,
214 threads_buffer_size: 10 * 1024 * 1024,
215 local_sink_enabled: true,
216 local_sink_max_level: None,
217 cpu_tracing_enabled: None,
218 telemetry_sink_url: None,
219 telemetry_sink_max_level: None,
220 telemetry_max_queue_bytes: None,
221 telemetry_hard_queue_bytes: None,
222 telemetry_max_in_flight_requests: None,
223 telemetry_request_timeout: None,
224 telemetry_retry_by_priority: None,
225 telemetry_make_request_decorator: Box::new(|| {
226 Arc::new(crate::request_decorator::TrivialRequestDecorator {})
227 }),
228 target_max_levels: HashMap::default(),
229 max_level_override: None,
230 interop_max_level_override: None,
231 install_log_capture: false,
232 install_tracing_capture: true,
233 extra_sinks: HashMap::default(),
234 system_metrics_enabled: true,
235 default_system_properties_enabled: true,
236 process_properties: HashMap::default(),
237 }
238 }
239 }
240
241 impl TelemetryGuardBuilder {
242 #[must_use]
244 pub fn add_sink<Sink>(mut self, max_level: LevelFilter, sink: Sink) -> Self
245 where
246 Sink: EventSink + 'static,
247 {
248 let type_id = TypeId::of::<Sink>();
249
250 self.extra_sinks
251 .entry(type_id)
252 .or_insert_with(|| (max_level, Box::new(sink)));
253
254 self
255 }
256
257 #[must_use]
259 pub fn with_max_level_override(mut self, level_filter: LevelFilter) -> Self {
260 self.max_level_override = Some(level_filter);
261 self
262 }
263
264 #[must_use]
265 pub fn with_local_sink_enabled(mut self, enabled: bool) -> Self {
266 self.local_sink_enabled = enabled;
267 self
268 }
269
270 #[must_use]
271 pub fn with_interop_max_level_override(mut self, level_filter: LevelFilter) -> Self {
272 self.interop_max_level_override = Some(level_filter);
273 self
274 }
275
276 #[must_use]
277 pub fn with_install_log_capture(mut self, enabled: bool) -> Self {
278 self.install_log_capture = enabled;
279 self
280 }
281
282 #[must_use]
283 pub fn with_install_tracing_capture(mut self, enabled: bool) -> Self {
284 self.install_tracing_capture = enabled;
285 self
286 }
287
288 #[must_use]
293 pub fn with_local_sink_max_level(mut self, level_filter: LevelFilter) -> Self {
294 self.local_sink_max_level = Some(level_filter);
295 self
296 }
297
298 #[must_use]
305 pub fn with_cpu_tracing_enabled(mut self, enabled: bool) -> Self {
306 self.cpu_tracing_enabled = Some(enabled);
307 self
308 }
309
310 #[must_use]
315 pub fn with_telemetry_sink_max_level(mut self, level_filter: LevelFilter) -> Self {
316 self.telemetry_sink_max_level = Some(level_filter);
317 self
318 }
319
320 #[must_use]
321 pub fn with_ctrlc_handling(self) -> Self {
322 ctrlc::set_handler(move || {
323 info!("Ctrl+C was hit!");
324 micromegas_tracing::guards::shutdown_telemetry();
325 std::process::exit(1);
326 })
327 .expect("Error setting Ctrl+C handler");
328 self
329 }
330
331 #[must_use]
337 pub fn with_max_queue_bytes(mut self, bytes: usize) -> Self {
338 self.telemetry_max_queue_bytes = Some(bytes);
339 self
340 }
341
342 #[must_use]
348 pub fn with_hard_queue_bytes(mut self, bytes: usize) -> Self {
349 self.telemetry_hard_queue_bytes = Some(bytes);
350 self
351 }
352
353 #[must_use]
358 pub fn with_max_in_flight_requests(mut self, max_in_flight_requests: usize) -> Self {
359 self.telemetry_max_in_flight_requests = Some(max_in_flight_requests);
360 self
361 }
362
363 #[must_use]
372 pub fn with_request_timeout(mut self, timeout: std::time::Duration) -> Self {
373 self.telemetry_request_timeout = Some(timeout);
374 self
375 }
376
377 #[must_use]
381 pub fn with_retry_by_priority(
382 mut self,
383 retry_by_priority: [core::iter::Take<tokio_retry::strategy::ExponentialBackoff>; 4],
384 ) -> Self {
385 self.telemetry_retry_by_priority = Some(retry_by_priority);
386 self
387 }
388
389 #[must_use]
390 pub fn with_request_decorator(
391 mut self,
392 make_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
393 ) -> Self {
394 self.telemetry_make_request_decorator = make_decorator;
395 self
396 }
397
398 #[must_use]
423 pub fn with_auth_from_env(mut self) -> Self {
424 use crate::api_key_decorator::ApiKeyRequestDecorator;
425 use crate::oidc_client_credentials_decorator::OidcClientCredentialsDecorator;
426
427 if let Ok(decorator) = ApiKeyRequestDecorator::from_env() {
429 info!("Configured telemetry sink with API key authentication");
430 self.telemetry_make_request_decorator = Box::new(move || Arc::new(decorator));
431 return self;
432 }
433
434 if let Ok(decorator) = OidcClientCredentialsDecorator::from_env() {
436 info!("Configured telemetry sink with OIDC client credentials authentication");
437 self.telemetry_make_request_decorator = Box::new(move || Arc::new(decorator));
438 return self;
439 }
440
441 info!(
443 "Telemetry sink authentication not configured - sending unauthenticated requests"
444 );
445 self
446 }
447
448 #[must_use]
449 pub fn with_system_metrics_enabled(mut self, enabled: bool) -> Self {
450 self.system_metrics_enabled = enabled;
451 self
452 }
453
454 #[must_use]
455 pub fn with_default_system_properties_enabled(mut self, enabled: bool) -> Self {
456 self.default_system_properties_enabled = enabled;
457 self
458 }
459
460 #[must_use]
465 pub fn with_telemetry_sink_url(mut self, url: String) -> Self {
466 self.telemetry_sink_url = Some(url);
467 self
468 }
469
470 #[must_use]
476 pub fn with_process_property(mut self, key: String, value: String) -> Self {
477 self.process_properties.insert(key, value);
478 self
479 }
480
481 #[must_use]
487 pub fn with_process_properties(
488 mut self,
489 process_properties: HashMap<String, String>,
490 ) -> Self {
491 self.process_properties.extend(process_properties);
492 self
493 }
494
495 fn populate_default_system_properties(&mut self) {
496 let props = &mut self.process_properties;
497 type DefaultProperties = Vec<(&'static str, Box<dyn FnOnce() -> String>)>;
499 let defaults: DefaultProperties = vec![
500 (
501 "exe",
502 Box::new(|| {
503 std::env::current_exe()
504 .unwrap_or_default()
505 .to_string_lossy()
506 .into_owned()
507 }),
508 ),
509 ("username", Box::new(whoami::username)),
510 ("realname", Box::new(whoami::realname)),
511 ("computer", Box::new(whoami::devicename)),
512 ("distro", Box::new(whoami::distro)),
513 (
514 "cpu_brand",
515 Box::new(micromegas_tracing::cpu_brand::get_cpu_brand),
516 ),
517 (
518 "physical_core_count",
519 Box::new(|| {
520 sysinfo::System::physical_core_count()
521 .map(|c: usize| c.to_string())
522 .unwrap_or_default()
523 }),
524 ),
525 (
526 "logical_cpu_count",
527 Box::new(|| {
528 use sysinfo::{CpuRefreshKind, RefreshKind};
529 let system = sysinfo::System::new_with_specifics(
530 RefreshKind::nothing().with_cpu(CpuRefreshKind::nothing()),
531 );
532 system.cpus().len().to_string()
533 }),
534 ),
535 (
536 "total_memory",
537 Box::new(|| {
538 use sysinfo::{MemoryRefreshKind, RefreshKind};
539 let system = sysinfo::System::new_with_specifics(
540 RefreshKind::nothing()
541 .with_memory(MemoryRefreshKind::nothing().with_ram()),
542 );
543 system.total_memory().to_string()
544 }),
545 ),
546 ];
547 for (key, make_value) in defaults {
548 props.entry(key.to_string()).or_insert_with(make_value);
549 }
550 }
551
552 pub fn build(mut self) -> anyhow::Result<TelemetryGuard> {
553 if let Some(raw) = std::env::var_os(PROCESS_PROPERTIES_ENV_VAR) {
559 merge_process_properties(&mut self.process_properties, &raw.to_string_lossy())?;
560 }
561 if self.default_system_properties_enabled {
562 self.populate_default_system_properties();
563 }
564 const LEVEL_EXPECTED: &str = "one of off, fatal, error, warn, info, debug, trace";
569 let local_sink_max_level = resolve(
570 self.local_sink_max_level,
571 LOCAL_SINK_MAX_LEVEL_ENV_VAR,
572 DEFAULT_LOCAL_SINK_MAX_LEVEL,
573 LEVEL_EXPECTED,
574 )?;
575 let telemetry_sink_max_level = resolve(
576 self.telemetry_sink_max_level,
577 TELEMETRY_SINK_MAX_LEVEL_ENV_VAR,
578 DEFAULT_TELEMETRY_SINK_MAX_LEVEL,
579 LEVEL_EXPECTED,
580 )?;
581 const NON_NEGATIVE_INTEGER: &str = "a non-negative integer";
582 let max_queue_bytes = resolve(
583 self.telemetry_max_queue_bytes,
584 MAX_QUEUE_BYTES_ENV_VAR,
585 HttpSinkConfig::DEFAULT_MAX_QUEUE_BYTES,
586 NON_NEGATIVE_INTEGER,
587 )?;
588 let hard_queue_bytes = resolve(
589 self.telemetry_hard_queue_bytes,
590 HARD_QUEUE_BYTES_ENV_VAR,
591 HttpSinkConfig::DEFAULT_HARD_QUEUE_BYTES,
592 NON_NEGATIVE_INTEGER,
593 )?;
594 let max_in_flight_requests = resolve(
595 self.telemetry_max_in_flight_requests,
596 MAX_IN_FLIGHT_REQUESTS_ENV_VAR,
597 HttpSinkConfig::DEFAULT_MAX_IN_FLIGHT_REQUESTS,
598 NON_NEGATIVE_INTEGER,
599 )?;
600 let request_timeout = match self.telemetry_request_timeout {
602 Some(timeout) => timeout,
603 None => env_override::<u64>(REQUEST_TIMEOUT_SECS_ENV_VAR, NON_NEGATIVE_INTEGER)?
604 .map(std::time::Duration::from_secs)
605 .unwrap_or(HttpSinkConfig::DEFAULT_REQUEST_TIMEOUT),
606 };
607 let target_max_level: Vec<_> = self
608 .target_max_levels
609 .into_iter()
610 .filter(|(key, _val)| key != "MAX_LEVEL")
611 .map(|(key, val)| {
612 (
613 key,
614 LevelFilter::from_str(val.as_str()).unwrap_or(LevelFilter::Off),
615 )
616 })
617 .collect();
618
619 let guard = {
620 lazy_static::lazy_static! {
621 static ref GLOBAL_WEAK_GUARD: Mutex<Weak<TracingSystemGuard>> = Mutex::new(Weak::new());
622 }
623 let mut weak_guard = GLOBAL_WEAK_GUARD.lock().unwrap();
624 let weak = &mut *weak_guard;
625
626 if let Some(arc) = weak.upgrade() {
627 arc
628 } else {
629 let mut sinks: Vec<(LevelFilter, BoxedEventSink)> = vec![];
630 let telemetry_sink_url = self
631 .telemetry_sink_url
632 .or_else(|| std::env::var("MICROMEGAS_TELEMETRY_URL").ok())
633 .filter(|url| !url.trim().is_empty());
634
635 if let Some(url) = telemetry_sink_url {
636 let retry_by_priority = self
637 .telemetry_retry_by_priority
638 .unwrap_or_else(HttpSinkConfig::default_retry_by_priority);
639 let config = HttpSinkConfig {
640 max_queue_bytes,
641 hard_queue_bytes,
642 max_in_flight_requests,
643 request_timeout,
644 retry_by_priority,
645 };
646 sinks.push((
647 telemetry_sink_max_level,
648 Box::new(HttpEventSink::new(
649 &url,
650 config,
651 self.telemetry_make_request_decorator,
652 )),
653 ));
654 }
655 if self.local_sink_enabled {
656 sinks.push((local_sink_max_level, Box::new(LocalEventSink::new())));
657 }
658 let mut extra_sinks = self.extra_sinks.into_values().collect();
659 sinks.append(&mut extra_sinks);
660
661 let sink: BoxedEventSink = Box::new(CompositeSink::new(
662 sinks,
663 target_max_level,
664 self.max_level_override,
665 ));
666
667 if self.install_log_capture {
669 install_log_interop(self.interop_max_level_override);
670 }
671 if self.install_tracing_capture {
672 install_tracing_interop(self.interop_max_level_override);
673 }
674
675 let arc = Arc::<TracingSystemGuard>::new(TracingSystemGuard::new(
676 self.logs_buffer_size,
677 self.metrics_buffer_size,
678 self.threads_buffer_size,
679 sink.into(),
680 self.process_properties,
681 resolve_cpu_tracing_enabled(
682 self.cpu_tracing_enabled,
683 std::env::var(ENABLE_CPU_TRACING_ENV_VAR).ok().as_deref(),
684 ),
685 )?);
686
687 if self.system_metrics_enabled {
688 spawn_system_monitor();
689 }
690
691 *weak = Arc::<TracingSystemGuard>::downgrade(&arc);
692 arc
693 }
694 };
695 Ok(TelemetryGuard {
697 _guard: guard,
698 _thread_guard: TracingThreadGuard::new(),
699 })
700 }
701 }
702
703 pub struct TelemetryGuard {
704 _thread_guard: TracingThreadGuard,
706 _guard: Arc<TracingSystemGuard>,
707 }
708
709 impl TelemetryGuard {
710 pub fn new() -> anyhow::Result<Self> {
711 TelemetryGuardBuilder::default().build()
712 }
713 }
714}
715
716#[cfg(not(target_arch = "wasm32"))]
717pub use native::*;
718
719#[cfg(target_arch = "wasm32")]
721mod wasm {
722 use std::collections::HashMap;
723 use std::sync::Arc;
724
725 use micromegas_tracing::guards::TracingSystemGuard;
726
727 use crate::ConsoleEventSink;
728
729 pub struct TelemetryGuard {
730 _guard: Arc<TracingSystemGuard>,
731 }
732
733 pub fn init_telemetry() -> anyhow::Result<TelemetryGuard> {
734 let guard = Arc::new(TracingSystemGuard::new(
735 0,
736 0,
737 0,
738 Arc::new(ConsoleEventSink),
739 HashMap::new(),
740 false,
741 )?);
742 Ok(TelemetryGuard { _guard: guard })
743 }
744}
745
746#[cfg(target_arch = "wasm32")]
747pub use wasm::*;