|
| 1 | +use libdd_trace_utils::trace_utils::TracerHeaderTags as DatadogTracerHeaderTags; |
| 2 | +use opentelemetry_proto::tonic::collector::trace::v1::{ |
| 3 | + ExportTraceServiceRequest, ExportTraceServiceResponse, |
| 4 | + trace_service_server::{TraceService, TraceServiceServer}, |
| 5 | +}; |
| 6 | +use std::mem::size_of_val; |
| 7 | +use std::net::SocketAddr; |
| 8 | +use std::sync::Arc; |
| 9 | +use tokio::sync::mpsc::Sender; |
| 10 | +use tokio_util::sync::CancellationToken; |
| 11 | +use tonic::{Request, Response, Status}; |
| 12 | +use tracing::{debug, error}; |
| 13 | + |
| 14 | +use crate::{ |
| 15 | + config::Config, |
| 16 | + otlp::processor::Processor as OtlpProcessor, |
| 17 | + tags::provider, |
| 18 | + traces::{ |
| 19 | + stats_generator::StatsGenerator, trace_aggregator::SendDataBuilderInfo, |
| 20 | + trace_processor::TraceProcessor, |
| 21 | + }, |
| 22 | +}; |
| 23 | + |
| 24 | +const OTLP_AGENT_GRPC_PORT: u16 = 4317; |
| 25 | +const DEFAULT_MAX_RECV_MSG_SIZE: usize = 4 * 1024 * 1024; // 4MB default |
| 26 | + |
| 27 | +struct OtlpGrpcService { |
| 28 | + config: Arc<Config>, |
| 29 | + tags_provider: Arc<provider::Provider>, |
| 30 | + processor: OtlpProcessor, |
| 31 | + trace_processor: Arc<dyn TraceProcessor + Send + Sync>, |
| 32 | + trace_tx: Sender<SendDataBuilderInfo>, |
| 33 | + stats_generator: Arc<StatsGenerator>, |
| 34 | +} |
| 35 | + |
| 36 | +#[tonic::async_trait] |
| 37 | +impl TraceService for OtlpGrpcService { |
| 38 | + async fn export( |
| 39 | + &self, |
| 40 | + request: Request<ExportTraceServiceRequest>, |
| 41 | + ) -> Result<Response<ExportTraceServiceResponse>, Status> { |
| 42 | + let inner_request = request.into_inner(); |
| 43 | + |
| 44 | + let traces = match self.processor.process_request(inner_request) { |
| 45 | + Ok(traces) => traces, |
| 46 | + Err(e) => { |
| 47 | + error!("OTLP gRPC | Failed to process request: {:?}", e); |
| 48 | + return Err(Status::internal(format!("Failed to process request: {e}"))); |
| 49 | + } |
| 50 | + }; |
| 51 | + |
| 52 | + let tracer_header_tags = DatadogTracerHeaderTags::default(); |
| 53 | + let body_size = size_of_val(&traces); |
| 54 | + if body_size == 0 { |
| 55 | + error!("OTLP gRPC | Not sending traces, processor returned empty data"); |
| 56 | + return Err(Status::internal( |
| 57 | + "Not sending traces, processor returned empty data", |
| 58 | + )); |
| 59 | + } |
| 60 | + |
| 61 | + let compute_trace_stats_on_extension = self.config.compute_trace_stats_on_extension; |
| 62 | + let (send_data_builder, processed_traces) = self.trace_processor.process_traces( |
| 63 | + self.config.clone(), |
| 64 | + self.tags_provider.clone(), |
| 65 | + tracer_header_tags, |
| 66 | + traces, |
| 67 | + body_size, |
| 68 | + None, |
| 69 | + ); |
| 70 | + |
| 71 | + if let Some(send_data_builder) = send_data_builder { |
| 72 | + if let Err(err) = self.trace_tx.send(send_data_builder).await { |
| 73 | + error!("OTLP gRPC | Error sending traces to the trace aggregator: {err}"); |
| 74 | + return Err(Status::internal(format!( |
| 75 | + "Error sending traces to the trace aggregator: {err}" |
| 76 | + ))); |
| 77 | + } |
| 78 | + debug!("OTLP gRPC | Successfully buffered traces to be aggregated."); |
| 79 | + } |
| 80 | + |
| 81 | + // Compute trace stats after process_traces() which performs obfuscation |
| 82 | + if compute_trace_stats_on_extension |
| 83 | + && let Err(err) = self.stats_generator.send(&processed_traces) |
| 84 | + { |
| 85 | + // Just log the error. Stats are not critical. |
| 86 | + error!("OTLP gRPC | Error sending traces to the stats concentrator: {err}"); |
| 87 | + } |
| 88 | + |
| 89 | + Ok(Response::new(ExportTraceServiceResponse { |
| 90 | + partial_success: None, |
| 91 | + })) |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +pub struct GrpcAgent { |
| 96 | + config: Arc<Config>, |
| 97 | + tags_provider: Arc<provider::Provider>, |
| 98 | + processor: OtlpProcessor, |
| 99 | + trace_processor: Arc<dyn TraceProcessor + Send + Sync>, |
| 100 | + trace_tx: Sender<SendDataBuilderInfo>, |
| 101 | + stats_generator: Arc<StatsGenerator>, |
| 102 | + port: u16, |
| 103 | + cancel_token: CancellationToken, |
| 104 | +} |
| 105 | + |
| 106 | +impl GrpcAgent { |
| 107 | + pub fn new( |
| 108 | + config: Arc<Config>, |
| 109 | + tags_provider: Arc<provider::Provider>, |
| 110 | + trace_processor: Arc<dyn TraceProcessor + Send + Sync>, |
| 111 | + trace_tx: Sender<SendDataBuilderInfo>, |
| 112 | + stats_generator: Arc<StatsGenerator>, |
| 113 | + ) -> Self { |
| 114 | + let port = Self::parse_port( |
| 115 | + config.otlp_config_receiver_protocols_grpc_endpoint.as_ref(), |
| 116 | + OTLP_AGENT_GRPC_PORT, |
| 117 | + ); |
| 118 | + let cancel_token = CancellationToken::new(); |
| 119 | + |
| 120 | + Self { |
| 121 | + config: Arc::clone(&config), |
| 122 | + tags_provider: Arc::clone(&tags_provider), |
| 123 | + processor: OtlpProcessor::new(Arc::clone(&config)), |
| 124 | + trace_processor, |
| 125 | + trace_tx, |
| 126 | + stats_generator, |
| 127 | + port, |
| 128 | + cancel_token, |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + #[must_use] |
| 133 | + pub fn cancel_token(&self) -> CancellationToken { |
| 134 | + self.cancel_token.clone() |
| 135 | + } |
| 136 | + |
| 137 | + fn parse_port(endpoint: Option<&String>, default_port: u16) -> u16 { |
| 138 | + if let Some(endpoint) = endpoint { |
| 139 | + let port = endpoint.split(':').nth(1); |
| 140 | + if let Some(port) = port { |
| 141 | + return port.parse::<u16>().unwrap_or_else(|_| { |
| 142 | + error!("Invalid OTLP gRPC port, using default port {default_port}"); |
| 143 | + default_port |
| 144 | + }); |
| 145 | + } |
| 146 | + |
| 147 | + error!("Invalid OTLP gRPC endpoint format, using default port {default_port}"); |
| 148 | + } |
| 149 | + |
| 150 | + default_port |
| 151 | + } |
| 152 | + |
| 153 | + pub async fn start(&self) -> Result<(), Box<dyn std::error::Error>> { |
| 154 | + let socket = SocketAddr::from(([127, 0, 0, 1], self.port)); |
| 155 | + |
| 156 | + let max_recv_msg_size = self |
| 157 | + .config |
| 158 | + .otlp_config_receiver_protocols_grpc_max_recv_msg_size_mib |
| 159 | + .map_or(DEFAULT_MAX_RECV_MSG_SIZE, |mib| { |
| 160 | + mib.unsigned_abs() as usize * 1024 * 1024 |
| 161 | + }); |
| 162 | + |
| 163 | + let service = OtlpGrpcService { |
| 164 | + config: Arc::clone(&self.config), |
| 165 | + tags_provider: Arc::clone(&self.tags_provider), |
| 166 | + processor: self.processor.clone(), |
| 167 | + trace_processor: Arc::clone(&self.trace_processor), |
| 168 | + trace_tx: self.trace_tx.clone(), |
| 169 | + stats_generator: Arc::clone(&self.stats_generator), |
| 170 | + }; |
| 171 | + |
| 172 | + let cancel_token = self.cancel_token.clone(); |
| 173 | + |
| 174 | + debug!( |
| 175 | + "OTLP gRPC | Starting collector on {} with max message size {} bytes", |
| 176 | + socket, max_recv_msg_size |
| 177 | + ); |
| 178 | + |
| 179 | + tonic::transport::Server::builder() |
| 180 | + .add_service( |
| 181 | + TraceServiceServer::new(service).max_decoding_message_size(max_recv_msg_size), |
| 182 | + ) |
| 183 | + .serve_with_shutdown(socket, async move { |
| 184 | + cancel_token.cancelled().await; |
| 185 | + debug!("OTLP gRPC | Shutdown signal received, shutting down"); |
| 186 | + }) |
| 187 | + .await?; |
| 188 | + |
| 189 | + Ok(()) |
| 190 | + } |
| 191 | +} |
| 192 | + |
| 193 | +#[cfg(test)] |
| 194 | +mod tests { |
| 195 | + use super::*; |
| 196 | + |
| 197 | + #[test] |
| 198 | + fn test_parse_port_with_valid_endpoint() { |
| 199 | + let endpoint = Some("localhost:4317".to_string()); |
| 200 | + assert_eq!( |
| 201 | + GrpcAgent::parse_port(endpoint.as_ref(), OTLP_AGENT_GRPC_PORT), |
| 202 | + 4317 |
| 203 | + ); |
| 204 | + } |
| 205 | + |
| 206 | + #[test] |
| 207 | + fn test_parse_port_with_custom_port() { |
| 208 | + let endpoint = Some("0.0.0.0:9999".to_string()); |
| 209 | + assert_eq!( |
| 210 | + GrpcAgent::parse_port(endpoint.as_ref(), OTLP_AGENT_GRPC_PORT), |
| 211 | + 9999 |
| 212 | + ); |
| 213 | + } |
| 214 | + |
| 215 | + #[test] |
| 216 | + fn test_parse_port_with_invalid_port_format() { |
| 217 | + let endpoint = Some("localhost:invalid".to_string()); |
| 218 | + assert_eq!( |
| 219 | + GrpcAgent::parse_port(endpoint.as_ref(), OTLP_AGENT_GRPC_PORT), |
| 220 | + OTLP_AGENT_GRPC_PORT |
| 221 | + ); |
| 222 | + } |
| 223 | + |
| 224 | + #[test] |
| 225 | + fn test_parse_port_with_missing_port() { |
| 226 | + let endpoint = Some("localhost".to_string()); |
| 227 | + assert_eq!( |
| 228 | + GrpcAgent::parse_port(endpoint.as_ref(), OTLP_AGENT_GRPC_PORT), |
| 229 | + OTLP_AGENT_GRPC_PORT |
| 230 | + ); |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn test_parse_port_with_none_endpoint() { |
| 235 | + let endpoint: Option<String> = None; |
| 236 | + assert_eq!( |
| 237 | + GrpcAgent::parse_port(endpoint.as_ref(), OTLP_AGENT_GRPC_PORT), |
| 238 | + OTLP_AGENT_GRPC_PORT |
| 239 | + ); |
| 240 | + } |
| 241 | +} |
0 commit comments