diff --git a/Cargo.lock b/Cargo.lock index 8970e45..c8c582f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -568,6 +568,7 @@ dependencies = [ "libdd-common 3.0.1", "libdd-trace-obfuscation", "libdd-trace-protobuf 3.0.0", + "libdd-trace-stats 1.0.4", "libdd-trace-utils 3.0.0", "reqwest", "rmp-serde", @@ -576,6 +577,7 @@ dependencies = [ "serial_test", "temp-env", "tempfile", + "thiserror 1.0.69", "tokio", "tracing", ] @@ -1509,12 +1511,12 @@ dependencies = [ "http", "http-body-util", "libdd-common 2.0.1", - "libdd-ddsketch", + "libdd-ddsketch 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "libdd-dogstatsd-client", "libdd-telemetry", "libdd-tinybytes 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "libdd-trace-protobuf 2.0.0", - "libdd-trace-stats", + "libdd-trace-stats 1.0.3", "libdd-trace-utils 2.0.2", "rmp-serde", "serde", @@ -1535,6 +1537,14 @@ dependencies = [ "prost 0.14.3", ] +[[package]] +name = "libdd-ddsketch" +version = "1.0.1" +source = "git+https://github.com/DataDog/libdatadog?rev=8c88979985154d6d97c0fc2ca9039682981eacad#8c88979985154d6d97c0fc2ca9039682981eacad" +dependencies = [ + "prost 0.14.3", +] + [[package]] name = "libdd-dogstatsd-client" version = "1.0.1" @@ -1563,7 +1573,7 @@ dependencies = [ "http-body-util", "libc", "libdd-common 2.0.1", - "libdd-ddsketch", + "libdd-ddsketch 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "serde", "serde_json", "sys-info", @@ -1655,11 +1665,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea447dc8a5d84c6b5eb6ea877c4fea4149fd29f6b45fcfc5cfd7edf82a18e056" dependencies = [ "hashbrown 0.15.5", - "libdd-ddsketch", + "libdd-ddsketch 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "libdd-trace-protobuf 2.0.0", "libdd-trace-utils 2.0.2", ] +[[package]] +name = "libdd-trace-stats" +version = "1.0.4" +source = "git+https://github.com/DataDog/libdatadog?rev=8c88979985154d6d97c0fc2ca9039682981eacad#8c88979985154d6d97c0fc2ca9039682981eacad" +dependencies = [ + "hashbrown 0.15.5", + "libdd-ddsketch 1.0.1 (git+https://github.com/DataDog/libdatadog?rev=8c88979985154d6d97c0fc2ca9039682981eacad)", + "libdd-trace-protobuf 3.0.0", + "libdd-trace-utils 3.0.0", +] + [[package]] name = "libdd-trace-utils" version = "2.0.2" diff --git a/crates/datadog-serverless-compat/src/main.rs b/crates/datadog-serverless-compat/src/main.rs index 8c20c41..0aae807 100644 --- a/crates/datadog-serverless-compat/src/main.rs +++ b/crates/datadog-serverless-compat/src/main.rs @@ -18,7 +18,8 @@ use zstd::zstd_safe::CompressionLevel; use datadog_trace_agent::{ aggregator::TraceAggregator, - config, env_verifier, mini_agent, proxy_flusher, stats_flusher, stats_processor, + config, env_verifier, mini_agent, proxy_flusher, stats_concentrator_service, stats_flusher, + stats_generator, stats_processor, trace_flusher::{self, TraceFlusher}, trace_processor, }; @@ -119,6 +120,12 @@ pub async fn main() { .ok() .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_LOG_INTAKE_PORT); + + let dd_serverless_stats_computation_enabled = + env::var("DD_SERVERLESS_STATS_COMPUTATION_ENABLED") + .map(|val| val.to_lowercase() != "false") + .unwrap_or(true); + debug!("Starting serverless trace mini agent"); let env_filter = format!("h2=off,hyper=off,rustls=off,{}", log_level); @@ -144,11 +151,6 @@ pub async fn main() { let env_verifier = Arc::new(env_verifier::ServerlessEnvVerifier::default()); - let trace_processor = Arc::new(trace_processor::ServerlessTraceProcessor {}); - - let stats_flusher = Arc::new(stats_flusher::ServerlessStatsFlusher {}); - let stats_processor = Arc::new(stats_processor::ServerlessStatsProcessor {}); - let config = match config::Config::new() { Ok(c) => Arc::new(c), Err(e) => { @@ -157,6 +159,29 @@ pub async fn main() { } }; + let (stats_concentrator_handle, stats_generator) = if dd_serverless_stats_computation_enabled { + info!("serverless stats computation enabled"); + let (service, handle) = + stats_concentrator_service::StatsConcentratorService::new(config.clone()); + tokio::spawn(service.run()); + ( + Some(handle.clone()), + Some(Arc::new(stats_generator::StatsGenerator::new(handle))), + ) + } else { + info!("serverless stats computation disabled"); + (None, None) + }; + + let trace_processor = Arc::new(trace_processor::ServerlessTraceProcessor { + stats_generator: stats_generator.clone(), + }); + + let stats_flusher = Arc::new(stats_flusher::ServerlessStatsFlusher { + stats_concentrator: stats_concentrator_handle.clone(), + }); + let stats_processor = Arc::new(stats_processor::ServerlessStatsProcessor {}); + let trace_aggregator = Arc::new(TokioMutex::new(TraceAggregator::default())); let trace_flusher = Arc::new(trace_flusher::ServerlessTraceFlusher::new( trace_aggregator, @@ -175,8 +200,9 @@ pub async fn main() { proxy_flusher, }); + let (_shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); tokio::spawn(async move { - let res = mini_agent.start_mini_agent().await; + let res = mini_agent.start_mini_agent(shutdown_rx).await; if let Err(e) = res { error!("Error when starting serverless trace mini agent: {e:?}"); } diff --git a/crates/datadog-trace-agent/Cargo.toml b/crates/datadog-trace-agent/Cargo.toml index 1a69733..8822105 100644 --- a/crates/datadog-trace-agent/Cargo.toml +++ b/crates/datadog-trace-agent/Cargo.toml @@ -24,14 +24,19 @@ async-trait = "0.1.64" tracing = { version = "0.1", default-features = false } serde = { version = "1.0.145", features = ["derive"] } serde_json = "1.0" +thiserror = { version = "1.0.58", default-features = false } libdd-common = { git = "https://github.com/DataDog/libdatadog", rev = "8c88979985154d6d97c0fc2ca9039682981eacad" } libdd-trace-protobuf = { git = "https://github.com/DataDog/libdatadog", rev = "8c88979985154d6d97c0fc2ca9039682981eacad" } +libdd-trace-stats = { git = "https://github.com/DataDog/libdatadog", rev = "8c88979985154d6d97c0fc2ca9039682981eacad" } libdd-trace-utils = { git = "https://github.com/DataDog/libdatadog", rev = "8c88979985154d6d97c0fc2ca9039682981eacad", features = [ "mini_agent", ] } libdd-trace-obfuscation = { git = "https://github.com/DataDog/libdatadog", rev = "8c88979985154d6d97c0fc2ca9039682981eacad" } datadog-fips = { path = "../datadog-fips" } -reqwest = { version = "0.12.23", features = ["json", "http2"], default-features = false } +reqwest = { version = "0.12.23", features = [ + "json", + "http2", +], default-features = false } bytes = "1.10.1" [dev-dependencies] diff --git a/crates/datadog-trace-agent/src/config.rs b/crates/datadog-trace-agent/src/config.rs index 5a7b8a8..99b75b4 100644 --- a/crates/datadog-trace-agent/src/config.rs +++ b/crates/datadog-trace-agent/src/config.rs @@ -109,6 +109,8 @@ pub struct Config { /// timeout for environment verification, in milliseconds pub verify_env_timeout_ms: u64, pub proxy_url: Option, + pub service: Option, + pub env: Option, } impl Config { @@ -251,6 +253,8 @@ impl Config { .or_else(|_| env::var("HTTPS_PROXY")) .ok(), tags, + service: env::var("DD_SERVICE").ok(), + env: env::var("DD_ENV").ok(), }) } } @@ -721,6 +725,8 @@ pub mod test_helpers { proxy_request_retry_backoff_base_ms: 100, verify_env_timeout_ms: 1000, proxy_url: None, + service: None, + env: None, } } } diff --git a/crates/datadog-trace-agent/src/lib.rs b/crates/datadog-trace-agent/src/lib.rs index a87bf56..daeed74 100644 --- a/crates/datadog-trace-agent/src/lib.rs +++ b/crates/datadog-trace-agent/src/lib.rs @@ -13,7 +13,9 @@ pub mod env_verifier; pub mod http_utils; pub mod mini_agent; pub mod proxy_flusher; +pub mod stats_concentrator_service; pub mod stats_flusher; +pub mod stats_generator; pub mod stats_processor; pub mod trace_flusher; pub mod trace_processor; diff --git a/crates/datadog-trace-agent/src/mini_agent.rs b/crates/datadog-trace-agent/src/mini_agent.rs index 7fa5a92..8ed2ce6 100644 --- a/crates/datadog-trace-agent/src/mini_agent.rs +++ b/crates/datadog-trace-agent/src/mini_agent.rs @@ -11,7 +11,7 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Instant; use tokio::sync::mpsc::{self, Receiver, Sender}; -use tracing::{debug, error, warn}; +use tracing::{debug, error}; use crate::http_utils::{log_and_create_http_response, verify_request_content_length}; use crate::proxy_flusher::{ProxyFlusher, ProxyRequest}; @@ -50,7 +50,10 @@ pub struct MiniAgent { } impl MiniAgent { - pub async fn start_mini_agent(&self) -> Result<(), Box> { + pub async fn start_mini_agent( + &self, + shutdown_rx: tokio::sync::oneshot::Receiver<()>, + ) -> Result<(), Box> { let now = Instant::now(); // verify we are in a serverless function environment. if not, shut down the mini agent. @@ -93,7 +96,7 @@ impl MiniAgent { let stats_config = self.config.clone(); let stats_flusher_handle = tokio::spawn(async move { stats_flusher - .start_stats_flusher(stats_config, stats_rx) + .start_stats_flusher(stats_config, stats_rx, shutdown_rx) .await; }); @@ -191,14 +194,14 @@ impl MiniAgent { let sentinel = std::path::Path::new(LAMBDA_LITE_SENTINEL_PATH); // SAFETY: LAMBDA_LITE_SENTINEL_PATH is a hard-coded absolute path, // so .parent() always returns Some. - if let Some(parent) = sentinel.parent() { - if let Err(e) = tokio::fs::create_dir_all(parent).await { - error!( - "Could not create parent directory for Lambda Lite sentinel \ + if let Some(parent) = sentinel.parent() + && let Err(e) = tokio::fs::create_dir_all(parent).await + { + error!( + "Could not create parent directory for Lambda Lite sentinel \ file at {}: {}.", - LAMBDA_LITE_SENTINEL_PATH, e - ); - } + LAMBDA_LITE_SENTINEL_PATH, e + ); } if let Err(e) = tokio::fs::write(sentinel, b"").await { error!( @@ -521,7 +524,7 @@ impl MiniAgent { INFO_ENDPOINT_PATH, PROFILING_ENDPOINT_PATH ], - "client_drop_p0s": true, + "client_drop_p0s": false, "config": config_json } ); diff --git a/crates/datadog-trace-agent/src/stats_concentrator_service.rs b/crates/datadog-trace-agent/src/stats_concentrator_service.rs new file mode 100644 index 0000000..db0bcac --- /dev/null +++ b/crates/datadog-trace-agent/src/stats_concentrator_service.rs @@ -0,0 +1,182 @@ +// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::Arc; +use tokio::sync::{mpsc, oneshot}; + +use crate::config::Config; +use libdd_trace_protobuf::pb::{ClientStatsPayload, TraceChunk}; +use libdd_trace_stats::span_concentrator::SpanConcentrator; +use std::time::{Duration, SystemTime}; +use tracing::{debug, error}; + +const S_TO_NS: u64 = 1_000_000_000; +const BUCKET_DURATION_NS: u64 = 10 * S_TO_NS; // 10 seconds + +/// When the channel is full, traces are dropped from stats computation rather than blocking +/// the trace request path or growing without bound. +const CONCENTRATOR_COMMAND_CHANNEL_CAPACITY: usize = 128; + +#[derive(Debug, thiserror::Error)] +pub enum StatsError { + #[error("Failed to send command to concentrator: {0}")] + SendError(Box>), + #[error("Failed to receive response from concentrator: {0}")] + RecvError(oneshot::error::RecvError), +} + +#[derive(Clone, Debug, Default)] +pub struct TracerMetadata { + // e.g. "python" + pub language: String, + // e.g. "3.11.0" + pub tracer_version: String, + // e.g. "f45568ad09d5480b99087d86ebda26e6" + pub runtime_id: String, + pub container_id: String, + // e.g. "prod" + pub env: String, + // e.g. "1.0.0" + pub app_version: String, +} + +pub enum ConcentratorCommand { + AddChunk(Box, TracerMetadata), + Flush(bool, oneshot::Sender>), +} + +/// A cloneable handle to the stats concentrator service, safe to share across async tasks. +#[derive(Clone)] +pub struct StatsConcentratorHandle { + tx: mpsc::Sender, +} + +impl StatsConcentratorHandle { + #[must_use] + pub fn new(tx: mpsc::Sender) -> Self { + Self { tx } + } + + /// Adds a trace chunk for stats computation. + pub fn add_chunk(&self, chunk: TraceChunk, metadata: TracerMetadata) -> Result<(), StatsError> { + match self + .tx + .try_send(ConcentratorCommand::AddChunk(Box::new(chunk), metadata)) + { + Ok(()) => Ok(()), + Err(mpsc::error::TrySendError::Full(_)) => { + debug!("Stats concentrator channel full, skipping stats computation"); + Ok(()) + } + Err(e) => Err(StatsError::SendError(Box::new(e))), + } + } + + pub async fn flush(&self, force_flush: bool) -> Result, StatsError> { + let (response_tx, response_rx) = oneshot::channel(); + match self + .tx + .try_send(ConcentratorCommand::Flush(force_flush, response_tx)) + { + Ok(()) => {} + Err(mpsc::error::TrySendError::Full(_)) => { + debug!("Stats concentrator channel full, skipping stats flush"); + return Ok(None); + } + Err(e) => return Err(StatsError::SendError(Box::new(e))), + } + response_rx.await.map_err(StatsError::RecvError) + } +} + +pub struct StatsConcentratorService { + concentrator: SpanConcentrator, + rx: mpsc::Receiver, + tracer_metadata: TracerMetadata, + config: Arc, +} + +impl StatsConcentratorService { + #[must_use] + pub fn new(config: Arc) -> (Self, StatsConcentratorHandle) { + let (tx, rx) = mpsc::channel(CONCENTRATOR_COMMAND_CHANNEL_CAPACITY); + let handle = StatsConcentratorHandle::new(tx); + // TODO: set span_kinds_stats_computed and peer_tag_keys + let concentrator = SpanConcentrator::new( + Duration::from_nanos(BUCKET_DURATION_NS), + SystemTime::now(), + vec![], + vec![], + ); + let service = Self { + concentrator, + rx, + tracer_metadata: TracerMetadata::default(), + config, + }; + (service, handle) + } + + pub async fn run(mut self) { + while let Some(command) = self.rx.recv().await { + match command { + ConcentratorCommand::AddChunk(chunk, metadata) => { + self.tracer_metadata = metadata; + for span in &chunk.spans { + self.concentrator.add_span(span); + } + } + ConcentratorCommand::Flush(force_flush, response_tx) => { + self.handle_flush(force_flush, response_tx); + } + } + } + } + + fn handle_flush( + &mut self, + force_flush: bool, + response_tx: oneshot::Sender>, + ) { + let stats_buckets = self.concentrator.flush(SystemTime::now(), force_flush); + let stats = if stats_buckets.is_empty() { + None + } else { + Some(ClientStatsPayload { + // Do not set hostname so the trace stats backend can aggregate stats properly + hostname: String::new(), + // Prefer env from the tracer payload, fall back to agent config + env: if !self.tracer_metadata.env.is_empty() { + self.tracer_metadata.env.clone() + } else { + self.config.env.clone().unwrap_or_default() + }, + version: self.tracer_metadata.app_version.clone(), + lang: self.tracer_metadata.language.clone(), + tracer_version: self.tracer_metadata.tracer_version.clone(), + runtime_id: self.tracer_metadata.runtime_id.clone(), + // Not supported yet + sequence: 0, + // Not supported yet + agent_aggregation: String::new(), + // One service per app for serverless + service: self.config.service.clone().unwrap_or_default(), + container_id: self.tracer_metadata.container_id.clone(), + // Not supported yet + tags: vec![], + // Not supported yet + git_commit_sha: String::new(), + // Not supported yet + image_tag: String::new(), + stats: stats_buckets, + // Not supported yet + process_tags: String::new(), + // Not supported yet + process_tags_hash: 0, + }) + }; + if let Err(e) = response_tx.send(stats) { + error!("Failed to return trace stats: {e:?}"); + } + } +} diff --git a/crates/datadog-trace-agent/src/stats_flusher.rs b/crates/datadog-trace-agent/src/stats_flusher.rs index 6c6e580..93052d2 100644 --- a/crates/datadog-trace-agent/src/stats_flusher.rs +++ b/crates/datadog-trace-agent/src/stats_flusher.rs @@ -3,29 +3,73 @@ use async_trait::async_trait; use std::{sync::Arc, time}; -use tokio::sync::{Mutex, mpsc::Receiver}; +use tokio::sync::mpsc::Receiver; +use tokio::sync::oneshot; use tracing::{debug, error}; use libdd_trace_protobuf::pb; use libdd_trace_utils::stats_utils; use crate::config::Config; +use crate::stats_concentrator_service::StatsConcentratorHandle; + +/// Whether the stats flusher should run `flush_stats` +fn should_flush_stats_buffer( + channel_has_tracer_stats: bool, + serverless_stats_enabled: bool, +) -> bool { + channel_has_tracer_stats || serverless_stats_enabled +} + +/// Serializes and sends a single `StatsPayload` to the intake. +async fn send_stats_payload(config: &Arc, payload: pb::StatsPayload) { + debug!("Stats payload to be sent: {payload:?}"); + let serialized = match stats_utils::serialize_stats_payload(payload) { + Ok(res) => res, + Err(err) => { + error!("Failed to serialize stats payload, dropping stats: {err}"); + return; + } + }; + #[allow(clippy::unwrap_used)] + match stats_utils::send_stats_payload( + serialized, + &config.trace_stats_intake, + config.trace_stats_intake.api_key.as_ref().unwrap(), + ) + .await + { + Ok(_) => debug!("Successfully flushed stats"), + Err(e) => error!("Error sending stats: {e:?}"), + } +} #[async_trait] pub trait StatsFlusher { /// Starts a stats flusher that listens for stats payloads sent to the tokio mpsc Receiver, - /// implementing flushing logic that calls flush_stats. + /// implementing flushing logic that calls flush_stats. Runs until the shutdown signal fires, + /// at which point it performs a final force flush and returns. async fn start_stats_flusher( &self, config: Arc, - mut rx: Receiver, + rx: Receiver, + shutdown_rx: oneshot::Receiver<()>, ); /// Flushes stats to the Datadog trace stats intake. - async fn flush_stats(&self, config: Arc, traces: Vec); + /// `force_flush` controls whether in-progress concentrator buckets are flushed (true on + /// shutdown, false on normal interval flushes). + async fn flush_stats( + &self, + config: Arc, + client_stats: Vec, + force_flush: bool, + ); } #[derive(Clone)] -pub struct ServerlessStatsFlusher {} +pub struct ServerlessStatsFlusher { + pub stats_concentrator: Option, +} #[async_trait] impl StatsFlusher for ServerlessStatsFlusher { @@ -33,60 +77,82 @@ impl StatsFlusher for ServerlessStatsFlusher { &self, config: Arc, mut rx: Receiver, + mut shutdown_rx: oneshot::Receiver<()>, ) { - let buffer: Arc>> = Arc::new(Mutex::new(Vec::new())); - - let buffer_producer = buffer.clone(); - let buffer_consumer = buffer.clone(); - - tokio::spawn(async move { - while let Some(stats_payload) = rx.recv().await { - let mut buffer = buffer_producer.lock().await; - buffer.push(stats_payload); - } - }); + let mut interval = + tokio::time::interval(time::Duration::from_secs(config.stats_flush_interval_secs)); + let mut buffer: Vec = Vec::new(); loop { - tokio::time::sleep(time::Duration::from_secs(config.stats_flush_interval_secs)).await; + tokio::select! { + // Receive client stats and add them to the buffer + Some(stats) = rx.recv() => { + buffer.push(stats); + } + + // Drain client stats in buffer and stats from concentrator on interval + _ = interval.tick() => { + let client_stats = std::mem::take(&mut buffer); + let should_flush = should_flush_stats_buffer( + !client_stats.is_empty(), + self.stats_concentrator.is_some(), + ); + if should_flush { + self.flush_stats(config.clone(), client_stats, false).await; + } + } - let mut buffer = buffer_consumer.lock().await; - if !buffer.is_empty() { - self.flush_stats(config.clone(), buffer.to_vec()).await; - buffer.clear(); + _ = &mut shutdown_rx => { + // Drain any client stats that arrived before the shutdown signal + while let Ok(stats) = rx.try_recv() { + buffer.push(stats); + } + // Force flush all in progress concentrator stats buckets on shutdown signal + self.flush_stats(config.clone(), std::mem::take(&mut buffer), true).await; + return; + } } } } - async fn flush_stats(&self, config: Arc, stats: Vec) { - if stats.is_empty() { - return; + /// Flushes client computed stats from the tracer and serverless computed stats as separate payloads + async fn flush_stats( + &self, + config: Arc, + client_stats: Vec, + force_flush: bool, + ) { + // Flush client computed stats from the tracer + if !client_stats.is_empty() { + let payload = stats_utils::construct_stats_payload(client_stats); + send_stats_payload(&config, payload).await; } - debug!("Flushing {} stats", stats.len()); - - let stats_payload = stats_utils::construct_stats_payload(stats); - debug!("Stats payload to be sent: {stats_payload:?}"); - - let serialized_stats_payload = match stats_utils::serialize_stats_payload(stats_payload) { - Ok(res) => res, - Err(err) => { - error!("Failed to serialize stats payload, dropping stats: {err}"); - return; - } - }; - - #[allow(clippy::unwrap_used)] - match stats_utils::send_stats_payload( - serialized_stats_payload, - &config.trace_stats_intake, - config.trace_stats_intake.api_key.as_ref().unwrap(), - ) - .await - { - Ok(_) => debug!("Successfully flushed stats"), - Err(e) => { - error!("Error sending stats: {e:?}") + // Flush concentrator stats + if let Some(ref concentrator) = self.stats_concentrator { + match concentrator.flush(force_flush).await { + Ok(Some(agent_stats)) => { + let mut payload = stats_utils::construct_stats_payload(vec![agent_stats]); + payload.client_computed = false; + send_stats_payload(&config, payload).await; + } + Ok(None) => {} + Err(e) => error!("Failed to flush concentrator stats: {e}"), } } } } + +#[cfg(test)] +mod tests { + use super::should_flush_stats_buffer; + + #[test] + fn should_flush_stats_buffer_all_cases() { + // (stats channel empty, serverless computed stats enabled with concentrator) + assert!(!should_flush_stats_buffer(false, false)); + assert!(should_flush_stats_buffer(true, false)); + assert!(should_flush_stats_buffer(false, true)); + assert!(should_flush_stats_buffer(true, true)); + } +} diff --git a/crates/datadog-trace-agent/src/stats_generator.rs b/crates/datadog-trace-agent/src/stats_generator.rs new file mode 100644 index 0000000..73af775 --- /dev/null +++ b/crates/datadog-trace-agent/src/stats_generator.rs @@ -0,0 +1,57 @@ +// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +use crate::stats_concentrator_service::{StatsConcentratorHandle, StatsError, TracerMetadata}; +use libdd_trace_utils::tracer_payload::TracerPayloadCollection; +use tracing::error; + +pub struct StatsGenerator { + stats_concentrator: StatsConcentratorHandle, +} + +#[derive(Debug, thiserror::Error)] +pub enum StatsGeneratorError { + #[error("Failed to send command to stats concentrator: {0}")] + ConcentratorCommandError(StatsError), + #[error("Unsupported tracer payload version. Failed to send trace stats.")] + TracerPayloadVersionError, +} + +// Sends tracer payloads to the stats concentrator +impl StatsGenerator { + #[must_use] + pub fn new(stats_concentrator: StatsConcentratorHandle) -> Self { + Self { stats_concentrator } + } + + pub fn send( + &self, + tracer_payload_collection: &TracerPayloadCollection, + ) -> Result<(), StatsGeneratorError> { + if let TracerPayloadCollection::V07(tracer_payloads) = tracer_payload_collection { + for tracer_payload in tracer_payloads { + let metadata = TracerMetadata { + language: tracer_payload.language_name.clone(), + tracer_version: tracer_payload.tracer_version.clone(), + runtime_id: tracer_payload.runtime_id.clone(), + container_id: tracer_payload.container_id.clone(), + env: tracer_payload.env.clone(), + app_version: tracer_payload.app_version.clone(), + }; + for chunk in &tracer_payload.chunks { + if let Err(err) = self + .stats_concentrator + .add_chunk(chunk.clone(), metadata.clone()) + { + error!("Failed to send trace stats to concentrator: {err}"); + return Err(StatsGeneratorError::ConcentratorCommandError(err)); + } + } + } + Ok(()) + } else { + error!("Unsupported tracer payload version. Failed to send trace stats."); + Err(StatsGeneratorError::TracerPayloadVersionError) + } + } +} diff --git a/crates/datadog-trace-agent/src/trace_processor.rs b/crates/datadog-trace-agent/src/trace_processor.rs index 96f8209..bd385e0 100644 --- a/crates/datadog-trace-agent/src/trace_processor.rs +++ b/crates/datadog-trace-agent/src/trace_processor.rs @@ -7,7 +7,7 @@ use async_trait::async_trait; use hyper::{StatusCode, http}; use libdd_common::http_common; use tokio::sync::mpsc::Sender; -use tracing::debug; +use tracing::{debug, error}; use libdd_trace_obfuscation::obfuscate::obfuscate_span; use libdd_trace_protobuf::pb; @@ -18,6 +18,7 @@ use libdd_trace_utils::tracer_payload::{TraceChunkProcessor, TracerPayloadCollec use crate::{ config::Config, http_utils::{self, log_and_create_http_response, log_and_create_traces_success_http_response}, + stats_generator::StatsGenerator, }; const TRACER_PAYLOAD_FUNCTION_TAGS_TAG_KEY: &str = "_dd.tags.function"; @@ -65,7 +66,10 @@ impl TraceChunkProcessor for ChunkProcessor { } } #[derive(Clone)] -pub struct ServerlessTraceProcessor {} +pub struct ServerlessTraceProcessor { + /// The stats generator to use for generating stats and sending them to the stats concentrator. + pub stats_generator: Option>, +} #[async_trait] impl TraceProcessor for ServerlessTraceProcessor { @@ -139,6 +143,13 @@ impl TraceProcessor for ServerlessTraceProcessor { } } + if let Some(stats_generator) = self.stats_generator.as_ref() + && !tracer_header_tags.client_computed_stats + && let Err(e) = stats_generator.send(&payload) + { + error!("Stats generator error: {e}"); + } + let send_data = SendData::new(body_size, payload, tracer_header_tags, &config.trace_intake); // send trace payload to our trace flusher @@ -219,6 +230,8 @@ mod tests { ..Default::default() }, tags: Tags::from_env_string("env:test,service:my-service"), + service: Some("test-service".to_string()), + env: Some("test-env".to_string()), } } @@ -254,7 +267,9 @@ mod tests { .body(http_common::Body::from(bytes)) .unwrap(); - let trace_processor = trace_processor::ServerlessTraceProcessor {}; + let trace_processor = trace_processor::ServerlessTraceProcessor { + stats_generator: None, + }; let res = trace_processor .process_traces( Arc::new(create_test_config()), @@ -326,7 +341,9 @@ mod tests { .body(http_common::Body::from(bytes)) .unwrap(); - let trace_processor = trace_processor::ServerlessTraceProcessor {}; + let trace_processor = trace_processor::ServerlessTraceProcessor { + stats_generator: None, + }; let res = trace_processor .process_traces( Arc::new(create_test_config()), diff --git a/crates/datadog-trace-agent/tests/common/helpers.rs b/crates/datadog-trace-agent/tests/common/helpers.rs index 6dd8d82..9808f47 100644 --- a/crates/datadog-trace-agent/tests/common/helpers.rs +++ b/crates/datadog-trace-agent/tests/common/helpers.rs @@ -23,6 +23,7 @@ pub async fn send_tcp_request( uri: &str, method: &str, body: Option>, + additional_headers: &[(&str, &str)], ) -> Result, Box> { let stream = timeout( Duration::from_secs(2), @@ -42,6 +43,10 @@ pub async fn send_tcp_request( .method(method) .header("Content-Type", "application/msgpack"); + for (name, value) in additional_headers { + request_builder = request_builder.header(*name, *value); + } + let response = if let Some(body_data) = body { let body_len = body_data.len(); request_builder = request_builder.header("Content-Length", body_len.to_string()); diff --git a/crates/datadog-trace-agent/tests/common/mock_server.rs b/crates/datadog-trace-agent/tests/common/mock_server.rs index f1beb1a..cd0cd6b 100644 --- a/crates/datadog-trace-agent/tests/common/mock_server.rs +++ b/crates/datadog-trace-agent/tests/common/mock_server.rs @@ -4,7 +4,7 @@ //! Simple mock HTTP server for testing flushers use http_body_util::BodyExt; -use hyper::{Request, Response, body::Incoming}; +use hyper::{Request, Response, StatusCode, body::Incoming}; use hyper_util::rt::TokioIo; use libdd_common::http_common; use std::net::SocketAddr; @@ -60,6 +60,7 @@ impl MockServer { // Capture the request let method = req.method().to_string(); let path = req.uri().path().to_string(); + let is_stats_intake = path.ends_with("/stats"); let headers: Vec<(String, String)> = req .headers() .iter() @@ -82,11 +83,18 @@ impl MockServer { body: body_bytes, }); - // Return 200 OK + // Trace intake accepts 2xx + // Stats intake accepts 202 + // see `libdd_trace_utils::stats_utils::send_stats_payload_with_client` + let (status, body) = if is_stats_intake { + (StatusCode::ACCEPTED, http_common::Body::empty()) + } else { + (StatusCode::OK, http_common::Body::from(r#"{"ok":true}"#)) + }; Ok::<_, hyper::http::Error>( Response::builder() - .status(200) - .body(http_common::Body::from(r#"{"ok":true}"#)) + .status(status) + .body(body) .unwrap(), ) } diff --git a/crates/datadog-trace-agent/tests/common/mocks.rs b/crates/datadog-trace-agent/tests/common/mocks.rs index 842c45f..dfd98cc 100644 --- a/crates/datadog-trace-agent/tests/common/mocks.rs +++ b/crates/datadog-trace-agent/tests/common/mocks.rs @@ -12,6 +12,7 @@ use libdd_trace_protobuf::pb; use libdd_trace_utils::trace_utils::{self, MiniAgentMetadata, SendData}; use std::sync::Arc; use tokio::sync::mpsc::{Receiver, Sender}; +use tokio::sync::oneshot; /// Mock trace processor that returns 200 OK for all requests #[allow(dead_code)] @@ -86,6 +87,7 @@ impl StatsFlusher for MockStatsFlusher { &self, _config: Arc, mut stats_rx: Receiver, + _shutdown_rx: oneshot::Receiver<()>, ) { // Consume messages from the channel without processing them while let Some(_stats) = stats_rx.recv().await { @@ -93,7 +95,12 @@ impl StatsFlusher for MockStatsFlusher { } } - async fn flush_stats(&self, _config: Arc, _traces: Vec) { + async fn flush_stats( + &self, + _config: Arc, + _traces: Vec, + _force_flush: bool, + ) { // Do nothing } } diff --git a/crates/datadog-trace-agent/tests/integration_test.rs b/crates/datadog-trace-agent/tests/integration_test.rs index 1491954..358f98c 100644 --- a/crates/datadog-trace-agent/tests/integration_test.rs +++ b/crates/datadog-trace-agent/tests/integration_test.rs @@ -28,7 +28,7 @@ const FLUSH_WAIT_DURATION: Duration = Duration::from_millis(1500); /// Helper to configure a config with mock server endpoints pub fn configure_mock_endpoints(config: &mut Config, mock_server_url: &str) { let trace_url = format!("{}/api/v0.2/traces", mock_server_url); - let stats_url = format!("{}/api/v0.6/stats", mock_server_url); + let stats_url = format!("{}/api/v0.2/stats", mock_server_url); config.trace_intake = libdd_common::Endpoint { url: trace_url.parse().unwrap(), @@ -47,20 +47,30 @@ pub fn configure_mock_endpoints(config: &mut Config, mock_server_url: &str) { /// Helper to create a mini agent with real flushers pub fn create_mini_agent_with_real_flushers(config: Arc) -> MiniAgent { use datadog_trace_agent::{ - aggregator::TraceAggregator, stats_flusher::ServerlessStatsFlusher, + aggregator::TraceAggregator, stats_concentrator_service::StatsConcentratorService, + stats_flusher::ServerlessStatsFlusher, stats_generator::StatsGenerator, stats_processor::ServerlessStatsProcessor, trace_flusher::ServerlessTraceFlusher, }; + let (service, stats_concentrator_handle) = StatsConcentratorService::new(config.clone()); + tokio::spawn(service.run()); + + let stats_generator = Some(Arc::new(StatsGenerator::new( + stats_concentrator_handle.clone(), + ))); + let aggregator = Arc::new(tokio::sync::Mutex::new(TraceAggregator::default())); MiniAgent { config: config.clone(), - trace_processor: Arc::new(ServerlessTraceProcessor {}), + trace_processor: Arc::new(ServerlessTraceProcessor { stats_generator }), trace_flusher: Arc::new(ServerlessTraceFlusher::new( aggregator.clone(), config.clone(), )), stats_processor: Arc::new(ServerlessStatsProcessor {}), - stats_flusher: Arc::new(ServerlessStatsFlusher {}), + stats_flusher: Arc::new(ServerlessStatsFlusher { + stats_concentrator: Some(stats_concentrator_handle), + }), env_verifier: Arc::new(MockEnvVerifier), proxy_flusher: Arc::new(ProxyFlusher::new(config.clone())), } @@ -102,6 +112,52 @@ pub fn verify_trace_request(mock_server: &common::mock_server::MockServer) { ); } +/// Helper to verify stats request sent to mock server +pub fn verify_stats_request(mock_server: &common::mock_server::MockServer) { + let stats_reqs = mock_server.get_requests_for_path("/api/v0.2/stats"); + + assert!( + !stats_reqs.is_empty(), + "Expected at least one stats request to mock server" + ); + + let stats_req = &stats_reqs[0]; + assert_eq!(stats_req.method, "POST", "Expected POST method"); + + let content_type = stats_req + .headers + .iter() + .find(|(k, _)| k.to_lowercase() == "content-type") + .map(|(_, v)| v.as_str()); + assert_eq!( + content_type, + Some("application/msgpack"), + "Expected msgpack content-type" + ); + + let api_key = stats_req + .headers + .iter() + .find(|(k, _)| k.to_lowercase() == "dd-api-key") + .map(|(_, v)| v.as_str()); + assert_eq!(api_key, Some("test-api-key"), "Expected API key header"); + + assert!( + !stats_req.body.is_empty(), + "Expected non-empty stats payload" + ); +} + +/// Helper to verify stats request was not sent to mock server +pub fn verify_no_stats_request(mock_server: &common::mock_server::MockServer) { + let stats_reqs = mock_server.get_requests_for_path("/api/v0.2/stats"); + assert!( + stats_reqs.is_empty(), + "Expected no stats request to mock server, received {} request(s)", + stats_reqs.len() + ); +} + #[cfg(test)] #[tokio::test] #[serial] @@ -110,7 +166,9 @@ async fn test_mini_agent_tcp_handles_requests() { let test_port = config.dd_apm_receiver_port; let mini_agent = MiniAgent { config: config.clone(), - trace_processor: Arc::new(ServerlessTraceProcessor {}), + trace_processor: Arc::new(ServerlessTraceProcessor { + stats_generator: None, + }), trace_flusher: Arc::new(MockTraceFlusher), stats_processor: Arc::new(MockStatsProcessor), stats_flusher: Arc::new(MockStatsFlusher), @@ -120,14 +178,15 @@ async fn test_mini_agent_tcp_handles_requests() { // Start the mini agent let agent_handle = tokio::spawn(async move { - let _ = mini_agent.start_mini_agent().await; + let (_shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let _ = mini_agent.start_mini_agent(shutdown_rx).await; }); // Give server time to start tokio::time::sleep(Duration::from_millis(100)).await; // Test /info endpoint - let info_response = send_tcp_request(test_port, "/info", "GET", None) + let info_response = send_tcp_request(test_port, "/info", "GET", None, &[]) .await .expect("Failed to send /info request"); assert_eq!( @@ -160,8 +219,8 @@ async fn test_mini_agent_tcp_handles_requests() { // Check client_drop_p0s flag assert_eq!( - json["client_drop_p0s"], true, - "Expected client_drop_p0s to be true" + json["client_drop_p0s"], false, + "Expected client_drop_p0s to be false" ); // Check config object @@ -181,9 +240,10 @@ async fn test_mini_agent_tcp_handles_requests() { // Test /v0.4/traces endpoint with real trace data let trace_payload = create_test_trace_payload(); - let trace_response = send_tcp_request(test_port, "/v0.4/traces", "POST", Some(trace_payload)) - .await - .expect("Failed to send /v0.4/traces request"); + let trace_response = + send_tcp_request(test_port, "/v0.4/traces", "POST", Some(trace_payload), &[]) + .await + .expect("Failed to send /v0.4/traces request"); assert_eq!( trace_response.status(), StatusCode::OK, @@ -206,7 +266,9 @@ async fn test_mini_agent_named_pipe_handles_requests() { let mini_agent = MiniAgent { config: config.clone(), - trace_processor: Arc::new(ServerlessTraceProcessor {}), + trace_processor: Arc::new(ServerlessTraceProcessor { + stats_generator: None, + }), trace_flusher: Arc::new(MockTraceFlusher), stats_processor: Arc::new(MockStatsProcessor), stats_flusher: Arc::new(MockStatsFlusher), @@ -216,7 +278,8 @@ async fn test_mini_agent_named_pipe_handles_requests() { // Start the mini agent let agent_handle = tokio::spawn(async move { - let _ = mini_agent.start_mini_agent().await; + let (_shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let _ = mini_agent.start_mini_agent(shutdown_rx).await; }); // Give server time to create pipe @@ -287,15 +350,72 @@ async fn test_mini_agent_tcp_with_real_flushers() { let mini_agent = create_mini_agent_with_real_flushers(config); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let agent_handle = tokio::spawn(async move { + let _ = mini_agent.start_mini_agent(shutdown_rx).await; + }); + + // Wait for server to be ready + let mut server_ready = false; + for _ in 0..20 { + tokio::time::sleep(Duration::from_millis(50)).await; + if let Ok(response) = send_tcp_request(test_port, "/info", "GET", None, &[]).await { + if response.status().is_success() { + server_ready = true; + break; + } + } + } + assert!( + server_ready, + "Mini agent server failed to start within timeout" + ); + + // Send trace data + let trace_payload = create_test_trace_payload(); + let trace_response = + send_tcp_request(test_port, "/v0.4/traces", "POST", Some(trace_payload), &[]) + .await + .expect("Failed to send /v0.4/traces request"); + assert_eq!(trace_response.status(), StatusCode::OK); + + // Wait for trace flush + tokio::time::sleep(FLUSH_WAIT_DURATION).await; + verify_trace_request(&mock_server); + + // Trigger shutdown to force flush in progress concentrator buckets + let _ = shutdown_tx.send(()); + tokio::time::sleep(FLUSH_WAIT_DURATION).await; + verify_stats_request(&mock_server); // Stats generator should generate stats from trace payload + + // Clean up + agent_handle.abort(); +} + +#[cfg(test)] +#[tokio::test] +#[serial] +async fn test_mini_agent_tcp_with_real_flushers_and_tracer_computed_stats() { + let mock_server: MockServer = MockServer::start().await; + tokio::time::sleep(Duration::from_millis(50)).await; + + let mut config = create_tcp_test_config(8128); // use different port to avoid race condition with other tests + configure_mock_endpoints(&mut config, &mock_server.url()); + let config = Arc::new(config); + let test_port = config.dd_apm_receiver_port; + + let mini_agent = create_mini_agent_with_real_flushers(config); + let agent_handle = tokio::spawn(async move { - let _ = mini_agent.start_mini_agent().await; + let (_shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); + let _ = mini_agent.start_mini_agent(shutdown_rx).await; }); // Wait for server to be ready let mut server_ready = false; for _ in 0..20 { tokio::time::sleep(Duration::from_millis(50)).await; - if let Ok(response) = send_tcp_request(test_port, "/info", "GET", None).await + if let Ok(response) = send_tcp_request(test_port, "/info", "GET", None, &[]).await && response.status().is_success() { server_ready = true; @@ -309,16 +429,24 @@ async fn test_mini_agent_tcp_with_real_flushers() { // Send trace data let trace_payload = create_test_trace_payload(); - let trace_response = send_tcp_request(test_port, "/v0.4/traces", "POST", Some(trace_payload)) - .await - .expect("Failed to send /v0.4/traces request"); + let trace_response = send_tcp_request( + test_port, + "/v0.4/traces", + "POST", + Some(trace_payload), + &[("Datadog-Client-Computed-Stats", "true")], + ) + .await + .expect("Failed to send /v0.4/traces request"); assert_eq!(trace_response.status(), StatusCode::OK); // Wait for flush tokio::time::sleep(FLUSH_WAIT_DURATION).await; verify_trace_request(&mock_server); + verify_no_stats_request(&mock_server); // Stats generator should not generate stats from trace payload when Datadog-Client-Computed-Stats header is present in trace payload + // Clean up agent_handle.abort(); } @@ -338,8 +466,9 @@ async fn test_mini_agent_named_pipe_with_real_flushers() { let mini_agent = create_mini_agent_with_real_flushers(config); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>(); let agent_handle = tokio::spawn(async move { - let _ = mini_agent.start_mini_agent().await; + let _ = mini_agent.start_mini_agent(shutdown_rx).await; }); // Wait for server to be ready @@ -366,10 +495,15 @@ async fn test_mini_agent_named_pipe_with_real_flushers() { .expect("Failed to send /v0.4/traces request over named pipe"); assert_eq!(trace_response.status(), StatusCode::OK); - // Wait for flush + // Wait for trace flush tokio::time::sleep(FLUSH_WAIT_DURATION).await; - verify_trace_request(&mock_server); + // Trigger shutdown to force flush in progress concentrator buckets + let _ = shutdown_tx.send(()); + tokio::time::sleep(FLUSH_WAIT_DURATION).await; + verify_stats_request(&mock_server); + + // Clean up agent_handle.abort(); }