Skip to main content

saluki_components/sources/dogstatsd/
mod.rs

1//! DogStatsD source.
2//!
3//! # Missing
4//!
5//! - Create a health handle for each listener.
6//! - Handle UDS stream framing without treating EOF the same way as UDP and UDS datagram framing.
7//! - Track dispatch failures without depending on whether all events were already iterated.
8
9use std::{
10    future::Future,
11    io,
12    num::NonZeroUsize,
13    path::PathBuf,
14    pin::Pin,
15    sync::{Arc, LazyLock},
16    time::{Duration, SystemTime, UNIX_EPOCH},
17};
18
19use async_trait::async_trait;
20use bytes::{Buf, BufMut};
21use bytesize::ByteSize;
22use saluki_common::sync::{
23    shutdown::{ShutdownCoordinator, ShutdownHandle},
24    work_queue::{self, WorkQueueReceiver, WorkQueueSender},
25};
26use saluki_core::{
27    accounting::{MemoryBounds, MemoryBoundsBuilder, MemoryLimiter, UsageExpr},
28    components::{sources::*, BuildContext},
29    data_model::{
30        event::{
31            eventd::EventD,
32            metric::{Metric, MetricMetadata, MetricOrigin},
33            service_check::ServiceCheck,
34            Event, EventType,
35        },
36        origin::OriginTagCardinality,
37        tags::{RawTags, SharedTagSet},
38    },
39    pooling::{ElasticObjectPool, ObjectPool as _},
40    runtime::{
41        self,
42        state::{AcquireError, ResourceLease},
43        ShutdownStrategy,
44    },
45    topology::{interconnect::EventBufferManager, EventsBuffer, OutputDefinition, DEFAULT_EVENTS_BUFFER_CAPACITY},
46};
47use saluki_env::{workload::CaptureEntityResolver, WorkloadProvider};
48use saluki_error::{generic_error, ErrorContext as _, GenericError};
49use saluki_io::{
50    buf::{BytesBuffer, ClearableIoBuffer as _, CollapsibleReadWriteIoBuffer as _, FixedSizeVec, ReadIoBuffer as _},
51    deser::{codec::dogstatsd::*, framing::FramingError},
52    net::{
53        dns::{resolve_host, ResolveHostError},
54        listener::Listener,
55        ConnectionAddress, ListenAddress, ProcessCredentialsError, ProcessIdentity, SocketSpecification, Stream,
56    },
57};
58use snafu::Snafu;
59use stringtheory::MetaString;
60use tokio::{
61    pin, select,
62    sync::{mpsc, oneshot},
63    time::{interval, MissedTickBehavior},
64};
65use tracing::{debug, error, info, trace, warn};
66
67mod forwarder;
68use self::forwarder::{forwarder_queue_capacity, PacketForwarder, PacketForwarderTarget};
69
70mod framer;
71use self::framer::{get_framer, DsdFramer, Frame};
72use crate::sources::dogstatsd::tags::WellKnownTags;
73
74mod filters;
75pub use self::filters::EnablePayloadsConfiguration;
76
77mod metrics;
78use self::metrics::{build_metrics, ForwarderMetrics, Metrics};
79
80mod replay;
81use self::replay::{CaptureRecord, CapturedTaggerHandle, TrafficCapture};
82pub use self::replay::{
83    CaptureTriggerBody, CaptureTriggerResponseBody, DogStatsDCaptureAPIHandler, DogStatsDCaptureControl,
84    DogStatsDReplayAPIHandler, DogStatsDReplayControl, ReplayControlError, ReplaySession, ReplaySessionResponseBody,
85    TimestampResolution, TrafficCaptureReader, CAPTURE_TRIGGER_ROUTE, DEFAULT_REPLAY_LOOPS, REPLAY_CREDENTIALS_GID,
86    REPLAY_SESSION_ROUTE,
87};
88
89mod origin;
90pub use self::origin::OriginEnrichmentConfiguration;
91use self::origin::{origin_from_packet, DogStatsDOriginTagResolver, ProcessOrigin};
92
93mod resolver;
94use self::resolver::ContextResolvers;
95
96mod tags;
97
98#[derive(Debug, Snafu)]
99#[snafu(context(suffix(false)))]
100enum Error {
101    #[snafu(display("Failed to acquire {} listener: {}", listener_type, source))]
102    FailedToAcquireListener {
103        listener_type: &'static str,
104        source: AcquireError,
105    },
106
107    #[snafu(display("No listeners could be created. Please specify a port (`dogstatsd_port`) or a socket path (`dogstatsd_socket` or `dogstatsd_stream_socket`) that can be listened on."))]
108    NoListeners,
109
110    #[snafu(context(false), display("Could not resolve bind_host: {}", source))]
111    UnresolvableBindHost { source: ResolveHostError },
112}
113
114/// Baseline byte cost per interner entry, used to convert the Core Agent's entry-count-based
115/// `dogstatsd_string_interner_size` to a byte size.
116///
117/// 4096 entries × 512 bytes = 2 MiB, matching ADP's previous default.
118const INTERNER_BASELINE_BYTES_PER_ENTRY: u64 = 512;
119const DOGSTATSD_LISTENER_WORKER_COUNT: usize = 1;
120const DOGSTATSD_PIPELINE_COUNT: usize = 1;
121const MIN_DOGSTATSD_WORKER_COUNT: usize = 2;
122
123fn default_decoder_worker_count(vcpus: usize) -> usize {
124    vcpus
125        .saturating_sub(DOGSTATSD_LISTENER_WORKER_COUNT + DOGSTATSD_PIPELINE_COUNT)
126        .max(MIN_DOGSTATSD_WORKER_COUNT)
127}
128
129const MIN_CAPTURE_DEPTH: usize = 1024;
130
131/// Which of the configured listeners the source requires.
132///
133/// This decides what happens when a listener can't be created, for example because its address is already in use.
134#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
135pub enum ListenerRequirement {
136    /// Every configured listener must be created, and at least one must be configured.
137    ///
138    /// A listener that can't be created stops the source from starting.
139    #[default]
140    All,
141
142    /// At least one listener must be created.
143    ///
144    /// A listener that can't be created is logged and skipped. The source fails to start if
145    /// no listener remains.
146    AtLeastOne,
147
148    /// No listener is required.
149    ///
150    /// A listener that can't be created is logged and skipped. If no listener remains, the source runs without
151    /// listeners until shutdown, and the rest of the server process keeps running.
152    Optional,
153}
154
155/// DogStatsD source.
156///
157/// Accepts metrics over TCP, UDP, or Unix Domain Sockets in the StatsD/DogStatsD format.
158pub struct DogStatsDConfiguration {
159    /// Hostname used when DogStatsD metrics do not carry an explicit `host:` tag.
160    pub default_hostname: MetaString,
161
162    /// The size of the buffer used to receive messages into, in bytes.
163    ///
164    /// Payloads can't exceed this size, or they will be truncated, leading to discarded messages.
165    pub buffer_size: usize,
166
167    /// The number of message buffers to allocate up front.
168    ///
169    /// This is the baseline pool size allocated at startup. The pool then grows on demand up to
170    /// `buffer_count_max` as active stream connections and datagram queues need additional buffers.
171    /// Higher values allocate more memory at startup but reduce on-demand allocations during bursts.
172    pub buffer_count: usize,
173
174    /// The maximum number of message buffers to allocate overall.
175    ///
176    /// The global pool starts at `buffer_count` buffers and grows on demand up to this limit. Active stream
177    /// connections use these buffers for reads, while connectionless listeners use them to queue received packets for
178    /// decoding. Increasing this value lets datagram listeners absorb larger bursts at the cost of up to one additional
179    /// `buffer_size` allocation per buffer. This limit bounds payload buffers, but not per-connection task and channel
180    /// bookkeeping. After a short grace period without pool growth, ADP releases idle buffers until the pool returns to
181    /// `buffer_count`.
182    ///
183    /// The pool never holds fewer buffers than `buffer_count`, so a value below the baseline is treated as equal to it.
184    pub buffer_count_max: usize,
185
186    /// The number of workers in the global pool that decodes connectionless DogStatsD packets.
187    ///
188    /// If set to `0`, the worker count is derived from the available vCPUs using the Core Agent's default formula.
189    /// Positive values force an exact worker count. Higher values can improve throughput when decoding is CPU-bound,
190    /// but also increase task scheduling and per-worker event buffering overhead.
191    pub workers_count: usize,
192
193    /// The port to listen on in UDP mode.
194    ///
195    /// If set to `0`, UDP isn't used.
196    pub port: u16,
197
198    /// The size of the receive buffer requested for each DogStatsD socket, in bytes.
199    ///
200    /// Applies to the UDP, TCP, and UDS sockets alike. If set to `0`, the OS default is used.
201    pub socket_receive_buffer_size: usize,
202
203    /// The port to listen on in TCP mode.
204    ///
205    /// If set to `0`, TCP isn't used.
206    pub tcp_port: u16,
207
208    /// The host to forward framed DogStatsD messages to over UDP.
209    ///
210    /// Forwarding is enabled only when this value is set and `statsd_forward_port` is non-zero. Setup failures
211    /// are logged, and send failures are tracked through telemetry.
212    pub statsd_forward_host: Option<MetaString>,
213
214    /// The port to forward framed DogStatsD messages to over UDP.
215    ///
216    /// Forwarding is enabled only when this value is non-zero and `statsd_forward_host` is set.
217    pub statsd_forward_port: u16,
218
219    /// The size of the DogStatsD packet queue, from `dogstatsd_queue_size`.
220    ///
221    /// The source doesn't queue received packets by count. It sizes the packet forwarder's queue from this value
222    /// instead: a quarter of it, and at least 64 packets.
223    pub queue_size: usize,
224
225    /// The Unix domain socket path to listen on, in datagram mode.
226    ///
227    /// If not set, UDS (in datagram mode) isn't used.
228    pub socket_path: Option<String>,
229
230    /// The Unix domain socket path to listen on, in stream mode.
231    ///
232    /// If not set, UDS (in stream mode) isn't used.
233    pub socket_stream_path: Option<String>,
234
235    /// Controls whether ADP logs oversized DogStatsD stream frames.
236    ///
237    /// When set to `true`, ADP emits a warning when a UDS stream frame exceeds the
238    /// configured DogStatsD buffer size. The frame is still rejected either way.
239    ///
240    /// Enable this when diagnosing clients that send oversized UDS stream frames.
241    pub stream_log_too_big: bool,
242
243    /// Which of the configured listeners the source requires.
244    ///
245    /// Defaults to [`ListenerRequirement::All`], where a listener that can't be created prevents the source from
246    /// starting. With [`ListenerRequirement::AtLeastOne`] or [`ListenerRequirement::Optional`], such a listener
247    /// is logged and skipped instead. If no listener remains, the source only fails to start under `AtLeastOne`;
248    /// under `Optional` the source runs without listeners until shutdown.
249    ///
250    /// Keep the default when every configured address is needed. Relax it when the server process should keep
251    /// running while some addresses are unavailable, and use `AtLeastOne` when a process supervisor should still
252    /// detect and restart a process that can receive no traffic.
253    pub listener_requirement: ListenerRequirement,
254
255    /// The Windows named pipe name to listen on.
256    ///
257    /// If set, ADP listens for DogStatsD stream traffic on `\\.\pipe\<name>` on Windows.
258    /// The listener is unsupported on non-Windows platforms.
259    pub pipe_name: Option<String>,
260
261    /// Windows named pipe security descriptor.
262    ///
263    /// This SDDL descriptor is applied when creating the named pipe listener.
264    pub windows_pipe_security_descriptor: String,
265
266    /// Whether ADP lowers DogStatsD parse-failure logs to debug level.
267    ///
268    /// When set to `true`, invalid metrics, events, and service checks still increment decode-failure telemetry, but
269    /// their parse-failure logs are emitted at debug level instead of warning level. Enable this to suppress noisy
270    /// parse-error logs from misbehaving clients.
271    pub disable_verbose_logs: bool,
272
273    /// Listener types that require DogStatsD messages to be newline-terminated.
274    ///
275    /// Valid values are `udp`, `uds`, and `named_pipe`. Invalid values are ignored.
276    ///
277    /// An empty list accepts the final message without a newline.
278    pub eol_required: Vec<String>,
279
280    /// The host address to bind DogStatsD UDP and TCP listeners to.
281    ///
282    /// When set, UDP and TCP listeners bind to this address. Accepts either an IP literal (for example,
283    /// `192.168.1.50`, `::1`) or a hostname that resolves via DNS (for example, `agent.internal`).
284    /// Ignored when `non_local_traffic` is `true`, and binds to `127.0.0.1` when unset.
285    pub bind_host: Option<String>,
286
287    /// Whether or not to listen for non-local traffic.
288    ///
289    /// If set to `true`, the UDP and TCP listeners bind to `0.0.0.0` and accept traffic from any interface. Otherwise,
290    /// they bind to `bind_host`, or `127.0.0.1` if `bind_host` isn't set.
291    pub non_local_traffic: bool,
292
293    /// Whether to autoscale UDP stream handlers using `SO_REUSEPORT`.
294    ///
295    /// When enabled on Linux, the DogStatsD source binds multiple UDP sockets to the configured port with
296    /// `SO_REUSEPORT`, allowing the kernel to load-balance incoming datagrams across independent stream handler
297    /// tasks. The number of sockets scales with available vCPUs: one stream handler base, plus one additional
298    /// per 8 vCPUs, capped at 4 total.
299    ///
300    /// Has no effect on non-Linux platforms because `SO_REUSEPORT` doesn't provide kernel-level load balancing
301    /// there; a warning is logged at startup if enabled outside of Linux.
302    ///
303    /// Enable this on multi-vCPU Linux deployments where UDP DogStatsD throughput is bottlenecked on a single
304    /// receive task.
305    pub autoscale_udp_listeners: bool,
306
307    /// Whether or not to allow heap allocations when resolving contexts.
308    ///
309    /// When resolving contexts during parsing, the metric name and tags are interned to reduce memory usage. The
310    /// interner has a fixed size, however, which means some strings can fail to be interned if the interner is full.
311    /// When set to `true`, we allow these strings to be allocated on the heap like normal, but this can lead to
312    /// increased (unbounded) memory usage. When set to `false`, if the metric name and all of its tags can't be
313    /// interned, the metric is skipped.
314    pub allow_context_heap_allocations: bool,
315
316    /// Whether or not to enable support for no-aggregation pipelines.
317    ///
318    /// When enabled, this influences how metrics are parsed, specifically around user-provided metric timestamps. When
319    /// metric timestamps are present, it's used as a signal to any aggregation transforms that the metric shouldn't
320    /// be aggregated.
321    pub no_aggregation_pipeline_support: bool,
322
323    /// Number of entries for the string interner, as interpreted by the Core Datadog Agent.
324    ///
325    /// When `context_string_interner_size_bytes` isn't set, this value is multiplied by 512 bytes per entry to
326    /// derive the interner byte size. This provides backwards compatibility for customers migrating configurations
327    /// from the Core Agent, where this setting represents an entry count rather than a byte size.
328    pub context_string_interner_entry_count: u64,
329
330    /// Total size of the string interner used for contexts, in bytes.
331    ///
332    /// When set, this takes priority over `context_string_interner_entry_count`. This controls the amount of memory
333    /// that can be used to intern metric names and tags. If the interner is full, metrics with contexts that haven't
334    /// already been resolved may or may not be dropped, depending on the value of `allow_context_heap_allocations`.
335    pub context_string_interner_size_bytes: Option<ByteSize>,
336
337    /// The maximum number of cached contexts to allow.
338    ///
339    /// This is the maximum number of resolved contexts that can be cached at any given time. This limit doesn't affect
340    /// the total number of contexts that can be _alive_ at any given time, which is dependent on the interner capacity
341    /// and whether or not heap allocations are allowed.
342    pub cached_contexts_limit: usize,
343
344    /// The maximum number of cached tagsets to allow.
345    ///
346    /// This is the maximum number of resolved tagsets that can be cached at any given time. This limit doesn't affect
347    /// the total number of tagsets that can be _alive_ at any given time, which is dependent on the interner capacity
348    /// and whether or not heap allocations are allowed.
349    pub cached_tagsets_limit: usize,
350
351    /// The number of seconds after which cached contexts will expire.
352    ///
353    /// Higher values allow for more effective caching for sparse metrics at the cost of increased memory usage.
354    pub context_expiry_seconds: u64,
355
356    /// Whether or not to enable permissive mode in the decoder.
357    ///
358    /// Permissive mode allows the decoder to relax its strictness around the allowed payloads, which lets it match the
359    /// decoding behavior of the Datadog Agent.
360    pub permissive_decoding: bool,
361
362    /// Whether timing (`ms`) metrics carry the `millisecond` unit.
363    ///
364    /// When `false`, timing metrics are sent without a unit. No other metric type carries a unit.
365    pub set_timing_unit: bool,
366
367    /// The minimum sample rate allowed for metrics.
368    ///
369    /// When metrics are sent with a sample rate _lower_ than this value then it will be clamped to this value. This is
370    /// done in order to ensure an upper bound on how many equivalent samples are tracked for the metric, as high sample
371    /// rates (very small numbers, such as `0.00000001`) can lead to large memory growth.
372    ///
373    /// A warning log will be emitted when clamping occurs, as this represents an effective loss of metric samples.
374    pub minimum_sample_rate: f64,
375
376    /// Which payload types to forward to the backend.
377    pub enable_payloads: EnablePayloadsConfiguration,
378
379    /// Configuration related to origin detection and enrichment.
380    pub origin_enrichment: OriginEnrichmentConfiguration,
381
382    /// Whether to break down DogStatsD processed-metric telemetry by UDS origin.
383    ///
384    /// When enabled, metric-message `dogstatsd.processed` telemetry includes an `origin` label derived from the
385    /// sender's UDS origin. This can add one telemetry series per origin and should primarily be used for diagnostics.
386    pub origin_telemetry_enabled: bool,
387
388    /// Workload provider to utilize for origin enrichment.
389    ///
390    /// Detected origins are only resolved to workload tags when a provider is set. Origin detection itself is
391    /// controlled by `origin_enrichment`.
392    pub workload_provider: Option<Arc<dyn WorkloadProvider + Send + Sync>>,
393
394    /// Resolver to use for mapping live sender PIDs to container entities before deferred processing.
395    ///
396    /// This resolver pins the sender entity while socket credentials are current so origin enrichment and traffic
397    /// capture do not resolve a stale or reused PID later. It is set separately from the workload provider because it
398    /// only needs a narrow live-PID lookup.
399    pub capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
400
401    /// Additional tags to add to all metrics.
402    ///
403    /// These are sorted and deduplicated before use, so callers may append tags required by the running environment.
404    pub additional_tags: Vec<String>,
405
406    /// The directory where DogStatsD capture files are written by default.
407    ///
408    /// When set to an empty path, callers must provide an explicit capture path when starting a capture session.
409    pub capture_path: PathBuf,
410
411    /// The maximum number of captured packets that can be queued for persistence.
412    ///
413    /// This controls the depth of the in-process capture queue. Values below `1024` are raised to `1024` before the
414    /// capture writer starts, preventing a zero-depth rendezvous channel from serializing DogStatsD stream handlers
415    /// behind capture persistence.
416    pub capture_depth: usize,
417
418    /// Control surface that starts and stops DogStatsD traffic capture.
419    ///
420    /// This is runtime wiring rather than configuration: the source binds the capture it creates to this handle, so
421    /// the caller creates the handle and keeps a clone to serve the capture API.
422    pub capture_control: DogStatsDCaptureControl,
423
424    /// Control surface that starts and stops DogStatsD traffic replay.
425    ///
426    /// This is runtime wiring rather than configuration: the source binds the captured tagger to this handle, so the
427    /// caller creates the handle and keeps a clone to serve the replay API.
428    pub replay_control: DogStatsDReplayControl,
429}
430
431#[derive(Clone, Copy, Default)]
432struct EolRequired {
433    udp: bool,
434    uds: bool,
435    named_pipe: bool,
436}
437
438impl EolRequired {
439    fn from_config_values(values: &[String]) -> Self {
440        let mut eol_required = Self::default();
441
442        for value in values {
443            match value.as_str() {
444                "udp" => eol_required.udp = true,
445                "uds" => eol_required.uds = true,
446                "named_pipe" => eol_required.named_pipe = true,
447                _ => warn!(
448                    value,
449                    "Invalid dogstatsd_eol_required value. Expected 'udp', 'uds', or 'named_pipe'."
450                ),
451            }
452        }
453
454        eol_required
455    }
456
457    fn for_listener(&self, listen_addr: &ListenAddress) -> bool {
458        match listen_addr {
459            ListenAddress::Udp(_) => self.udp,
460            ListenAddress::Tcp(_) => false,
461            ListenAddress::Unixgram(_) | ListenAddress::Unix(_) => self.uds,
462            ListenAddress::NamedPipe { .. } => self.named_pipe,
463        }
464    }
465}
466
467#[cfg(test)]
468impl DogStatsDConfiguration {
469    /// Creates a fixture configuration, for tests that exercise source behavior rather than configuration.
470    ///
471    /// Values match the effective defaults the configuration system resolves, so a test only states the settings it
472    /// cares about. `capture_depth` is the exception: a default configuration leaves it at `0`, which the capture
473    /// writer raises to its minimum, so the fixture states that minimum directly.
474    fn for_test() -> Self {
475        Self {
476            default_hostname: MetaString::default(),
477            buffer_size: 8192,
478            buffer_count: 128,
479            buffer_count_max: 32_768,
480            workers_count: 0,
481            port: 8125,
482            socket_receive_buffer_size: 0,
483            tcp_port: 0,
484            statsd_forward_host: None,
485            statsd_forward_port: 0,
486            queue_size: 1024,
487            socket_path: None,
488            socket_stream_path: None,
489            stream_log_too_big: false,
490            listener_requirement: ListenerRequirement::default(),
491            pipe_name: None,
492            windows_pipe_security_descriptor: "D:AI(A;;GA;;;WD)".to_string(),
493            disable_verbose_logs: false,
494            eol_required: Vec::new(),
495            bind_host: None,
496            non_local_traffic: false,
497            autoscale_udp_listeners: false,
498            allow_context_heap_allocations: true,
499            no_aggregation_pipeline_support: true,
500            context_string_interner_entry_count: 4096,
501            context_string_interner_size_bytes: None,
502            cached_contexts_limit: 500_000,
503            cached_tagsets_limit: 500_000,
504            context_expiry_seconds: 20,
505            permissive_decoding: true,
506            set_timing_unit: false,
507            minimum_sample_rate: 0.000000003845,
508            enable_payloads: EnablePayloadsConfiguration::for_test(),
509            origin_enrichment: OriginEnrichmentConfiguration::for_test(),
510            origin_telemetry_enabled: false,
511            workload_provider: None,
512            capture_entity_resolver: None,
513            additional_tags: Vec::new(),
514            capture_path: PathBuf::new(),
515            capture_depth: MIN_CAPTURE_DEPTH,
516            capture_control: DogStatsDCaptureControl::default(),
517            replay_control: DogStatsDReplayControl::default(),
518        }
519    }
520}
521
522impl DogStatsDConfiguration {
523    /// Gets the effective source-wide DogStatsD tags.
524    fn additional_tags(&self) -> Vec<String> {
525        let mut tags = self.additional_tags.clone();
526        tags.sort_unstable();
527        tags.dedup();
528        tags
529    }
530
531    /// Returns the effective string interner size in bytes.
532    ///
533    /// If `context_string_interner_size_bytes` is set, it's used directly. Otherwise,
534    /// `context_string_interner_entry_count` is multiplied by 512 bytes per entry to derive the byte size.
535    fn effective_context_string_interner_bytes(&self) -> ByteSize {
536        match self.context_string_interner_size_bytes {
537            Some(explicit_bytes) => explicit_bytes,
538            None => {
539                saluki_antithesis::always_le!(
540                    self.context_string_interner_entry_count,
541                    u64::MAX / INTERNER_BASELINE_BYTES_PER_ENTRY,
542                    "dogstatsd interner byte-size multiply does not overflow",
543                    { "entry_count": self.context_string_interner_entry_count }
544                );
545                ByteSize::b(
546                    self.context_string_interner_entry_count
547                        .saturating_mul(INTERNER_BASELINE_BYTES_PER_ENTRY),
548                )
549            }
550        }
551    }
552
553    fn eol_required(&self) -> EolRequired {
554        EolRequired::from_config_values(&self.eol_required)
555    }
556
557    fn statsd_forward_target(&self) -> Option<(&MetaString, u16)> {
558        let host = self.statsd_forward_host.as_ref()?;
559        if self.statsd_forward_port == 0 {
560            return None;
561        }
562
563        Some((host, self.statsd_forward_port))
564    }
565
566    fn packet_forwarder_target(&self) -> Option<PacketForwarderTarget> {
567        let (host, port) = self.statsd_forward_target()?;
568        Some(PacketForwarderTarget::new(
569            host.clone(),
570            port,
571            forwarder_queue_capacity(self.queue_size),
572            get_adjusted_buffer_size(self.buffer_size),
573        ))
574    }
575
576    /// Returns the number of UDP stream handlers to spawn, derived from `dogstatsd_autoscale_udp_listeners` and
577    /// the number of available vCPUs.
578    ///
579    /// Returns `None` when autoscaling is disabled, which keeps the legacy single-socket behavior. The platform
580    /// gate for `SO_REUSEPORT` lives inside the listener—this method intentionally stays platform-agnostic.
581    fn udp_streams_to_yield(&self) -> Option<NonZeroUsize> {
582        if !self.autoscale_udp_listeners {
583            return None;
584        }
585
586        #[cfg(not(target_os = "linux"))]
587        if self.autoscale_udp_listeners {
588            warn!("UDP stream handler autoscaling not supported on non-Linux platforms. Default to single stream handler.");
589            return None;
590        }
591
592        let vcpus = std::thread::available_parallelism().map(NonZeroUsize::get).unwrap_or(1);
593        let streams = (1 + vcpus / 8).min(4);
594        NonZeroUsize::new(streams)
595    }
596
597    /// Returns the effective maximum size of the I/O buffer pool.
598    ///
599    /// The pool can never hold fewer buffers than the configured baseline, so a `dogstatsd_buffer_count_max` below
600    /// `dogstatsd_buffer_count` (including a legacy config that only raised `dogstatsd_buffer_count`) is treated as
601    /// equal to the baseline rather than reducing capacity.
602    fn effective_max_buffer_count(&self) -> usize {
603        self.buffer_count_max.max(self.buffer_count)
604    }
605
606    fn decoder_worker_count(&self) -> NonZeroUsize {
607        let worker_count = if self.workers_count == 0 {
608            let vcpus = std::thread::available_parallelism().map(NonZeroUsize::get).unwrap_or(1);
609            default_decoder_worker_count(vcpus)
610        } else {
611            self.workers_count
612        };
613
614        NonZeroUsize::new(worker_count).expect("DogStatsD decoder worker count must be non-zero")
615    }
616
617    /// Using the current configuration, determines which listeners should be created and adds an address for each into
618    /// a `Vec<ListenAddress>`. This function has no side effects so that it can be unit tested whereas build_listeners`
619    /// actually binds the listeners on the system.
620    ///
621    /// `bind_host` is the pre-resolved IP that UDP and TCP listeners should bind to (provided by
622    /// `resolve_bind_ip`). Precedence matches the Agent:
623    ///   - `non_local_traffic=true` → `0.0.0.0` (`bind_host` ignored)
624    ///   - `bind_host=Some(ip)`     → `ip`
625    ///   - `bind_host=None`         → `127.0.0.1`
626    fn build_addresses(&self, bind_host: Option<std::net::IpAddr>) -> Vec<ListenAddress> {
627        let bind_ip: std::net::IpAddr = if self.non_local_traffic {
628            [0, 0, 0, 0].into()
629        } else {
630            bind_host.unwrap_or_else(|| [127, 0, 0, 1].into())
631        };
632
633        let mut addresses: Vec<ListenAddress> = Vec::new();
634
635        if self.port != 0 {
636            addresses.push(ListenAddress::Udp(std::net::SocketAddr::new(bind_ip, self.port)));
637        }
638
639        if self.tcp_port != 0 {
640            addresses.push(ListenAddress::Tcp(std::net::SocketAddr::new(bind_ip, self.tcp_port)));
641        }
642
643        if let Some(socket_path) = &self.socket_path {
644            addresses.push(ListenAddress::Unixgram(socket_path.into()));
645        }
646
647        if let Some(socket_stream_path) = &self.socket_stream_path {
648            addresses.push(ListenAddress::Unix(socket_stream_path.into()));
649        }
650
651        if let Some(pipe_name) = &self.pipe_name {
652            addresses.push(ListenAddress::named_pipe_with_input_buffer_size(
653                pipe_name,
654                &self.windows_pipe_security_descriptor,
655                self.buffer_size as u32,
656            ));
657        }
658
659        addresses
660    }
661
662    fn uds_origin_detection_unsupported_on_platform(&self, addresses: &[ListenAddress]) -> bool {
663        self.origin_enrichment.enabled
664            && cfg!(not(target_os = "linux"))
665            && addresses
666                .iter()
667                .any(|address| matches!(address, ListenAddress::Unixgram(_) | ListenAddress::Unix(_)))
668    }
669
670    fn warn_if_uds_origin_detection_unsupported(&self, addresses: &[ListenAddress]) {
671        if self.uds_origin_detection_unsupported_on_platform(addresses) {
672            warn!(
673                "DogStatsD UDS origin detection is enabled, but PID-based Unix socket credentials are unsupported on \
674                 this platform. Metrics are accepted without PID-based origin enrichment."
675            );
676        }
677    }
678
679    /// Resolves the IP that UDP and TCP listeners bind to, if `bind_host` applies.
680    ///
681    /// The lookup is skipped when `non_local_traffic` is set, since `bind_host` is then unused, so an unresolvable
682    /// hostname that wouldn't be used doesn't stop the source from starting.
683    async fn resolve_bind_ip(&self) -> Result<Option<std::net::IpAddr>, Error> {
684        match &self.bind_host {
685            Some(host) if !self.non_local_traffic => Ok(Some(resolve_host(host).await?)),
686            _ => Ok(None),
687        }
688    }
689
690    /// Handles `error`, raised because `listeners` can't be created.
691    ///
692    /// The error is not propagated if the listener requirement skips failed listeners.
693    fn handle_listener_failure(&self, error: Error, listeners: &str) -> Result<(), Error> {
694        // A key registered as a different type of resource is a programming error, not a listener that couldn't be
695        // created, so it's never skipped.
696        let is_key_collision = matches!(
697            error,
698            Error::FailedToAcquireListener {
699                source: AcquireError::TypeMismatch { .. },
700                ..
701            }
702        );
703        let fail = match self.listener_requirement {
704            ListenerRequirement::All => true,
705            ListenerRequirement::AtLeastOne | ListenerRequirement::Optional => false,
706        };
707        if is_key_collision || fail {
708            return Err(error);
709        }
710
711        error!(error = %error, "Can't create DogStatsD {}.", listeners);
712        Ok(())
713    }
714
715    /// Acquires the appropriate `Listener` objects from the resource registry.
716    ///
717    /// The listeners are leased, not owned: the registry keeps the bound sockets when this source is torn down, so a
718    /// rebuilt source gets the same sockets back rather than racing to re-bind addresses it just released.
719    ///
720    /// The listener requirement decides whether a listener that can't be created is skipped, and whether ending up with
721    /// no listener at all is an error.
722    async fn build_listeners(&self, context: &BuildContext) -> Result<Vec<ResourceLease<Listener>>, Error> {
723        let addresses = match self.resolve_bind_ip().await {
724            Ok(bind_ip) => self.build_addresses(bind_ip),
725            Err(e) => {
726                // An unresolvable `bind_host` only prevents the UDP and TCP listeners.
727                self.handle_listener_failure(e, "UDP and TCP listeners")?;
728                self.build_addresses(None)
729                    .into_iter()
730                    .filter(|address| !matches!(address, ListenAddress::Udp(_) | ListenAddress::Tcp(_)))
731                    .collect()
732            }
733        };
734
735        self.warn_if_uds_origin_detection_unsupported(&addresses);
736
737        let mut listeners = Vec::new();
738        let socket_receive_buffer_size =
739            (self.socket_receive_buffer_size != 0).then_some(self.socket_receive_buffer_size);
740        let udp_streams_to_yield = self.udp_streams_to_yield();
741        for address in addresses {
742            let listener_type = address.listener_type();
743            let listener_streams = matches!(address, ListenAddress::Udp(_))
744                .then_some(udp_streams_to_yield)
745                .flatten();
746            let spec = SocketSpecification::new(address)
747                .with_udp_streams(listener_streams)
748                .with_receive_buffer_size(socket_receive_buffer_size);
749            match context.acquire_resource(spec).await {
750                Ok(listener) => listeners.push(listener),
751                Err(source) => self.handle_listener_failure(
752                    Error::FailedToAcquireListener { listener_type, source },
753                    &format!("{listener_type} listener"),
754                )?,
755            }
756        }
757
758        if listeners.is_empty() {
759            match self.listener_requirement {
760                ListenerRequirement::All | ListenerRequirement::AtLeastOne => return Err(Error::NoListeners),
761                // The server process keeps running. The source runs without listeners until shutdown.
762                ListenerRequirement::Optional => error!(error = %Error::NoListeners, "Could not start DogStatsD."),
763            }
764        }
765        Ok(listeners)
766    }
767}
768
769#[async_trait]
770impl SourceBuilder for DogStatsDConfiguration {
771    async fn build(&self, context: BuildContext) -> Result<Box<dyn Source + Send>, GenericError> {
772        let listeners = self.build_listeners(&context).await?;
773
774        // Every listener requires at least one I/O buffer to ensure that all listeners can be serviced without
775        // deadlocking any of the others. Multi-socket connectionless listeners require one buffer per yielded socket.
776        let min_buffers: usize = listeners.iter().map(|listener| listener.min_buffer_reservation()).sum();
777        let max_buffers = self.effective_max_buffer_count();
778        // Without listeners, `min_buffers` is zero, so the check below can't catch a capacity of zero. The datagram
779        // queue needs room for at least one buffer either way.
780        if max_buffers == 0 {
781            return Err(generic_error!(
782                "The maximum I/O buffer count must be greater than zero."
783            ));
784        }
785        if max_buffers < min_buffers {
786            return Err(generic_error!(
787                "The maximum I/O buffer count ({}) must be at least {} to service all configured listeners.",
788                max_buffers,
789                min_buffers,
790            ));
791        }
792
793        // Single CapturedTaggerHandle is cloned to both the resolver (reader of the captured store) and the replay
794        // control surface (writer). Both sides reference the same atomic slot.
795        let captured_tagger = CapturedTaggerHandle::new();
796
797        let maybe_origin_tags_resolver = self.workload_provider.clone().map(|provider| {
798            DogStatsDOriginTagResolver::new(self.origin_enrichment.clone(), provider, captured_tagger.clone())
799        });
800        let context_resolvers = ContextResolvers::new(self, context.component_context(), maybe_origin_tags_resolver)
801            .error_context("Failed to create context resolvers.")?;
802
803        let codec_config = DogStatsDCodecConfiguration::default()
804            .with_timestamps(self.no_aggregation_pipeline_support)
805            .with_permissive_mode(self.permissive_decoding)
806            .with_minimum_sample_rate(self.minimum_sample_rate)
807            .with_client_origin_detection(self.origin_enrichment.origin_detection_client)
808            .with_timing_unit(self.set_timing_unit);
809
810        let traffic_capture = TrafficCapture::with_workload_provider(
811            self.capture_path.clone(),
812            self.capture_depth,
813            self.workload_provider.clone(),
814        );
815        self.capture_control.bind(traffic_capture.clone());
816        self.replay_control.bind(captured_tagger);
817
818        let decoder_context = DecoderContext {
819            codec: DogStatsDCodec::from_configuration(codec_config),
820            context_resolvers,
821            default_hostname: self.default_hostname.clone(),
822            enable_payloads: self.enable_payloads,
823            origin_detection_enabled: self.origin_enrichment.enabled,
824            stream_log_too_big: self.stream_log_too_big,
825            disable_verbose_logs: self.disable_verbose_logs,
826            additional_tags: self.additional_tags().into(),
827            traffic_capture,
828        };
829
830        // The pool allocates `buffer_count` buffers up front and may grow on demand up to `max_buffers`. The effective
831        // maximum is never below the baseline, so configs that only raise `dogstatsd_buffer_count` keep their full
832        // capacity instead of being silently reduced to the `dogstatsd_buffer_count_max` default.
833        let (io_buffer_pool, io_buffer_pool_shrinker) =
834            build_io_buffer_pool(self.buffer_count, max_buffers, self.buffer_size);
835        Ok(Box::new(DogStatsD {
836            listeners,
837            decoder_worker_count: self.decoder_worker_count(),
838            io_buffer_pool,
839            io_buffer_queue_capacity: max_buffers,
840            io_buffer_pool_shrinker: Box::pin(io_buffer_pool_shrinker),
841            decoder_context,
842            origin_telemetry_enabled: self.origin_telemetry_enabled,
843            eol_required: self.eol_required(),
844            capture_entity_resolver: self.capture_entity_resolver.clone(),
845            packet_forwarder_target: self.packet_forwarder_target(),
846        }))
847    }
848
849    fn outputs(&self) -> &[OutputDefinition<EventType>] {
850        static OUTPUTS: LazyLock<Vec<OutputDefinition<EventType>>> = LazyLock::new(|| {
851            vec![
852                OutputDefinition::named_output("metrics", EventType::Metric),
853                OutputDefinition::named_output("events", EventType::EventD),
854                OutputDefinition::named_output("service_checks", EventType::ServiceCheck),
855            ]
856        });
857        &OUTPUTS
858    }
859}
860
861impl MemoryBounds for DogStatsDConfiguration {
862    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
863        let additional_buffers = self.effective_max_buffer_count().saturating_sub(self.buffer_count);
864        let adjusted_buffer_size = get_adjusted_buffer_size(self.buffer_size);
865
866        builder
867            .minimum()
868            // Capture the size of the heap allocation when the component is built.
869            .with_single_value::<DogStatsD>("source struct")
870            // We allocate the baseline buffer pool up front.
871            .with_expr(UsageExpr::product(
872                "buffers",
873                UsageExpr::config("dogstatsd_buffer_count", self.buffer_count),
874                UsageExpr::config("dogstatsd_buffer_size", adjusted_buffer_size),
875            ))
876            // We also allocate the backing storage for the string interner up front, which is used by our context
877            // resolver.
878            .with_expr(UsageExpr::config(
879                "dogstatsd_string_interner_size_bytes",
880                self.effective_context_string_interner_bytes().as_u64() as usize,
881            ));
882
883        // The pool can grow on demand up to its maximum, so account for the additional headroom as firm usage.
884        builder.firm().with_expr(UsageExpr::product(
885            "elastic buffers",
886            UsageExpr::constant("dogstatsd_buffer_count_max_extra", additional_buffers),
887            UsageExpr::config("dogstatsd_buffer_size", adjusted_buffer_size),
888        ));
889
890        // Each packet forwarder queue slot keeps a buffer as large as the largest packet it has carried, up to a receive
891        // buffer. This is the worst case: slots are usually much smaller.
892        if self.statsd_forward_target().is_some() {
893            builder.firm().with_expr(UsageExpr::product(
894                "packet forwarder queue",
895                UsageExpr::constant("forwarder_queue_capacity", forwarder_queue_capacity(self.queue_size)),
896                UsageExpr::config("dogstatsd_buffer_size", adjusted_buffer_size),
897            ));
898        }
899    }
900}
901
902/// DogStatsD source.
903pub struct DogStatsD {
904    listeners: Vec<ResourceLease<Listener>>,
905    decoder_worker_count: NonZeroUsize,
906    io_buffer_pool: ElasticObjectPool<BytesBuffer>,
907    io_buffer_queue_capacity: usize,
908    io_buffer_pool_shrinker: Pin<Box<dyn Future<Output = ()> + Send>>,
909    decoder_context: DecoderContext,
910    origin_telemetry_enabled: bool,
911    eol_required: EolRequired,
912    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
913    packet_forwarder_target: Option<PacketForwarderTarget>,
914}
915
916struct ListenerContext {
917    listener: ResourceLease<Listener>,
918    datagram_sender: WorkQueueSender<QueuedDatagram>,
919    io_buffer_pool: ElasticObjectPool<BytesBuffer>,
920    origin_telemetry_enabled: bool,
921    eol_required: EolRequired,
922    decoder_context: DecoderContext,
923    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
924    packet_forwarder: Option<PacketForwarder>,
925}
926
927#[derive(Clone)]
928struct HandlerContext {
929    listen_addr: ListenAddress,
930    eol_required: bool,
931    io_buffer_pool: ElasticObjectPool<BytesBuffer>,
932    datagram_sender: WorkQueueSender<QueuedDatagram>,
933    datagram_context: Option<Arc<DatagramSocketContext>>,
934    metrics: Metrics,
935    decoder_context: DecoderContext,
936    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
937    packet_forwarder: Option<PacketForwarder>,
938}
939
940#[derive(Clone)]
941struct DecoderContext {
942    codec: DogStatsDCodec,
943    context_resolvers: ContextResolvers,
944    default_hostname: MetaString,
945    enable_payloads: EnablePayloadsConfiguration,
946    origin_detection_enabled: bool,
947    stream_log_too_big: bool,
948    disable_verbose_logs: bool,
949    additional_tags: Arc<[String]>,
950    traffic_capture: TrafficCapture,
951}
952
953struct DatagramSocketContext {
954    listen_addr: ListenAddress,
955    eol_required: bool,
956    metrics: Metrics,
957    packet_forwarder: Option<PacketForwarder>,
958}
959
960struct QueuedDatagram {
961    result: io::Result<ReceivedBuffer>,
962    socket_context: Arc<DatagramSocketContext>,
963}
964
965struct DogStatsDDecoder {
966    source_context: SourceContext,
967    context: DecoderContext,
968    event_buffer: EventBufferManager<DEFAULT_EVENTS_BUFFER_CAPACITY>,
969}
970
971#[derive(Clone, Copy)]
972enum BufferDecodeMode {
973    Connectionless,
974    Connected,
975}
976
977impl BufferDecodeMode {
978    fn is_eof(self, bytes_read: usize) -> bool {
979        match self {
980            Self::Connectionless => true,
981            Self::Connected => bytes_read == 0,
982        }
983    }
984
985    fn should_stop_on_eof(self, eof: bool) -> bool {
986        matches!(self, Self::Connected) && eof
987    }
988
989    fn should_stop_on_framing_error(self) -> bool {
990        matches!(self, Self::Connected)
991    }
992}
993
994struct BufferDecodeContext<'a> {
995    listen_addr: &'a ListenAddress,
996    metrics: &'a Metrics,
997    packet_forwarder: Option<&'a PacketForwarder>,
998    mode: BufferDecodeMode,
999    framer: DsdFramer,
1000
1001    /// The last PID seen on this connection, so that captured frames keep it on reads that carry no credentials.
1002    last_pid: Option<i32>,
1003}
1004
1005impl<'a> BufferDecodeContext<'a> {
1006    fn new(
1007        listen_addr: &'a ListenAddress, eol_required: bool, metrics: &'a Metrics,
1008        packet_forwarder: Option<&'a PacketForwarder>, mode: BufferDecodeMode,
1009    ) -> Self {
1010        Self {
1011            listen_addr,
1012            metrics,
1013            packet_forwarder,
1014            mode,
1015            framer: get_framer(listen_addr, eol_required),
1016            last_pid: None,
1017        }
1018    }
1019}
1020
1021#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1022enum DecodeOutcome {
1023    Continue,
1024    Stop,
1025}
1026
1027#[async_trait]
1028impl Source for DogStatsD {
1029    async fn run(mut self: Box<Self>, mut context: SourceContext) -> Result<(), GenericError> {
1030        let global_shutdown = context.take_shutdown_handle();
1031        pin!(global_shutdown);
1032
1033        let mut health = context.take_health_handle();
1034
1035        // This source spawns everything below as its own children. Thus, the source does not finish until they finish.
1036        // When the body of the source returns, the children receive the shutdown signal.
1037        //
1038        // Brutal: the shrinker loops forever with no terminal condition of its own, so waiting for it would hold
1039        // every shutdown open until its timeout expired.
1040        runtime::worker("io_buffer_pool_shrinker", self.io_buffer_pool_shrinker)
1041            .with_shutdown_strategy(ShutdownStrategy::Brutal)
1042            .spawn();
1043
1044        // Each decoder gets its own queue. Sharing one receiver between decoders serializes decoding: handing the
1045        // receiver to the next decoder puts it behind the previous decoder's decode work on the same runtime thread.
1046        let (datagram_sender, datagram_receivers) =
1047            work_queue::bounded(self.decoder_worker_count, self.io_buffer_queue_capacity);
1048        let decoder_context = self.decoder_context;
1049
1050        // Decoders must drain their queue to completion, so they deliberately ignore the shutdown signal and stop only
1051        // once their queue closes -- which happens when every listener and stream handler has dropped its datagram
1052        // sender. This makes shutdown lossless. The listeners stop when the body of this source returns. The decoders
1053        // can see the close only after the listeners and their stream handlers stop. Then the decoders drain the
1054        // datagrams that remain.
1055        //
1056        // When dispatch is backpressured, the drain can take longer than five seconds, the default timeout of a
1057        // closure-based child. Thus, the decoders have no timeout of their own, and are halted with the source if the
1058        // component's shutdown timeout expires.
1059        for (worker_id, datagram_receiver) in datagram_receivers.into_iter().enumerate() {
1060            let decoder_source_context = context.clone();
1061            let decoder_context = decoder_context.clone();
1062
1063            runtime::worker(
1064                format!("datagram_decoder_{worker_id}"),
1065                drive_datagram_decoder(datagram_receiver, decoder_source_context, decoder_context),
1066            )
1067            .with_shutdown_timeout(Duration::MAX)
1068            .spawn();
1069        }
1070
1071        // One packet forwarder serves every listener. Its forwarding loop stops once every listener, stream handler, and
1072        // decoder has dropped its handle, after sending whatever is still queued.
1073        let packet_forwarder = self
1074            .packet_forwarder_target
1075            .as_ref()
1076            .map(|target| target.to_forwarder(ForwarderMetrics::new(context.component_context())));
1077        if let Some(packet_forwarder) = &packet_forwarder {
1078            packet_forwarder.spawn();
1079        }
1080
1081        // For each listener, spawn a dedicated task to run it. There may be none, when no listener could be created and
1082        // the listener requirement is `Optional`. The source then only waits for shutdown.
1083        for listener in self.listeners {
1084            let task_name = format!("listener_{}", listener.listen_address().listener_type());
1085            let listener_source_context = context.clone();
1086
1087            // TODO: Create a health handle for each listener.
1088            //
1089            // We need to rework `HealthRegistry` to look a little more like `ComponentRegistry` so that we can have it
1090            // already be scoped properly, otherwise all we can do here at present is either have a relative name, like
1091            // `uds-stream`, or try and hardcode the full component name, which we will inevitably forget to update if
1092            // we tweak the topology configuration, etc.
1093            let listener_context = ListenerContext {
1094                listener,
1095                datagram_sender: datagram_sender.clone(),
1096                io_buffer_pool: self.io_buffer_pool.clone(),
1097                origin_telemetry_enabled: self.origin_telemetry_enabled,
1098                eol_required: self.eol_required,
1099                decoder_context: decoder_context.clone(),
1100                capture_entity_resolver: self.capture_entity_resolver.clone(),
1101                packet_forwarder: packet_forwarder.clone(),
1102            };
1103
1104            // An accept loop has no terminal condition of its own, so the listener needs the shutdown signal. It has no
1105            // shutdown timeout of its own: the topology shutdown timeout applies to the source and everything it spawned.
1106            //
1107            // Each listener is needed. A fatal accept error stops a listener without a request to stop. Then the source
1108            // has nothing to listen on, so the listener stops the source. The source does not continue to run.
1109            runtime::worker_with_shutdown(task_name, move |process_shutdown| {
1110                process_listener(listener_source_context, listener_context, process_shutdown)
1111            })
1112            .with_shutdown_timeout(Duration::MAX)
1113            .needed()
1114            .spawn();
1115        }
1116        drop(datagram_sender);
1117        drop(packet_forwarder);
1118
1119        health.mark_ready();
1120        debug!("DogStatsD source started.");
1121
1122        // Wait for the global shutdown signal, then notify listeners to shutdown.
1123        //
1124        // We also handle liveness here, which doesn't really matter for _this_ task, since the real work is happening
1125        // in the listeners, but we need to satisfy the health checker.
1126        loop {
1127            select! {
1128                _ = &mut global_shutdown => {
1129                    debug!("Received shutdown signal.");
1130                    break
1131                },
1132                _ = health.live() => continue,
1133            }
1134        }
1135
1136        // This return stops the listeners, and after they stop, the decoders drain. The source finishes when all of its
1137        // children finish.
1138        debug!("Stopping DogStatsD source...");
1139
1140        Ok(())
1141    }
1142}
1143
1144fn build_io_buffer_pool(
1145    min_buffers: usize, max_buffers: usize, buffer_size: usize,
1146) -> (ElasticObjectPool<BytesBuffer>, impl Future<Output = ()> + Send) {
1147    saluki_antithesis::always_le!(
1148        buffer_size,
1149        usize::MAX - 4,
1150        "dogstatsd buffer size add does not overflow",
1151        { "buffer_size": buffer_size }
1152    );
1153    let adjusted_buffer_size = get_adjusted_buffer_size(buffer_size);
1154    ElasticObjectPool::with_builder("dsd_packet_bufs", min_buffers, max_buffers, move || {
1155        FixedSizeVec::with_capacity(adjusted_buffer_size)
1156    })
1157}
1158
1159fn is_connectionless_listen_address(listen_addr: &ListenAddress) -> bool {
1160    match listen_addr {
1161        ListenAddress::Udp(_) => true,
1162        #[cfg(unix)]
1163        ListenAddress::Unixgram(_) => true,
1164        _ => false,
1165    }
1166}
1167
1168async fn process_listener(
1169    source_context: SourceContext, listener_context: ListenerContext, process_shutdown: ShutdownHandle,
1170) {
1171    let ListenerContext {
1172        mut listener,
1173        datagram_sender,
1174        io_buffer_pool,
1175        origin_telemetry_enabled,
1176        eol_required,
1177        decoder_context,
1178        capture_entity_resolver,
1179        packet_forwarder,
1180    } = listener_context;
1181
1182    pin!(process_shutdown);
1183
1184    let listen_addr = listener.listen_address().clone();
1185    let metrics = build_metrics(
1186        &listen_addr,
1187        source_context.component_context(),
1188        origin_telemetry_enabled,
1189    );
1190    let datagram_context = is_connectionless_listen_address(&listen_addr).then(|| {
1191        Arc::new(DatagramSocketContext {
1192            listen_addr: listen_addr.clone(),
1193            eol_required: eol_required.for_listener(&listen_addr),
1194            metrics: metrics.clone(),
1195            packet_forwarder: packet_forwarder.clone(),
1196        })
1197    });
1198
1199    info!(%listen_addr, "DogStatsD listener started.");
1200
1201    loop {
1202        select! {
1203            // This signal fires when the body of the source returns. That return closes the scope that this listener
1204            // belongs to.
1205            _ = &mut process_shutdown => {
1206                debug!(%listen_addr, "Received shutdown signal. Waiting for existing stream handlers to finish...");
1207                break;
1208            }
1209            result = listener.accept() => match result {
1210                Ok(stream) => {
1211                    debug!(%listen_addr, "Spawning new stream handler.");
1212
1213                    let handler_context = HandlerContext {
1214                        listen_addr: listen_addr.clone(),
1215                        eol_required: eol_required.for_listener(&listen_addr),
1216                        io_buffer_pool: io_buffer_pool.clone(),
1217                        datagram_sender: datagram_sender.clone(),
1218                        datagram_context: datagram_context.clone(),
1219                        metrics: metrics.clone(),
1220                        decoder_context: decoder_context.clone(),
1221                        capture_entity_resolver: capture_entity_resolver.clone(),
1222                        packet_forwarder: packet_forwarder.clone(),
1223                    };
1224
1225                    let task_name = format!("conn_{}", listen_addr.listener_type());
1226
1227                    // Each handler is a child of the listener. Thus, the listener does not finish until its stream
1228                    // handlers finish. The handlers receive the shutdown signal when the listener no longer accepts
1229                    // connections.
1230                    let handler_source_context = source_context.clone();
1231                    runtime::worker_with_shutdown(task_name, move |shutdown| {
1232                        process_stream(stream, handler_source_context, handler_context, shutdown)
1233                    })
1234                    .spawn();
1235                }
1236                Err(e) => {
1237                    error!(%listen_addr, error = %e, "Failed to accept connection. Stopping listener.");
1238                    break
1239                }
1240            }
1241        }
1242    }
1243
1244    info!(%listen_addr, "DogStatsD listener stopped accepting connections.");
1245}
1246
1247async fn process_stream(
1248    stream: Stream, source_context: SourceContext, handler_context: HandlerContext, shutdown_handle: ShutdownHandle,
1249) {
1250    select! {
1251        _ = shutdown_handle => {
1252            debug!("Stream handler received shutdown signal.");
1253        },
1254        _ = drive_stream(stream, source_context, handler_context) => {},
1255    }
1256}
1257
1258fn origin_detection_error_for_telemetry(
1259    origin_detection_enabled: bool, bytes_read: usize, peer_addr: &ConnectionAddress,
1260) -> Option<ProcessCredentialsError> {
1261    match peer_addr {
1262        ConnectionAddress::ProcessLike(identity @ ProcessIdentity::Error(error))
1263            if origin_detection_enabled && bytes_read > 0 && identity.is_telemetry_error() =>
1264        {
1265            Some(*error)
1266        }
1267        _ => None,
1268    }
1269}
1270
1271struct ReceivedBuffer {
1272    buffer: Option<BytesBuffer>,
1273    bytes_read: usize,
1274    peer_addr: ConnectionAddress,
1275    process_origin: Option<ProcessOrigin>,
1276    buffer_sender: Option<oneshot::Sender<BytesBuffer>>,
1277}
1278
1279impl ReceivedBuffer {
1280    fn with_return(
1281        buffer: BytesBuffer, bytes_read: usize, peer_addr: ConnectionAddress, process_origin: Option<ProcessOrigin>,
1282    ) -> (Self, oneshot::Receiver<BytesBuffer>) {
1283        let (buffer_sender, returned_buffer) = oneshot::channel();
1284        (
1285            Self {
1286                buffer: Some(buffer),
1287                bytes_read,
1288                peer_addr,
1289                process_origin,
1290                buffer_sender: Some(buffer_sender),
1291            },
1292            returned_buffer,
1293        )
1294    }
1295
1296    fn without_return(
1297        buffer: BytesBuffer, bytes_read: usize, peer_addr: ConnectionAddress, process_origin: Option<ProcessOrigin>,
1298    ) -> Self {
1299        Self {
1300            buffer: Some(buffer),
1301            bytes_read,
1302            peer_addr,
1303            process_origin,
1304            buffer_sender: None,
1305        }
1306    }
1307
1308    fn parts_mut(&mut self) -> (&mut BytesBuffer, usize, &ConnectionAddress, Option<&ProcessOrigin>) {
1309        let Self {
1310            buffer,
1311            bytes_read,
1312            peer_addr,
1313            process_origin,
1314            ..
1315        } = self;
1316        (
1317            buffer.as_mut().expect("Received buffer already taken."),
1318            *bytes_read,
1319            peer_addr,
1320            process_origin.as_ref(),
1321        )
1322    }
1323
1324    #[cfg(all(test, unix))]
1325    fn buffer(&self) -> &BytesBuffer {
1326        self.buffer.as_ref().expect("Received buffer already taken.")
1327    }
1328
1329    #[cfg(all(test, unix))]
1330    fn buffer_mut(&mut self) -> &mut BytesBuffer {
1331        self.buffer.as_mut().expect("Received buffer already taken.")
1332    }
1333}
1334
1335impl Drop for ReceivedBuffer {
1336    fn drop(&mut self) {
1337        if let Some(sender) = self.buffer_sender.take() {
1338            let buffer = self.buffer.take().expect("Received buffer already taken.");
1339            let _ = sender.send(buffer);
1340        }
1341    }
1342}
1343
1344struct BufferedStreamReader {
1345    receiver: Option<mpsc::Receiver<io::Result<ReceivedBuffer>>>,
1346
1347    // Held but never fired explicitly, so that dropping this reader signals the worker to stop.
1348    _shutdown_coordinator: ShutdownCoordinator,
1349}
1350
1351impl BufferedStreamReader {
1352    fn new(
1353        stream: Stream, io_buffer_pool: ElasticObjectPool<BytesBuffer>, memory_limiter: MemoryLimiter,
1354        origin_detection_enabled: bool, traffic_capture: TrafficCapture,
1355        capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
1356    ) -> Self {
1357        debug_assert!(!stream.is_connectionless());
1358        let (packets_tx, receiver) = mpsc::channel(1);
1359        let (shutdown_coordinator, shutdown_handle) = ShutdownHandle::paired();
1360
1361        let reader = receive_connected_stream(
1362            stream,
1363            io_buffer_pool,
1364            memory_limiter,
1365            origin_detection_enabled,
1366            traffic_capture,
1367            capture_entity_resolver,
1368            packets_tx,
1369        );
1370
1371        runtime::worker("stream_reader", async move {
1372            select! {
1373                _ = shutdown_handle => debug!("Stream reader cancelled."),
1374                _ = reader => {},
1375            }
1376        })
1377        .spawn();
1378
1379        Self {
1380            receiver: Some(receiver),
1381            _shutdown_coordinator: shutdown_coordinator,
1382        }
1383    }
1384
1385    fn take_receiver(&mut self) -> mpsc::Receiver<io::Result<ReceivedBuffer>> {
1386        self.receiver.take().expect("Buffered stream receiver already taken")
1387    }
1388}
1389
1390async fn receive_connected_stream(
1391    mut stream: Stream, io_buffer_pool: ElasticObjectPool<BytesBuffer>, memory_limiter: MemoryLimiter,
1392    origin_detection_enabled: bool, traffic_capture: TrafficCapture,
1393    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
1394    packets_tx: mpsc::Sender<io::Result<ReceivedBuffer>>,
1395) {
1396    debug!("Stream reader started.");
1397
1398    let mut retained_buffer: Option<BytesBuffer> = None;
1399    loop {
1400        memory_limiter.wait_for_capacity().await;
1401
1402        let mut buffer = match retained_buffer.take() {
1403            Some(mut buffer) => {
1404                buffer.collapse();
1405                buffer
1406            }
1407            None => acquire_io_buffer(&io_buffer_pool).await,
1408        };
1409        let (bytes_read, peer_addr) = match stream.receive(&mut buffer).await {
1410            Ok(received) => received,
1411            Err(error) => {
1412                let _ = packets_tx.send(Err(error)).await;
1413                break;
1414            }
1415        };
1416        let process_origin = resolve_process_origin_if_needed(
1417            origin_detection_enabled,
1418            &traffic_capture,
1419            capture_entity_resolver.as_deref(),
1420            &peer_addr,
1421        );
1422
1423        let (received, returned_buffer) = ReceivedBuffer::with_return(buffer, bytes_read, peer_addr, process_origin);
1424
1425        if packets_tx.send(Ok(received)).await.is_err() {
1426            debug!("Failed to enqueue DogStatsD packet for decoding: receiver dropped.");
1427            break;
1428        }
1429
1430        match returned_buffer.await {
1431            Ok(buffer) if buffer.has_remaining() => retained_buffer = Some(buffer),
1432            Ok(buffer) => drop(buffer),
1433            Err(_) => break,
1434        }
1435    }
1436
1437    debug!("Stream reader stopped.");
1438}
1439
1440async fn receive_connectionless_stream(
1441    mut stream: Stream, io_buffer_pool: ElasticObjectPool<BytesBuffer>, memory_limiter: MemoryLimiter,
1442    origin_detection_enabled: bool, traffic_capture: TrafficCapture,
1443    capture_entity_resolver: Option<Arc<dyn CaptureEntityResolver + Send + Sync>>,
1444    mut datagram_sender: WorkQueueSender<QueuedDatagram>, socket_context: Arc<DatagramSocketContext>,
1445) {
1446    debug!(listen_addr = %socket_context.listen_addr, "Datagram reader started.");
1447
1448    loop {
1449        memory_limiter.wait_for_capacity().await;
1450
1451        let mut buffer = acquire_io_buffer(&io_buffer_pool).await;
1452        let result = match stream.receive(&mut buffer).await {
1453            Ok((bytes_read, peer_addr)) => {
1454                let process_origin = resolve_process_origin_if_needed(
1455                    origin_detection_enabled,
1456                    &traffic_capture,
1457                    capture_entity_resolver.as_deref(),
1458                    &peer_addr,
1459                );
1460                Ok(ReceivedBuffer::without_return(
1461                    buffer,
1462                    bytes_read,
1463                    peer_addr,
1464                    process_origin,
1465                ))
1466            }
1467            Err(error) => Err(error),
1468        };
1469
1470        let queued = QueuedDatagram {
1471            result,
1472            socket_context: socket_context.clone(),
1473        };
1474        if datagram_sender.send(queued).await.is_err() {
1475            debug!(
1476                listen_addr = %socket_context.listen_addr,
1477                "Failed to enqueue DogStatsD packet for decoding: receiver dropped."
1478            );
1479            break;
1480        }
1481    }
1482
1483    debug!(listen_addr = %socket_context.listen_addr, "Datagram reader stopped.");
1484}
1485
1486async fn acquire_io_buffer(io_buffer_pool: &ElasticObjectPool<BytesBuffer>) -> BytesBuffer {
1487    let buffer = io_buffer_pool.acquire().await;
1488    trace!(
1489        remaining = buffer.remaining(),
1490        capacity = buffer.capacity(),
1491        "Acquired new buffer from pool."
1492    );
1493    buffer
1494}
1495
1496impl DogStatsDDecoder {
1497    fn new(source_context: SourceContext, context: DecoderContext) -> Self {
1498        Self {
1499            source_context,
1500            context,
1501            event_buffer: EventBufferManager::default(),
1502        }
1503    }
1504
1505    async fn decode_buffer(
1506        &mut self, context: &mut BufferDecodeContext<'_>, mut received: ReceivedBuffer,
1507    ) -> DecodeOutcome {
1508        let (buffer, bytes_read, peer_addr, process_origin) = received.parts_mut();
1509        self.decode_buffer_contents(context, buffer, bytes_read, peer_addr, process_origin)
1510            .await
1511    }
1512
1513    async fn decode_buffer_contents(
1514        &mut self, context: &mut BufferDecodeContext<'_>, io_buffer: &mut BytesBuffer, bytes_read: usize,
1515        peer_addr: &ConnectionAddress, process_origin: Option<&ProcessOrigin>,
1516    ) -> DecodeOutcome {
1517        let listen_addr = context.listen_addr;
1518        let metrics = context.metrics;
1519        let packet_forwarder = context.packet_forwarder;
1520        let mode = context.mode;
1521
1522        let payload = received_payload(io_buffer, bytes_read);
1523        let traffic_capture = &self.context.traffic_capture;
1524        capture_unixgram_traffic(listen_addr, traffic_capture, peer_addr, process_origin, payload);
1525
1526        let capture_stream_frames = matches!(listen_addr, ListenAddress::Unix(_)) && traffic_capture.is_ongoing();
1527        if capture_stream_frames {
1528            if let Some(process_id) = process_id_from_peer_addr(peer_addr) {
1529                context.last_pid = Some(process_id);
1530            }
1531        }
1532
1533        metrics.bytes_received().increment(bytes_read as u64);
1534        metrics.bytes_received_size().record(bytes_read as f64);
1535        let origin_detection_errors =
1536            origin_detection_error_for_telemetry(self.context.origin_detection_enabled, bytes_read, peer_addr)
1537                .and_then(|error| metrics.origin_detection_errors(error));
1538
1539        if matches!(mode, BufferDecodeMode::Connectionless) {
1540            metrics.packet_receive_success().increment(1);
1541            if let Some(origin_detection_errors) = origin_detection_errors {
1542                origin_detection_errors.increment(1);
1543            }
1544        }
1545
1546        let eof = mode.is_eof(bytes_read);
1547        trace!(
1548            buffer_len = io_buffer.remaining(),
1549            buffer_cap = io_buffer.remaining_mut(),
1550            %listen_addr,
1551            %peer_addr,
1552            eof,
1553            "Received {} bytes from socket.",
1554            bytes_read
1555        );
1556
1557        if should_drop_oversized_named_pipe_frame(listen_addr, io_buffer) {
1558            metrics.framing_errors().increment(1);
1559            debug!(%listen_addr, %peer_addr, "DogStatsD named pipe frame exceeded the configured buffer size. Dropping frame.");
1560            io_buffer.clear();
1561            return DecodeOutcome::Continue;
1562        }
1563
1564        let mut frames = context.framer.frames(io_buffer.cursor(), eof, capture_stream_frames);
1565        loop {
1566            let frame_result = frames.next();
1567            let completed_outer_frames = frames.take_completed_outer_frames();
1568            if completed_outer_frames > 0 {
1569                metrics
1570                    .packet_receive_success()
1571                    .increment(completed_outer_frames as u64);
1572                if let Some(origin_detection_errors) = origin_detection_errors {
1573                    origin_detection_errors.increment(completed_outer_frames as u64);
1574                }
1575            }
1576
1577            match frame_result {
1578                Some(Ok(Frame::Outer(payload))) => {
1579                    let _ = self.context.traffic_capture.enqueue(build_capture_record(
1580                        context.last_pid,
1581                        process_origin,
1582                        payload,
1583                    ));
1584                }
1585                Some(Ok(Frame::Message(frame))) => {
1586                    if matches!(listen_addr, ListenAddress::NamedPipe { .. }) {
1587                        capture_named_pipe_frame(&self.context.traffic_capture, frame);
1588                        metrics.packet_receive_success().increment(1);
1589                    }
1590                    self.decode_frame(frame, listen_addr, peer_addr, process_origin, metrics, packet_forwarder)
1591                        .await;
1592                }
1593                None => {
1594                    if mode.should_stop_on_eof(eof) {
1595                        debug!(%listen_addr, %peer_addr, "Stream received EOF. Shutting down handler.");
1596                        return DecodeOutcome::Stop;
1597                    }
1598                    return DecodeOutcome::Continue;
1599                }
1600                Some(Err(error)) => {
1601                    metrics.framing_errors().increment(1);
1602                    if should_warn_stream_log_too_big(listen_addr, &error, self.context.stream_log_too_big) {
1603                        warn!(
1604                            %listen_addr,
1605                            %peer_addr,
1606                            error = %error,
1607                            "DogStatsD stream frame exceeded the configured buffer size."
1608                        );
1609                    }
1610
1611                    if mode.should_stop_on_framing_error() {
1612                        debug!(%listen_addr, %peer_addr, %error, "Error decoding frame. Stopping stream.");
1613                        return DecodeOutcome::Stop;
1614                    }
1615
1616                    debug!(%listen_addr, %peer_addr, %error, "Error decoding datagram frame. Continuing listener.");
1617                    return DecodeOutcome::Continue;
1618                }
1619            }
1620        }
1621    }
1622
1623    async fn decode_frame(
1624        &mut self, frame: &[u8], listen_addr: &ListenAddress, peer_addr: &ConnectionAddress,
1625        process_origin: Option<&ProcessOrigin>, metrics: &Metrics, packet_forwarder: Option<&PacketForwarder>,
1626    ) {
1627        trace!(%listen_addr, %peer_addr, frame = %frame.escape_ascii(), "Decoded frame.");
1628        if let Some(forwarder) = packet_forwarder {
1629            forwarder.forward(frame).await;
1630        }
1631
1632        match self.handle_frame(frame, metrics, process_origin) {
1633            Ok(Some(event)) => {
1634                if let Some(event_buffer) = self.event_buffer.try_push(event) {
1635                    debug!(%listen_addr, %peer_addr, "Event buffer is full. Forwarding events.");
1636                    dispatch_events(event_buffer, &self.source_context).await;
1637                }
1638            }
1639            Ok(None) => {}
1640            Err(error) => {
1641                log_parse_failure(self.context.disable_verbose_logs, listen_addr, peer_addr, frame, &error);
1642            }
1643        }
1644    }
1645
1646    async fn flush_events(&mut self) {
1647        if let Some(event_buffer) = self.event_buffer.consume() {
1648            dispatch_events(event_buffer, &self.source_context).await;
1649        }
1650    }
1651
1652    fn handle_frame(
1653        &mut self, frame: &[u8], source_metrics: &Metrics, process_origin: Option<&ProcessOrigin>,
1654    ) -> Result<Option<Event>, ParseError> {
1655        let DecoderContext {
1656            codec,
1657            context_resolvers,
1658            default_hostname,
1659            enable_payloads,
1660            origin_detection_enabled,
1661            additional_tags,
1662            ..
1663        } = &mut self.context;
1664
1665        let resolve_telemetry_origin = || {
1666            (source_metrics.origin_telemetry_enabled() && *origin_detection_enabled)
1667                .then(|| {
1668                    process_origin
1669                        .and_then(ProcessOrigin::container_entity_id)
1670                        .map(ToString::to_string)
1671                })
1672                .flatten()
1673        };
1674
1675        let parsed = match codec.decode_packet(frame) {
1676            Ok(parsed) => parsed,
1677            Err(e) => {
1678                // Try and determine what the message type was, if possible, to increment the correct error counter.
1679                match parse_message_type(frame) {
1680                    MessageType::MetricSample => {
1681                        source_metrics.record_metric_parse_failed(resolve_telemetry_origin().as_deref())
1682                    }
1683                    MessageType::Event => source_metrics.event_decode_failed().increment(1),
1684                    MessageType::ServiceCheck => source_metrics.service_check_decode_failed().increment(1),
1685                }
1686
1687                return Err(e);
1688            }
1689        };
1690
1691        let event = match parsed {
1692            ParsedPacket::Metric(metric_packet) => {
1693                if metric_packet.num_points == 0 {
1694                    return Ok(None);
1695                }
1696                let events_len = metric_packet.num_points;
1697                if !enable_payloads.allow_metric(&metric_packet) {
1698                    trace!(
1699                        metric.name = metric_packet.metric_name,
1700                        "Skipping metric due to filter configuration."
1701                    );
1702                    return Ok(None);
1703                }
1704
1705                match handle_metric_packet(
1706                    metric_packet,
1707                    context_resolvers,
1708                    process_origin,
1709                    additional_tags,
1710                    default_hostname,
1711                ) {
1712                    Some(metric) => {
1713                        source_metrics.record_metrics_received(events_len, resolve_telemetry_origin().as_deref());
1714                        Event::Metric(metric)
1715                    }
1716                    None => {
1717                        // We can only fail to get a metric back if we failed to resolve the context.
1718                        source_metrics.failed_context_resolve_total().increment(1);
1719                        return Ok(None);
1720                    }
1721                }
1722            }
1723            ParsedPacket::Event(event) => {
1724                if !enable_payloads.allow_event(&event) {
1725                    trace!("Skipping event {} due to filter configuration.", event.title);
1726                    return Ok(None);
1727                }
1728                match handle_event_packet(event, context_resolvers, process_origin, additional_tags) {
1729                    Some(event) => {
1730                        source_metrics.events_received().increment(1);
1731                        Event::EventD(event)
1732                    }
1733                    None => {
1734                        source_metrics.failed_context_resolve_total().increment(1);
1735                        return Ok(None);
1736                    }
1737                }
1738            }
1739            ParsedPacket::ServiceCheck(service_check) => {
1740                if !enable_payloads.allow_service_check(&service_check) {
1741                    trace!(
1742                        "Skipping service check {} due to filter configuration.",
1743                        service_check.name
1744                    );
1745                    return Ok(None);
1746                }
1747                match handle_service_check_packet(service_check, context_resolvers, process_origin, additional_tags) {
1748                    Some(service_check) => {
1749                        source_metrics.service_checks_received().increment(1);
1750                        Event::ServiceCheck(service_check)
1751                    }
1752                    None => {
1753                        source_metrics.failed_context_resolve_total().increment(1);
1754                        return Ok(None);
1755                    }
1756                }
1757            }
1758        };
1759
1760        Ok(Some(event))
1761    }
1762}
1763
1764async fn drive_datagram_decoder(
1765    mut datagram_receiver: WorkQueueReceiver<QueuedDatagram>, source_context: SourceContext,
1766    decoder_context: DecoderContext,
1767) {
1768    let mut decoder = DogStatsDDecoder::new(source_context, decoder_context);
1769    let mut buffer_flush = interval(Duration::from_millis(100));
1770    buffer_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
1771
1772    loop {
1773        select! {
1774            maybe_datagram = datagram_receiver.recv() => {
1775                let Some(QueuedDatagram { result, socket_context }) = maybe_datagram else {
1776                    break;
1777                };
1778                let DatagramSocketContext {
1779                    listen_addr,
1780                    eol_required,
1781                    metrics,
1782                    packet_forwarder,
1783                } = socket_context.as_ref();
1784
1785                let received = match result {
1786                    Ok(received) => received,
1787                    Err(error) => {
1788                        metrics.packet_receive_failure().increment(1);
1789                        warn!(%listen_addr, %error, "I/O error while reading datagram. Continuing listener.");
1790                        continue;
1791                    }
1792                };
1793
1794                let mut buffer_decode_context = BufferDecodeContext::new(
1795                    listen_addr,
1796                    *eol_required,
1797                    metrics,
1798                    packet_forwarder.as_ref(),
1799                    BufferDecodeMode::Connectionless,
1800                );
1801                let outcome = decoder.decode_buffer(&mut buffer_decode_context, received).await;
1802                debug_assert_eq!(outcome, DecodeOutcome::Continue);
1803            }
1804            _ = buffer_flush.tick() => {
1805                decoder.flush_events().await;
1806            }
1807        }
1808    }
1809
1810    decoder.flush_events().await;
1811    debug!("Datagram decoder drained its queue.");
1812}
1813
1814async fn drive_stream(stream: Stream, source_context: SourceContext, handler_context: HandlerContext) {
1815    if stream.is_connectionless() {
1816        let memory_limiter = source_context.topology_context().memory_limiter().clone();
1817        let socket_context = handler_context
1818            .datagram_context
1819            .clone()
1820            .expect("connectionless stream must have a datagram context");
1821        receive_connectionless_stream(
1822            stream,
1823            handler_context.io_buffer_pool,
1824            memory_limiter,
1825            handler_context.decoder_context.origin_detection_enabled,
1826            handler_context.decoder_context.traffic_capture.clone(),
1827            handler_context.capture_entity_resolver,
1828            handler_context.datagram_sender,
1829            socket_context,
1830        )
1831        .await;
1832        return;
1833    }
1834
1835    drive_connected_stream(stream, source_context, handler_context).await;
1836}
1837
1838async fn drive_connected_stream(stream: Stream, source_context: SourceContext, handler_context: HandlerContext) {
1839    let listen_addr = handler_context.listen_addr.clone();
1840    let metrics = handler_context.metrics.clone();
1841    let memory_limiter = source_context.topology_context().memory_limiter().clone();
1842    let mut stream_reader = BufferedStreamReader::new(
1843        stream,
1844        handler_context.io_buffer_pool.clone(),
1845        memory_limiter,
1846        handler_context.decoder_context.origin_detection_enabled,
1847        handler_context.decoder_context.traffic_capture.clone(),
1848        handler_context.capture_entity_resolver.clone(),
1849    );
1850    let receiver = stream_reader.take_receiver();
1851
1852    debug!(%listen_addr, "Stream handler started.");
1853
1854    metrics.connections_active().increment(1);
1855    drive_decoder(receiver, source_context, handler_context).await;
1856    metrics.connections_active().decrement(1);
1857
1858    debug!(%listen_addr, "Stream handler stopped.");
1859}
1860
1861async fn drive_decoder(
1862    mut stream_receiver: mpsc::Receiver<io::Result<ReceivedBuffer>>, source_context: SourceContext,
1863    handler_context: HandlerContext,
1864) {
1865    let HandlerContext {
1866        listen_addr,
1867        eol_required,
1868        metrics,
1869        decoder_context,
1870        packet_forwarder,
1871        ..
1872    } = handler_context;
1873    let mut decoder = DogStatsDDecoder::new(source_context, decoder_context);
1874    // Set a buffer flush interval of 100ms, which will ensure we always flush buffered events at least every 100ms if
1875    // we're otherwise idle and not receiving packets from the client.
1876    let mut buffer_flush = interval(Duration::from_millis(100));
1877    buffer_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
1878    let mut buffer_decode_context = BufferDecodeContext::new(
1879        &listen_addr,
1880        eol_required,
1881        &metrics,
1882        packet_forwarder.as_ref(),
1883        BufferDecodeMode::Connected,
1884    );
1885
1886    'read: loop {
1887        select! {
1888            // We read from the stream.
1889            maybe_read_result = stream_receiver.recv() => match maybe_read_result {
1890                Some(Ok(received)) => {
1891                    let outcome = decoder.decode_buffer(&mut buffer_decode_context, received).await;
1892                    if outcome == DecodeOutcome::Stop {
1893                        break 'read;
1894                    }
1895                },
1896                Some(Err(e)) => {
1897                    metrics.packet_receive_failure().increment(1);
1898                    warn!(%listen_addr, error = %e, "I/O error while decoding. Stopping stream.");
1899                    break 'read;
1900                },
1901                None => {
1902                    warn!(%listen_addr, "Buffered stream reader stopped unexpectedly. Stopping stream.");
1903                    break 'read;
1904                }
1905            },
1906
1907            _ = buffer_flush.tick() => {
1908                decoder.flush_events().await;
1909            },
1910
1911        }
1912    }
1913
1914    decoder.flush_events().await;
1915}
1916
1917fn should_drop_oversized_named_pipe_frame(listen_addr: &ListenAddress, buffer: &BytesBuffer) -> bool {
1918    matches!(listen_addr, ListenAddress::NamedPipe { .. })
1919        && buffer.remaining_mut() == 0
1920        && memchr::memchr(b'\n', buffer.chunk()).is_none()
1921}
1922
1923fn should_warn_stream_log_too_big(listen_addr: &ListenAddress, error: &FramingError, stream_log_too_big: bool) -> bool {
1924    stream_log_too_big
1925        && matches!(listen_addr, ListenAddress::Unix(_))
1926        && matches!(error, FramingError::InvalidFrame { .. })
1927}
1928
1929fn log_parse_failure(
1930    disable_verbose_logs: bool, listen_addr: &ListenAddress, peer_addr: &ConnectionAddress, frame: &[u8],
1931    error: &ParseError,
1932) {
1933    let frame = String::from_utf8_lossy(frame);
1934    if disable_verbose_logs {
1935        debug!(%listen_addr, %peer_addr, %frame, %error, "Failed to parse frame.");
1936    } else {
1937        warn!(%listen_addr, %peer_addr, %frame, %error, "Failed to parse frame.");
1938    }
1939}
1940
1941fn capture_named_pipe_frame(traffic_capture: &TrafficCapture, frame: &[u8]) {
1942    if !frame.is_empty() && traffic_capture.is_ongoing() {
1943        let _ = traffic_capture.enqueue(build_capture_record(None, None, frame));
1944    }
1945}
1946
1947fn capture_unixgram_traffic(
1948    listen_addr: &ListenAddress, traffic_capture: &TrafficCapture, peer_addr: &ConnectionAddress,
1949    process_origin: Option<&ProcessOrigin>, payload: &[u8],
1950) {
1951    if payload.is_empty() || !matches!(listen_addr, ListenAddress::Unixgram(_)) || !traffic_capture.is_ongoing() {
1952        return;
1953    }
1954
1955    let _ = traffic_capture.enqueue(build_capture_record(
1956        process_id_from_peer_addr(peer_addr),
1957        process_origin,
1958        payload,
1959    ));
1960}
1961
1962fn build_capture_record(
1963    process_id: Option<i32>, process_origin: Option<&ProcessOrigin>, payload: &[u8],
1964) -> CaptureRecord {
1965    CaptureRecord {
1966        timestamp_ns: capture_timestamp_ns(),
1967        payload: payload.to_vec(),
1968        pid: process_id,
1969        container_id: process_origin
1970            .and_then(ProcessOrigin::container_entity_id)
1971            .map(ToString::to_string),
1972    }
1973}
1974
1975fn process_id_from_peer_addr(peer_addr: &ConnectionAddress) -> Option<i32> {
1976    match peer_addr {
1977        ConnectionAddress::ProcessLike(ProcessIdentity::Credentials(creds)) => Some(creds.pid),
1978        _ => None,
1979    }
1980}
1981
1982fn resolve_process_origin(
1983    capture_entity_resolver: Option<&(dyn CaptureEntityResolver + Send + Sync)>, peer_addr: &ConnectionAddress,
1984) -> Option<ProcessOrigin> {
1985    let creds = peer_addr.process_credentials()?;
1986    if creds.gid == REPLAY_CREDENTIALS_GID {
1987        return Some(ProcessOrigin::Replay(creds.uid));
1988    }
1989
1990    let process_id = u32::try_from(creds.pid).ok()?;
1991    Some(match capture_entity_resolver {
1992        Some(resolver) => ProcessOrigin::Pinned(resolver.resolve_container_entity_for_live_pid(process_id)),
1993        None => ProcessOrigin::Unpinned(process_id),
1994    })
1995}
1996
1997fn resolve_process_origin_if_needed(
1998    origin_detection_enabled: bool, traffic_capture: &TrafficCapture,
1999    capture_entity_resolver: Option<&(dyn CaptureEntityResolver + Send + Sync)>, peer_addr: &ConnectionAddress,
2000) -> Option<ProcessOrigin> {
2001    if !origin_detection_enabled && !traffic_capture.is_ongoing() {
2002        return None;
2003    }
2004
2005    resolve_process_origin(capture_entity_resolver, peer_addr)
2006}
2007
2008fn received_payload(buffer: &BytesBuffer, bytes_read: usize) -> &[u8] {
2009    let chunk = buffer.chunk();
2010    let start = chunk.len().saturating_sub(bytes_read);
2011    &chunk[start..]
2012}
2013
2014fn capture_timestamp_ns() -> i64 {
2015    SystemTime::now()
2016        .duration_since(UNIX_EPOCH)
2017        .map(|duration| duration.as_nanos().min(i64::MAX as u128) as i64)
2018        .unwrap_or_default()
2019}
2020
2021fn handle_metric_packet(
2022    packet: MetricPacket, context_resolvers: &mut ContextResolvers, process_origin: Option<&ProcessOrigin>,
2023    additional_tags: &[String], default_hostname: &MetaString,
2024) -> Option<Metric> {
2025    let (well_known_tags, mut tags) = WellKnownTags::split_raw_tags(&packet.tags);
2026    tags.extend(additional_tags.iter().map(String::as_str));
2027
2028    let origin = origin_from_packet(
2029        packet.local_data,
2030        packet.external_data,
2031        packet.cardinality,
2032        &well_known_tags,
2033    );
2034    let origin_tags = context_resolvers.resolve_origin_tags(origin, process_origin);
2035
2036    // Choose the right context resolver based on whether or not this metric is pre-aggregated.
2037    let context_resolver = if packet.timestamp.is_some() {
2038        context_resolvers.no_agg()
2039    } else {
2040        context_resolvers.primary()
2041    };
2042
2043    let hostname = well_known_tags.hostname.unwrap_or(default_hostname);
2044
2045    // Try to resolve the context for this metric. This fails if the interner is out of capacity.
2046    let context =
2047        context_resolver.resolve_with_host_and_origin_tags(packet.metric_name, hostname, &tags, origin_tags)?;
2048
2049    let metric_origin = well_known_tags
2050        .jmx_check_name
2051        .map(MetricOrigin::jmx_check)
2052        .unwrap_or_else(MetricOrigin::dogstatsd);
2053    let metadata = MetricMetadata::default()
2054        .with_origin(metric_origin)
2055        .with_unit(packet.unit.map_or_else(MetaString::empty, MetaString::from_static));
2056
2057    Some(Metric::from_parts(context, packet.values, metadata))
2058}
2059
2060/// Resolves the tags and origin tags of an event or service check, along with the value of any `host:` tag.
2061///
2062/// Returns `None` if the tags can't be resolved.
2063fn resolve_tags_and_origin_tags<'a>(
2064    context_resolvers: &mut ContextResolvers, raw_tags: &'a RawTags<'_>, local_data: Option<&str>,
2065    external_data: Option<&str>, cardinality: Option<OriginTagCardinality>, process_origin: Option<&ProcessOrigin>,
2066    additional_tags: &'a [String],
2067) -> Option<(SharedTagSet, SharedTagSet, Option<&'a str>)> {
2068    let (well_known_tags, mut tags) = WellKnownTags::split_raw_tags(raw_tags);
2069    tags.extend(additional_tags.iter().map(String::as_str));
2070
2071    let origin = origin_from_packet(local_data, external_data, cardinality, &well_known_tags);
2072    let origin_tags = context_resolvers.resolve_origin_tags(origin, process_origin);
2073
2074    let tags = context_resolvers.tags().create_tag_set(&tags)?;
2075    Some((tags, origin_tags, well_known_tags.hostname))
2076}
2077
2078fn handle_event_packet(
2079    packet: EventPacket, context_resolvers: &mut ContextResolvers, process_origin: Option<&ProcessOrigin>,
2080    additional_tags: &[String],
2081) -> Option<EventD> {
2082    let (tags, origin_tags, tagged_hostname) = resolve_tags_and_origin_tags(
2083        context_resolvers,
2084        &packet.tags,
2085        packet.local_data,
2086        packet.external_data,
2087        packet.cardinality,
2088        process_origin,
2089        additional_tags,
2090    )?;
2091
2092    // When no d: field is present, backfill the current time—matching the stock Datadog Agent's
2093    // behavior in pkg/aggregator/aggregator.go (addEvent), which sets e.Ts = time.Now().Unix()
2094    // for any event with Ts == 0.
2095    let timestamp = packet
2096        .timestamp
2097        .or_else(|| SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()));
2098
2099    let eventd = EventD::new(packet.title, packet.text)
2100        .with_timestamp(timestamp)
2101        // An `h:` field takes precedence; otherwise, fall back to a `host:` tag, matching the reference DogStatsD
2102        // server. An empty `host:` tag gives an explicitly empty hostname, which host enrichment leaves alone, as
2103        // the reference DogStatsD server does.
2104        .with_hostname(packet.hostname.or(tagged_hostname).map(|s| s.into()))
2105        .with_aggregation_key(packet.aggregation_key.map(|s| s.into()))
2106        .with_alert_type(packet.alert_type)
2107        .with_priority(packet.priority)
2108        // When no source type is provided, default to "api"—the same default the stock Datadog
2109        // Agent applies when serializing DogStatsD events to the intake JSON format. The agent
2110        // groups events by source type name and uses "api" as the key for events without an
2111        // explicit `s:` field. See: pkg/serializer/internal/metrics/events.go (writeItem).
2112        .with_source_type_name(Some(
2113            packet
2114                .source_type_name
2115                .map(|s| s.into())
2116                .unwrap_or_else(|| "api".into()),
2117        ))
2118        .with_tags(tags)
2119        .with_origin_tags(origin_tags);
2120
2121    Some(eventd)
2122}
2123
2124fn handle_service_check_packet(
2125    packet: ServiceCheckPacket, context_resolvers: &mut ContextResolvers, process_origin: Option<&ProcessOrigin>,
2126    additional_tags: &[String],
2127) -> Option<ServiceCheck> {
2128    let (tags, origin_tags, tagged_hostname) = resolve_tags_and_origin_tags(
2129        context_resolvers,
2130        &packet.tags,
2131        packet.local_data,
2132        packet.external_data,
2133        packet.cardinality,
2134        process_origin,
2135        additional_tags,
2136    )?;
2137
2138    // When no d: field is present, backfill the current time—matching the stock Datadog Agent's
2139    // behavior, which sets the timestamp to time.Now().Unix() for any service check with a zero
2140    // timestamp.
2141    let timestamp = packet
2142        .timestamp
2143        .or_else(|| SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()));
2144
2145    let service_check = ServiceCheck::new(packet.name, packet.status)
2146        .with_timestamp(timestamp)
2147        // An `h:` field takes precedence; otherwise, fall back to a `host:` tag, matching the reference DogStatsD
2148        // server. An empty `host:` tag gives an explicitly empty hostname, which host enrichment leaves alone, as
2149        // the reference DogStatsD server does.
2150        .with_hostname(packet.hostname.or(tagged_hostname).map(|s| s.into()))
2151        .with_tags(tags)
2152        .with_origin_tags(origin_tags)
2153        .with_message(packet.message.map(|s| s.into()));
2154
2155    Some(service_check)
2156}
2157
2158async fn dispatch_events(mut event_buffer: EventsBuffer, source_context: &SourceContext) {
2159    debug!(events_len = event_buffer.len(), "Forwarding events.");
2160
2161    // TODO: This is maybe a little dicey because if we fail to dispatch the events, we may not have iterated over all of
2162    // them, so there might still be eventd events when get to the service checks point, and eventd events and/or service
2163    // check events when we get to the metrics point, and so on.
2164    //
2165    // There's probably something to be said for erroring out fully if this happens, since we should only fail to
2166    // dispatch if the downstream component fails entirely... and unless we have a way to restart the component, then
2167    // we're going to continue to fail to dispatch any more events until the process is restarted anyways.
2168
2169    // Dispatch any eventd events, if present.
2170    if event_buffer.has_event_type(EventType::EventD) {
2171        let eventd_events = event_buffer.take_events::<EventD>().map(Event::EventD);
2172        let events_output = source_context.dispatcher().buffered_named("events");
2173
2174        // The `events` output is always wired in the DSD topology, so a missing output is an invariant violation that
2175        // crashes this component.
2176        if events_output.is_err() {
2177            saluki_antithesis::unreachable!("dsd 'events' output missing at dispatch");
2178        }
2179
2180        if let Err(e) = events_output
2181            .expect("events output should always exist")
2182            .send_all(eventd_events)
2183            .await
2184        {
2185            error!(error = %e, "Failed to dispatch eventd events.");
2186
2187            saluki_antithesis::unreachable!("dsd dispatch failed mid-buffer", { "stream": "events" });
2188        }
2189    }
2190
2191    // Dispatch any service check events, if present.
2192    if event_buffer.has_event_type(EventType::ServiceCheck) {
2193        let service_check_events = event_buffer.take_events::<ServiceCheck>().map(Event::ServiceCheck);
2194        let service_checks_output = source_context.dispatcher().buffered_named("service_checks");
2195
2196        if service_checks_output.is_err() {
2197            saluki_antithesis::unreachable!("dsd 'service_checks' output missing at dispatch");
2198        }
2199
2200        if let Err(e) = service_checks_output
2201            .expect("service checks output should always exist")
2202            .send_all(service_check_events)
2203            .await
2204        {
2205            error!(error = %e, "Failed to dispatch service check events.");
2206
2207            saluki_antithesis::unreachable!("dsd dispatch failed mid-buffer", { "stream": "service_checks" });
2208        }
2209    }
2210
2211    // Finally, if there are events left, they'll be metrics, so dispatch them.
2212    if !event_buffer.is_empty() {
2213        if let Err(e) = source_context
2214            .dispatcher()
2215            .dispatch_named("metrics", event_buffer)
2216            .await
2217        {
2218            error!(error = %e, "Failed to dispatch metric events.");
2219
2220            saluki_antithesis::unreachable!("dsd dispatch failed mid-buffer", { "stream": "metrics" });
2221        }
2222    }
2223}
2224
2225const fn get_adjusted_buffer_size(buffer_size: usize) -> usize {
2226    // This is a little goofy, but hear me out:
2227    //
2228    // In the Datadog Agent, the way the UDS listener works is that if it's in stream mode, it will do a standalone
2229    // socket read to get _just_ the length delimiter, which is 4 bytes. After that, it will do a read to get the packet
2230    // data itself, up to the limit of `dogstatsd_buffer_size`. This means that a _full_ UDS stream packet can be up to
2231    // `dogstatsd_buffer_size + 4` bytes.
2232    //
2233    // This isn't a problem in the Agent due to how it does the reads, but it's a problem for us because we want to be
2234    // able to get an entire frame in a single buffer for the purpose of decoding the frame. Rather than rewriting our
2235    // read loop such that we have to change the logic depending on UDP/UDS datagram vs UDS stream, we simply increase
2236    // the buffer size by 4 bytes to account for the length delimiter.
2237    //
2238    // We do it this way so that we don't have to change the buffer size in the configuration, since if you just ported
2239    // over a Datadog Agent configuration, the value would be too small, and vise versa.
2240    buffer_size + 4
2241}
2242
2243#[cfg(test)]
2244mod tests;