diff --git a/bottlecap/src/bin/bottlecap/main.rs b/bottlecap/src/bin/bottlecap/main.rs index e000b7a34..660ee3627 100644 --- a/bottlecap/src/bin/bottlecap/main.rs +++ b/bottlecap/src/bin/bottlecap/main.rs @@ -511,6 +511,7 @@ async fn extension_loop_active( trace_processor.clone(), trace_agent_channel.clone(), stats_concentrator.clone(), + Arc::clone(&proxy_aggregator), ); // Validate and get the appropriate flush strategy for the current mode @@ -1391,6 +1392,7 @@ fn start_otlp_agent( trace_processor: Arc, trace_tx: Sender, stats_concentrator: StatsConcentratorHandle, + proxy_aggregator: Arc>, ) -> Option { if !should_enable_otlp_agent(config) { return None; @@ -1405,6 +1407,7 @@ fn start_otlp_agent( trace_processor, trace_tx, stats_generator, + proxy_aggregator, cancel_token.clone(), ); diff --git a/bottlecap/src/config/mod.rs b/bottlecap/src/config/mod.rs index bd27a54ff..9ba632b3e 100644 --- a/bottlecap/src/config/mod.rs +++ b/bottlecap/src/config/mod.rs @@ -145,6 +145,12 @@ pub struct LambdaConfig { /// present in the Lambda event payload (`DD_DSM_KAFKA_GROUP`). pub dsm_kafka_group: Option, + /// `DD_METRICS_OTEL_ENABLED`: the tracer libraries' flag for sending `OpenTelemetry` + /// metrics to `localhost:4318`. When set, the extension also accepts + /// `/v1/metrics` and forwards it to Datadog's OTLP intake, as + /// `DD_OTLP_CONFIG_METRICS_ENABLED` does. + pub metrics_otel_enabled: bool, + /// `DD_TRACE_EXPERIMENTAL_FEATURES_ENABLED`: gates `additional_metric_tags` and /// `additional_metric_tags_cardinality_limit` below, matching the Serverless /// Compatibility Layer (`datadog-trace-agent`). @@ -187,6 +193,7 @@ impl Default for LambdaConfig { dsm_consume_enabled: false, dsm_exchange_name: None, dsm_kafka_group: None, + metrics_otel_enabled: false, trace_experimental_features_enabled: false, additional_metric_tags: Vec::new(), additional_metric_tags_cardinality_limit: None, @@ -326,6 +333,10 @@ pub struct LambdaConfigSource { #[serde(deserialize_with = "deser_opt_str")] pub dsm_kafka_group: Option, + /// `DD_METRICS_OTEL_ENABLED`: see `LambdaConfig::metrics_otel_enabled`. + #[serde(deserialize_with = "deser_opt_bool")] + pub metrics_otel_enabled: Option, + /// `DD_TRACE_EXPERIMENTAL_FEATURES_ENABLED`: see `LambdaConfig::trace_experimental_features_enabled`. #[serde(deserialize_with = "deser_opt_bool")] pub trace_experimental_features_enabled: Option, @@ -367,6 +378,7 @@ impl DatadogConfigExtension for LambdaConfig { api_security_sample_delay, trace_remove_integration_service_names_enabled, lambda_durable_function_log_buffer_size, + metrics_otel_enabled, trace_experimental_features_enabled, ], option: [span_dedup_timeout, api_key_secret_reload_interval, appsec_rules, serverless_error_sampler_enabled, dsm_exchange_name, dsm_kafka_group], diff --git a/bottlecap/src/otlp/agent.rs b/bottlecap/src/otlp/agent.rs index 20dccc3bc..c897c6ecb 100644 --- a/bottlecap/src/otlp/agent.rs +++ b/bottlecap/src/otlp/agent.rs @@ -1,7 +1,7 @@ use axum::{ Router, extract::{Request, State}, - http::{StatusCode, header}, + http::{HeaderValue, StatusCode, header}, response::{IntoResponse, Response}, routing::post, }; @@ -14,7 +14,10 @@ use opentelemetry_proto::tonic::collector::trace::v1::{ use prost::Message; use std::net::SocketAddr; use std::sync::Arc; -use tokio::{net::TcpListener, sync::mpsc::Sender}; +use tokio::{ + net::TcpListener, + sync::{Mutex, mpsc::Sender}, +}; use tokio_util::sync::CancellationToken; use tonic_types::Status as ProtoStatus; use tracing::{debug, error}; @@ -22,9 +25,13 @@ use tracing::{debug, error}; use crate::{ config::Config, http::{extract_request_body, handler_not_found}, - otlp::processor::{OtlpEncoding, Processor as OtlpProcessor}, + otlp::{ + processor::{OtlpEncoding, Processor as OtlpProcessor}, + should_enable_otlp_metrics, should_enable_otlp_traces, + }, tags::provider, traces::{ + proxy_aggregator::{self, ProxyRequest}, stats_generator::StatsGenerator, trace_aggregator::SendDataBuilderInfo, trace_processor::{StatsComputedBy, TraceProcessor}, @@ -36,6 +43,19 @@ const OTLP_AGENT_GRPC_PORT: u16 = 4317; const DEFAULT_MAX_RECV_MSG_SIZE: usize = 4 * 1024 * 1024; // 4MB default const MAX_RECV_MSG_SIZE_CAP: usize = 50 * 1024 * 1024; // 50MB cap (matches trace agent) +const OTLP_METRICS_PATH: &str = "/v1/metrics"; +const DD_OTEL_METRIC_CONFIG_HEADER: &str = "dd-otel-metric-config"; +// Turns resource attributes (service, env, runtime-id, DD_TAGS) into metric tags. +const DD_OTEL_METRIC_CONFIG: &str = r#"{"resource_attributes_as_tags": true}"#; + +/// State for `/v1/metrics`: requests are queued unchanged and sent to Datadog's OTLP intake +/// by the proxy flusher. +#[derive(Clone)] +struct MetricsProxy { + config: Arc, + proxy_aggregator: Arc>, +} + /// Shared state and trace processing pipeline used by both HTTP and gRPC handlers. #[derive(Clone)] struct TracePipeline { @@ -140,6 +160,8 @@ impl TraceService for TracePipeline { pub struct Agent { pipeline: TracePipeline, + metrics_proxy: Option, + traces_enabled: bool, cancel_token: CancellationToken, http_port: Option, grpc_port: Option, @@ -152,18 +174,27 @@ impl Agent { trace_processor: Arc, trace_tx: Sender, stats_generator: Arc, + proxy_aggregator: Arc>, cancel_token: CancellationToken, ) -> Self { - let http_port = config - .otlp_config_receiver_protocols_http_endpoint - .as_ref() - .map(|ep| Self::parse_port(Some(ep), OTLP_AGENT_HTTP_PORT)); + let traces_enabled = should_enable_otlp_traces(&config); + let metrics_enabled = should_enable_otlp_metrics(&config); + + let http_endpoint = config.otlp_config_receiver_protocols_http_endpoint.as_ref(); + let http_port = (metrics_enabled || (traces_enabled && http_endpoint.is_some())) + .then(|| Self::parse_port(http_endpoint, OTLP_AGENT_HTTP_PORT)); let grpc_port = config .otlp_config_receiver_protocols_grpc_endpoint .as_ref() + .filter(|_| traces_enabled) .map(|ep| Self::parse_port(Some(ep), OTLP_AGENT_GRPC_PORT)); + let metrics_proxy = metrics_enabled.then(|| MetricsProxy { + config: Arc::clone(&config), + proxy_aggregator, + }); + let pipeline = TracePipeline { config: Arc::clone(&config), tags_provider: Arc::clone(&tags_provider), @@ -175,6 +206,8 @@ impl Agent { Self { pipeline, + metrics_proxy, + traces_enabled, cancel_token, http_port, grpc_port, @@ -208,11 +241,14 @@ impl Agent { let mut handles: Vec> = Vec::new(); if let Some(port) = self.http_port { - let pipeline = self.pipeline.clone(); + let router = Self::http_router( + self.traces_enabled.then(|| self.pipeline.clone()), + self.metrics_proxy.clone(), + ); let cancel_token = self.cancel_token.clone(); handles.push(tokio::spawn(async move { - if let Err(e) = Self::start_http(port, pipeline, cancel_token).await { + if let Err(e) = Self::start_http(port, router, cancel_token).await { error!("OTLP HTTP agent error: {e:?}"); } })); @@ -241,16 +277,31 @@ impl Agent { Ok(()) } + fn http_router(pipeline: Option, metrics_proxy: Option) -> Router { + let mut router = Router::new(); + if let Some(pipeline) = pipeline { + router = router.merge( + Router::new() + .route("/v1/traces", post(Self::v1_traces)) + .with_state(pipeline), + ); + } + if let Some(metrics_proxy) = metrics_proxy { + router = router.merge( + Router::new() + .route(OTLP_METRICS_PATH, post(Self::v1_metrics)) + .with_state(metrics_proxy), + ); + } + router.fallback(handler_not_found) + } + async fn start_http( port: u16, - pipeline: TracePipeline, + router: Router, cancel_token: CancellationToken, ) -> Result<(), Box> { let socket = SocketAddr::from(([127, 0, 0, 1], port)); - let router = Router::new() - .route("/v1/traces", post(Self::v1_traces)) - .fallback(handler_not_found) - .with_state(pipeline); let listener = TcpListener::bind(&socket).await?; debug!("OTLP HTTP | Starting collector on {}", socket); @@ -366,6 +417,49 @@ impl Agent { } } + async fn v1_metrics(State(metrics_proxy): State, request: Request) -> Response { + let encoding = OtlpEncoding::from_content_type( + request + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + ); + + let (mut parts, body) = match extract_request_body(request).await { + Ok(r) => r, + Err(e) => { + error!("OTLP HTTP | Failed to extract metrics request body: {e}"); + return Self::otlp_error_response( + StatusCode::BAD_REQUEST, + format!("Failed to extract request body: {e}"), + encoding, + ); + } + }; + + parts.headers.insert( + DD_OTEL_METRIC_CONFIG_HEADER, + HeaderValue::from_static(DD_OTEL_METRIC_CONFIG), + ); + let proxy_request = ProxyRequest { + headers: parts.headers, + body, + target_url: format!( + "https://otlp.{}{OTLP_METRICS_PATH}", + metrics_proxy.config.site + ), + }; + metrics_proxy + .proxy_aggregator + .lock() + .await + .add(proxy_request); + debug!("OTLP HTTP | Queued metrics for the OTLP intake"); + + // An empty trace export response encodes the same as an empty metrics one. + Self::otlp_success_response(encoding) + } + fn otlp_error_response( status_code: StatusCode, message: String, @@ -451,9 +545,116 @@ impl Agent { } #[cfg(test)] +#[allow(clippy::unwrap_used)] mod tests { use super::*; + use axum::body::Body; + use tower::ServiceExt; + + fn metrics_proxy() -> MetricsProxy { + MetricsProxy { + config: Arc::new(Config { + site: "datadoghq.eu".to_string(), + ..Config::default() + }), + proxy_aggregator: Arc::new(Mutex::new(proxy_aggregator::Aggregator::default())), + } + } + + fn post_request(path: &str, content_type: &str, body: &'static [u8]) -> Request { + Request::builder() + .method("POST") + .uri(path) + .header(header::CONTENT_TYPE, content_type) + .body(Body::from(body)) + .unwrap() + } + + #[tokio::test] + async fn test_v1_metrics_queues_request_for_otlp_intake() { + let metrics_proxy = metrics_proxy(); + let router = Agent::http_router(None, Some(metrics_proxy.clone())); + + let response = router + .oneshot(post_request( + "/v1/metrics", + "application/x-protobuf", + b"\x0a\x02\x08\x01", + )) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get(header::CONTENT_TYPE).unwrap(), + "application/x-protobuf" + ); + + let batch = metrics_proxy.proxy_aggregator.lock().await.get_batch(); + assert_eq!(batch.len(), 1); + let request = batch.first().unwrap(); + assert_eq!(request.target_url, "https://otlp.datadoghq.eu/v1/metrics"); + assert_eq!(request.body.as_ref(), b"\x0a\x02\x08\x01"); + assert_eq!( + request.headers.get(header::CONTENT_TYPE).unwrap(), + "application/x-protobuf" + ); + assert_eq!( + request.headers.get(DD_OTEL_METRIC_CONFIG_HEADER).unwrap(), + DD_OTEL_METRIC_CONFIG + ); + } + + #[tokio::test] + async fn test_v1_metrics_replies_json_for_json_request() { + let router = Agent::http_router(None, Some(metrics_proxy())); + + let response = router + .oneshot(post_request("/v1/metrics", "application/json", b"{}")) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::OK); + assert_eq!( + response.headers().get(header::CONTENT_TYPE).unwrap(), + "application/json" + ); + } + + #[tokio::test] + async fn test_v1_metrics_not_found_when_metrics_disabled() { + let router = Agent::http_router(None, None); + + let response = router + .oneshot(post_request("/v1/metrics", "application/x-protobuf", b"")) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + } + + #[tokio::test] + async fn test_v1_traces_not_found_when_only_metrics_enabled() { + let metrics_proxy = metrics_proxy(); + let router = Agent::http_router(None, Some(metrics_proxy.clone())); + + let response = router + .oneshot(post_request("/v1/traces", "application/x-protobuf", b"")) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::NOT_FOUND); + assert!( + metrics_proxy + .proxy_aggregator + .lock() + .await + .get_batch() + .is_empty() + ); + } + #[test] fn test_parse_port_with_valid_endpoint() { let endpoint = Some("localhost:8080".to_string()); diff --git a/bottlecap/src/otlp/mod.rs b/bottlecap/src/otlp/mod.rs index 28f26039b..25d062ea7 100644 --- a/bottlecap/src/otlp/mod.rs +++ b/bottlecap/src/otlp/mod.rs @@ -8,6 +8,11 @@ pub mod transform; #[must_use] pub fn should_enable_otlp_agent(config: &Arc) -> bool { + should_enable_otlp_traces(config) || should_enable_otlp_metrics(config) +} + +#[must_use] +pub fn should_enable_otlp_traces(config: &Config) -> bool { config.otlp_config_traces_enabled && (config .otlp_config_receiver_protocols_http_endpoint @@ -17,6 +22,13 @@ pub fn should_enable_otlp_agent(config: &Arc) -> bool { .is_some()) } +/// Metrics are forwarded to Datadog's OTLP intake as-is, over HTTP only. They don't need an +/// endpoint to be configured: the listener falls back to the tracers' default port. +#[must_use] +pub fn should_enable_otlp_metrics(config: &Config) -> bool { + config.otlp_config_metrics_enabled || config.ext.metrics_otel_enabled +} + #[cfg(test)] mod tests { use super::*; @@ -131,4 +143,70 @@ mod tests { Ok(()) }); } + + #[test] + fn test_should_enable_otlp_metrics_from_otlp_config_without_endpoints() { + figment::Jail::expect_with(|jail| { + jail.clear_env(); + jail.set_env("DD_OTLP_CONFIG_METRICS_ENABLED", "true"); + + let config = Arc::new(get_config(Path::new(""))); + assert!(should_enable_otlp_agent(&config)); + assert!(should_enable_otlp_metrics(&config)); + assert!(!should_enable_otlp_traces(&config)); + + Ok(()) + }); + } + + #[test] + fn test_should_enable_otlp_metrics_from_tracer_flag() { + figment::Jail::expect_with(|jail| { + jail.clear_env(); + jail.set_env("DD_METRICS_OTEL_ENABLED", "true"); + + let config = Arc::new(get_config(Path::new(""))); + assert!(should_enable_otlp_agent(&config)); + assert!(should_enable_otlp_metrics(&config)); + + Ok(()) + }); + } + + #[test] + fn test_should_enable_otlp_metrics_with_traces_disabled() { + figment::Jail::expect_with(|jail| { + jail.clear_env(); + jail.set_env("DD_OTLP_CONFIG_TRACES_ENABLED", "false"); + jail.set_env( + "DD_OTLP_CONFIG_RECEIVER_PROTOCOLS_HTTP_ENDPOINT", + "0.0.0.0:4318", + ); + jail.set_env("DD_METRICS_OTEL_ENABLED", "true"); + + let config = Arc::new(get_config(Path::new(""))); + assert!(should_enable_otlp_agent(&config)); + assert!(!should_enable_otlp_traces(&config)); + assert!(should_enable_otlp_metrics(&config)); + + Ok(()) + }); + } + + #[test] + fn test_should_not_enable_otlp_metrics_by_default() { + figment::Jail::expect_with(|jail| { + jail.clear_env(); + jail.set_env( + "DD_OTLP_CONFIG_RECEIVER_PROTOCOLS_HTTP_ENDPOINT", + "0.0.0.0:4318", + ); + + let config = Arc::new(get_config(Path::new(""))); + assert!(should_enable_otlp_traces(&config)); + assert!(!should_enable_otlp_metrics(&config)); + + Ok(()) + }); + } } diff --git a/bottlecap/tests/otlp_metrics_forwarding_test.rs b/bottlecap/tests/otlp_metrics_forwarding_test.rs new file mode 100644 index 000000000..ac0deafd9 --- /dev/null +++ b/bottlecap/tests/otlp_metrics_forwarding_test.rs @@ -0,0 +1,162 @@ +// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 +// Integration tests are exempt from the production lint policy in Cargo.toml. +#![allow( + unreachable_pub, + clippy::pedantic, + clippy::panic, + clippy::unwrap_used, + clippy::expect_used +)] + +//! An OTLP metrics export posted to the OTLP agent reaches the intake unchanged, with the API +//! key and the header that turns resource attributes into tags. The agent always targets +//! `https://otlp.`; here the queued request is pointed at a local intake before the flush. + +mod fixtures; +#[path = "common/harness.rs"] +mod harness; + +use std::collections::HashMap; +use std::io::Write; +use std::sync::Arc; + +use bottlecap::LAMBDA_RUNTIME_SLUG; +use bottlecap::config::{Config, DEFAULT_APM_ERROR_TPS, LambdaConfig}; +use bottlecap::otlp::agent::Agent; +use bottlecap::tags::provider::Provider; +use bottlecap::traces::proxy_aggregator::{Aggregator as ProxyAggregator, ProxyRequest}; +use bottlecap::traces::proxy_flusher::Flusher as ProxyFlusher; +use bottlecap::traces::stats_concentrator_service::StatsConcentratorService; +use bottlecap::traces::stats_generator::StatsGenerator; +use bottlecap::traces::trace_processor::{ServerlessTraceProcessor, new_error_sampler}; +use datadog_fips::reqwest_adapter::create_reqwest_client_builder; +use dogstatsd::api_key::ApiKeyFactory; +use flate2::{Compression, write::GzEncoder}; +use harness::prelude::*; +use libdd_trace_obfuscation::obfuscation_config::ObfuscationConfig; +use tokio::sync::Mutex; +use tokio_util::sync::CancellationToken; + +const METRICS_EXPORT: &str = r#"{"resourceMetrics":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"otlp-forwarding-test"}},{"key":"runtime-id","value":{"stringValue":"8f0c1c9e-runtime"}}]},"scopeMetrics":[{"scope":{"name":"test"},"metrics":[{"name":"otlp.forwarding.requests","sum":{"aggregationTemporality":1,"isMonotonic":true,"dataPoints":[{"asInt":"3","timeUnixNano":"1700000000000000000"}]}}]}]}]}"#; + +#[tokio::test] +async fn metrics_export_is_forwarded_unchanged_with_metric_config_header() { + let intake = FaultIntake::start(FaultMode::Ok).await; + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let config = Arc::new(Config { + api_key: TEST_API_KEY.to_string(), + site: "datadoghq.com".to_string(), + otlp_config_traces_enabled: false, + otlp_config_receiver_protocols_http_endpoint: Some(format!("127.0.0.1:{port}")), + ext: LambdaConfig { + metrics_otel_enabled: true, + ..Default::default() + }, + ..Config::default() + }); + let tags = Arc::new(Provider::new( + Arc::clone(&config), + LAMBDA_RUNTIME_SLUG.to_string(), + &HashMap::from([( + "function_arn".to_string(), + "arn:aws:lambda:us-east-1:123456789012:function:test".to_string(), + )]), + )); + let proxy_aggregator = Arc::new(Mutex::new(ProxyAggregator::default())); + + // Traces are disabled, so the trace pipeline is only there to satisfy the constructor. + let (trace_tx, _trace_rx) = tokio::sync::mpsc::channel(1); + let (_concentrator, concentrator_handle) = StatsConcentratorService::new(Arc::clone(&config)); + let cancel_token = CancellationToken::new(); + let agent = Agent::new( + Arc::clone(&config), + Arc::clone(&tags), + Arc::new(ServerlessTraceProcessor { + obfuscation_config: Arc::new(ObfuscationConfig::default()), + error_sampler: new_error_sampler(DEFAULT_APM_ERROR_TPS), + error_rare_sample_tracer_drop: false, + }), + trace_tx, + Arc::new(StatsGenerator::new(concentrator_handle)), + Arc::clone(&proxy_aggregator), + cancel_token.clone(), + ); + tokio::spawn(async move { + let _ = agent.start().await; + }); + + let mut gzip = GzEncoder::new(Vec::new(), Compression::default()); + gzip.write_all(METRICS_EXPORT.as_bytes()).unwrap(); + let body = gzip.finish().unwrap(); + + // Test-only client towards local servers; the FIPS adapter is what production uses. + let client = create_reqwest_client_builder() + .expect("client builder") + .no_proxy() + .build() + .expect("client"); + let deadline = Instant::now() + secs(5); + let response = loop { + match client + .post(format!("http://127.0.0.1:{port}/v1/metrics")) + .header("content-type", "application/json") + .header("content-encoding", "gzip") + .body(body.clone()) + .send() + .await + { + Ok(response) => break response, + Err(e) if e.is_connect() && Instant::now() < deadline => { + tokio::time::sleep(ms(20)).await; + } + Err(e) => panic!("OTLP agent did not accept the export: {e}"), + } + }; + assert_eq!(response.status(), 200); + assert_eq!( + response.headers().get("content-type").unwrap(), + "application/json" + ); + + let mut queued = proxy_aggregator.lock().await.get_batch(); + assert_eq!(queued.len(), 1); + let request = queued.pop().unwrap(); + assert_eq!(request.target_url, "https://otlp.datadoghq.com/v1/metrics"); + proxy_aggregator.lock().await.add(ProxyRequest { + target_url: format!("{}/v1/metrics", intake.url()), + ..request + }); + + let flusher = ProxyFlusher::new( + Arc::new(ApiKeyFactory::new(TEST_API_KEY)), + Arc::clone(&proxy_aggregator), + tags, + Arc::clone(&config), + client, + ); + let failed = flusher.flush(None).await; + assert!( + failed.is_none(), + "flush failed: {failed:?}. {}", + intake.summary() + ); + + let sent = intake.requests_to("/v1/metrics"); + assert_eq!(sent.len(), 1, "{}", intake.summary()); + assert_eq!(sent[0].api_key(), Some(TEST_API_KEY)); + assert_eq!( + sent[0].header("dd-otel-metric-config"), + Some(r#"{"resource_attributes_as_tags": true}"#) + ); + assert_eq!(sent[0].header("content-type"), Some("application/json")); + assert_eq!(sent[0].header("content-encoding"), Some("gzip")); + assert_eq!(sent[0].body, body); + assert_eq!(sent[0].body_text().unwrap(), METRICS_EXPORT); + + cancel_token.cancel(); +} diff --git a/integration-tests/lambda/otlp-metrics-node/index.js b/integration-tests/lambda/otlp-metrics-node/index.js new file mode 100644 index 000000000..4052a11ed --- /dev/null +++ b/integration-tests/lambda/otlp-metrics-node/index.js @@ -0,0 +1,19 @@ +// dd-trace (DD_METRICS_OTEL_ENABLED) registers the global MeterProvider and exports to +// localhost:4318/v1/metrics every OTEL_METRIC_EXPORT_INTERVAL ms. +const { metrics } = require('@opentelemetry/api'); + +const COUNTER_NAME = 'integration.otlp_metrics.requests'; +const COUNTER_INCREMENT = 5; +const EXPORT_WAIT_MS = 3000; + +exports.handler = async (event, context) => { + metrics.getMeter('otlp-metrics-node').createCounter(COUNTER_NAME).add(COUNTER_INCREMENT); + + // The function freezes after it returns, so wait for a periodic export during the invocation. + await new Promise(resolve => setTimeout(resolve, EXPORT_WAIT_MS)); + + return { + statusCode: 200, + body: JSON.stringify({ message: 'Success', requestId: context.awsRequestId }), + }; +}; diff --git a/integration-tests/lib/stacks/otlp.ts b/integration-tests/lib/stacks/otlp.ts index 62f2f2feb..ef01ff1a9 100644 --- a/integration-tests/lib/stacks/otlp.ts +++ b/integration-tests/lib/stacks/otlp.ts @@ -146,5 +146,33 @@ export class Otlp extends cdk.Stack { }); dotnetFunction.addToRolePolicy(defaultDatadogSecretPolicy); dotnetFunction.addLayers(extensionLayer); + + // The default Node layer bundles dd-trace 5.80, which predates OTel metrics; this one + // bundles dd-trace 6.24. + const otelMetricsNodeLayer = lambda.LayerVersion.fromLayerVersionArn( + this, + 'DatadogNodeOtelMetricsLayer', + 'arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Node24-x:144' + ); + const otelMetricsFunctionName = `${id}-otel-metrics-node-lambda`; + const otelMetricsFunction = new lambda.Function(this, otelMetricsFunctionName, { + runtime: defaultNodeRuntime, + architecture: lambda.Architecture.ARM_64, + handler: '/opt/nodejs/node_modules/datadog-lambda-js/handler.handler', + code: lambda.Code.fromAsset('./lambda/otlp-metrics-node'), + functionName: otelMetricsFunctionName, + timeout: cdk.Duration.seconds(30), + memorySize: 256, + environment: { + ...defaultDatadogEnvVariables, + DD_SERVICE: otelMetricsFunctionName, + DD_LAMBDA_HANDLER: 'index.handler', + DD_METRICS_OTEL_ENABLED: 'true', + OTEL_METRIC_EXPORT_INTERVAL: '1000', + }, + logGroup: createLogGroup(this, otelMetricsFunctionName) + }); + otelMetricsFunction.addToRolePolicy(defaultDatadogSecretPolicy); + otelMetricsFunction.addLayers(extensionLayer, otelMetricsNodeLayer); } } diff --git a/integration-tests/tests/otlp.test.ts b/integration-tests/tests/otlp.test.ts index c16128f34..656c379d9 100644 --- a/integration-tests/tests/otlp.test.ts +++ b/integration-tests/tests/otlp.test.ts @@ -1,14 +1,20 @@ import { invokeAndCollectTelemetry, FunctionConfig } from './utils/default'; -import { DatadogTelemetry } from './utils/datadog'; +import { DatadogTelemetry, getMetricCountByService } from './utils/datadog'; import { IDENTIFIER, DATADOG_INDEXING_WAIT_5_MIN_MS } from '../config'; const runtimes = ['node', 'python', 'java', 'dotnet'] as const; type Runtime = typeof runtimes[number]; const stackName = `${IDENTIFIER}-otlp`; +const otelMetricsFunctionName = `${stackName}-otel-metrics-node-lambda`; +// Must match lambda/otlp-metrics-node/index.js. +const OTEL_COUNTER_NAME = 'integration.otlp_metrics.requests'; +const OTEL_COUNTER_INCREMENT = 5; describe('OTLP Integration Tests', () => { let telemetry: Record; + let metricsStartTime: number; + let metricsEndTime: number; beforeAll(async () => { // Build function configs for all runtimes plus response validation and gRPC @@ -25,13 +31,22 @@ describe('OTLP Integration Tests', () => { functionName: `${stackName}-node-grpc-lambda`, runtime: 'nodeGrpc', }, + { + functionName: otelMetricsFunctionName, + runtime: 'otelMetrics', + }, ]; console.log('Invoking all OTLP Lambda functions...'); + // Back up 60s so the metric's rollup bucket falls inside the query range. + metricsStartTime = Date.now() - 60_000; + // Invoke all OTLP functions and collect telemetry telemetry = await invokeAndCollectTelemetry(functions, 1, 1, 0, {}, DATADOG_INDEXING_WAIT_5_MIN_MS); + metricsEndTime = Date.now(); + console.log('All OTLP Lambda invocations and data fetching completed'); }, 1800000); @@ -120,4 +135,33 @@ describe('OTLP Integration Tests', () => { expect(trace.spans.length).toBeGreaterThan(0); }); }); + + describe('OTLP Metrics Forwarding', () => { + it('should invoke the OTel metrics Lambda successfully', () => { + const result = telemetry['otelMetrics']?.threads[0]?.[0]; + expect(result).toBeDefined(); + expect(result.statusCode).toBe(200); + }); + + it('should deliver the counter to Datadog with its full value', async () => { + const count = await getMetricCountByService( + OTEL_COUNTER_NAME, + otelMetricsFunctionName, + metricsStartTime, + metricsEndTime, + ); + expect(count).toBe(OTEL_COUNTER_INCREMENT); + }); + + it('should tag the counter with runtime-id', async () => { + const count = await getMetricCountByService( + OTEL_COUNTER_NAME, + otelMetricsFunctionName, + metricsStartTime, + metricsEndTime, + 'runtime-id:*', + ); + expect(count).toBe(OTEL_COUNTER_INCREMENT); + }); + }); }); diff --git a/integration-tests/tests/utils/datadog.ts b/integration-tests/tests/utils/datadog.ts index 6dfde2dd2..8541dd244 100644 --- a/integration-tests/tests/utils/datadog.ts +++ b/integration-tests/tests/utils/datadog.ts @@ -404,6 +404,36 @@ export async function getMetricCountWithTag( return pointlist.reduce((acc, [, value]) => acc + (value || 0), 0); } +/** + * Sums a count metric for one service over the window. Metrics forwarded to the OTLP intake + * are tagged from their resource attributes, so they carry `service` rather than `functionname`. + */ +export async function getMetricCountByService( + metricName: string, + service: string, + fromTime: number, + toTime: number, + tagFilter?: string, +): Promise { + const filter = [`service:${service.toLowerCase()}`, tagFilter].filter(Boolean).join(','); + const query = `sum:${metricName}{${filter}}.as_count()`; + + console.log(`Querying metric count: ${query}`); + + const response = await requestWithRetry(() => datadogClient.get('/api/v1/query', { + params: { + query, + from: Math.floor(fromTime / 1000), + to: Math.floor(toTime / 1000), + }, + }), query); + + const series = response.data.series || []; + return series + .flatMap((s: any) => s.pointlist || []) + .reduce((acc: number, [, value]: [number, number]) => acc + (value || 0), 0); +} + async function getMetrics( metricName: string, functionName: string,