Skip to content
Closed
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
108 changes: 97 additions & 11 deletions data_plane/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
//! queries with query runs, all through the Planner's executor
//! ([`engine`]); every other query, and any planned query it cannot
//! answer, is forwarded to Prometheus (or refused with `--no-forward`).
//!
//! Forward mode (`--raw-store-url`, [`raw_forward`]): every accepted Remote
//! Write request is also delivered to a raw store (VictoriaMetrics), which
//! then answers every query the plan does not and every other API path
//! (labels, series, metadata), proxied with `x-asap-execution: forwarded`.

pub mod engine;
pub mod ingestion;
Expand All @@ -18,6 +23,7 @@ pub mod pipelines;
pub mod prometheus;
pub mod push;
pub mod query;
pub mod raw_forward;
pub mod remote_write;
pub mod result_cache;
pub mod segment;
Expand All @@ -30,7 +36,7 @@ use std::sync::Arc;
use std::time::Duration;

use axum::body::Bytes;
use axum::extract::{DefaultBodyLimit, RawQuery, State};
use axum::extract::{DefaultBodyLimit, OriginalUri, RawQuery, State};
use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
Expand Down Expand Up @@ -62,6 +68,9 @@ pub struct DataPlane {
/// gets an error with the reason ([`EngineOptions::no_forward`]).
pub no_forward: bool,
client: reqwest::Client,
/// Forward mode: delivers accepted Remote Write bodies to the raw store,
/// which also answers what the plan does not. `None`: off.
pub raw_forward: Option<raw_forward::RawForwarder>,
}

impl DataPlane {
Expand Down Expand Up @@ -94,9 +103,26 @@ impl DataPlane {
limits: remote_write::Limits::default(),
samples: AtomicU64::new(0),
client: forward_client(DEFAULT_FORWARD_TIMEOUT),
raw_forward: None,
})
}

/// Turns forward mode on: accepted Remote Write bodies are delivered to
/// the raw store at `options.url`, and queries the plan does not answer,
/// as well as any other path, are proxied to it (in place of
/// `prometheus_url`). Refused with `--no-forward`, which forbids proxying.
pub fn with_raw_forward(
mut self,
options: raw_forward::RawForwardOptions,
) -> anyhow::Result<Self> {
if self.no_forward {
anyhow::bail!("--raw-store-url proxies unplanned queries, which --no-forward refuses");
}
self.prometheus_url = options.url.clone();
self.raw_forward = Some(raw_forward::RawForwarder::start(options)?);
Ok(self)
}

/// Bounds each forwarded query by `timeout`, from sending the request to
/// reading the whole response (default [`DEFAULT_FORWARD_TIMEOUT`]).
pub fn with_forward_timeout(mut self, timeout: Duration) -> Self {
Expand All @@ -116,15 +142,43 @@ pub fn router(state: Arc<DataPlane>) -> Router {
// axum refuses bodies over 2 MB by default; Remote Write allows up to
// `max_compressed_bytes` and answers larger bodies with 413.
let write_body_limit = DefaultBodyLimit::max(state.limits.max_compressed_bytes);
Router::new()
let forward_mode = state.raw_forward.is_some();
let router = Router::new()
.route("/api/v1/write", post(write).layer(write_body_limit))
.route("/api/v1/query", get(query).post(query))
.route("/api/v1/query_range", get(query_range).post(query_range))
.route("/api/v1/status/asap", get(status))
.route("/metrics", get(metrics))
.route("/api/v1/precompute/watermark", post(watermark))
.route("/-/ready", get(ready))
.with_state(state)
.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.
let router = if forward_mode {
router.fallback(proxy)
} else {
router
};
router.with_state(state)
}

/// Forward mode: proxies a request the data plane does not serve to the raw
/// store, with `x-asap-execution: forwarded`.
async fn proxy(
state: State<Arc<DataPlane>>,
method: Method,
OriginalUri(uri): OriginalUri,
headers: HeaderMap,
body: Bytes,
) -> Response {
forward_path(
state,
uri.path(),
method,
RawQuery(uri.query().map(str::to_string)),
headers,
body,
)
.await
}

async fn write(State(state): State<Arc<DataPlane>>, body: Bytes) -> Response {
Expand All @@ -136,8 +190,26 @@ async fn write(State(state): State<Arc<DataPlane>>, body: Bytes) -> Response {
if count == 0 {
return StatusCode::NO_CONTENT.into_response();
}
// Forward mode: room in the raw store's queue first, so a refused
// request reaches neither store and a retry duplicates nothing.
let reservation = match &state.raw_forward {
Some(forwarder) => match forwarder.reserve(body.len() as u64) {
Some(reservation) => Some(reservation),
None => {
return (
StatusCode::SERVICE_UNAVAILABLE,
"the raw store's forward queue is full",
)
.into_response()
}
},
None => None,
};
match state.engine.try_ingest(samples) {
Ok(()) => {
if let Some(reservation) = reservation {
reservation.commit(body);
}
state.samples.fetch_add(count, Ordering::Relaxed);
StatusCode::NO_CONTENT.into_response()
}
Expand Down Expand Up @@ -228,6 +300,7 @@ async fn status(State(state): State<Arc<DataPlane>>) -> Response {
"samples_queued": state.engine.queued_samples(),
"precompute_backlog": state.engine.precompute_backlog(),
"ingestion": state.engine.stats(),
"raw_forward": state.raw_forward.as_ref().map(|f| f.status()),
});
(
[(header::CONTENT_TYPE, "application/json")],
Expand All @@ -240,11 +313,11 @@ async fn status(State(state): State<Arc<DataPlane>>) -> Response {
/// thread CPU and wall time, query latency, counters, backlogs, watermark
/// lag, bytes held and each thread's CPU time ([`metrics`]).
async fn metrics(State(state): State<Arc<DataPlane>>) -> Response {
(
[(header::CONTENT_TYPE, "text/plain; version=0.0.4")],
state.engine.render_metrics(),
)
.into_response()
let mut text = state.engine.render_metrics();
if let Some(forwarder) = &state.raw_forward {
forwarder.render(&mut text);
}
([(header::CONTENT_TYPE, "text/plain; version=0.0.4")], text).into_response()
}

/// `text` as a header value: characters a header cannot carry (controls and
Expand Down Expand Up @@ -493,14 +566,27 @@ fn forwarded_headers(headers: &HeaderMap) -> HeaderMap {
/// `Authorization` and tenancy headers such as `X-Scope-OrgID`) and returns
/// Prometheus's status, body and `Content-Type`.
async fn forward(
State(state): State<Arc<DataPlane>>,
state: State<Arc<DataPlane>>,
endpoint: &str,
method: Method,
query: RawQuery,
headers: HeaderMap,
body: Bytes,
) -> Response {
let path = format!("/api/v1/{endpoint}");
forward_path(state, &path, method, query, headers, body).await
}

/// [`forward`] for any `path` of the Prometheus (or raw store) server.
async fn forward_path(
State(state): State<Arc<DataPlane>>,
path: &str,
method: Method,
RawQuery(query): RawQuery,
headers: HeaderMap,
body: Bytes,
) -> Response {
let mut url = format!("{}/api/v1/{endpoint}", state.prometheus_url);
let mut url = format!("{}{path}", state.prometheus_url);
if let Some(query) = query {
url = format!("{url}?{query}");
}
Expand Down
27 changes: 27 additions & 0 deletions data_plane/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,20 @@ struct Args {
/// with an error giving the reason.
#[arg(long)]
no_forward: bool,
/// Forward mode (off by default): deliver every accepted Remote Write
/// request to this raw store (a VictoriaMetrics single-node base URL),
/// which also answers every query the plan does not answer and every
/// other API path, in place of `--prometheus-url`. Cannot be used with
/// `--no-forward`.
#[arg(long, conflicts_with = "no_forward")]
raw_store_url: Option<String>,
/// Forward mode: bytes of Remote Write bodies queued or in flight to the
/// raw store beyond which writes are refused with 503.
#[arg(long, default_value_t = data_plane::raw_forward::RawForwardOptions::new("").max_queued_bytes)]
raw_forward_queue_bytes: u64,
/// Forward mode: Remote Write requests delivered to the raw store at once.
#[arg(long, default_value_t = data_plane::raw_forward::RawForwardOptions::new("").concurrency)]
raw_forward_concurrency: usize,
/// The most bytes one ingestion or query run may hold.
#[arg(long, default_value_t = EngineOptions::default().run_memory_limit_bytes)]
run_memory_limit_bytes: usize,
Expand Down Expand Up @@ -219,6 +233,19 @@ async fn main() -> anyhow::Result<()> {
)?
.with_forward_timeout(Duration::from_secs(args.forward_timeout_seconds)),
);
let state = match &args.raw_store_url {
Some(url) => {
let mut options = data_plane::raw_forward::RawForwardOptions::new(url.clone());
options.max_queued_bytes = args.raw_forward_queue_bytes;
options.concurrency = args.raw_forward_concurrency;
let state = Arc::try_unwrap(state)
.map_err(|_| anyhow::anyhow!("the data plane is already shared"))?
.with_raw_forward(options)?;
tracing::info!(raw_store = %url, "forward mode: raw samples and unplanned queries go to the raw store");
Arc::new(state)
}
None => state,
};
tracing::info!(queries = state.queries.len(), "installed plan");
let listener = tokio::net::TcpListener::bind(&args.listen).await?;
tracing::info!(address = %listener.local_addr()?, "listening");
Expand Down
Loading