diff --git a/Cargo.lock b/Cargo.lock index a526c9a89..4404e2199 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "ahash" version = "0.8.12" @@ -910,6 +916,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -970,14 +985,17 @@ dependencies = [ "clap", "common", "control_plane", + "flate2", "form_urlencoded", "futures", "http-body-util", "internal_metrics", "libc", + "otlp", "precompute", "prometheus_http", "prometheus_remote_write", + "prost", "query", "reqwest", "serde_json", @@ -988,6 +1006,7 @@ dependencies = [ "tower", "tracing", "tracing-subscriber", + "victoriametrics_remote_write", ] [[package]] @@ -1644,7 +1663,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1685,6 +1704,17 @@ dependencies = [ "rustc_version", ] +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -2533,6 +2563,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.3" @@ -2663,6 +2703,57 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opentelemetry" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "236e667b670a5cdf90c258f5a55794ec5ac5027e960c224bff8367a59e1e6426" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f8870d3024727e99212eb3bb1762ec16e255e3e6f58eeb3dc8db1aa226746d" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", + "tonic", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84dfad6042089c7fc1f6118b7040dc2eb4ab520abbf410b79dc481032af39570" +dependencies = [ + "async-trait", + "futures-channel", + "futures-executor", + "futures-util", + "glob", + "opentelemetry", + "thiserror 2.0.20", +] + +[[package]] +name = "otlp" +version = "0.1.0" +dependencies = [ + "flate2", + "opentelemetry-proto", + "prost", + "thiserror 1.0.69", +] + [[package]] name = "packedvec" version = "1.2.5" @@ -3013,7 +3104,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3261,7 +3352,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3439,6 +3530,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simdutf8" version = "0.1.5" @@ -3637,7 +3734,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3838,6 +3935,27 @@ dependencies = [ "tokio", ] +[[package]] +name = "tonic" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52" +dependencies = [ + "async-trait", + "base64", + "bytes", + "http", + "http-body", + "http-body-util", + "percent-encoding", + "pin-project", + "prost", + "tokio-stream", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "tower" version = "0.5.3" @@ -4055,6 +4173,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "victoriametrics_remote_write" +version = "0.1.0" +dependencies = [ + "prometheus_remote_write", + "prost", + "thiserror 1.0.69", + "zstd", +] + [[package]] name = "virtue" version = "0.0.18" @@ -4195,7 +4323,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4460,6 +4588,12 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index db849d999..a7c0e8fd2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,9 @@ [workspace] resolver = "2" members = [ + "crates/adapters/ingest/otlp", "crates/adapters/ingest/prometheus-remote-write", + "crates/adapters/ingest/victoriametrics-remote-write", "crates/adapters/query/prometheus-http", "crates/common", "crates/control-plane", @@ -45,11 +47,13 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus control_plane = { path = "crates/control-plane" } common = { path = "crates/common" } internal_metrics = { path = "crates/internal-metrics" } +otlp = { path = "crates/adapters/ingest/otlp" } precompute = { path = "crates/precompute" } prometheus_http = { path = "crates/adapters/query/prometheus-http" } prometheus_remote_write = { path = "crates/adapters/ingest/prometheus-remote-write" } query = { path = "crates/query" } storage = { path = "crates/storage" } +victoriametrics_remote_write = { path = "crates/adapters/ingest/victoriametrics-remote-write" } # asap_sketchlib#271's head, ahead of the Planner's pin (389530c): DDSketch # view merges in place, with width-specialized loops (a 1 h quantile over diff --git a/README.md b/README.md index 0c7caf824..3bcbde083 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,15 @@ cargo run -p control_plane -- \ cargo run -p data_plane -- --plan plan.json --prometheus-url http://localhost:9090 ``` +Besides Prometheus Remote Write, the data plane ingests VictoriaMetrics +Remote Write (the same protobuf, zstd-compressed) on `/api/v1/import` and +OTLP/HTTP metrics (protobuf, optionally gzip) on `/v1/metrics`, the routes +ASAPQuery serves them on. An OTLP data point becomes a sample of the series +named by its metric (`_sum` and `_count` for histograms and +summaries) and labeled by its scope's, resource's and own attributes. Both +routes answer as Remote Write does (400, 503, 500), and are not served in +forward mode, which delivers only Remote Write bodies to the raw store. + `--deployment-capabilities caps.json` replaces the default `DeploymentCapabilities`: every summary the Planner's executor builds, raw data kept by the data plane, and no query-time result kept across @@ -237,6 +246,8 @@ not stored) with a Prometheus `execution` error (422, | `crates/storage/` | package `storage`: raw samples and views in memory, the view cache, segments, persistence and the persist threads | | `crates/internal-metrics/` | package `internal_metrics`: the backend's measurements of itself, exported on `/metrics` | | `crates/adapters/ingest/prometheus-remote-write/` | package `prometheus_remote_write`: Remote Write v1 decoding and validation | +| `crates/adapters/ingest/victoriametrics-remote-write/` | package `victoriametrics_remote_write`: VictoriaMetrics Remote Write (the Remote Write protobuf, zstd-compressed), `POST /api/v1/import` | +| `crates/adapters/ingest/otlp/` | package `otlp`: OTLP/HTTP metrics decoding into samples, `POST /v1/metrics` | | `crates/adapters/query/prometheus-http/` | package `prometheus_http`: query parameters, response bodies and the fallback client of a Prometheus-compatible server | | `benchmarks/` | the backend alone: `micro/` benchmarks (examples of `data_plane`) and `scripts/` | | `eval/` | comparisons with other systems and the live demo; see [eval/README.md](eval/README.md) | diff --git a/crates/adapters/ingest/otlp/Cargo.toml b/crates/adapters/ingest/otlp/Cargo.toml new file mode 100644 index 000000000..8590127cd --- /dev/null +++ b/crates/adapters/ingest/otlp/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "otlp" +version.workspace = true +edition.workspace = true + +# OTLP (OpenTelemetry) metrics over HTTP: request decoding into data +# points. An adapter: no workspace dependency, so it never sees an engine +# or a store. +[dependencies] +# The OTLP protobuf messages (no gRPC server; the crate still builds +# tonic's codegen types and the OpenTelemetry SDK it depends on). +opentelemetry-proto = { version = "0.28", default-features = false, features = ["gen-tonic-messages", "metrics"] } +prost = "0.13" +flate2 = "1.0" +thiserror.workspace = true diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs new file mode 100644 index 000000000..08d8917ef --- /dev/null +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -0,0 +1,553 @@ +//! OTLP (OpenTelemetry protocol) metrics decoding: an +//! `ExportMetricsServiceRequest` body, as `POST /v1/metrics` receives it, +//! into one [`Point`] per sample, the way ASAPQuery's OTLP receiver reads it. +//! +//! Each data point becomes samples of Prometheus-style series: the metric's +//! name as `__name__`, plus the scope's, the resource's and the point's +//! attributes as labels (a later one replaces an earlier one of the same +//! name). Gauges and sums give one sample; histograms, exponential +//! histograms and summaries give `_sum` (when set) and +//! `_count`. Data points that carry a sketch payload attribute +//! (`kll.`, `cms.` or `countsketch.sketch_payload`) are skipped, as +//! ASAPQuery skips them. + +use std::collections::BTreeMap; +use std::io::Read; + +use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; +use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue}; +use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point, Gauge, Sum}; +use prost::Message; + +/// The OTLP protobuf messages, for senders and tests. +pub use opentelemetry_proto::tonic as proto; + +/// Request size limits; a request over any limit is rejected whole. +#[derive(Debug, Clone)] +pub struct Limits { + pub max_decompressed_bytes: usize, + pub max_points: usize, +} + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum OtlpError { + #[error("Gzip decode error: {0}")] + Gzip(String), + #[error("decompressed request exceeds {0} bytes")] + DecompressedTooLarge(usize), + #[error("Protobuf decode error: {0}")] + Protobuf(String), + #[error("request has more than {0} points")] + TooManyPoints(usize), +} + +/// One sample of a series. +#[derive(Debug, Clone, PartialEq)] +pub struct Point { + /// `__name__` and the attributes, sorted by name, each name once. + pub labels: Vec<(String, String)>, + pub timestamp_ms: i64, + pub value: f64, +} + +/// The points of an OTLP metrics request body, in request order. +/// `content_encoding` is the request's `Content-Encoding`: `gzip` bodies +/// are decompressed; any other encoding is read as is, as ASAPQuery does. +/// Errors: the body is not gzip (when it says so) or not an +/// `ExportMetricsServiceRequest`, or is over a limit. +pub fn decode( + body: &[u8], + content_encoding: Option<&str>, + limits: &Limits, +) -> Result, OtlpError> { + let gzip = content_encoding.is_some_and(|e| e.trim().eq_ignore_ascii_case("gzip")); + let decompressed; + let request = if gzip { + decompressed = gunzip(body, limits.max_decompressed_bytes)?; + &decompressed[..] + } else if body.len() > limits.max_decompressed_bytes { + return Err(OtlpError::DecompressedTooLarge( + limits.max_decompressed_bytes, + )); + } else { + body + }; + let request = ExportMetricsServiceRequest::decode(request) + .map_err(|e| OtlpError::Protobuf(e.to_string()))?; + points(&request, limits.max_points) +} + +/// `body` gunzipped, reading at most one byte past `max_bytes`. +fn gunzip(body: &[u8], max_bytes: usize) -> Result, OtlpError> { + let mut out = Vec::new(); + flate2::read::GzDecoder::new(body) + .take(max_bytes as u64 + 1) + .read_to_end(&mut out) + .map_err(|e| OtlpError::Gzip(e.to_string()))?; + if out.len() > max_bytes { + return Err(OtlpError::DecompressedTooLarge(max_bytes)); + } + Ok(out) +} + +/// The points of `request`, at most `max_points`. +fn points( + request: &ExportMetricsServiceRequest, + max_points: usize, +) -> Result, OtlpError> { + let mut points = Vec::new(); + for resource_metrics in &request.resource_metrics { + let resource = resource_metrics.resource.as_ref(); + for scope_metrics in &resource_metrics.scope_metrics { + // The scope's attributes, then the resource's over them. + let mut scope_labels = BTreeMap::new(); + if let Some(scope) = &scope_metrics.scope { + insert_attributes(&mut scope_labels, &scope.attributes); + } + if let Some(resource) = resource { + insert_attributes(&mut scope_labels, &resource.attributes); + } + for metric in &scope_metrics.metrics { + if metric.name.is_empty() { + continue; + } + // One data point's samples: a value per name suffix (none + // when `None`), labeled by the point's attributes over the + // scope's and resource's. + let mut push = |attributes: &[KeyValue], + nanos: u64, + values: &[(&str, Option)]| + -> Result<(), OtlpError> { + if has_sketch_payload(attributes) { + return Ok(()); + } + let mut labels = scope_labels.clone(); + insert_attributes(&mut labels, attributes); + for &(suffix, value) in values { + let Some(value) = value else { continue }; + if points.len() >= max_points { + return Err(OtlpError::TooManyPoints(max_points)); + } + let name = format!("{}{suffix}", metric.name); + let mut labels = labels.clone(); + labels.insert("__name__".to_string(), name); + points.push(Point { + labels: labels.into_iter().collect(), + timestamp_ms: (nanos / 1_000_000) as i64, + value, + }); + } + Ok(()) + }; + match &metric.data { + Some(Data::Gauge(Gauge { data_points })) + | Some(Data::Sum(Sum { data_points, .. })) => { + for p in data_points { + push( + &p.attributes, + p.time_unix_nano, + &[("", Some(number(&p.value)))], + )?; + } + } + Some(Data::Histogram(histogram)) => { + for p in &histogram.data_points { + let count = Some(p.count as f64); + push( + &p.attributes, + p.time_unix_nano, + &[("_sum", p.sum), ("_count", count)], + )?; + } + } + Some(Data::ExponentialHistogram(histogram)) => { + for p in &histogram.data_points { + let count = Some(p.count as f64); + push( + &p.attributes, + p.time_unix_nano, + &[("_sum", p.sum), ("_count", count)], + )?; + } + } + Some(Data::Summary(summary)) => { + for p in &summary.data_points { + let count = Some(p.count as f64); + push( + &p.attributes, + p.time_unix_nano, + &[("_sum", Some(p.sum)), ("_count", count)], + )?; + } + } + None => {} + } + } + } + } + Ok(points) +} + +/// Whether a data point carries a sketch in place of a value. +fn has_sketch_payload(attributes: &[KeyValue]) -> bool { + attributes.iter().any(|kv| { + matches!( + kv.key.as_str(), + "kll.sketch_payload" | "cms.sketch_payload" | "countsketch.sketch_payload" + ) && matches!( + kv.value.as_ref().and_then(|v| v.value.as_ref()), + Some(any_value::Value::BytesValue(_)) + ) + }) +} + +/// Inserts each attribute with a name into `labels`, its value as text. +fn insert_attributes(labels: &mut BTreeMap, attributes: &[KeyValue]) { + for kv in attributes { + if kv.key.is_empty() { + continue; + } + let value = match kv.value.as_ref().and_then(|v| v.value.as_ref()) { + Some(any_value::Value::StringValue(s)) => s.clone(), + Some(any_value::Value::IntValue(i)) => i.to_string(), + Some(any_value::Value::DoubleValue(d)) => d.to_string(), + Some(any_value::Value::BoolValue(b)) => b.to_string(), + Some(any_value::Value::BytesValue(bytes)) => format!("{bytes:?}"), + _ => String::new(), + }; + labels.insert(kv.key.clone(), value); + } +} + +/// A number data point's value; 0 when it has none. +fn number(value: &Option) -> f64 { + match value { + Some(number_data_point::Value::AsDouble(x)) => *x, + Some(number_data_point::Value::AsInt(x)) => *x as f64, + None => 0.0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope}; + + const LIMITS: Limits = Limits { + max_decompressed_bytes: 128 * 1024 * 1024, + max_points: 1_000_000, + }; + + fn encode(request: &ExportMetricsServiceRequest) -> Vec { + request.encode_to_vec() + } + use opentelemetry_proto::tonic::metrics::v1::{ + ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, HistogramDataPoint, + Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary, SummaryDataPoint, + }; + use opentelemetry_proto::tonic::resource::v1::Resource; + + fn attribute(key: &str, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { value: Some(value) }), + } + } + + fn text(key: &str, value: &str) -> KeyValue { + attribute(key, any_value::Value::StringValue(value.to_string())) + } + + fn number_point( + attributes: Vec, + nanos: u64, + value: number_data_point::Value, + ) -> NumberDataPoint { + NumberDataPoint { + attributes, + time_unix_nano: nanos, + value: Some(value), + ..Default::default() + } + } + + fn metric(name: &str, data: Data) -> Metric { + Metric { + name: name.to_string(), + data: Some(data), + ..Default::default() + } + } + + /// A request with one resource and one scope holding `metrics`. + fn request(metrics: Vec) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: Some(Resource { + attributes: vec![text("service.name", "api-gateway")], + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + scope: Some(InstrumentationScope { + name: "exporter".to_string(), + attributes: vec![text("scope", "s"), text("service.name", "scope's")], + ..Default::default() + }), + metrics, + ..Default::default() + }], + ..Default::default() + }], + } + } + + fn labels(pairs: &[(&str, &str)]) -> Vec<(String, String)> { + let mut labels: Vec<(String, String)> = pairs + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(); + labels.sort(); + labels + } + + const NANOS: u64 = 1_700_000_000_123_456_789; + const MS: i64 = 1_700_000_000_123; + + /// Gauges and sums give one point each, labeled by the metric name and + /// the scope's, resource's and point's attributes (the resource's over + /// the scope's, the point's over both), at the point's time in ms. A + /// counter, a gauge and an up-down counter as the OTLP test exporter + /// sends them. + #[test] + fn gauges_and_sums_give_one_point_each() { + let body = encode(&request(vec![ + metric( + "http_requests_total", + Data::Sum(Sum { + data_points: vec![number_point( + vec![text("method", "GET"), text("status", "200")], + NANOS, + number_data_point::Value::AsInt(42), + )], + is_monotonic: true, + ..Default::default() + }), + ), + metric( + "http_active_connections", + Data::Gauge(Gauge { + data_points: vec![number_point( + vec![ + text("scope", "point's"), + attribute("shard", any_value::Value::IntValue(3)), + ], + NANOS, + number_data_point::Value::AsDouble(-1.5), + )], + }), + ), + ])); + let points = decode(&body, None, &LIMITS).unwrap(); + assert_eq!( + points, + vec![ + Point { + labels: labels(&[ + ("__name__", "http_requests_total"), + ("method", "GET"), + ("scope", "s"), + ("service.name", "api-gateway"), + ("status", "200"), + ]), + timestamp_ms: MS, + value: 42.0, + }, + Point { + labels: labels(&[ + ("__name__", "http_active_connections"), + ("scope", "point's"), + ("service.name", "api-gateway"), + ("shard", "3"), + ]), + timestamp_ms: MS, + value: -1.5, + }, + ] + ); + } + + /// Histograms, exponential histograms and summaries give `_sum` (when + /// set) and `_count` points; buckets and quantiles are not read. + #[test] + fn distributions_give_sum_and_count_points() { + let body = encode(&request(vec![ + metric( + "http_request_duration_seconds", + Data::Histogram(Histogram { + data_points: vec![ + HistogramDataPoint { + time_unix_nano: NANOS, + count: 3, + sum: Some(0.45), + bucket_counts: vec![1, 2], + explicit_bounds: vec![0.1], + ..Default::default() + }, + HistogramDataPoint { + attributes: vec![text("method", "PUT")], + time_unix_nano: NANOS, + count: 1, + sum: None, + ..Default::default() + }, + ], + ..Default::default() + }), + ), + metric( + "size", + Data::ExponentialHistogram(ExponentialHistogram { + data_points: vec![ExponentialHistogramDataPoint { + time_unix_nano: NANOS, + count: 7, + sum: Some(70.0), + ..Default::default() + }], + ..Default::default() + }), + ), + metric( + "latency", + Data::Summary(Summary { + data_points: vec![SummaryDataPoint { + time_unix_nano: NANOS, + count: 2, + sum: 5.0, + ..Default::default() + }], + }), + ), + ])); + let points: Vec<(String, f64)> = decode(&body, None, &LIMITS) + .unwrap() + .into_iter() + .map(|point| { + let name = point.labels.iter().find(|(n, _)| n == "__name__").unwrap(); + (name.1.clone(), point.value) + }) + .collect(); + let expected: Vec<(String, f64)> = [ + ("http_request_duration_seconds_sum", 0.45), + ("http_request_duration_seconds_count", 3.0), + ("http_request_duration_seconds_count", 1.0), + ("size_sum", 70.0), + ("size_count", 7.0), + ("latency_sum", 5.0), + ("latency_count", 2.0), + ] + .into_iter() + .map(|(name, value)| (name.to_string(), value)) + .collect(); + assert_eq!(points, expected); + } + + /// Sketch payload points and unnamed metrics are skipped; a point with + /// no value reads 0, as in ASAPQuery. + #[test] + fn skips_sketch_payloads_and_unnamed_metrics() { + let sketch = attribute( + "kll.sketch_payload", + any_value::Value::BytesValue(vec![1, 2]), + ); + let body = encode(&request(vec![ + metric( + "m", + Data::Gauge(Gauge { + data_points: vec![ + number_point(vec![sketch], NANOS, number_data_point::Value::AsDouble(9.0)), + NumberDataPoint { + time_unix_nano: NANOS, + ..Default::default() + }, + ], + }), + ), + metric( + "", + Data::Gauge(Gauge { + data_points: vec![number_point( + vec![], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + }), + ), + ])); + let points = decode(&body, None, &LIMITS).unwrap(); + assert_eq!(points.len(), 1); + assert_eq!(points[0].value, 0.0); + } + + fn gzip(bytes: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() + } + + fn one_gauge() -> Vec { + encode(&request(vec![metric( + "g", + Data::Gauge(Gauge { + data_points: vec![ + number_point(vec![], NANOS, number_data_point::Value::AsDouble(1.0)), + number_point(vec![], NANOS + 1, number_data_point::Value::AsDouble(2.0)), + ], + }), + )])) + } + + /// A gzip body decodes to the points of the same body uncompressed. + #[test] + fn gzip_bodies_decode_as_uncompressed_ones() { + let body = one_gauge(); + let limits = LIMITS; + assert_eq!( + decode(&gzip(&body), Some(" GZIP "), &limits), + decode(&body, None, &limits) + ); + assert!(matches!( + decode(&body, Some("gzip"), &limits), + Err(OtlpError::Gzip(_)) + )); + } + + /// Bodies that are not OTLP protobuf, and bodies over a limit, are + /// rejected. + #[test] + fn rejects_malformed_and_oversized_bodies() { + let limits = LIMITS; + assert!(matches!( + decode(&[0xff; 8], None, &limits), + Err(OtlpError::Protobuf(_)) + )); + let body = one_gauge(); + let small = Limits { + max_decompressed_bytes: 4, + ..LIMITS + }; + assert_eq!( + decode(&body, None, &small), + Err(OtlpError::DecompressedTooLarge(4)) + ); + assert_eq!( + decode(&gzip(&body), Some("gzip"), &small), + Err(OtlpError::DecompressedTooLarge(4)) + ); + let one = Limits { + max_points: 1, + ..LIMITS + }; + assert_eq!(decode(&body, None, &one), Err(OtlpError::TooManyPoints(1))); + } +} diff --git a/crates/adapters/ingest/prometheus-remote-write/src/lib.rs b/crates/adapters/ingest/prometheus-remote-write/src/lib.rs index e4bbcab72..2be8f7195 100644 --- a/crates/adapters/ingest/prometheus-remote-write/src/lib.rs +++ b/crates/adapters/ingest/prometheus-remote-write/src/lib.rs @@ -129,19 +129,8 @@ impl Decoder { decompressed: buffer, cache, } = self; - let decoded = (|| { - let decoded = decompress_into(body, limits, buffer)?; - // Room for one sample per 40 encoded bytes: a sender's one-sample - // series take 60 to 150, so this grows only for tiny label sets. - let mut samples = Vec::with_capacity(decoded.len() / 40); - let mut request = Reader::new(decoded); - while let Some((field, value)) = request.field()? { - if let (1, Value::Bytes(series)) = (field, value) { - decode_series(series, cache, &mut samples, limits)?; - } - } - Ok(samples) - })(); + let decoded = decompress_into(body, limits, buffer) + .and_then(|request| decode_request(request, cache, limits)); // An unusually large request's buffer is not kept, whether or not the // request decoded: a short body claiming a large size and then failing // to decompress must not leave the decoder holding that buffer. @@ -150,10 +139,51 @@ impl Decoder { } decoded } + + /// The samples of an uncompressed Remote Write v1 `WriteRequest`, as + /// [`Decoder::decode`] reads a decompressed body: for a protocol that + /// sends the same protobuf compressed another way (VictoriaMetrics + /// sends it zstd-compressed). Errors: `request` is over + /// `max_decompressed_bytes`, or as [`Decoder::decode`] after + /// decompression. + pub fn decode_uncompressed( + &mut self, + request: &[u8], + limits: &Limits, + ) -> Result, RemoteWriteError> { + if request.len() > limits.max_decompressed_bytes { + return Err(RemoteWriteError::DecompressedTooLarge( + limits.max_decompressed_bytes, + )); + } + decode_request(request, &mut self.cache, limits) + } +} + +/// The samples of the encoded `WriteRequest` `request`, in request order. +/// `#[inline(always)]`: inlined into both callers, the request loop keeps +/// the codegen it had inside `Decoder::decode` (with `#[inline]` alone, one +/// series per sample decodes about 2% slower). +#[inline(always)] +fn decode_request( + request: &[u8], + cache: &mut SeriesCache, + limits: &Limits, +) -> Result, RemoteWriteError> { + // Room for one sample per 40 encoded bytes: a sender's one-sample + // series take 60 to 150, so this grows only for tiny label sets. + let mut samples = Vec::with_capacity(request.len() / 40); + let mut reader = Reader::new(request); + while let Some((field, value)) = reader.field()? { + if let (1, Value::Bytes(series)) = (field, value) { + decode_series(series, cache, &mut samples, limits)?; + } + } + Ok(samples) } /// The largest decompression buffer a decoder keeps between requests. -const KEPT_DECOMPRESSED_BYTES: usize = 32 * 1024 * 1024; +pub const KEPT_DECOMPRESSED_BYTES: usize = 32 * 1024 * 1024; /// The snappy-decompressed bytes of `body`, within the size limits, /// written into `buffer` (grown as needed). @@ -814,6 +844,47 @@ mod tests { ); } + /// An uncompressed request decodes to the samples of the same request + /// snappy-compressed, and is held to the decompressed size limit. + #[test] + fn uncompressed_requests_decode_as_compressed_ones() { + let request = WriteRequest { + timeseries: vec![ + series(&[("__name__", "m"), ("job", "a")], &[(1, 1.0), (2, 2.0)]), + series(&[("job", "b"), ("__name__", "m")], &[(3, f64::NAN)]), + ], + }; + let limits = Limits::default(); + let compressed = Decoder::new(Labeled::default()) + .labeled(&encode(&request), &limits) + .unwrap(); + let mut decoder = Decoder::new(Labeled::default()); + let samples = decoder + .decode_uncompressed(&request.encode_to_vec(), &limits) + .unwrap(); + let uncompressed: Vec<(Labels, i64, u64)> = samples + .into_iter() + .map(|(series, timestamp_ms, value)| { + ( + decoder.cache.builder.series[series].clone(), + timestamp_ms, + value.to_bits(), + ) + }) + .collect(); + assert_eq!(uncompressed, compressed); + let small = Limits { + max_decompressed_bytes: 4, + ..Limits::default() + }; + assert_eq!( + decoder + .decode_uncompressed(&request.encode_to_vec(), &small) + .err(), + Some(RemoteWriteError::DecompressedTooLarge(4)) + ); + } + /// The fast sample path reads what the generic one reads, and leaves /// any other layout (fields swapped, an unknown field, a value-less or /// negative-timestamp sample) to it. diff --git a/crates/adapters/ingest/victoriametrics-remote-write/Cargo.toml b/crates/adapters/ingest/victoriametrics-remote-write/Cargo.toml new file mode 100644 index 000000000..7ab7d3786 --- /dev/null +++ b/crates/adapters/ingest/victoriametrics-remote-write/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "victoriametrics_remote_write" +version.workspace = true +edition.workspace = true + +# VictoriaMetrics Remote Write: Prometheus Remote Write v1's protobuf, +# zstd-compressed. An adapter: it depends only on the adapter whose +# protobuf it reads, so it never sees an engine or a store. +[dependencies] +prometheus_remote_write.workspace = true +zstd = "0.13" +# `encode`, for senders and tests. +prost = "0.13" +thiserror.workspace = true diff --git a/crates/adapters/ingest/victoriametrics-remote-write/src/lib.rs b/crates/adapters/ingest/victoriametrics-remote-write/src/lib.rs new file mode 100644 index 000000000..ce24c5918 --- /dev/null +++ b/crates/adapters/ingest/victoriametrics-remote-write/src/lib.rs @@ -0,0 +1,351 @@ +//! VictoriaMetrics Remote Write decoding: a Prometheus Remote Write v1 +//! `WriteRequest`, zstd-compressed instead of snappy-compressed. +//! +//! [`Decoder`] decompresses a body and hands the protobuf to +//! `prometheus_remote_write`'s decoder, so the samples are walked, validated +//! and built into the caller's types exactly as a Prometheus Remote Write +//! body's are. + +use std::io::Read; + +use prometheus_remote_write::{Limits, RemoteWriteError, SampleBuilder, KEPT_DECOMPRESSED_BYTES}; + +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum VictoriaMetricsRemoteWriteError { + #[error("zstd decompression failed: {0}")] + Zstd(String), + /// Over a size limit, or not a valid Remote Write request once + /// decompressed. + #[error(transparent)] + RemoteWrite(#[from] RemoteWriteError), +} + +/// A decoder's state, kept between requests: its zstd context and +/// decompression buffer, and the Remote Write decoder (with its series +/// cache) it hands the protobuf to. +pub struct Decoder { + zstd: zstd::bulk::Decompressor<'static>, + /// A request's decompressed bytes are written over the last one's. + decompressed: Vec, + remote_write: prometheus_remote_write::Decoder, +} + +impl Decoder { + pub fn new(builder: B) -> Self { + Self { + zstd: zstd::bulk::Decompressor::new().expect("a zstd context"), + decompressed: Vec::new(), + remote_write: prometheus_remote_write::Decoder::new(builder), + } + } + + /// The samples of a zstd-compressed Remote Write v1 body, in request + /// order ([`prometheus_remote_write::Decoder::decode_uncompressed`]). + /// Errors: the body is over `max_compressed_bytes`, decompresses to + /// more than `max_decompressed_bytes` or is not zstd, or the protobuf is + /// rejected as a Prometheus Remote Write body's would be. + pub fn decode( + &mut self, + body: &[u8], + limits: &Limits, + ) -> Result, VictoriaMetricsRemoteWriteError> { + let decoded = decompress_into(body, limits, &mut self.zstd, &mut self.decompressed) + .and_then(|()| { + Ok(self + .remote_write + .decode_uncompressed(&self.decompressed, limits)?) + }); + if self.decompressed.capacity() > KEPT_DECOMPRESSED_BYTES { + self.decompressed = Vec::new(); + } + decoded + } +} + +/// Writes the zstd-decompressed bytes of `body` into `buffer` (replacing +/// its contents), within the size limits. A body whose frame states its +/// size (as senders write it) is decompressed in one pass with `zstd`; +/// any other (no size, several frames) is streamed, reading at most one +/// byte past `max_decompressed_bytes`, so a body that decompresses to more +/// is rejected without being decompressed whole. +fn decompress_into( + body: &[u8], + limits: &Limits, + zstd: &mut zstd::bulk::Decompressor<'static>, + buffer: &mut Vec, +) -> Result<(), VictoriaMetricsRemoteWriteError> { + if body.len() > limits.max_compressed_bytes { + return Err(RemoteWriteError::CompressedTooLarge(limits.max_compressed_bytes).into()); + } + let max = limits.max_decompressed_bytes; + buffer.clear(); + if let Ok(Some(len)) = zstd::zstd_safe::get_frame_content_size(body) { + if len > max as u64 { + return Err(RemoteWriteError::DecompressedTooLarge(max).into()); + } + buffer.reserve(len as usize); + // Fails when the body holds more than this frame: streamed below. + if zstd.decompress_to_buffer(body, buffer).is_ok() { + return Ok(()); + } + buffer.clear(); + } + let zstd_error = |e: std::io::Error| VictoriaMetricsRemoteWriteError::Zstd(e.to_string()); + let mut decompressor = zstd::stream::read::Decoder::with_buffer(body).map_err(zstd_error)?; + // No window larger than the largest request allowed: a small frame + // cannot make the decoder allocate more. + let window_log = (usize::BITS - max.max(1 << 10).leading_zeros()).min(31); + decompressor + .window_log_max(window_log) + .map_err(zstd_error)?; + decompressor + .take(max as u64 + 1) + .read_to_end(buffer) + .map_err(zstd_error)?; + if buffer.len() > max { + return Err(RemoteWriteError::DecompressedTooLarge(max).into()); + } + Ok(()) +} + +/// Zstd-compressed encoding of `request`, as a VictoriaMetrics sender +/// sends it. +pub fn encode(request: &prometheus_remote_write::WriteRequest) -> Vec { + use prost::Message; + zstd::bulk::compress(&request.encode_to_vec(), 0).expect("zstd compresses any input") +} + +#[cfg(test)] +mod tests { + use super::*; + use prometheus_remote_write::{Label, Sample, TimeSeries, WriteRequest}; + use std::cell::RefCell; + use std::rc::Rc; + + type Labels = Vec<(String, String)>; + + /// A builder whose series handle is an index into `series`, the labels + /// of each series it interned, in order; shared, so a test reads it + /// while the decoder holds the builder. + #[derive(Clone, Default)] + struct Labeled { + series: Rc>>, + } + + impl SampleBuilder for Labeled { + type Series = usize; + type Sample = (usize, i64, f64); + + fn intern(&mut self, labels: &[(&str, &str)]) -> usize { + let mut series = self.series.borrow_mut(); + series.push(pairs(labels)); + series.len() - 1 + } + + fn sample(series: usize, timestamp_ms: i64, value: f64) -> Self::Sample { + (series, timestamp_ms, value) + } + } + + impl Labeled { + /// `samples` with each series' labels and each value's bits. + fn labeled(&self, samples: Vec<(usize, i64, f64)>) -> Vec<(Labels, i64, u64)> { + let series = self.series.borrow(); + samples + .into_iter() + .map(|(s, timestamp_ms, value)| (series[s].clone(), timestamp_ms, value.to_bits())) + .collect() + } + } + + fn pairs(labels: &[(&str, &str)]) -> Labels { + labels + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect() + } + + fn series(labels: &[(&str, &str)], samples: &[(i64, f64)]) -> TimeSeries { + TimeSeries { + labels: labels + .iter() + .map(|(name, value)| Label { + name: name.to_string(), + value: value.to_string(), + }) + .collect(), + samples: samples + .iter() + .map(|&(timestamp, value)| Sample { value, timestamp }) + .collect(), + } + } + + /// Ported from ASAPQuery's `test_zstd_decode_single_sample`. + #[test] + fn decodes_a_single_zstd_sample() { + let request = WriteRequest { + timeseries: vec![series( + &[("__name__", "vm_metric"), ("region", "us-east-1")], + &[(1_700_000_000_000, 99.9)], + )], + }; + let builder = Labeled::default(); + let mut decoder = Decoder::new(builder.clone()); + let samples = decoder + .decode(&encode(&request), &Limits::default()) + .unwrap(); + assert_eq!( + builder.labeled(samples), + vec![( + pairs(&[("__name__", "vm_metric"), ("region", "us-east-1")]), + 1_700_000_000_000, + 99.9f64.to_bits() + )] + ); + } + + /// A body without its size in the frame header, as a streaming + /// encoder writes it, and one of two frames, decode as the one-frame + /// body with its size does. + #[test] + fn decodes_streamed_and_multi_frame_bodies() { + let request = WriteRequest { + timeseries: vec![ + series(&[("__name__", "m"), ("job", "a")], &[(1, 1.0)]), + series(&[("__name__", "m"), ("job", "b")], &[(2, 2.0)]), + ], + }; + let protobuf = prost::Message::encode_to_vec(&request); + let limits = Limits::default(); + let builder = Labeled::default(); + let mut decoder = Decoder::new(builder.clone()); + let sized = decoder.decode(&encode(&request), &limits).unwrap(); + let streamed = zstd::encode_all(protobuf.as_slice(), 0).unwrap(); + assert!(matches!( + zstd::zstd_safe::get_frame_content_size(&streamed), + Ok(None) + )); + assert_eq!(decoder.decode(&streamed, &limits).unwrap(), sized); + let (first, second) = protobuf.split_at(protobuf.len() / 2); + let mut frames = zstd::bulk::compress(first, 0).unwrap(); + frames.extend(zstd::bulk::compress(second, 0).unwrap()); + assert_eq!(decoder.decode(&frames, &limits).unwrap(), sized); + // A sized frame over the limit is rejected before decompressing. + let small = Limits { + max_decompressed_bytes: protobuf.len() - 1, + ..Limits::default() + }; + assert_eq!( + decoder.decode(&encode(&request), &small).err(), + Some(RemoteWriteError::DecompressedTooLarge(protobuf.len() - 1).into()) + ); + assert_eq!(builder.labeled(sized).len(), 2); + } + + /// Ported from ASAPQuery's `test_decode_invalid_zstd`. + #[test] + fn rejects_a_body_that_is_not_zstd() { + let mut decoder = Decoder::new(Labeled::default()); + assert!(matches!( + decoder.decode(b"not-zstd-data", &Limits::default()), + Err(VictoriaMetricsRemoteWriteError::Zstd(_)) + )); + } + + /// A zstd body decodes to the samples of the same request sent as + /// Prometheus Remote Write (snappy), stale markers included, and the + /// decoder's series cache carries over between requests. + #[test] + fn decodes_what_prometheus_remote_write_decodes() { + let request = WriteRequest { + timeseries: vec![ + series(&[("__name__", "m"), ("job", "a")], &[(1, 1.0), (2, 2.5)]), + series(&[("job", "b"), ("__name__", "m")], &[(3, -1.0)]), + series(&[("__name__", "m"), ("job", "a")], &[(4, f64::NAN)]), + ], + }; + let limits = Limits::default(); + let snappy_builder = Labeled::default(); + let snappy = prometheus_remote_write::Decoder::new(snappy_builder.clone()) + .decode(&prometheus_remote_write::encode(&request), &limits) + .unwrap(); + let snappy = snappy_builder.labeled(snappy); + let builder = Labeled::default(); + let mut decoder = Decoder::new(builder.clone()); + for _ in 0..2 { + let samples = decoder.decode(&encode(&request), &limits).unwrap(); + assert_eq!(builder.labeled(samples), snappy); + } + assert_eq!(builder.series.borrow().len(), 2); + } + + /// Series are validated as Prometheus Remote Write's are. + #[test] + fn rejects_invalid_series() { + let limits = Limits::default(); + let mut decoder = Decoder::new(Labeled::default()); + let unnamed = WriteRequest { + timeseries: vec![series(&[("job", "api")], &[(1, 1.0)])], + }; + assert_eq!( + decoder.decode(&encode(&unnamed), &limits).err(), + Some(RemoteWriteError::MissingMetricName.into()) + ); + let garbage = zstd::encode_all(&[0xffu8; 8][..], 0).unwrap(); + assert!(matches!( + decoder.decode(&garbage, &limits), + Err(VictoriaMetricsRemoteWriteError::RemoteWrite( + RemoteWriteError::Protobuf(_) + )) + )); + } + + /// Bodies over a size limit, compressed or decompressed, are rejected, + /// and so are requests with too many samples. + #[test] + fn enforces_limits() { + let request = WriteRequest { + timeseries: vec![series(&[("__name__", "x")], &[(1, 1.0), (2, 2.0)])], + }; + let body = encode(&request); + let mut decoder = Decoder::new(Labeled::default()); + for (limits, error) in [ + ( + Limits { + max_compressed_bytes: 1, + ..Limits::default() + }, + RemoteWriteError::CompressedTooLarge(1), + ), + ( + Limits { + max_decompressed_bytes: 4, + ..Limits::default() + }, + RemoteWriteError::DecompressedTooLarge(4), + ), + ( + Limits { + max_samples: 1, + ..Limits::default() + }, + RemoteWriteError::TooManySamples(1), + ), + ] { + assert_eq!(decoder.decode(&body, &limits).err(), Some(error.into())); + } + // A zstd bomb: 64 MiB of zeros, rejected after decompressing one + // byte past the limit, and no large buffer kept. + let bomb = zstd::encode_all(&vec![0u8; 64 << 20][..], 3).unwrap(); + let limits = Limits { + max_decompressed_bytes: 1 << 20, + ..Limits::default() + }; + assert_eq!( + decoder.decode(&bomb, &limits).err(), + Some(RemoteWriteError::DecompressedTooLarge(1 << 20).into()) + ); + assert!(decoder.decompressed.capacity() <= KEPT_DECOMPRESSED_BYTES); + } +} diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 6b6308a51..6641d81b7 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -9,6 +9,8 @@ internal_metrics.workspace = true precompute.workspace = true prometheus_http.workspace = true prometheus_remote_write.workspace = true +victoriametrics_remote_write.workspace = true +otlp.workspace = true query.workspace = true storage.workspace = true # The data plane's allocator (main.rs): many small per-request allocations. @@ -39,6 +41,9 @@ libc = "0.2" # cache (tests/remote_write_reference.rs). snap = "1.1" ahash = "0.8" +# OTLP bodies, plain and gzip (tests/ingest_protocols.rs). +flate2 = "1.0" +prost = "0.13" # The micro benchmarks live in benchmarks/micro/ and build as examples of this # crate (`cargo run --release -p data_plane --example `). diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 9d6499640..ee3623c78 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -1,10 +1,12 @@ -//! Backend data plane: receives Prometheus Remote Write samples and serves -//! the Prometheus query API for an installed plan. +//! Backend data plane: receives Prometheus Remote Write samples (and +//! VictoriaMetrics Remote Write and OTLP) and serves the Prometheus query +//! API for an installed plan. //! -//! The protocols are adapters: `prometheus_remote_write` decodes Remote -//! Write requests ([`remote_write`] interns their series into the store), -//! and `prometheus_http` reads query parameters, writes responses and -//! sends what the plan does not answer to Prometheus. +//! The protocols are adapters: `prometheus_remote_write`, +//! `victoriametrics_remote_write` and `otlp` decode ingest requests +//! ([`remote_write`] interns their series into the store), and +//! `prometheus_http` reads query parameters, writes responses and sends +//! what the plan does not answer to Prometheus. //! //! The installed plan is ASAPPlanner's `InstallablePlan`: one selected //! physical ASAP DAG. The precompute engine's ingest shards store the raw @@ -142,11 +144,19 @@ pub fn router(state: Arc) -> Router { .route("/api/v1/precompute/watermark", post(watermark)) .route("/-/ready", get(ready)); // Forward mode: any other path (labels, series, metadata, the raw - // store's UI) is proxied to the raw store. Off: those paths are 404. + // store's UI) is proxied to the raw store. Off: those paths are 404, + // except the VictoriaMetrics Remote Write and OTLP ingest routes, served + // only then: forward mode delivers Remote Write bodies alone to the raw + // store, which would miss their samples. let router = if forward_mode { router.fallback(proxy) } else { router + .route( + "/api/v1/import", + post(write_victoriametrics).layer(write_body_limit), + ) + .route("/v1/metrics", post(write_otlp).layer(write_body_limit)) }; router.with_state(state) } @@ -194,33 +204,83 @@ async fn write(State(state): State>, body: Bytes) -> Response { }, None => None, }; - match state.engine.try_ingest(samples) { - Ok(()) => { - if let Some(reservation) = reservation { - reservation.commit(body); - } - StatusCode::NO_CONTENT.into_response() - } - // Remote Write senders retry on 503. - Err(IngestError::Busy) => ( - StatusCode::SERVICE_UNAVAILABLE, - IngestError::Busy.to_string(), - ) - .into_response(), - Err(IngestError::Stopped) => { - tracing::error!("Remote Write refused: the engine has stopped"); - ( - StatusCode::INTERNAL_SERVER_ERROR, - IngestError::Stopped.to_string(), - ) - .into_response() - } + if let Some(refused) = ingest(&state, samples, "Remote Write") { + return refused; + } + if let Some(reservation) = reservation { + reservation.commit(body); } + StatusCode::NO_CONTENT.into_response() } Err(error) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(), } } +/// `POST /api/v1/import`: a VictoriaMetrics Remote Write body (the Remote +/// Write protobuf, zstd-compressed), ingested as `/api/v1/write` ingests a +/// Prometheus one; 204 once the engine has it. Not served in forward mode +/// (see [`router`]). +async fn write_victoriametrics(State(state): State>, body: Bytes) -> Response { + let samples = match remote_write::decode_victoriametrics_samples(&body, &state.limits) { + Ok(samples) => samples, + Err(error) => return (StatusCode::BAD_REQUEST, error.to_string()).into_response(), + }; + if !samples.is_empty() { + if let Some(refused) = ingest(&state, samples, "VictoriaMetrics Remote Write") { + return refused; + } + } + StatusCode::NO_CONTENT.into_response() +} + +/// `POST /v1/metrics`: an OTLP/HTTP metrics body (protobuf, gzip when its +/// `Content-Encoding` says so), each data point ingested as a sample +/// ([`otlp`]); 200 with `{"rejected": 0}` once the engine has them, as +/// ASAPQuery answers. Not served in forward mode (see [`router`]). +async fn write_otlp( + State(state): State>, + headers: HeaderMap, + body: Bytes, +) -> Response { + let content_encoding = headers + .get(header::CONTENT_ENCODING) + .and_then(|value| value.to_str().ok()); + let samples = match remote_write::decode_otlp_samples(&body, content_encoding, &state.limits) { + Ok(samples) => samples, + Err(error) => return (StatusCode::BAD_REQUEST, error.to_string()).into_response(), + }; + if !samples.is_empty() { + if let Some(refused) = ingest(&state, samples, "OTLP") { + return refused; + } + } + axum::Json(serde_json::json!({ "rejected": 0 })).into_response() +} + +/// Hands decoded samples to the engine: `None` once it has them, or the +/// response refusing them when it is busy (503, which senders retry) or has +/// stopped (500). +fn ingest( + state: &DataPlane, + samples: Vec, + protocol: &str, +) -> Option { + let refused = match state.engine.try_ingest(samples).err()? { + IngestError::Busy => ( + StatusCode::SERVICE_UNAVAILABLE, + IngestError::Busy.to_string(), + ), + IngestError::Stopped => { + tracing::error!("{protocol} refused: the engine has stopped"); + ( + StatusCode::INTERNAL_SERVER_ERROR, + IngestError::Stopped.to_string(), + ) + } + }; + Some(refused.into_response()) +} + /// `POST /api/v1/precompute/watermark?time_ms=T`: the producer states that /// every sample at or before `T` has been written. Once the engine has run /// every write acknowledged before this request, every window with diff --git a/crates/data-plane/src/remote_write.rs b/crates/data-plane/src/remote_write.rs index cef64ad62..69cbe62d4 100644 --- a/crates/data-plane/src/remote_write.rs +++ b/crates/data-plane/src/remote_write.rs @@ -1,12 +1,14 @@ -//! Remote Write ingest: the `prometheus_remote_write` adapter's decoder, -//! with each series interned into the store's series table, so a request -//! decodes straight into the engine's [`RawSample`]s. +//! Ingest decoding: the ingest adapters' decoders (Prometheus and +//! VictoriaMetrics Remote Write, OTLP), with each series interned into the +//! store's series table, so a request decodes into the engine's +//! [`RawSample`]s. use std::cell::RefCell; use prometheus_remote_write::{Decoder, Limits, RemoteWriteError, SampleBuilder}; use storage::series_ids::{intern_pairs, Series}; use storage::store::RawSample; +use victoriametrics_remote_write::VictoriaMetricsRemoteWriteError; /// The samples of a snappy-compressed Remote Write v1 body, each with its /// interned series, in request order ([`Decoder::decode`]). Each thread @@ -19,6 +21,43 @@ pub fn decode_samples(body: &[u8], limits: &Limits) -> Result, Re DECODER.with(|decoder| decoder.borrow_mut().decode(body, limits)) } +/// The samples of a zstd-compressed VictoriaMetrics Remote Write body, as +/// [`decode_samples`] decodes a Prometheus one +/// ([`victoriametrics_remote_write::Decoder::decode`]). +pub fn decode_victoriametrics_samples( + body: &[u8], + limits: &Limits, +) -> Result, VictoriaMetricsRemoteWriteError> { + thread_local! { + static DECODER: RefCell> = + RefCell::new(victoriametrics_remote_write::Decoder::new(Interned)); + } + DECODER.with(|decoder| decoder.borrow_mut().decode(body, limits)) +} + +/// The samples of an OTLP metrics body ([`otlp::decode`]), each point's +/// series interned, within Remote Write's decompressed size and sample +/// limits. `content_encoding` is the request's `Content-Encoding`. +pub fn decode_otlp_samples( + body: &[u8], + content_encoding: Option<&str>, + limits: &Limits, +) -> Result, otlp::OtlpError> { + let limits = otlp::Limits { + max_decompressed_bytes: limits.max_decompressed_bytes, + max_points: limits.max_samples, + }; + let points = otlp::decode(body, content_encoding, &limits)?; + Ok(points + .into_iter() + .map(|point| RawSample { + labels: intern_pairs(&point.labels), + timestamp_ms: point.timestamp_ms, + value: point.value, + }) + .collect()) +} + /// Interns each series into the store's series table and builds the /// engine's samples. struct Interned; diff --git a/crates/data-plane/tests/ingest_protocols.rs b/crates/data-plane/tests/ingest_protocols.rs new file mode 100644 index 000000000..c50e3b669 --- /dev/null +++ b/crates/data-plane/tests/ingest_protocols.rs @@ -0,0 +1,266 @@ +//! The VictoriaMetrics Remote Write (`/api/v1/import`) and OTLP +//! (`/v1/metrics`) routes ingest the samples a Prometheus Remote Write +//! request (`/api/v1/write`) with the same series and samples ingests. + +mod common; + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{header, Request, StatusCode}; +use axum::Router; +use data_plane::{router, DataPlane}; +use http_body_util::BodyExt; +use otlp::proto::collector::metrics::v1::ExportMetricsServiceRequest; +use otlp::proto::common::v1::{any_value, AnyValue, KeyValue}; +use otlp::proto::metrics::v1::{ + metric::Data, number_data_point, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, +}; +use prometheus_remote_write::{Label, Sample, TimeSeries, WriteRequest}; +use serde_json::{json, Value}; +use tower::ServiceExt; + +const QUERY: &str = "sum by (job) (sum_over_time(data[1m]))"; +const SERIES: usize = 6; +/// Samples every second, from 1 s to `END_S`. +const END_S: i64 = 180; + +fn value(series: usize, second: i64) -> f64 { + ((second * (series as i64 + 1)) % 17) as f64 +} + +/// Series `i`'s labels: `data`, its instance and one of three jobs. +fn labels(i: usize) -> [(&'static str, String); 3] { + [ + ("__name__", "data".to_string()), + ("instance", format!("i{i}")), + ("job", format!("job{}", i % 3)), + ] +} + +fn remote_write_request() -> WriteRequest { + WriteRequest { + timeseries: (0..SERIES) + .map(|i| TimeSeries { + labels: labels(i) + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(), + samples: (1..=END_S) + .map(|second| Sample { + timestamp: second * 1000, + value: value(i, second), + }) + .collect(), + }) + .collect(), + } +} + +/// The same series and samples as one OTLP gauge per series, the labels +/// other than `__name__` as point attributes. +fn otlp_request() -> ExportMetricsServiceRequest { + let metrics = (0..SERIES) + .map(|i| { + let attributes: Vec = labels(i)[1..] + .iter() + .map(|(name, value)| KeyValue { + key: name.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.clone())), + }), + }) + .collect(); + Metric { + name: "data".into(), + data: Some(Data::Gauge(Gauge { + data_points: (1..=END_S) + .map(|second| NumberDataPoint { + attributes: attributes.clone(), + time_unix_nano: second as u64 * 1_000_000_000, + value: Some(number_data_point::Value::AsDouble(value(i, second))), + ..Default::default() + }) + .collect(), + })), + ..Default::default() + } + }) + .collect(); + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics, + ..Default::default() + }], + ..Default::default() + }], + } +} + +fn data_plane() -> (Arc, Router) { + let state = Arc::new( + DataPlane::with_options( + common::one_query_plan_json(QUERY, SERIES, json!({})), + "http://127.0.0.1:1".into(), + common::no_forward_options(), + ) + .unwrap(), + ); + let app = router(state.clone()); + (state, app) +} + +async fn post( + app: &Router, + uri: &str, + content_encoding: Option<&str>, + body: Vec, +) -> (StatusCode, String) { + let mut request = Request::post(uri); + if let Some(encoding) = content_encoding { + request = request.header(header::CONTENT_ENCODING, encoding); + } + let response = app + .clone() + .oneshot(request.body(Body::from(body)).unwrap()) + .await + .unwrap(); + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + (status, String::from_utf8_lossy(&body).into_owned()) +} + +/// After the barrier at `END_S`, `QUERY` at every 10 s evaluation of the +/// last minute, answered from the plan; and the samples the engine +/// accepted. +async fn answers(state: &DataPlane, app: &Router) -> (Vec, u64) { + common::barrier(app, END_S * 1000).await; + let mut answers = Vec::new(); + for time_s in (END_S - 60..=END_S).step_by(10) { + let (status, execution, body) = common::get(app, &common::instant_uri(QUERY, time_s)).await; + assert_eq!(status, StatusCode::OK, "at {time_s}: {body}"); + assert_eq!(execution.as_deref(), Some("plan")); + answers.push(body); + } + (answers, state.engine.stats().samples_accepted) +} + +fn gzip(bytes: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() +} + +#[tokio::test(flavor = "multi_thread")] +async fn victoriametrics_and_otlp_ingest_what_remote_write_ingests() { + let (state, app) = data_plane(); + let (status, error) = post( + &app, + "/api/v1/write", + None, + prometheus_remote_write::encode(&remote_write_request()), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "{error}"); + let expected = answers(&state, &app).await; + assert_eq!(expected.1, SERIES as u64 * END_S as u64); + // The sum per job of the last minute's samples, at the newest step. + let newest = common::per_job(expected.0.last().unwrap()); + let sums: Vec<(String, f64)> = (0..3) + .map(|job| { + let sum = (0..SERIES) + .filter(|i| i % 3 == job) + .flat_map(|i| (END_S - 59..=END_S).map(move |s| value(i, s))) + .sum(); + (format!("job{job}"), sum) + }) + .collect(); + assert_eq!(newest, sums); + + let (state, app) = data_plane(); + let (status, error) = post( + &app, + "/api/v1/import", + None, + victoriametrics_remote_write::encode(&remote_write_request()), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "{error}"); + assert_eq!(answers(&state, &app).await, expected); + + for gzipped in [false, true] { + let (state, app) = data_plane(); + let body = prost::Message::encode_to_vec(&otlp_request()); + let (body, encoding) = if gzipped { + (gzip(&body), Some("gzip")) + } else { + (body, None) + }; + let (status, response) = post(&app, "/v1/metrics", encoding, body).await; + assert_eq!(status, StatusCode::OK, "{response}"); + assert_eq!(response, r#"{"rejected":0}"#); + assert_eq!(answers(&state, &app).await, expected, "gzip: {gzipped}"); + } +} + +/// The three decoders give the same samples: each of the same interned +/// series (the same `&'static Series`), timestamp and value. +#[test] +fn decoders_give_the_same_series_and_samples() { + use data_plane::remote_write::{ + decode_otlp_samples, decode_samples, decode_victoriametrics_samples, + }; + type Decoded = Vec<(usize, i64, u64)>; + let identity = |samples: Vec| -> Decoded { + samples + .into_iter() + .map(|s| { + ( + s.labels as *const _ as usize, + s.timestamp_ms, + s.value.to_bits(), + ) + }) + .collect() + }; + let limits = prometheus_remote_write::Limits::default(); + let request = remote_write_request(); + let remote_write = + identity(decode_samples(&prometheus_remote_write::encode(&request), &limits).unwrap()); + let victoriametrics = identity( + decode_victoriametrics_samples(&victoriametrics_remote_write::encode(&request), &limits) + .unwrap(), + ); + assert_eq!(victoriametrics, remote_write); + let otlp = identity( + decode_otlp_samples( + &prost::Message::encode_to_vec(&otlp_request()), + None, + &limits, + ) + .unwrap(), + ); + // The OTLP request lists the same series and samples in the same order. + assert_eq!(otlp, remote_write); + assert_eq!(otlp.len(), SERIES * END_S as usize); +} + +/// Malformed bodies are rejected with 400 and ingest nothing. +#[tokio::test] +async fn rejects_malformed_bodies() { + let (state, app) = data_plane(); + for (uri, encoding) in [ + ("/api/v1/import", None), + ("/v1/metrics", None), + ("/v1/metrics", Some("gzip")), + ] { + let (status, _) = post(&app, uri, encoding, vec![0xff; 8]).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{uri} {encoding:?}"); + } + assert_eq!(state.engine.stats().samples_accepted, 0); +}