Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 29 additions & 12 deletions lib/saluki-components/src/sources/dogstatsd/framer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ impl DsdFramer {
}
}

/// Something found at the front of the buffer.
/// A DogStatsD message or an outer frame payload borrowed from the input buffer.
#[derive(Debug, Eq, PartialEq)]
pub enum Frame<'a> {
/// A DogStatsD message.
/// A DogStatsD wire line, including its newline if present.
///
/// The delimiter remains part of the wire line so callers can account for bytes received.
Message(&'a [u8]),

/// The payload of an outer frame, yielded before the messages it holds when outer frame capture is on.
Expand All @@ -63,9 +65,8 @@ pub enum Frame<'a> {
///
/// Frames borrow the buffer, not `Frames`, so `Frames` can be used freely while they're held.
///
/// Dropping `Frames` partway through an outer frame skips that frame's remaining messages, since the buffer has already
/// been advanced past them. After an error, `Frames` yields nothing more. A new drain starts afresh, since the framer
/// keeps no state.
/// Dropping `Frames` partway through an outer frame skips its remaining messages. The cursor already took the payload.
/// An error ends the current drain. The framer keeps no state between drains.
pub struct Frames<'a> {
cursor: ReadCursor<'a>,
framer: DsdFramer,
Expand All @@ -90,19 +91,19 @@ impl<'a> Frames<'a> {
Some(Err(error))
}

fn next_line(&mut self) -> Option<Result<&'a [u8], FramingError>> {
fn next_line(&mut self) -> Option<Result<Frame<'a>, FramingError>> {
let unread = self.cursor.unread();
if unread.is_empty() {
return None;
}

let len = match memchr::memchr(b'\n', unread) {
Some(idx) => return Some(Ok(&self.cursor.take(idx + 1)[..idx])),
Some(idx) => return Some(Ok(Frame::Message(self.cursor.take(idx + 1)))),
None if !self.is_eof => return None,
None if self.framer.eol_required => return self.fail(missing_newline(unread.len())),
None => unread.len(),
};
Some(Ok(self.cursor.take(len)))
Some(Ok(Frame::Message(self.cursor.take(len))))
}

fn next_nested(&mut self) -> Option<Result<Frame<'a>, FramingError>> {
Expand Down Expand Up @@ -130,7 +131,7 @@ impl<'a> Frames<'a> {
};

let (message, rest) = match memchr::memchr(b'\n', payload) {
Some(idx) => (&payload[..idx], &payload[idx + 1..]),
Some(idx) => payload.split_at(idx + 1),
None if self.framer.eol_required => return self.fail(missing_newline(payload.len())),
None => (payload, &payload[payload.len()..]),
};
Expand All @@ -157,7 +158,7 @@ impl<'a> Iterator for Frames<'a> {
return None;
}
match self.framer.mode {
Mode::NonStream => self.next_line().map(|result| result.map(Frame::Message)),
Mode::NonStream => self.next_line(),
Mode::Stream => self.next_nested(),
}
}
Expand Down Expand Up @@ -292,7 +293,9 @@ mod tests {
got.push(Got::Completed(completed));
}
match frame {
Some(Ok(Frame::Message(message))) => got.push(Got::Message(message.to_vec())),
Some(Ok(Frame::Message(message))) => {
got.push(Got::Message(message.strip_suffix(b"\n").unwrap_or(message).to_vec()))
}
Some(Ok(Frame::Outer(outer))) => got.push(Got::Outer(outer.to_vec())),
Some(Err(e)) => {
got.push(Got::Error(e));
Expand Down Expand Up @@ -322,6 +325,16 @@ mod tests {
Got::Error(super::missing_newline(frame_len))
}

#[test]
fn lines_preserve_delimiters_without_counting_stream_prefixes() {
for (framer, mut buf) in [(direct(false), bytes(b"a\nbc")), (nested(false), stream(&[b"a\nbc"]))] {
let mut frames = framer.frames(buf.cursor(), true, false);
assert_eq!(frames.next(), Some(Ok(Frame::Message(b"a\n"))));
assert_eq!(frames.next(), Some(Ok(Frame::Message(b"bc"))));
assert_eq!(frames.next(), None);
}
}

#[test]
fn stream_single_outer_frame_multiple_messages() {
let mut buf = stream(&[b"frame1\nframe2\nframe3\n"]);
Expand Down Expand Up @@ -450,7 +463,11 @@ mod tests {
assert_eq!(frames.next(), Some(Ok(Frame::Outer(b"aa\nbb\n"))));
frames.next()
};
assert_eq!(held, Some(Ok(Frame::Message(b"aa"))), "frames outlive `Frames`");
assert_eq!(
held,
Some(Ok(Frame::Message(b"aa\n"))),
"frames retain the exact wire line and outlive `Frames`"
);
assert_eq!(buf.chunk()[..4], [0, 0, 0, 0], "front is at the next outer frame");

assert_eq!(
Expand Down
107 changes: 97 additions & 10 deletions lib/saluki-components/src/sources/dogstatsd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use std::{
future::Future,
io,
mem::size_of,
num::NonZeroUsize,
path::PathBuf,
pin::Pin,
Expand All @@ -24,12 +25,12 @@ use saluki_common::sync::{
work_queue::{self, WorkQueueReceiver, WorkQueueSender},
};
use saluki_core::{
accounting::{MemoryBounds, MemoryBoundsBuilder, MemoryLimiter, UsageExpr},
accounting::{ByteBudget, ByteBudgetBatch, MemoryBounds, MemoryBoundsBuilder, MemoryLimiter, UsageExpr},
components::{sources::*, BuildContext},
data_model::{
event::{
eventd::EventD,
metric::{Metric, MetricMetadata, MetricOrigin},
metric::{DogStatsDAdmission, Metric, MetricMetadata, MetricOrigin},
service_check::ServiceCheck,
Event, EventType,
},
Expand Down Expand Up @@ -983,6 +984,8 @@ struct DogStatsDDecoder {
source_context: SourceContext,
context: DecoderContext,
event_buffer: EventBufferManager<DEFAULT_EVENTS_BUFFER_CAPACITY>,
admission_budget: Option<ByteBudgetBatch>,
configured_tag_bytes: usize,
}

#[derive(Clone, Copy)]
Expand Down Expand Up @@ -1062,7 +1065,16 @@ impl Source for DogStatsD {
// receiver to the next decoder puts it behind the previous decoder's decode work on the same runtime thread.
let (datagram_sender, datagram_receivers) =
work_queue::bounded(self.decoder_worker_count, self.io_buffer_queue_capacity);
let decoder_context = self.decoder_context;
let mut decoder_context = self.decoder_context;
let _reclaimer = context.topology_context().memory_limiter().byte_budget().map(|budget| {
DogStatsDAdmission::register_counters();
let primary = decoder_context.context_resolvers.primary().clone();
let no_agg = decoder_context.context_resolvers.no_agg().clone();
budget.register_reclaimer(move || {
primary.evict_idle_for_budget();
no_agg.evict_idle_for_budget();
})
});

// Decoders must drain their queue to completion, so they deliberately ignore the shutdown signal and stop only
// once their queue closes -- which happens when every listener and stream handler has dropped its datagram
Expand Down Expand Up @@ -1513,10 +1525,21 @@ async fn acquire_io_buffer(io_buffer_pool: &ElasticObjectPool<BytesBuffer>) -> B
impl DogStatsDDecoder {
fn new(source_context: SourceContext, context: DecoderContext) -> Self {
let event_buffer = source_context.dispatcher().event_buffer_manager();
let admission_budget = source_context
.topology_context()
.memory_limiter()
.byte_budget()
.map(ByteBudget::batch);
Comment thread
blt marked this conversation as resolved.
Resolved
let configured_tag_bytes = context
.additional_tags
.iter()
.fold(0usize, |bytes, tag| bytes.saturating_add(tag.len().saturating_add(32)));
Self {
source_context,
context,
event_buffer,
admission_budget,
configured_tag_bytes,
}
}

Expand Down Expand Up @@ -1600,12 +1623,15 @@ impl DogStatsDDecoder {
payload,
));
}
Some(Ok(Frame::Message(frame))) => {
Some(Ok(Frame::Message(line))) => {
if matches!(listen_addr, ListenAddress::NamedPipe { .. }) {
capture_named_pipe_frame(&self.context.traffic_capture, frame);
capture_named_pipe_frame(
&self.context.traffic_capture,
line.strip_suffix(b"\n").unwrap_or(line),
);
metrics.packet_receive_success().increment(1);
}
self.decode_frame(frame, listen_addr, peer_addr, process_origin, metrics, packet_forwarder)
self.decode_frame(line, listen_addr, peer_addr, process_origin, metrics, packet_forwarder)
.await;
}
None => {
Expand Down Expand Up @@ -1639,15 +1665,16 @@ impl DogStatsDDecoder {
}

async fn decode_frame(
&mut self, frame: &[u8], listen_addr: &ListenAddress, peer_addr: &ConnectionAddress,
&mut self, line: &[u8], listen_addr: &ListenAddress, peer_addr: &ConnectionAddress,
process_origin: Option<&ProcessOrigin>, metrics: &Metrics, packet_forwarder: Option<&PacketForwarder>,
) {
let frame = line.strip_suffix(b"\n").unwrap_or(line);
trace!(%listen_addr, %peer_addr, frame = %frame.escape_ascii(), "Decoded frame.");
if let Some(forwarder) = packet_forwarder {
forwarder.forward(frame).await;
}

match self.handle_frame(frame, metrics, process_origin) {
match self.handle_frame(line, metrics, process_origin) {
Ok(Some(event)) => {
if let Some(event_buffer) = self.event_buffer.try_push(event) {
debug!(%listen_addr, %peer_addr, "Event buffer is full. Forwarding events.");
Expand All @@ -1662,13 +1689,16 @@ impl DogStatsDDecoder {
}

async fn flush_events(&mut self) {
if let Some(batch) = &mut self.admission_budget {
batch.release();
}
if let Some(event_buffer) = self.event_buffer.consume() {
dispatch_events(event_buffer, &self.source_context).await;
}
}

fn handle_frame(
&mut self, frame: &[u8], source_metrics: &Metrics, process_origin: Option<&ProcessOrigin>,
&mut self, line: &[u8], source_metrics: &Metrics, process_origin: Option<&ProcessOrigin>,
) -> Result<Option<Event>, ParseError> {
let DecoderContext {
codec,
Expand All @@ -1679,6 +1709,16 @@ impl DogStatsDDecoder {
additional_tags,
..
} = &mut self.context;
let budget = &mut self.admission_budget;
let frame = line.strip_suffix(b"\n").unwrap_or(line);
let wire_bytes = line.len();
if let Some(budget) = budget {
let bytes = estimate_frame_bytes(frame, wire_bytes, self.configured_tag_bytes);
if !budget.try_spend(bytes) {
DogStatsDAdmission::record_refused(wire_bytes);
Comment thread
blt marked this conversation as resolved.
Resolved
return Ok(None);
}
}

let resolve_telemetry_origin = || {
(source_metrics.origin_telemetry_enabled() && *origin_detection_enabled)
Expand Down Expand Up @@ -1727,7 +1767,10 @@ impl DogStatsDDecoder {
additional_tags,
default_hostname,
) {
Some(metric) => {
Some(mut metric) => {
if budget.is_some() {
metric.metadata_mut().track_dogstatsd_admission(wire_bytes);
Comment thread
blt marked this conversation as resolved.
Resolved
}
source_metrics.record_metrics_received(events_len, resolve_telemetry_origin().as_deref());
Event::Metric(metric)
}
Expand All @@ -1745,6 +1788,9 @@ impl DogStatsDDecoder {
}
match handle_event_packet(event, context_resolvers, process_origin, additional_tags) {
Some(event) => {
if budget.is_some() {
DogStatsDAdmission::record_admitted();
}
source_metrics.events_received().increment(1);
Event::EventD(event)
}
Expand All @@ -1764,6 +1810,9 @@ impl DogStatsDDecoder {
}
match handle_service_check_packet(service_check, context_resolvers, process_origin, additional_tags) {
Some(service_check) => {
if budget.is_some() {
DogStatsDAdmission::record_admitted();
}
source_metrics.service_checks_received().increment(1);
Event::ServiceCheck(service_check)
}
Expand Down Expand Up @@ -2173,6 +2222,44 @@ fn handle_service_check_packet(
Some(service_check)
}

fn estimate_frame_bytes(frame: &[u8], wire_bytes: usize, configured_tag_bytes: usize) -> usize {
// Count all commas because they can introduce tags even in permissive or malformed input.
wire_bytes
.saturating_mul(2)
.saturating_add(memchr::memchr_iter(b',', frame).count().saturating_mul(32))
.saturating_add(configured_tag_bytes)
.saturating_add(packed_sample_bytes(frame))
.saturating_add(288)
}

fn packed_sample_bytes(frame: &[u8]) -> usize {
if parse_message_type(frame) != MessageType::MetricSample {
return 0;
}
let Some(name_end) = memchr::memchr2(b':', b'|', frame).filter(|&i| frame[i] == b':') else {
return 0;
};
let value_and_type = &frame[name_end + 1..];
let Some(value_end) = memchr::memchr(b'|', value_and_type) else {
return 0;
};
if !matches!(
&value_and_type[value_end + 1..],
[b'c' | b'g' | b'h' | b'd', ..] | [b'm', b's', ..]
) {
return 0;
}
let separators = memchr::memchr_iter(b':', &value_and_type[..value_end]).count();
if separators == 0 {
Comment thread
blt marked this conversation as resolved.
Resolved
return 0;
}
// Scalar samples hold a timestamp and value. Histogram and timer samples hold a value and weight.
// Round up for collection growth and use the same allowance per sample for distribution sketches.
(separators + 1)
.next_power_of_two()
.saturating_mul(size_of::<[f64; 2]>())
}

async fn dispatch_events(mut event_buffer: EventsBuffer, source_context: &SourceContext) {
debug!(events_len = event_buffer.len(), "Forwarding events.");

Expand Down
26 changes: 25 additions & 1 deletion lib/saluki-components/src/sources/dogstatsd/tests/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ use tokio::time::timeout;

use super::*;
use crate::sources::dogstatsd::should_warn_stream_log_too_big;
use crate::sources::dogstatsd::{handle_metric_packet, BufferDecodeMode, DecodeOutcome, PacketForwarder};
use crate::sources::dogstatsd::{
estimate_frame_bytes, handle_metric_packet, BufferDecodeMode, DecodeOutcome, PacketForwarder,
};

fn packets_ok_key(listener_type: &str) -> Key {
source_counter(
Expand All @@ -28,6 +30,28 @@ fn origin_detection_errors_key(reason: &str) -> Key {
)
}

#[test]
fn packed_numeric_frames_reserve_for_sample_storage() {
for metric_type in [b"h".as_slice(), b"ms", b"d", b"c", b"g"] {
let samples = 4095 - metric_type.len();
let mut line = b"x:".to_vec();
line.extend(b"1:".repeat(samples - 1));
line.extend(b"1|");
line.extend(metric_type);
let wire_bytes = line.len() + 1;
assert!((8191..=8192).contains(&wire_bytes));
assert!(
estimate_frame_bytes(&line, wire_bytes, 0) >= samples * 16,
"packed metric type {metric_type:?} needs space for {samples} samples"
);
}

// Colons outside the value segment, or inside a set member, are not sample separators.
for line in [b"x:1|h|#k:v".as_slice(), b"x:1:2:3|s"] {
assert_eq!(estimate_frame_bytes(line, line.len(), 0), line.len() * 2 + 288);
}
}

#[tokio::test]
async fn connectionless_decoder_dispatches_full_and_flushed_buffers_and_forwards_frames() {
let recorder = TestRecorder::default();
Expand Down
Loading