1use std::sync::Arc;
2use std::sync::LazyLock;
3use std::time::Duration;
4
5use async_trait::async_trait;
6use axum::body::Bytes;
7use otlp_protos::opentelemetry::proto::collector::logs::v1::ExportLogsServiceRequest;
8use otlp_protos::opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest;
9use otlp_protos::opentelemetry::proto::collector::trace::v1::ExportTraceServiceRequest;
10use otlp_protos::opentelemetry::proto::logs::v1::ResourceLogs as OtlpResourceLogs;
11use otlp_protos::opentelemetry::proto::trace::v1::ResourceSpans as OtlpResourceSpans;
12use prost::Message;
13use saluki_common::collections::FastHashSet;
14use saluki_core::{
15 accounting::{MemoryBounds, MemoryBoundsBuilder},
16 components::{
17 sources::{Source, SourceBuilder, SourceContext},
18 BuildContext, ComponentContext,
19 },
20 data_model::{
21 event::{Event, EventType},
22 tags::{SharedTagSet, TagSet},
23 },
24 observability::ComponentMetricsExt as _,
25 runtime,
26 topology::{interconnect::BufferedDispatcher, EventsBuffer, OutputDefinition},
27};
28use saluki_env::WorkloadProvider;
29use saluki_error::ErrorContext as _;
30use saluki_error::{generic_error, GenericError};
31use saluki_io::net::{server::http::Http2Config, ListenAddress};
32use saluki_metrics::MetricsBuilder;
33use stringtheory::MetaString;
34use tokio::pin;
35use tokio::select;
36use tokio::sync::mpsc;
37use tokio::time::{interval, MissedTickBehavior};
38use tracing::{debug, error};
39
40use crate::common::otlp::{
41 build_metrics,
42 proxy::{OtlpProxy, OtlpProxyDestinations},
43 receiver::OtlpReceiver,
44 traces::translator::OtlpTracesSettings,
45 CorsConfiguration, Metrics, OtlpHandler, OtlpRoute, OtlpRoutes, OtlpServerConfiguration, OtlpTlsConfiguration,
46};
47
48mod debug_output;
49mod logs;
50mod metrics;
51mod resolver;
52use datadog_agent_apm::semantics::SemanticRegistryProvider;
53
54use self::debug_output::OtlpDebugOutput;
55pub use self::debug_output::OtlpDebugVerbosity;
56use self::logs::render::{CONTENT_BUFFER_RETENTION_LIMIT_BYTES, CONTENT_FIELDS_RETENTION_LIMIT_BYTES};
57use self::logs::translator::OtlpLogsTranslator;
58pub use self::metrics::config::{
59 CumulativeMonotonicMode, HistogramMode, InitialCumulativeMonotonicValue, OtlpMetricsSettings, SummaryMode,
60};
61use self::metrics::translator::OtlpMetricsTranslator;
62use self::resolver::build_context_resolver;
63pub use self::resolver::OtlpContextSettings;
64use crate::common::otlp::origin::OtlpOriginTagResolver;
65use crate::common::otlp::traces::translator::OtlpTracesTranslator;
66
67fn parse_configured_metric_tags(raw: &str) -> SharedTagSet {
71 let mut tags = TagSet::default();
72 for tag in raw.split(',') {
73 let tag = tag.trim();
74 if !tag.is_empty() {
75 tags.insert_tag(tag);
76 }
77 }
78 tags.into_shared()
79}
80
81fn apply_static_metric_tags(metrics: &mut OtlpMetricsSettings, static_tags: Vec<String>) {
83 if !static_tags.is_empty() {
84 metrics.tags = static_tags.join(",");
85 }
86}
87
88pub struct OtlpConfiguration {
90 pub default_hostname: MetaString,
92
93 pub receiver: OtlpReceiver,
95
96 pub routes: OtlpRoutes,
100
101 pub proxy_destinations: Option<OtlpProxyDestinations>,
105
106 pub metrics: OtlpMetricsSettings,
110
111 pub traces: OtlpTracesSettings,
113
114 pub contexts: OtlpContextSettings,
116
117 pub debug_verbosity: OtlpDebugVerbosity,
119
120 pub max_resource_len: usize,
125
126 pub semantic_registry: SemanticRegistryProvider,
132
133 pub workload_provider: Arc<dyn WorkloadProvider + Send + Sync>,
135}
136
137impl OtlpConfiguration {
138 pub fn with_static_metric_tags(mut self, static_tags: Vec<String>) -> Self {
140 apply_static_metric_tags(&mut self.metrics, static_tags);
141 self
142 }
143
144 fn traces_translator(&self, origin_tag_resolver: OtlpOriginTagResolver) -> OtlpTracesTranslator {
145 OtlpTracesTranslator::new(
146 self.traces.clone(),
147 self.max_resource_len,
148 self.semantic_registry.clone(),
149 origin_tag_resolver,
150 )
151 .with_default_hostname(self.default_hostname.clone())
152 }
153
154 fn metrics_translator_config(&self) -> metrics::config::OtlpMetricsTranslatorConfig {
155 metrics::config::OtlpMetricsTranslatorConfig::from_settings(&self.metrics)
156 }
157
158 fn metrics_translator(
162 &self, context: &ComponentContext, origin_tag_resolver: OtlpOriginTagResolver,
163 ) -> Result<OtlpMetricsTranslator, GenericError> {
164 let context_resolver = build_context_resolver(&self.contexts, context, None)?;
167
168 OtlpMetricsTranslator::new(
169 self.metrics_translator_config(),
170 self.default_hostname.clone(),
171 context_resolver,
172 origin_tag_resolver,
173 parse_configured_metric_tags(&self.metrics.tags),
174 metrics::telemetry::OtlpMetricsTranslatorMetrics::from_component_context(context),
175 )
176 }
177}
178
179#[async_trait]
180impl SourceBuilder for OtlpConfiguration {
181 fn outputs(&self) -> &[OutputDefinition<EventType>] {
182 static OUTPUTS: LazyLock<Vec<OutputDefinition<EventType>>> = LazyLock::new(|| {
183 vec![
184 OutputDefinition::named_output("metrics", EventType::Metric),
185 OutputDefinition::named_output("logs", EventType::Log),
186 OutputDefinition::named_output("traces", EventType::Trace),
187 ]
188 });
189
190 &OUTPUTS
191 }
192
193 async fn build(&self, context: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
194 if self.routes == OtlpRoutes::ALL_DISABLED {
195 return Err(generic_error!(
196 "Every OTLP signal is disabled, so the OTLP source has nothing to serve."
197 ));
198 }
199
200 self.receiver.check_endpoints()?;
201
202 let proxy = if self.routes.any_proxied() {
203 let destinations = self.proxy_destinations.as_ref().ok_or_else(|| {
204 generic_error!("An OTLP signal is proxied, but the OTLP source has no proxy destinations.")
205 })?;
206 let metrics_builder = MetricsBuilder::from_component_context(context.component_context());
207 Some(OtlpProxy::new(destinations, metrics_builder)?)
208 } else {
209 None
210 };
211
212 let grpc_endpoint = self.receiver.grpc.listen_address()?;
214 let http_endpoint = self.receiver.http.listen_address()?;
215
216 let origin_tag_resolver = OtlpOriginTagResolver::new(Arc::clone(&self.workload_provider));
219 let metrics_translator = if self.routes.metrics == OtlpRoute::Internal {
220 Some(self.metrics_translator(context.component_context(), origin_tag_resolver.clone())?)
221 } else {
222 None
223 };
224 let logs_translator =
225 (self.routes.logs == OtlpRoute::Internal).then(|| OtlpLogsTranslator::new(origin_tag_resolver.clone()));
226 let traces_translator =
227 (self.routes.traces == OtlpRoute::Internal).then(|| self.traces_translator(origin_tag_resolver.clone()));
228
229 let grpc_max_recv_msg_size_bytes = self.receiver.grpc.max_recv_msg_size_mib as usize * 1024 * 1024;
230 let grpc_http2_config = self.receiver.grpc.http2_config();
231 let http_max_request_body_size = self.receiver.http.max_request_body_size;
232 let cors = self.receiver.http.cors.clone();
233 let (http_tls_config, grpc_tls_config) = self.receiver.tls_configurations()?;
234 let metrics = build_metrics(context.component_context());
235 let debug_output = OtlpDebugOutput::new(self.debug_verbosity);
236
237 Ok(Box::new(Otlp {
238 routes: self.routes,
239 proxy,
240 grpc_endpoint,
241 http_endpoint,
242 grpc_max_recv_msg_size_bytes,
243 grpc_http2_config,
244 http_max_request_body_size,
245 metrics_translator,
246 logs_translator,
247 traces_translator,
248 cors,
249 http_tls_config,
250 grpc_tls_config,
251 metrics,
252 debug_output,
253 }))
254 }
255}
256
257impl MemoryBounds for OtlpConfiguration {
258 fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
259 builder
260 .minimum()
261 .with_single_value::<Otlp>("source struct")
262 .with_single_value::<SourceHandler>("source handler")
263 .with_fixed_amount("logs render buffer", CONTENT_BUFFER_RETENTION_LIMIT_BYTES)
264 .with_fixed_amount("logs render field list", CONTENT_FIELDS_RETENTION_LIMIT_BYTES);
265 }
266}
267
268pub struct Otlp {
269 routes: OtlpRoutes,
270 proxy: Option<OtlpProxy>,
271 grpc_endpoint: Option<ListenAddress>,
272 http_endpoint: Option<ListenAddress>,
273 grpc_max_recv_msg_size_bytes: usize,
274 grpc_http2_config: Http2Config,
275 http_max_request_body_size: u64,
276 metrics_translator: Option<OtlpMetricsTranslator>,
278 logs_translator: Option<OtlpLogsTranslator>,
279 traces_translator: Option<OtlpTracesTranslator>,
280 cors: CorsConfiguration,
281 http_tls_config: Option<OtlpTlsConfiguration>,
282 grpc_tls_config: Option<OtlpTlsConfiguration>,
283 metrics: Metrics, debug_output: OtlpDebugOutput,
285}
286
287#[async_trait]
288impl Source for Otlp {
289 async fn run(self: Box<Self>, mut context: SourceContext) -> Result<(), GenericError> {
290 let Self {
291 routes,
292 proxy,
293 grpc_endpoint,
294 http_endpoint,
295 grpc_max_recv_msg_size_bytes,
296 grpc_http2_config,
297 http_max_request_body_size,
298 metrics_translator,
299 logs_translator,
300 traces_translator,
301 cors,
302 http_tls_config,
303 grpc_tls_config,
304 metrics,
305 debug_output,
306 } = *self;
307
308 let global_shutdown = context.take_shutdown_handle();
309 pin!(global_shutdown);
310
311 let mut health = context.take_health_handle();
312 let memory_limiter = context.topology_context().memory_limiter();
313
314 let (tx, rx) = mpsc::channel::<OtlpSignal>(1024);
316
317 let handler = SourceHandler::new(tx, metrics.clone(), debug_output);
319 let mut server_config =
320 OtlpServerConfiguration::new(http_endpoint, grpc_endpoint, grpc_max_recv_msg_size_bytes)
321 .with_routes(routes)
322 .with_cors(cors)
323 .with_grpc_http2_config(grpc_http2_config)
324 .with_http_max_request_body_size(http_max_request_body_size);
325
326 if let Some(tls) = http_tls_config {
327 server_config = server_config.with_http_tls(tls);
328 }
329 if let Some(tls) = grpc_tls_config {
330 server_config = server_config.with_grpc_tls(tls);
331 }
332 if let Some(proxy) = proxy {
333 server_config = server_config.with_proxy(proxy);
334 }
335
336 server_config
337 .build(
338 handler,
339 memory_limiter.clone(),
340 metrics.clone(),
341 context.topology_context().global_thread_pool(),
342 )
343 .await?;
344
345 if routes.any_internal() {
354 let converter_context = context.clone();
355 runtime::worker(
356 "resource_converter",
357 run_converter(
358 rx,
359 converter_context,
360 metrics_translator,
361 logs_translator,
362 traces_translator,
363 metrics,
364 ),
365 )
366 .on_runtime(context.topology_context().global_thread_pool().clone())
367 .with_shutdown_timeout(Duration::MAX)
368 .needed()
369 .spawn();
370 }
371
372 health.mark_ready();
373 debug!("OTLP source started.");
374
375 loop {
377 select! {
378 _ = &mut global_shutdown => {
379 debug!("Received shutdown signal.");
380 break
381 },
382 _ = health.live() => continue,
383 }
384 }
385
386 debug!("OTLP source stopped.");
387
388 Ok(())
389 }
390}
391
392enum OtlpSignal {
393 Metrics(ExportMetricsServiceRequest),
394 Logs(OtlpResourceLogs),
395 Traces(OtlpResourceSpans),
396}
397
398struct SourceHandler {
400 tx: mpsc::Sender<OtlpSignal>,
401 metrics: Metrics,
402 debug_output: OtlpDebugOutput,
403}
404
405impl SourceHandler {
406 fn new(tx: mpsc::Sender<OtlpSignal>, metrics: Metrics, debug_output: OtlpDebugOutput) -> Self {
407 Self {
408 tx,
409 metrics,
410 debug_output,
411 }
412 }
413}
414
415#[async_trait]
416impl OtlpHandler for SourceHandler {
417 async fn handle_metrics(&self, body: Bytes) -> Result<(), GenericError> {
418 let request = ExportMetricsServiceRequest::decode(body).map_err(|e| {
419 self.metrics.metrics_errors_decode().increment(1);
420 generic_error!("Failed to decode metrics export request: {}", e)
421 })?;
422 self.debug_output.log_metrics(&request);
423
424 self.tx.send(OtlpSignal::Metrics(request)).await.map_err(|e| {
428 self.metrics.metrics_errors_channel().increment(1);
429 generic_error!("Failed to send metrics request to converter: channel is closed: {}", e)
430 })?;
431 Ok(())
432 }
433
434 async fn handle_logs(&self, body: Bytes) -> Result<(), GenericError> {
435 let request = ExportLogsServiceRequest::decode(body).error_context("Failed to decode logs export request.")?;
436 self.debug_output.log_logs(&request);
437
438 for resource_logs in request.resource_logs {
439 self.tx
440 .send(OtlpSignal::Logs(resource_logs))
441 .await
442 .error_context("Failed to send resource logs to converter: channel is closed.")?;
443 }
444 Ok(())
445 }
446
447 async fn handle_traces(&self, body: Bytes) -> Result<(), GenericError> {
448 let request =
449 ExportTraceServiceRequest::decode(body).error_context("Failed to decode trace export request.")?;
450 self.debug_output.log_traces(&request);
451
452 for resource_spans in request.resource_spans {
453 self.tx
454 .send(OtlpSignal::Traces(resource_spans))
455 .await
456 .error_context("Failed to send resource spans to converter: channel is closed.")?;
457 }
458 Ok(())
459 }
460}
461
462async fn run_converter(
463 mut receiver: mpsc::Receiver<OtlpSignal>, source_context: SourceContext,
464 mut metrics_translator: Option<OtlpMetricsTranslator>, mut logs_translator: Option<OtlpLogsTranslator>,
465 mut traces_translator: Option<OtlpTracesTranslator>, metrics: Metrics,
466) {
467 debug!("OTLP resource converter task started.");
468
469 let mut buffer_flush = interval(Duration::from_millis(100));
472 buffer_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
473
474 let mut metrics_dispatcher: Option<BufferedDispatcher<'_, EventsBuffer>> = None;
475 let mut logs_dispatcher: Option<BufferedDispatcher<'_, EventsBuffer>> = None;
476 let mut traces_dispatcher: Option<BufferedDispatcher<'_, EventsBuffer>> = None;
477
478 loop {
479 select! {
480 maybe_signal = receiver.recv() => {
481 let Some(otlp_signal) = maybe_signal else {
482 debug!("Converter task's input closed.");
483 break;
484 };
485
486 match otlp_signal {
489 OtlpSignal::Metrics(request) => {
490 let metrics_translator = metrics_translator
491 .as_mut()
492 .expect("metrics translator should exist for internal metrics");
493 let mut detected_languages = FastHashSet::default();
494
495 for resource_metrics in request.resource_metrics {
496 match metrics_translator.translate_metrics(resource_metrics, &metrics) {
497 Ok((events, languages)) => {
498 detected_languages.extend(languages);
499 for event in events {
500 let dispatcher = metrics_dispatcher.get_or_insert_with(|| {
501 source_context
502 .dispatcher()
503 .buffered_named("metrics")
504 .expect("metrics output should exist")
505 });
506 if let Err(e) = dispatcher.push(event).await {
507 error!(error = %e, "Failed to dispatch metric event.");
508 metrics.metrics_errors_dispatch().increment(1);
509 }
510 }
511 }
512 Err(e) => {
513 error!(error = %e, "Failed to handle resource metrics.");
514 }
515 }
516 }
517
518 for event in metrics_translator.emit_usage_beacons(detected_languages) {
520 let dispatcher = metrics_dispatcher.get_or_insert_with(|| {
521 source_context
522 .dispatcher()
523 .buffered_named("metrics")
524 .expect("metrics output should exist")
525 });
526 if let Err(e) = dispatcher.push(event).await {
527 error!(error = %e, "Failed to dispatch usage beacon metric event.");
528 }
529 }
530 }
531 OtlpSignal::Logs(resource_logs) => {
532 let logs_translator = logs_translator
533 .as_mut()
534 .expect("logs translator should exist for internal logs");
535 for log in logs_translator.translate_logs(resource_logs, &metrics) {
536 let dispatcher = logs_dispatcher.get_or_insert_with(|| {
537 source_context
538 .dispatcher()
539 .buffered_named("logs")
540 .expect("logs output should exist")
541 });
542 if let Err(e) = dispatcher.push(Event::Log(log)).await {
543 error!(error = %e, "Failed to dispatch log event.");
544 }
545 }
546 }
547 OtlpSignal::Traces(resource_spans) => {
548 let traces_translator = traces_translator
549 .as_mut()
550 .expect("traces translator should exist for internal traces");
551 for trace_event in traces_translator.translate_spans(resource_spans, &metrics) {
552 let dispatcher = traces_dispatcher.get_or_insert_with(|| {
553 source_context
554 .dispatcher()
555 .buffered_named("traces")
556 .expect("traces output should exist")
557 });
558 if let Err(e) = dispatcher.push(trace_event).await {
559 error!(error = %e, "Failed to dispatch trace event.");
560 }
561 }
562 }
563 }
564 },
565 _ = buffer_flush.tick() => {
566 if let Some(dispatcher) = metrics_dispatcher.take() {
567 if let Err(e) = dispatcher.flush().await {
568 error!(error = %e, "Failed to flush metric events.");
569 metrics.metrics_errors_flush().increment(1);
570 }
571 }
572 if let Some(dispatcher) = logs_dispatcher.take() {
573 if let Err(e) = dispatcher.flush().await {
574 error!(error = %e, "Failed to flush log events.");
575 }
576 }
577 if let Some(dispatcher) = traces_dispatcher.take() {
578 if let Err(e) = dispatcher.flush().await {
579 error!(error = %e, "Failed to flush trace events.");
580 }
581 }
582 },
583 }
584 }
585
586 if let Some(dispatcher) = metrics_dispatcher.take() {
587 if let Err(e) = dispatcher.flush().await {
588 error!(error = %e, "Failed to flush metric events.");
589 metrics.metrics_errors_flush().increment(1);
590 }
591 }
592 if let Some(dispatcher) = logs_dispatcher.take() {
593 if let Err(e) = dispatcher.flush().await {
594 error!(error = %e, "Failed to flush log events.");
595 }
596 }
597 if let Some(dispatcher) = traces_dispatcher.take() {
598 if let Err(e) = dispatcher.flush().await {
599 error!(error = %e, "Failed to flush trace events.");
600 }
601 }
602
603 debug!("OTLP resource converter task stopped.");
604}
605
606#[cfg(test)]
607mod tests {
608 use std::num::NonZeroUsize;
609 use std::sync::Arc;
610 use std::time::Duration;
611
612 use datadog_agent_apm::semantics::test_util::TestRegistryPublisher;
613 use datadog_agent_apm::semantics::SemanticRegistryProvider;
614 use otlp_protos::opentelemetry::proto::collector::logs::v1::logs_service_client::LogsServiceClient;
615 use otlp_protos::opentelemetry::proto::logs::v1::{LogRecord, ResourceLogs, ScopeLogs};
616 use prost::Message;
617 use saluki_core::components::{
618 sources::SourceBuilder as _, test_util::TestComponentDriver, BuildContext, ComponentContext,
619 };
620 use saluki_core::data_model::event::Event;
621 use saluki_core::data_model::origin::OriginTagCardinality;
622 use saluki_core::runtime::state::{DataspaceUpdate, IdentifierFilter};
623 use saluki_core::runtime::NodeSnapshot;
624 use saluki_io::net::BoundListenAddress;
625 use saluki_metrics::test::TestRecorder;
626 use stringtheory::MetaString;
627
628 use super::{
629 apply_static_metric_tags, parse_configured_metric_tags, CumulativeMonotonicMode, ExportLogsServiceRequest,
630 HistogramMode, InitialCumulativeMonotonicValue, OtlpConfiguration, OtlpContextSettings, OtlpDebugVerbosity,
631 OtlpMetricsSettings, SummaryMode,
632 };
633 use crate::common::datadog::test_util::init_crypto_provider;
634 use crate::common::otlp::origin::OtlpOriginTagResolver;
635 use crate::common::otlp::proxy::OtlpProxyDestinations;
636 use crate::common::otlp::receiver::receiver;
637 use crate::common::otlp::traces::translator::{
638 custom_status_code_registry, traces_settings, translate_custom_status_code,
639 };
640 use crate::common::otlp::{build_metrics, Metrics, OtlpHandler, OtlpRoute, OtlpRoutes};
641 use crate::common::proxy::Destination;
642
643 fn metrics_settings() -> OtlpMetricsSettings {
645 OtlpMetricsSettings {
646 tag_cardinality: OriginTagCardinality::Low,
647 histogram_mode: HistogramMode::Distributions,
648 send_histogram_aggregations: false,
649 resource_attributes_as_tags: false,
650 instrumentation_scope_metadata_as_tags: true,
651 cumulative_monotonic_mode: CumulativeMonotonicMode::ToDelta,
652 initial_cumulative_monotonic_value: InitialCumulativeMonotonicValue::Auto,
653 tags: String::new(),
654 summary_mode: SummaryMode::Gauges,
655 delta_ttl: Duration::from_secs(3600),
656 }
657 }
658
659 fn source_configuration() -> OtlpConfiguration {
661 OtlpConfiguration {
662 default_hostname: MetaString::default(),
663 receiver: receiver(),
664 routes: OtlpRoutes::ALL_INTERNAL,
665 proxy_destinations: None,
666 metrics: metrics_settings(),
667 traces: traces_settings(),
668 contexts: OtlpContextSettings {
669 allow_context_heap_allocs: true,
670 cached_contexts_limit: 500_000,
671 cached_tagsets_limit: 500_000,
672 string_interner_size: 2 * 1024 * 1024,
673 },
674 debug_verbosity: OtlpDebugVerbosity::None,
675 max_resource_len: usize::MAX,
676 semantic_registry: SemanticRegistryProvider::default(),
677 workload_provider: Arc::new(saluki_env::workload::providers::NoopWorkloadProvider),
678 }
679 }
680
681 fn tags(raw: &str) -> Vec<String> {
682 parse_configured_metric_tags(raw)
683 .into_iter()
684 .map(|t| t.to_string())
685 .collect()
686 }
687
688 fn config_with_metrics(metrics: OtlpMetricsSettings) -> OtlpConfiguration {
689 OtlpConfiguration {
690 metrics,
691 ..source_configuration()
692 }
693 }
694
695 #[test]
696 fn injected_provider_reaches_the_traces_translator() {
697 let (publisher, provider) = TestRegistryPublisher::new();
698 let mut config = source_configuration();
699 config.traces.string_interner_size = NonZeroUsize::new(64 * 1024).unwrap();
700 config.semantic_registry = provider;
701 let mut translator =
702 config.traces_translator(OtlpOriginTagResolver::new(Arc::clone(&config.workload_provider)));
703 let metrics = Metrics::for_tests();
704 assert_eq!(translate_custom_status_code(&mut translator, &metrics), None);
705
706 publisher.assign([("a", custom_status_code_registry())]);
707 assert_eq!(translate_custom_status_code(&mut translator, &metrics), Some(418.0));
708 }
709
710 #[test]
711 fn default_hostname_reaches_the_traces_translator() {
712 use otlp_protos::opentelemetry::proto::trace::v1::{ResourceSpans, ScopeSpans, Span};
713
714 let mut config = source_configuration();
715 config.traces.string_interner_size = NonZeroUsize::new(64 * 1024).unwrap();
716 config.default_hostname = MetaString::from("data-plane-host");
717 let mut translator =
718 config.traces_translator(OtlpOriginTagResolver::new(Arc::clone(&config.workload_provider)));
719 let resource_spans = ResourceSpans {
720 scope_spans: vec![ScopeSpans {
721 spans: vec![Span {
722 trace_id: vec![1; 16],
723 span_id: vec![1; 8],
724 name: "span".to_owned(),
725 end_time_unix_nano: 2,
726 ..Default::default()
727 }],
728 ..Default::default()
729 }],
730 ..Default::default()
731 };
732
733 let hostnames: Vec<String> = translator
735 .translate_spans(resource_spans, &Metrics::for_tests())
736 .filter_map(Event::try_into_trace)
737 .map(|trace| trace.payload.hostname.to_string())
738 .collect();
739 assert_eq!(hostnames, ["data-plane-host"]);
740 }
741
742 #[test]
743 fn empty_static_tags_preserve_explicit_otlp_metric_tags() {
744 let mut metrics = metrics_settings();
745 metrics.tags = "configured:true".to_string();
746
747 apply_static_metric_tags(&mut metrics, Vec::new());
748
749 assert_eq!(metrics.tags, "configured:true");
750 }
751
752 #[test]
753 fn static_metric_tags_replace_explicit_otlp_metric_tags() {
754 let config = config_with_metrics(OtlpMetricsSettings {
755 tags: "configured:true".to_string(),
756 ..metrics_settings()
757 })
758 .with_static_metric_tags(vec!["provider_kind:autopilot".to_string()]);
759
760 assert_eq!(config.metrics.tags, "provider_kind:autopilot");
761 }
762
763 #[test]
764 fn histogram_mode_flows_to_metrics_translator() {
765 for mode in [
766 HistogramMode::NoBuckets,
767 HistogramMode::Counters,
768 HistogramMode::Distributions,
769 ] {
770 let config = config_with_metrics(OtlpMetricsSettings {
771 histogram_mode: mode,
772 ..metrics_settings()
773 });
774
775 assert_eq!(config.metrics_translator_config().hist_mode, mode);
776 }
777 }
778
779 #[test]
780 fn summary_mode_flows_to_metrics_translator() {
781 for (mode, expected_quantiles) in [(SummaryMode::Gauges, true), (SummaryMode::NoQuantiles, false)] {
783 let config = config_with_metrics(OtlpMetricsSettings {
784 summary_mode: mode,
785 ..metrics_settings()
786 });
787
788 assert_eq!(config.metrics_translator_config().quantiles, expected_quantiles);
789 }
790 }
791
792 #[test]
793 fn histogram_aggregation_flows_to_metrics_translator() {
794 for send in [false, true] {
795 let config = config_with_metrics(OtlpMetricsSettings {
796 send_histogram_aggregations: send,
797 ..metrics_settings()
798 });
799
800 assert_eq!(config.metrics_translator_config().send_histogram_aggregations, send);
801 }
802 }
803
804 #[test]
805 fn nobuckets_with_histogram_aggregations_is_valid() {
806 let config = config_with_metrics(OtlpMetricsSettings {
807 histogram_mode: HistogramMode::NoBuckets,
808 send_histogram_aggregations: true,
809 ..metrics_settings()
810 });
811
812 assert!(config.metrics_translator_config().validate().is_ok());
813 }
814
815 #[test]
816 fn nobuckets_without_histogram_aggregations_is_invalid() {
817 let config = config_with_metrics(OtlpMetricsSettings {
819 histogram_mode: HistogramMode::NoBuckets,
820 send_histogram_aggregations: false,
821 ..metrics_settings()
822 });
823
824 assert!(config.metrics_translator_config().validate().is_err());
825 }
826
827 #[test]
828 fn cumulative_monotonic_mode_flows_to_metrics_translator() {
829 for mode in [CumulativeMonotonicMode::ToDelta, CumulativeMonotonicMode::RawValue] {
830 let config = config_with_metrics(OtlpMetricsSettings {
831 cumulative_monotonic_mode: mode,
832 ..metrics_settings()
833 });
834
835 assert_eq!(config.metrics_translator_config().cumulative_monotonic_mode, mode);
836 }
837 }
838
839 #[test]
840 fn initial_cumulative_monotonic_value_flows_to_metrics_translator() {
841 for value in [
842 InitialCumulativeMonotonicValue::Auto,
843 InitialCumulativeMonotonicValue::Drop,
844 InitialCumulativeMonotonicValue::Keep,
845 ] {
846 let config = config_with_metrics(OtlpMetricsSettings {
847 initial_cumulative_monotonic_value: value,
848 ..metrics_settings()
849 });
850
851 assert_eq!(
852 config.metrics_translator_config().initial_cumulative_monotonic_value,
853 value
854 );
855 }
856 }
857
858 #[test]
859 fn delta_ttl_flows_to_metrics_translator() {
860 let config = config_with_metrics(OtlpMetricsSettings {
862 delta_ttl: Duration::from_secs(7200),
863 ..metrics_settings()
864 });
865
866 assert_eq!(config.metrics_translator_config().delta_ttl, Duration::from_secs(7200));
867 }
868
869 #[test]
870 fn tag_settings_flow_to_metrics_translator() {
871 let config = config_with_metrics(OtlpMetricsSettings {
872 tag_cardinality: OriginTagCardinality::High,
873 resource_attributes_as_tags: true,
874 ..metrics_settings()
875 });
876 let translator_config = config.metrics_translator_config();
877
878 assert_eq!(translator_config.tag_cardinality, OriginTagCardinality::High);
879 assert!(translator_config.resource_attributes_as_tags);
880 }
881
882 #[test]
883 fn instrumentation_scope_metadata_as_tags_flows_to_metrics_translator() {
884 let config = config_with_metrics(OtlpMetricsSettings {
885 instrumentation_scope_metadata_as_tags: false,
886 ..metrics_settings()
887 });
888
889 assert!(
890 !config
891 .metrics_translator_config()
892 .instrumentation_scope_metadata_as_tags
893 );
894 }
895
896 #[test]
897 fn empty_configuration_yields_no_tags() {
898 assert!(tags("").is_empty());
899 }
900
901 #[test]
902 fn single_tag_is_parsed() {
903 assert_eq!(tags("env:prod"), vec!["env:prod".to_string()]);
904 }
905
906 #[test]
907 fn multiple_tags_are_split_on_comma() {
908 assert_eq!(
909 tags("env:prod,team:core"),
910 vec!["env:prod".to_string(), "team:core".to_string()]
911 );
912 }
913
914 #[test]
915 fn duplicate_tags_are_deduplicated() {
916 assert_eq!(tags("env:prod,env:prod"), vec!["env:prod".to_string()]);
917 }
918
919 #[test]
920 fn whitespace_around_commas_is_stripped() {
921 assert_eq!(
922 tags("env:prod, team:core"),
923 vec!["env:prod".to_string(), "team:core".to_string()]
924 );
925 }
926
927 #[test]
928 fn trailing_and_doubled_commas_produce_no_empty_tags() {
929 assert_eq!(tags("env:prod,"), vec!["env:prod".to_string()]);
930 assert_eq!(
931 tags("env:prod,,team:core"),
932 vec!["env:prod".to_string(), "team:core".to_string()]
933 );
934 }
935
936 #[tokio::test]
941 async fn source_handler_increments_decode_error_on_malformed_body() {
942 let recorder = TestRecorder::default();
943 let _recorder_guard = metrics::set_default_local_recorder(&recorder);
944
945 let metrics = build_metrics(&ComponentContext::test_source("otlp_test"));
946 let (tx, _rx) = tokio::sync::mpsc::channel::<super::OtlpSignal>(1);
947 let handler = super::SourceHandler::new(tx, metrics, super::OtlpDebugOutput::default());
948
949 let result = handler.handle_metrics(bytes::Bytes::from_static(b"not protobuf")).await;
951 assert!(result.is_err());
952
953 let tags: &[(&str, &str)] = &[
954 ("component_id", "otlp_test"),
955 ("component_type", "source"),
956 ("reason", "decode"),
957 ];
958 assert_eq!(recorder.counter(("component_errors_total", tags)), Some(1));
959 }
960
961 #[tokio::test]
962 async fn source_handler_increments_channel_error_on_closed_channel() {
963 let recorder = TestRecorder::default();
964 let _recorder_guard = metrics::set_default_local_recorder(&recorder);
965
966 let metrics = build_metrics(&ComponentContext::test_source("otlp_test"));
967 let (tx, rx) = tokio::sync::mpsc::channel::<super::OtlpSignal>(1);
969 drop(rx);
970 let handler = super::SourceHandler::new(tx, metrics, super::OtlpDebugOutput::default());
971
972 let request = otlp_protos::opentelemetry::proto::collector::metrics::v1::ExportMetricsServiceRequest::default();
974 let body = bytes::Bytes::from(request.encode_to_vec());
975 let result = handler.handle_metrics(body).await;
976 assert!(result.is_err());
977
978 let tags: &[(&str, &str)] = &[
979 ("component_id", "otlp_test"),
980 ("component_type", "source"),
981 ("reason", "channel"),
982 ];
983 assert_eq!(recorder.counter(("component_errors_total", tags)), Some(1));
984
985 let decode_tags: &[(&str, &str)] = &[
987 ("component_id", "otlp_test"),
988 ("component_type", "source"),
989 ("reason", "decode"),
990 ];
991 assert_eq!(recorder.counter(("component_errors_total", decode_tags)), Some(0));
992 }
993
994 #[tokio::test]
995 async fn an_empty_endpoint_leaves_its_server_unbound() {
996 let mut config = source_configuration();
997 config.receiver.grpc.endpoint = String::new();
998 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
999
1000 let (control, _outputs) = TestComponentDriver::source(config)
1001 .await
1002 .expect("source should build with only an HTTP endpoint");
1003
1004 let mut bound = control
1005 .supervisor()
1006 .dataspace()
1007 .subscribe::<BoundListenAddress>(IdentifierFilter::exact("http-server-otlp-http"));
1008 match bound.recv().await {
1009 Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(_))) => {}
1010 update => panic!("expected the HTTP server to bind, got {update:?}"),
1011 }
1012
1013 let grpc = control
1014 .supervisor()
1015 .dataspace()
1016 .current_values::<BoundListenAddress>(IdentifierFilter::exact("http-server-otlp-grpc"));
1017 assert!(grpc.is_empty(), "the gRPC server should not bind, got {grpc:?}");
1018
1019 fn http_servers(node: &NodeSnapshot, names: &mut Vec<String>) {
1024 for child in &node.children {
1025 if child.name.starts_with("http_server_") {
1026 names.push(child.name.to_string());
1027 }
1028 http_servers(child, names);
1029 }
1030 }
1031 let mut servers = Vec::new();
1032 http_servers(&control.supervisor().tree_handle().snapshot().root, &mut servers);
1033 assert_eq!(servers, ["http_server_otlp-http"]);
1034
1035 control.shutdown().await.expect("source should stop cleanly");
1036 }
1037
1038 #[tokio::test]
1039 async fn an_empty_endpoint_leaves_its_tls_settings_unused() {
1040 let mut config = source_configuration();
1042 config.receiver.grpc.endpoint = String::new();
1043 config.receiver.grpc.tls.cert_file = "/missing/cert.pem".to_string();
1044 config.receiver.grpc.tls.ca_file = "/missing/ca.pem".to_string();
1045 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
1046
1047 let (control, _outputs) = TestComponentDriver::source(config)
1048 .await
1049 .expect("source should build when only the unused server has bad TLS settings");
1050
1051 let mut bound = control
1052 .supervisor()
1053 .dataspace()
1054 .subscribe::<BoundListenAddress>(IdentifierFilter::exact("http-server-otlp-http"));
1055 match bound.recv().await {
1056 Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(_))) => {}
1057 update => panic!("expected the HTTP server to bind, got {update:?}"),
1058 }
1059
1060 control.shutdown().await.expect("source should stop cleanly");
1061 }
1062
1063 #[tokio::test]
1064 async fn build_fails_when_both_endpoints_are_empty() {
1065 let config = source_configuration();
1066
1067 let error = TestComponentDriver::source(config)
1068 .await
1069 .err()
1070 .expect("source should fail to build without an endpoint");
1071 assert!(
1072 format!("{error:#}").contains("receiver endpoints are both empty")
1073 && format!("{error:#}").contains("otlp_config.receiver.protocols.grpc.endpoint"),
1074 "unexpected error: {error:#}"
1075 );
1076 }
1077
1078 #[tokio::test]
1079 async fn build_fails_when_every_signal_is_disabled() {
1080 let mut config = source_configuration();
1081 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1082 config.routes = OtlpRoutes::ALL_DISABLED;
1083
1084 let error = TestComponentDriver::source(config)
1085 .await
1086 .err()
1087 .expect("source should fail to build without a signal to serve");
1088 assert!(
1089 format!("{error:#}").contains("Every OTLP signal is disabled"),
1090 "unexpected error: {error:#}"
1091 );
1092 }
1093
1094 #[tokio::test]
1095 async fn accepted_logs_are_dispatched_before_the_source_stops() {
1096 const REQUESTS: usize = 16;
1099 const RECORDS: usize = 512;
1100
1101 let mut config = source_configuration();
1102 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1103 config.receiver.grpc.max_recv_msg_size_mib = 4;
1104 config.receiver.grpc.keepalive.time = Duration::from_secs(2 * 60 * 60);
1106 config.receiver.grpc.keepalive.timeout = Duration::from_secs(20);
1107 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
1108
1109 let (mut control, mut outputs) = TestComponentDriver::options()
1110 .with_interconnect_capacity(NonZeroUsize::MIN)
1111 .source(config)
1112 .await
1113 .expect("source should build");
1114 let mut logs = outputs.take_named_output("logs");
1115
1116 let mut bound = control
1117 .supervisor()
1118 .dataspace()
1119 .subscribe::<BoundListenAddress>(IdentifierFilter::exact("http-server-otlp-grpc"));
1120 let address = match bound.recv().await {
1121 Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(address))) => address,
1122 update => panic!("expected the gRPC server to bind, got {update:?}"),
1123 };
1124 let channel = tonic::transport::Endpoint::from_shared(format!("http://{address}"))
1125 .expect("endpoint should parse")
1126 .connect()
1127 .await
1128 .expect("should connect to the gRPC server");
1129 let mut client = LogsServiceClient::new(channel);
1130 for _ in 0..REQUESTS {
1131 let request = ExportLogsServiceRequest {
1132 resource_logs: vec![ResourceLogs {
1133 scope_logs: vec![ScopeLogs {
1134 log_records: vec![LogRecord::default(); RECORDS],
1135 ..Default::default()
1136 }],
1137 ..Default::default()
1138 }],
1139 };
1140 client.export(request).await.expect("export should succeed");
1141 }
1142
1143 control.signal_shutdown();
1144 let (result, events) = tokio::join!(control.wait(), logs.collect_events());
1145 result.expect("source should stop cleanly");
1146 assert_eq!(
1147 events.len(),
1148 REQUESTS * RECORDS,
1149 "every accepted log must be dispatched"
1150 );
1151
1152 for event in events {
1153 let Event::Log(log) = event else {
1154 panic!("expected a log, got {event:?}");
1155 };
1156 assert_eq!(log.message(), r#"{"message":"","status":""}"#);
1157 assert!(log.additional_properties().is_empty());
1158 }
1159 }
1160
1161 #[tokio::test]
1162 async fn the_grpc_message_size_limit_is_in_mib() {
1163 use otlp_protos::opentelemetry::proto::common::v1::{any_value, AnyValue};
1164
1165 const MIB: usize = 1024 * 1024;
1166
1167 let mut config = source_configuration();
1168 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1169 config.receiver.grpc.max_recv_msg_size_mib = 1;
1170 config.receiver.grpc.keepalive.time = Duration::from_secs(2 * 60 * 60);
1172 config.receiver.grpc.keepalive.timeout = Duration::from_secs(20);
1173
1174 let (control, mut outputs) = TestComponentDriver::source(config).await.expect("source should build");
1175 let _logs = outputs.take_named_output("logs");
1176 let mut bound = control
1177 .supervisor()
1178 .dataspace()
1179 .subscribe::<BoundListenAddress>(IdentifierFilter::exact("http-server-otlp-grpc"));
1180 let address = match bound.recv().await {
1181 Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(address))) => address,
1182 update => panic!("expected the gRPC server to bind, got {update:?}"),
1183 };
1184 let channel = tonic::transport::Endpoint::from_shared(format!("http://{address}"))
1185 .expect("endpoint should parse")
1186 .connect()
1187 .await
1188 .expect("should connect to the gRPC server");
1189 let mut client = LogsServiceClient::new(channel);
1190 let request = |body_len: usize| ExportLogsServiceRequest {
1191 resource_logs: vec![ResourceLogs {
1192 scope_logs: vec![ScopeLogs {
1193 log_records: vec![LogRecord {
1194 body: Some(AnyValue {
1195 value: Some(any_value::Value::StringValue("x".repeat(body_len))),
1196 }),
1197 ..Default::default()
1198 }],
1199 ..Default::default()
1200 }],
1201 ..Default::default()
1202 }],
1203 };
1204
1205 client
1207 .export(request(MIB / 2))
1208 .await
1209 .expect("a message under the limit should be accepted");
1210 client
1211 .export(request(2 * MIB))
1212 .await
1213 .expect_err("a message over the limit should be rejected");
1214
1215 control.shutdown().await.expect("source should stop cleanly");
1216 }
1217
1218 #[tokio::test]
1219 async fn a_source_without_internal_signals_keeps_its_outputs_open() {
1220 init_crypto_provider();
1223 let mut config = source_configuration();
1224 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1225 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
1226 config.routes = OtlpRoutes {
1227 metrics: OtlpRoute::Proxied,
1228 logs: OtlpRoute::Disabled,
1229 traces: OtlpRoute::Proxied,
1230 };
1231 let destination = |port| Destination::Tcp {
1232 host: "127.0.0.1".to_string(),
1233 port,
1234 };
1235 config.proxy_destinations = Some(OtlpProxyDestinations {
1236 grpc: Some(destination(4319)),
1237 http: Some(destination(4320)),
1238 });
1239
1240 let (control, mut outputs) = TestComponentDriver::source(config).await.expect("source should build");
1241 let mut metrics = outputs.take_named_output("metrics");
1242 control.wait_until_ready().await;
1243
1244 let closed = tokio::time::timeout(Duration::from_millis(500), metrics.collect_events()).await;
1245 assert!(
1246 closed.is_err(),
1247 "the metrics output closed while the source was running"
1248 );
1249 assert!(!control.is_finished(), "the source stopped on its own");
1250 control.shutdown().await.expect("source should stop cleanly");
1251 }
1252
1253 #[tokio::test]
1254 async fn settings_of_disabled_metrics_do_not_stop_the_traces_proxy() {
1255 init_crypto_provider();
1258 let mut config = source_configuration();
1259 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1260 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
1261 config.routes = OtlpRoutes {
1262 metrics: OtlpRoute::Disabled,
1263 logs: OtlpRoute::Disabled,
1264 traces: OtlpRoute::Proxied,
1265 };
1266 config.metrics = OtlpMetricsSettings {
1267 histogram_mode: HistogramMode::NoBuckets,
1268 send_histogram_aggregations: false,
1269 ..metrics_settings()
1270 };
1271 let destination = |port| Destination::Tcp {
1272 host: "127.0.0.1".to_string(),
1273 port,
1274 };
1275 config.proxy_destinations = Some(OtlpProxyDestinations {
1276 grpc: Some(destination(4319)),
1277 http: Some(destination(4320)),
1278 });
1279
1280 let (control, _outputs) = TestComponentDriver::source(config).await.expect("source should build");
1281 control.wait_until_ready().await;
1282
1283 for server in ["http-server-otlp-grpc", "http-server-otlp-http"] {
1284 let mut bound = control
1285 .supervisor()
1286 .dataspace()
1287 .subscribe::<BoundListenAddress>(IdentifierFilter::exact(server));
1288 match bound.recv().await {
1289 Some(DataspaceUpdate::Asserted(_, BoundListenAddress::Tcp(_))) => {}
1290 update => panic!("expected {server} to bind, got {update:?}"),
1291 }
1292 }
1293
1294 control.shutdown().await.expect("source should stop cleanly");
1295 }
1296
1297 #[tokio::test]
1298 async fn build_fails_when_internal_metrics_have_invalid_settings() {
1299 let mut config = source_configuration();
1300 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1301 config.metrics = OtlpMetricsSettings {
1302 histogram_mode: HistogramMode::NoBuckets,
1303 send_histogram_aggregations: false,
1304 ..metrics_settings()
1305 };
1306
1307 let error = TestComponentDriver::source(config)
1308 .await
1309 .err()
1310 .expect("source should fail to build with invalid metrics settings");
1311 assert!(
1312 format!("{error:#}").contains("Failed to validate OTLP metrics translator configuration"),
1313 "unexpected error: {error:#}"
1314 );
1315 }
1316
1317 #[tokio::test]
1318 async fn a_proxied_signal_needs_proxy_destinations() {
1319 init_crypto_provider();
1320 let mut config = source_configuration();
1321 config.receiver.grpc.endpoint = "127.0.0.1:0".to_string();
1322 config.receiver.http.endpoint = "127.0.0.1:0".to_string();
1323 config.routes = OtlpRoutes {
1324 traces: OtlpRoute::Proxied,
1325 ..OtlpRoutes::ALL_INTERNAL
1326 };
1327
1328 match config.build(BuildContext::test_source("otlp_proxy_destinations")).await {
1329 Ok(_) => panic!("build should fail without proxy destinations"),
1330 Err(e) => assert_eq!(
1331 e.to_string(),
1332 "An OTLP signal is proxied, but the OTLP source has no proxy destinations."
1333 ),
1334 }
1335
1336 let destination = |port| Destination::Tcp {
1337 host: "127.0.0.1".to_string(),
1338 port,
1339 };
1340 config.proxy_destinations = Some(OtlpProxyDestinations {
1341 grpc: Some(destination(4319)),
1342 http: Some(destination(4320)),
1343 });
1344 if let Err(e) = config.build(BuildContext::test_source("otlp_proxy_destinations")).await {
1345 panic!("build should succeed with proxy destinations: {e}");
1346 }
1347 }
1348}