diff --git a/Cargo.lock b/Cargo.lock index 4404e2199..ad40a02a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -831,6 +831,19 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +[[package]] +name = "clickhouse_http" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "common", + "form_urlencoded", + "reqwest", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "cmake" version = "0.1.58" @@ -983,8 +996,10 @@ dependencies = [ "asap_sketchlib", "axum", "clap", + "clickhouse_http", "common", "control_plane", + "elastic_http", "flate2", "form_urlencoded", "futures", @@ -1641,6 +1656,19 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]] +name = "elastic_http" +version = "0.1.0" +dependencies = [ + "async-trait", + "axum", + "common", + "reqwest", + "serde_json", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "enquote" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index a7c0e8fd2..1c533a992 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,8 @@ members = [ "crates/adapters/ingest/otlp", "crates/adapters/ingest/prometheus-remote-write", "crates/adapters/ingest/victoriametrics-remote-write", + "crates/adapters/query/clickhouse-http", + "crates/adapters/query/elastic-http", "crates/adapters/query/prometheus-http", "crates/common", "crates/control-plane", @@ -44,8 +46,10 @@ clap = { version = "4.0", features = ["derive", "env"] } tokio = { version = "1.0", features = ["full"] } axum = "0.7" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +clickhouse_http = { path = "crates/adapters/query/clickhouse-http" } control_plane = { path = "crates/control-plane" } common = { path = "crates/common" } +elastic_http = { path = "crates/adapters/query/elastic-http" } internal_metrics = { path = "crates/internal-metrics" } otlp = { path = "crates/adapters/ingest/otlp" } precompute = { path = "crates/precompute" } diff --git a/README.md b/README.md index 3bcbde083..c139f74ad 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,16 @@ cost and predicted usage per node and per query. The data facts the plan assumed are printed. The Planner returns a plan only when its executor compiles it; otherwise the control plane fails. +`--clickhouse-url URL` (with `--clickhouse-database`, default `default`) +serves ClickHouse's query route on ASAPQuery's path, `/clickhouse/query` +(`query` in the URL or a form), and `--elastic-url URL` (with +`--elastic-index`) Elasticsearch's, `POST /_sql` and `POST /_search`. Each +query goes through the plan first; the control plane plans PromQL only, so +today every one is forwarded to its server with the client's +`Authorization`, and the server's answer is returned as is +(`x-asap-execution: forwarded`). Without the flag the routes are not +served; neither flag can be used with `--no-forward`. + `--forward-timeout-seconds` bounds each forwarded query (default 120, matching Prometheus's default query timeout); a query that runs longer gets 502. @@ -248,6 +258,8 @@ not stored) with a Prometheus `execution` error (422, | `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/clickhouse-http/` | package `clickhouse_http`: the `query` parameter, TabSeparated bodies and the fallback client of a ClickHouse server, `/clickhouse/query` | +| `crates/adapters/query/elastic-http/` | package `elastic_http`: `_sql` and `_search` bodies and the fallback client of an Elasticsearch server, `POST /_sql`, `POST /_search` | | `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/query/clickhouse-http/Cargo.toml b/crates/adapters/query/clickhouse-http/Cargo.toml new file mode 100644 index 000000000..380da2598 --- /dev/null +++ b/crates/adapters/query/clickhouse-http/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "clickhouse_http" +version.workspace = true +edition.workspace = true + +# ClickHouse's HTTP interface: the query parameter, TabSeparated response +# bodies, and the fallback client of a ClickHouse server. An adapter: of +# this workspace it depends on `common` only, never on an engine or a store. +[dependencies] +common.workspace = true +# `common::FallbackClient`'s async method. +async-trait.workspace = true +form_urlencoded = "1" +reqwest.workspace = true +thiserror.workspace = true + +[dev-dependencies] +axum.workspace = true +tokio.workspace = true diff --git a/crates/adapters/query/clickhouse-http/src/fallback.rs b/crates/adapters/query/clickhouse-http/src/fallback.rs new file mode 100644 index 000000000..ab1a18b4d --- /dev/null +++ b/crates/adapters/query/clickhouse-http/src/fallback.rs @@ -0,0 +1,235 @@ +//! The client of a ClickHouse server that answers the queries the data +//! plane does not, as ASAPQuery's `ClickHouseHttpFallback` sends them. + +use std::time::Duration; + +use async_trait::async_trait; +use common::{ + FallbackClient, FallbackError, FallbackResponse, QueryEval, QueryLanguage, QueryRequest, + SqlDialect, +}; +use reqwest::header::{self, HeaderName, HeaderValue}; + +/// Sends queries to one ClickHouse server's HTTP interface. +pub struct ClickHouseHttpFallback { + /// `/?database=`, where every query is posted. + query_url: String, + client: reqwest::Client, +} + +impl ClickHouseHttpFallback { + /// A client of the server at `base_url` that runs queries in + /// `database`, each request bounded by `timeout`, from sending it to + /// reading the whole response. + pub fn new(base_url: &str, database: &str, timeout: Duration) -> Self { + let database: String = form_urlencoded::byte_serialize(database.as_bytes()).collect(); + Self { + query_url: format!("{}/?database={database}", base_url.trim_end_matches('/')), + client: reqwest::Client::builder() + .timeout(timeout) + .build() + .expect("reqwest client with only a timeout set"), + } + } +} + +#[async_trait] +impl FallbackClient for ClickHouseHttpFallback { + /// `POST /?database=` with the query as the body, so the + /// server answers in its default format (TabSeparated) unless the + /// query names one. A ClickHouse SQL instant query only: ClickHouse has + /// no range queries. Header pairs that are not valid HTTP headers are + /// skipped. + async fn execute( + &self, + request: &QueryRequest, + headers: &[(String, String)], + ) -> Result { + if request.language != QueryLanguage::SQL(SqlDialect::ClickhouseSQL) { + return Err(FallbackError::new(format!( + "a ClickHouse server answers ClickHouse SQL, not {:?}", + request.language + ))); + } + if let QueryEval::Range { .. } = request.eval { + return Err(FallbackError::new("ClickHouse has no range queries")); + } + let mut upstream = self.client.post(&self.query_url); + for (name, value) in headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::try_from(name.as_str()), + HeaderValue::try_from(value.as_str()), + ) { + upstream = upstream.header(name, value); + } + } + let upstream = upstream + .body(request.query.clone()) + .send() + .await + .map_err(|error| FallbackError::new(format!("forwarding to ClickHouse: {error}")))?; + let status_code = upstream.status().as_u16(); + // A server that names no type sent bytes of unknown type (RFC 9110 + // section 8.3). + let content_type = upstream + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or("application/octet-stream") + .to_string(); + let body = upstream + .bytes() + .await + .map_err(|error| FallbackError::new(format!("reading ClickHouse response: {error}")))?; + Ok(FallbackResponse { + status_code, + content_type, + body: body.into(), + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::{OriginalUri, State}; + use axum::http::{HeaderMap, StatusCode}; + use axum::routing::post; + use axum::Router; + + use super::*; + + /// What the mock server received: path and query, `Authorization`, body. + type Received = Arc, String)>>>; + + /// A ClickHouse server that records each request and answers 200 with + /// a TabSeparated row, or, for a query on `missing`, 404 with + /// ClickHouse's plain-text exception; its base URL. + async fn server(received: Received) -> String { + async fn record( + State(received): State, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + body: String, + ) -> (StatusCode, [(header::HeaderName, &'static str); 1], String) { + let authorization = headers + .get(header::AUTHORIZATION) + .map(|v| v.to_str().unwrap().to_string()); + let missing = body.contains("missing"); + received + .lock() + .unwrap() + .push((uri.to_string(), authorization, body)); + if missing { + return ( + StatusCode::NOT_FOUND, + [(header::CONTENT_TYPE, "text/plain; charset=UTF-8")], + "Code: 60. DB::Exception: Table default.missing does not exist.".into(), + ); + } + ( + StatusCode::OK, + [( + header::CONTENT_TYPE, + "text/tab-separated-values; charset=UTF-8", + )], + "1\n".into(), + ) + } + let app = Router::new().route("/", post(record)).with_state(received); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{address}/") + } + + fn request(query: &str) -> QueryRequest { + QueryRequest { + language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL), + query: query.into(), + eval: QueryEval::Instant { time_ms: 0 }, + } + } + + /// From ASAPQuery's `test_execute_query_success` and + /// `test_url_with_database_param`: the query is posted as the body to + /// `/?database=` with the client's headers, and the server's + /// status, `Content-Type` and body come back unchanged, an exception + /// included (`test_execute_query_error_response`). + #[tokio::test] + async fn posts_the_query_and_returns_the_response_unchanged() { + let received = Received::default(); + let fallback = ClickHouseHttpFallback::new( + &server(received.clone()).await, + "test db", + Duration::from_secs(5), + ); + let headers = [("Authorization".to_string(), "Basic dTpw".to_string())]; + let response = fallback + .execute(&request("SELECT 1"), &headers) + .await + .unwrap(); + assert_eq!( + response, + FallbackResponse { + status_code: 200, + content_type: "text/tab-separated-values; charset=UTF-8".into(), + body: b"1\n".to_vec(), + } + ); + let error = fallback + .execute(&request("SELECT * FROM missing"), &[]) + .await + .unwrap(); + assert_eq!(error.status_code, 404); + assert_eq!( + error.body, + b"Code: 60. DB::Exception: Table default.missing does not exist." + ); + let received = received.lock().unwrap(); + assert_eq!( + received[0], + ( + "/?database=test+db".to_string(), + Some("Basic dTpw".to_string()), + "SELECT 1".to_string() + ) + ); + assert_eq!(received[1].1, None); + } + + /// A range query (ASAPQuery's `test_range_query_not_implemented`) or a + /// query in another language is not sent; an unreachable server + /// (`test_clickhouse_server_unreachable`) is an error. + #[tokio::test] + async fn refuses_what_clickhouse_cannot_answer_and_reports_an_unreachable_server() { + let fallback = + ClickHouseHttpFallback::new("http://127.0.0.1:1", "default", Duration::from_secs(5)); + let range = QueryRequest { + eval: QueryEval::Range { + start_ms: 0, + end_ms: 60_000, + step_ms: 15_000, + }, + ..request("SELECT 1") + }; + assert_eq!( + fallback.execute(&range, &[]).await, + Err(FallbackError::new("ClickHouse has no range queries")) + ); + let promql = QueryRequest { + language: QueryLanguage::PromQL, + ..request("up") + }; + assert!(fallback.execute(&promql, &[]).await.is_err()); + let error = fallback + .execute(&request("SELECT 1"), &[]) + .await + .unwrap_err(); + assert!( + error.message.starts_with("forwarding to ClickHouse: "), + "{error}" + ); + } +} diff --git a/crates/adapters/query/clickhouse-http/src/lib.rs b/crates/adapters/query/clickhouse-http/src/lib.rs new file mode 100644 index 000000000..1bbab6a47 --- /dev/null +++ b/crates/adapters/query/clickhouse-http/src/lib.rs @@ -0,0 +1,237 @@ +//! ClickHouse's HTTP interface as the data plane speaks it, on ASAPQuery's +//! route (`/clickhouse/query`): the query, TabSeparated result +//! bodies, and the [`fallback`] client that sends a query the data plane +//! does not answer to a ClickHouse server. An adapter: it depends on +//! `common` only. + +use std::collections::BTreeSet; +use std::io::Write as _; + +use common::{QueryEval, QueryLanguage, QueryRequest, QueryResult, SqlDialect, TableValue}; + +pub mod fallback; + +/// The request has no query (400). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("missing parameter \"query\"")] +pub struct MissingQuery; + +/// The `Content-Type` of a TabSeparated body, as ClickHouse sends it. +pub const TAB_SEPARATED_CONTENT_TYPE: &str = "text/tab-separated-values; charset=UTF-8"; + +/// The ClickHouse SQL query of a request, evaluated at `now_ms` (ClickHouse +/// queries name no evaluation time): the `query` parameter of the URL query +/// or of a form body, else, as ASAPQuery reads it, the whole body (the +/// ClickHouse HTTP interface's plain SQL `POST`). +pub fn parse_query( + url_query: Option<&str>, + body: &[u8], + now_ms: i64, +) -> Result { + let parameter = form_urlencoded::parse(url_query.unwrap_or_default().as_bytes()) + .chain(form_urlencoded::parse(body)) + .find(|(name, _)| name == "query"); + let query = match parameter { + Some((_, query)) => query.into_owned(), + None if !body.is_empty() => std::str::from_utf8(body) + .map_err(|_| MissingQuery)? + .to_string(), + None => return Err(MissingQuery), + }; + Ok(QueryRequest { + language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL), + query, + eval: QueryEval::Instant { time_ms: now_ms }, + }) +} + +/// A result a TabSeparated body cannot hold (a range or a scalar). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("a ClickHouse response cannot hold a {0} result")] +pub struct UnsupportedResult(&'static str); + +/// `result` in ClickHouse's default format, TabSeparated: one line per row, +/// values separated by tabs, with `\`, tab, newline, carriage return and +/// NUL escaped. A table +/// writes its rows; an instant vector one row per series: its label values +/// (every label any series has, by name; empty where it has none), then its +/// value. +pub fn tab_separated(result: &QueryResult) -> Result, UnsupportedResult> { + let mut body = Vec::new(); + match result { + QueryResult::Table(table) => { + for row in &table.rows { + for (index, cell) in row.iter().enumerate() { + if index > 0 { + body.push(b'\t'); + } + match cell { + TableValue::String(text) => write_escaped(&mut body, text), + TableValue::Float(value) => write_float(&mut body, *value), + } + } + body.push(b'\n'); + } + } + QueryResult::Vector(vector) => { + let names: BTreeSet<&String> = vector + .series + .iter() + .flat_map(|series| series.labels.keys()) + .collect(); + for series in &vector.series { + for name in &names { + write_escaped( + &mut body, + series.labels.get(*name).map_or("", String::as_str), + ); + body.push(b'\t'); + } + write_float(&mut body, series.value); + body.push(b'\n'); + } + } + QueryResult::Matrix(_) => return Err(UnsupportedResult("range")), + QueryResult::Scalar(_) => return Err(UnsupportedResult("scalar")), + } + Ok(body) +} + +/// TabSeparated's escapes for the characters that end a value or a row. +fn write_escaped(body: &mut Vec, text: &str) { + for byte in text.bytes() { + match byte { + b'\\' => body.extend_from_slice(b"\\\\"), + b'\t' => body.extend_from_slice(b"\\t"), + b'\n' => body.extend_from_slice(b"\\n"), + b'\r' => body.extend_from_slice(b"\\r"), + b'\0' => body.extend_from_slice(b"\\0"), + _ => body.push(byte), + } + } +} + +/// As ClickHouse writes a `Float64`: shortest round-trip digits, `nan`, +/// `inf` and `-inf`. +fn write_float(body: &mut Vec, value: f64) { + if value.is_nan() { + body.extend_from_slice(b"nan"); + } else if value.is_infinite() { + body.extend_from_slice(if value > 0.0 { b"inf" } else { b"-inf" }); + } else { + write!(body, "{value}").expect("writing to a Vec does not fail"); + } +} + +#[cfg(test)] +mod tests { + use common::{InstantVector, InstantVectorElement, LabelSet, RangeVector, Table}; + + use super::*; + + fn clickhouse(query: &str, now_ms: i64) -> QueryRequest { + QueryRequest { + language: QueryLanguage::SQL(SqlDialect::ClickhouseSQL), + query: query.into(), + eval: QueryEval::Instant { time_ms: now_ms }, + } + } + + /// From ASAPQuery's `test_parse_get_request`, `test_parse_post_request_form` + /// and `test_missing_query_parameter`: the query comes from the URL + /// query, the form body or the plain body and is evaluated now; without + /// one the request is refused. + #[test] + fn parses_the_query_parameter() { + assert_eq!( + parse_query(Some("query=SELECT%201"), b"", 7), + Ok(clickhouse("SELECT 1", 7)) + ); + assert_eq!( + parse_query(None, b"query=SELECT+*+FROM+table", 7), + Ok(clickhouse("SELECT * FROM table", 7)) + ); + assert_eq!( + parse_query(None, b"SELECT count() FROM t WHERE a=1", 7), + Ok(clickhouse("SELECT count() FROM t WHERE a=1", 7)) + ); + assert_eq!(parse_query(Some("database=d"), b"", 7), Err(MissingQuery)); + assert_eq!(parse_query(None, b"\xff", 7), Err(MissingQuery)); + assert_eq!(MissingQuery.to_string(), "missing parameter \"query\""); + } + + /// ASAPQuery's `test_format_success_response`: one row per series, its + /// label values then its value. + #[test] + fn writes_an_instant_vector_as_rows() { + let series = |host: &str, value| InstantVectorElement { + labels: LabelSet::from([("hostname".to_string(), host.to_string())]), + value, + }; + let result = QueryResult::Vector(InstantVector { + timestamp_ms: 1000, + series: vec![series("host1", 91.0), series("host2", 77.5)], + }); + assert_eq!(tab_separated(&result).unwrap(), b"host1\t91\nhost2\t77.5\n"); + } + + /// A table writes its rows in column order, with values escaped and + /// floats as ClickHouse writes them; a series lacking a label another + /// has gets an empty value there. + #[test] + fn writes_tables_and_escapes_values() { + let table = QueryResult::Table(Table { + columns: vec!["job".into(), "p99".into()], + rows: vec![ + vec![ + TableValue::String("a\tb\\c\nd".into()), + TableValue::Float(0.25), + ], + vec![TableValue::String("e".into()), TableValue::Float(f64::NAN)], + vec![ + TableValue::String("f".into()), + TableValue::Float(f64::NEG_INFINITY), + ], + ], + }); + assert_eq!( + tab_separated(&table).unwrap(), + b"a\\tb\\\\c\\nd\t0.25\ne\tnan\nf\t-inf\n" + ); + let labels = |pairs: &[(&str, &str)]| -> LabelSet { + pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + }; + let vector = QueryResult::Vector(InstantVector { + timestamp_ms: 0, + series: vec![ + InstantVectorElement { + labels: labels(&[("a", "1"), ("b", "2")]), + value: 1.0, + }, + InstantVectorElement { + labels: labels(&[("b", "3")]), + value: 2.0, + }, + ], + }); + assert_eq!(tab_separated(&vector).unwrap(), b"1\t2\t1\n\t3\t2\n"); + } + + /// Ranges and scalars have no ClickHouse form (ASAPQuery answered 501). + #[test] + fn refuses_ranges_and_scalars() { + let range = QueryResult::Matrix(RangeVector { series: vec![] }); + assert_eq!( + tab_separated(&range).unwrap_err().to_string(), + "a ClickHouse response cannot hold a range result" + ); + let scalar = QueryResult::Scalar(common::Sample { + timestamp_ms: 0, + value: 1.0, + }); + assert!(tab_separated(&scalar).is_err()); + } +} diff --git a/crates/adapters/query/elastic-http/Cargo.toml b/crates/adapters/query/elastic-http/Cargo.toml new file mode 100644 index 000000000..10cda72df --- /dev/null +++ b/crates/adapters/query/elastic-http/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "elastic_http" +version.workspace = true +edition.workspace = true + +# Elasticsearch's `_sql` and `_search` HTTP APIs: request bodies, `_search` +# response bodies, and the fallback client of an Elasticsearch server. An +# adapter: of this workspace it depends on `common` only, never on an +# engine or a store. +[dependencies] +common.workspace = true +# `common::FallbackClient`'s async method. +async-trait.workspace = true +reqwest.workspace = true +serde_json.workspace = true +thiserror.workspace = true + +[dev-dependencies] +axum.workspace = true +tokio.workspace = true diff --git a/crates/adapters/query/elastic-http/src/fallback.rs b/crates/adapters/query/elastic-http/src/fallback.rs new file mode 100644 index 000000000..0f1479dd5 --- /dev/null +++ b/crates/adapters/query/elastic-http/src/fallback.rs @@ -0,0 +1,257 @@ +//! The client of an Elasticsearch server that answers the queries the data +//! plane does not, as ASAPQuery's `ElasticHttpFallback` sends them. + +use std::time::Duration; + +use async_trait::async_trait; +use common::{ + FallbackClient, FallbackError, FallbackResponse, QueryEval, QueryLanguage, QueryRequest, + SqlDialect, +}; +use reqwest::header::{self, HeaderName, HeaderValue}; + +/// Rows per page an Elasticsearch SQL query asks for, as ASAPQuery asks. +const SQL_FETCH_SIZE: u64 = 1000; + +/// Sends queries to one Elasticsearch server. +pub struct ElasticHttpFallback { + /// Without a trailing `/`. + base_url: String, + /// The index (or index pattern) a Query DSL search reads; empty: every + /// index (`/_search`). + index: String, + client: reqwest::Client, +} + +impl ElasticHttpFallback { + /// A client of the server at `base_url` whose Query DSL searches read + /// `index`, each request bounded by `timeout`, from sending it to + /// reading the whole response. + pub fn new(base_url: &str, index: &str, timeout: Duration) -> Self { + Self { + base_url: base_url.trim_end_matches('/').to_string(), + index: index.to_string(), + client: reqwest::Client::builder() + .timeout(timeout) + .build() + .expect("reqwest client with only a timeout set"), + } + } +} + +#[async_trait] +impl FallbackClient for ElasticHttpFallback { + /// Elasticsearch SQL: `POST /_sql` with `{"query", "fetch_size"}`, the + /// query without a trailing `;`. Query DSL: `POST //_search` + /// with the query as the body. Instant queries only: Elasticsearch has + /// no range queries. Header pairs that are not valid HTTP headers are + /// skipped. + async fn execute( + &self, + request: &QueryRequest, + headers: &[(String, String)], + ) -> Result { + if let QueryEval::Range { .. } = request.eval { + return Err(FallbackError::new("Elasticsearch has no range queries")); + } + let (url, body) = match &request.language { + QueryLanguage::SQL(SqlDialect::ElasticSQL) => { + let body = serde_json::json!({ + "query": request.query.trim().trim_end_matches(';'), + "fetch_size": SQL_FETCH_SIZE, + }); + (format!("{}/_sql", self.base_url), body.to_string()) + } + QueryLanguage::ElasticDSL if self.index.is_empty() => { + (format!("{}/_search", self.base_url), request.query.clone()) + } + QueryLanguage::ElasticDSL => ( + format!("{}/{}/_search", self.base_url, self.index), + request.query.clone(), + ), + language => { + let message = + format!("Elasticsearch answers its SQL and Query DSL, not {language:?}"); + return Err(FallbackError::new(message)); + } + }; + let mut upstream = self + .client + .post(url) + .header(header::CONTENT_TYPE, "application/json"); + for (name, value) in headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::try_from(name.as_str()), + HeaderValue::try_from(value.as_str()), + ) { + upstream = upstream.header(name, value); + } + } + let upstream = + upstream.body(body).send().await.map_err(|error| { + FallbackError::new(format!("forwarding to Elasticsearch: {error}")) + })?; + let status_code = upstream.status().as_u16(); + // A server that names no type sent bytes of unknown type (RFC 9110 + // section 8.3). + let content_type = upstream + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or("application/octet-stream") + .to_string(); + let body = upstream.bytes().await.map_err(|error| { + FallbackError::new(format!("reading Elasticsearch response: {error}")) + })?; + Ok(FallbackResponse { + status_code, + content_type, + body: body.into(), + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use axum::extract::{OriginalUri, State}; + use axum::http::HeaderMap; + use axum::routing::post; + use axum::Router; + + use super::*; + + /// What the mock server received: path, `Content-Type`, + /// `Authorization`, body. + type Received = Arc, String)>>>; + + /// An Elasticsearch server that records each request and answers 200 + /// with a JSON body naming its path; its base URL. + async fn server(received: Received) -> String { + async fn record( + State(received): State, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + body: String, + ) -> ([(header::HeaderName, &'static str); 1], String) { + let header = |name| { + headers + .get(name) + .map(|v: &HeaderValue| v.to_str().unwrap().to_string()) + }; + received.lock().unwrap().push(( + uri.to_string(), + header(header::CONTENT_TYPE).unwrap_or_default(), + header(header::AUTHORIZATION), + body, + )); + ( + [(header::CONTENT_TYPE, "application/json")], + format!("{{\"path\":\"{}\"}}", uri.path()), + ) + } + let app = Router::new() + .route("/_sql", post(record)) + .route("/_search", post(record)) + .route("/:index/_search", post(record)) + .with_state(received); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{address}/") + } + + fn request(language: QueryLanguage, query: &str) -> QueryRequest { + QueryRequest { + language, + query: query.into(), + eval: QueryEval::Instant { time_ms: 0 }, + } + } + + /// An SQL query is posted to `/_sql` wrapped with ASAPQuery's fetch + /// size and without its `;`; a Query DSL query to the index's + /// `_search` (or `/_search` with no index) as sent; both as JSON with + /// the client's `Authorization`. The server's response comes back + /// unchanged. + #[tokio::test] + async fn posts_sql_and_query_dsl_and_returns_the_response_unchanged() { + let received = Received::default(); + let url = server(received.clone()).await; + let fallback = ElasticHttpFallback::new(&url, "logs-*", Duration::from_secs(5)); + let headers = [("Authorization".to_string(), "ApiKey k".to_string())]; + let sql = request( + QueryLanguage::SQL(SqlDialect::ElasticSQL), + " SELECT COUNT(*) FROM logs; ", + ); + let response = fallback.execute(&sql, &headers).await.unwrap(); + assert_eq!( + response, + FallbackResponse { + status_code: 200, + content_type: "application/json".into(), + body: br#"{"path":"/_sql"}"#.to_vec(), + } + ); + let search = r#"{"query": {"match_all": {}}}"#; + fallback + .execute(&request(QueryLanguage::ElasticDSL, search), &[]) + .await + .unwrap(); + ElasticHttpFallback::new(&url, "", Duration::from_secs(5)) + .execute(&request(QueryLanguage::ElasticDSL, search), &[]) + .await + .unwrap(); + let received = received.lock().unwrap(); + let json = "application/json".to_string(); + let (path, content_type, authorization, body) = &received[0]; + assert_eq!( + (path.as_str(), content_type, authorization.as_deref()), + ("/_sql", &json, Some("ApiKey k")) + ); + assert_eq!( + serde_json::from_str::(body).unwrap(), + serde_json::json!({"query": "SELECT COUNT(*) FROM logs", "fetch_size": 1000}) + ); + assert_eq!( + received[1], + ( + "/logs-*/_search".to_string(), + json.clone(), + None, + search.to_string() + ) + ); + assert_eq!(received[2].0, "/_search"); + } + + /// A range query or a query in another language is not sent; an + /// unreachable server is an error. + #[tokio::test] + async fn refuses_what_elasticsearch_cannot_answer_and_reports_an_unreachable_server() { + let fallback = ElasticHttpFallback::new("http://127.0.0.1:1", "", Duration::from_secs(5)); + let range = QueryRequest { + eval: QueryEval::Range { + start_ms: 0, + end_ms: 60_000, + step_ms: 15_000, + }, + ..request(QueryLanguage::ElasticDSL, "{}") + }; + assert_eq!( + fallback.execute(&range, &[]).await, + Err(FallbackError::new("Elasticsearch has no range queries")) + ); + let clickhouse = request(QueryLanguage::SQL(SqlDialect::ClickhouseSQL), "SELECT 1"); + assert!(fallback.execute(&clickhouse, &[]).await.is_err()); + let error = fallback + .execute(&request(QueryLanguage::ElasticDSL, "{}"), &[]) + .await + .unwrap_err(); + assert!( + error.message.starts_with("forwarding to Elasticsearch: "), + "{error}" + ); + } +} diff --git a/crates/adapters/query/elastic-http/src/lib.rs b/crates/adapters/query/elastic-http/src/lib.rs new file mode 100644 index 000000000..c4d38a226 --- /dev/null +++ b/crates/adapters/query/elastic-http/src/lib.rs @@ -0,0 +1,194 @@ +//! Elasticsearch's HTTP query APIs as the data plane speaks them, on +//! ASAPQuery's routes: `POST /_sql` (Elasticsearch SQL) and `POST /_search` +//! (Query DSL) request bodies, `_search` response and error bodies, and the +//! [`fallback`] client that sends a query the data plane does not answer to +//! an Elasticsearch server. An adapter: it depends on `common` only. + +use common::{QueryEval, QueryLanguage, QueryRequest, QueryResult, SqlDialect}; +use serde_json::{json, Map, Value}; + +pub mod fallback; + +/// A request body that is not the query its endpoint takes: the reason. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct BadRequestBody(String); + +impl BadRequestBody { + /// The 400 body: a `parsing_exception` with the reason. + pub fn error_body(&self) -> Value { + error_body("parsing_exception", &self.0) + } +} + +/// The 400 body refusing a `GET`, ASAPQuery's reason: Elasticsearch +/// queries are posted as JSON. +pub fn get_refused_body() -> Value { + let reason = "GET requests not supported for Elasticsearch queries. Use POST with Query DSL."; + error_body("illegal_argument_exception", reason) +} + +/// The `query` string of a `_sql` body (`{"query": "SELECT …", …}`; other +/// fields such as `time_zone` are not kept), evaluated at `now_ms`: +/// Elasticsearch queries name no evaluation time. +pub fn parse_sql(body: &[u8], now_ms: i64) -> Result { + let body: Value = serde_json::from_slice(body) + .map_err(|error| BadRequestBody(format!("Invalid JSON: {error}")))?; + let query = body + .get("query") + .and_then(Value::as_str) + .ok_or_else(|| BadRequestBody("missing parameter \"query\"".into()))?; + Ok(QueryRequest { + language: QueryLanguage::SQL(SqlDialect::ElasticSQL), + query: query.to_string(), + eval: QueryEval::Instant { time_ms: now_ms }, + }) +} + +/// A `_search` body, a Query DSL JSON object, kept as sent (the fallback +/// sends these bytes), evaluated at `now_ms`. +pub fn parse_search(body: &[u8], now_ms: i64) -> Result { + let query = std::str::from_utf8(body) + .map_err(|error| BadRequestBody(format!("Invalid JSON: {error}")))?; + serde_json::from_str::>(query) + .map_err(|error| BadRequestBody(format!("Invalid JSON: {error}")))?; + Ok(QueryRequest { + language: QueryLanguage::ElasticDSL, + query: query.to_string(), + eval: QueryEval::Instant { time_ms: now_ms }, + }) +} + +/// Elasticsearch's error body for a 400: `{"error": {"type", "reason"}, +/// "status": 400}`. Sent with HTTP 400, as Elasticsearch does (ASAPQuery +/// sent it with 200). +fn error_body(error_type: &str, reason: &str) -> Value { + json!({"error": {"type": error_type, "reason": reason}, "status": 400}) +} + +/// A result a `_search` response cannot hold (anything but an instant +/// vector). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("an Elasticsearch response cannot hold a {0} result")] +pub struct UnsupportedResult(&'static str); + +/// An instant vector as a `_search` response, as ASAPQuery writes it: one +/// hit per series, whose `_source` holds its labels and its `value`. +pub fn search_response(result: &QueryResult) -> Result { + let vector = match result { + QueryResult::Vector(vector) => vector, + QueryResult::Matrix(_) => return Err(UnsupportedResult("range")), + QueryResult::Scalar(_) => return Err(UnsupportedResult("scalar")), + QueryResult::Table(_) => return Err(UnsupportedResult("table")), + }; + let hits: Vec = vector + .series + .iter() + .map(|series| { + let mut source: Map = series + .labels + .iter() + .map(|(name, value)| (name.clone(), json!(value))) + .collect(); + source.insert("value".into(), json!(series.value)); + json!({ "_source": source }) + }) + .collect(); + Ok(json!({ + "took": 0, + "timed_out": false, + "hits": {"total": {"value": hits.len(), "relation": "eq"}, "hits": hits}, + })) +} + +#[cfg(test)] +mod tests { + use common::{InstantVector, InstantVectorElement, LabelSet, RangeVector}; + + use super::*; + + /// From ASAPQuery's `test_parse_sql_query` and + /// `test_parse_sql_query_with_params`: only the `query` string is kept. + #[test] + fn parses_a_sql_body() { + let body = json!({ + "query": "SELECT status, COUNT(*) FROM logs GROUP BY status", + "time_zone": "UTC", + }); + assert_eq!( + parse_sql(body.to_string().as_bytes(), 7), + Ok(QueryRequest { + language: QueryLanguage::SQL(SqlDialect::ElasticSQL), + query: "SELECT status, COUNT(*) FROM logs GROUP BY status".into(), + eval: QueryEval::Instant { time_ms: 7 }, + }) + ); + assert_eq!( + parse_sql(br#"{"fetch_size": 10}"#, 7), + Err(BadRequestBody("missing parameter \"query\"".into())) + ); + } + + /// From ASAPQuery's `test_parse_json_post_request`, + /// `test_parse_query_with_timestamp` and `test_invalid_json`: a Query + /// DSL body is kept byte for byte; a body that is not a JSON object is + /// refused. + #[test] + fn parses_a_search_body() { + let body = r#"{"query": {"bool": {"filter": [{"range": {"@timestamp": {"gte": 1640000000.0, "lte": 1640086400.0}}}]}}}"#; + let request = parse_search(body.as_bytes(), 7).unwrap(); + assert_eq!(request.language, QueryLanguage::ElasticDSL); + assert_eq!(request.query, body); + assert_eq!(request.eval, QueryEval::Instant { time_ms: 7 }); + for bad in [&b"not valid json"[..], b"[1]", b"\xff"] { + let error = parse_search(bad, 7).unwrap_err(); + assert!(error.to_string().starts_with("Invalid JSON: "), "{error}"); + } + } + + /// ASAPQuery's `test_format_error_response`: a body that does not + /// parse is a `parsing_exception`; a `GET` an + /// `illegal_argument_exception`. + #[test] + fn writes_error_bodies() { + assert_eq!( + BadRequestBody("Invalid query syntax".into()).error_body(), + json!({"error": {"type": "parsing_exception", "reason": "Invalid query syntax"}, "status": 400}) + ); + assert_eq!( + get_refused_body()["error"]["type"], + "illegal_argument_exception" + ); + } + + /// From ASAPQuery's `test_format_success_response`: an empty vector has + /// no hits; each series is a hit of its labels and value. Other + /// results have no `_search` form (ASAPQuery answered 501). + #[test] + fn writes_an_instant_vector_as_hits() { + let empty = QueryResult::Vector(InstantVector { + timestamp_ms: 0, + series: vec![], + }); + assert_eq!( + search_response(&empty).unwrap(), + json!({"took": 0, "timed_out": false, "hits": {"total": {"value": 0, "relation": "eq"}, "hits": []}}) + ); + let one = QueryResult::Vector(InstantVector { + timestamp_ms: 0, + series: vec![InstantVectorElement { + labels: LabelSet::from([("status".to_string(), "500".to_string())]), + value: 3.0, + }], + }); + assert_eq!( + search_response(&one).unwrap()["hits"]["hits"], + json!([{"_source": {"status": "500", "value": 3.0}}]) + ); + let range = QueryResult::Matrix(RangeVector { series: vec![] }); + assert_eq!( + search_response(&range).unwrap_err().to_string(), + "an Elasticsearch response cannot hold a range result" + ); + } +} diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 6641d81b7..24896ad26 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -4,7 +4,9 @@ version.workspace = true edition.workspace = true [dependencies] +clickhouse_http.workspace = true common.workspace = true +elastic_http.workspace = true internal_metrics.workspace = true precompute.workspace = true prometheus_http.workspace = true diff --git a/crates/data-plane/src/dispatcher.rs b/crates/data-plane/src/dispatcher.rs index db25fd91d..a1d03a3b5 100644 --- a/crates/data-plane/src/dispatcher.rs +++ b/crates/data-plane/src/dispatcher.rs @@ -6,11 +6,15 @@ //! answers ([`common::Answer`]: labels shared with the //! interned series and the result cache), not through //! [`ExecutorQueryEngine::execute`]'s [`common::QueryResult`], which would -//! copy every series' labels per query. +//! copy every series' labels per query. The other protocols' routes +//! ([`QueryDispatcher::dispatch`]) go through `execute`. use std::sync::{Arc, OnceLock}; -use common::{Answer, AnswerSource, InstalledPlan, PhysicalASAPNodeId, PlanId, QueryEngineError}; +use common::{ + Answer, AnswerSource, EngineQueryResult, InstalledPlan, PhysicalASAPNodeId, PlanId, + QueryEngineError, QueryLanguage, QueryRequest, QueryResult, +}; use query::{ExecutorQueryEngine, Unanswered}; /// The dispatcher's verdict on one query. @@ -155,6 +159,29 @@ impl QueryDispatcher { Err(unanswered) => QueryOutcome::NotAnswerable(NotAnswerableReason::new(unanswered)), } } + + /// `request` through [`ExecutorQueryEngine::execute`]. Only a PromQL query can + /// be the plan's: the control plane plans PromQL workloads only, and + /// the data plane stores time series only, which SQL and Query DSL + /// plans do not read. A query in another language is unmatched, even + /// when its text equals a planned query's. + pub async fn dispatch(&self, request: &QueryRequest) -> QueryOutcome { + if request.language != QueryLanguage::PromQL { + return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched); + } + let Some(source) = self.resolve(&request.query) else { + return QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched); + }; + match self.engine.execute(&source, request).await { + Ok(EngineQueryResult::Ready { result }) => QueryOutcome::Ready(result), + Ok(EngineQueryResult::NotReady) => { + QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady( + "the stored data does not cover the query, or the plan changed".into(), + )) + } + Err(error) => QueryOutcome::NotAnswerable(NotAnswerableReason::EngineError(error)), + } + } } #[cfg(test)] @@ -258,6 +285,40 @@ mod tests { ); } + /// Through `ExecutorQueryEngine::execute`, a planned PromQL query is answered as + /// an instant vector with the values the Prometheus path gives, and is + /// not ready where that path is not; the same text in ClickHouse SQL is + /// unmatched. + #[tokio::test] + async fn dispatches_a_query_request_by_language() { + let engine = engine(&test_support::plan(QUERY, false)).await; + let dispatcher = engine.dispatcher(); + let request = |language, time_ms| QueryRequest { + language, + query: QUERY.into(), + eval: common::QueryEval::Instant { time_ms }, + }; + let QueryOutcome::Ready(QueryResult::Vector(vector)) = dispatcher + .dispatch(&request(QueryLanguage::PromQL, 30_000)) + .await + else { + panic!("not answered"); + }; + let values: Vec = vector.series.iter().map(|series| series.value).collect(); + assert_eq!((vector.timestamp_ms, values), (30_000, vec![10.0])); + assert!(matches!( + dispatcher + .dispatch(&request(QueryLanguage::PromQL, 60_000)) + .await, + QueryOutcome::NotAnswerable(NotAnswerableReason::NotReady(_)) + )); + let sql = QueryLanguage::SQL(common::SqlDialect::ClickhouseSQL); + assert_eq!( + dispatcher.dispatch(&request(sql, 30_000)).await, + QueryOutcome::NotAnswerable(NotAnswerableReason::Unmatched) + ); + } + /// Under `--no-forward` an unmatched query is refused, naming it. #[test] fn an_unmatched_query_is_refused_without_forwarding() { diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index ee3623c78..57366176b 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -1,12 +1,14 @@ //! Backend data plane: receives Prometheus Remote Write samples (and //! VictoriaMetrics Remote Write and OTLP) and serves the Prometheus query -//! API for an installed plan. +//! API for an installed plan (and, when their servers are given, the +//! ClickHouse and Elasticsearch query APIs). //! //! 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. +//! `prometheus_http`, `clickhouse_http` and `elastic_http` read query +//! requests, write responses and send what the plan does not answer to +//! their protocol's server. //! //! The installed plan is ASAPPlanner's `InstallablePlan`: one selected //! physical ASAP DAG. The precompute engine's ingest shards store the raw @@ -41,6 +43,7 @@ use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::Router; +use common::{FallbackClient, QueryRequest, QueryResult}; use dispatcher::{Fallback, NotAnswerableReason, QueryOutcome}; use engine::{EngineHandle, EngineOptions}; use precompute::engine::IngestError; @@ -72,6 +75,12 @@ pub struct DataPlane { /// 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, + /// The ClickHouse server that answers `/clickhouse/query`; `None`: the + /// route is not served. + clickhouse_fallback: Option>, + /// The Elasticsearch server that answers `/_sql` and `/_search`; + /// `None`: the routes are not served. + elastic_fallback: Option>, } impl DataPlane { @@ -103,9 +112,41 @@ impl DataPlane { limits: prometheus_remote_write::Limits::default(), fallback: PrometheusHttpFallback::new(&prometheus_url, DEFAULT_FORWARD_TIMEOUT), raw_forward: None, + clickhouse_fallback: None, + elastic_fallback: None, }) } + /// Serves ClickHouse's query route, `/clickhouse/query`, forwarding + /// every query the plan does not answer to `fallback`. Refused with + /// `--no-forward`, which forbids forwarding. + pub fn with_clickhouse_fallback( + mut self, + fallback: impl FallbackClient + 'static, + ) -> anyhow::Result { + if self.no_forward { + anyhow::bail!( + "--clickhouse-url forwards unplanned queries, which --no-forward refuses" + ); + } + self.clickhouse_fallback = Some(Arc::new(fallback)); + Ok(self) + } + + /// Serves Elasticsearch's query routes, `/_sql` and `/_search`, + /// forwarding every query the plan does not answer to `fallback`. + /// Refused with `--no-forward`, which forbids forwarding. + pub fn with_elastic_fallback( + mut self, + fallback: impl FallbackClient + 'static, + ) -> anyhow::Result { + if self.no_forward { + anyhow::bail!("--elastic-url forwards unplanned queries, which --no-forward refuses"); + } + self.elastic_fallback = Some(Arc::new(fallback)); + Ok(self) + } + /// 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 the @@ -158,7 +199,183 @@ pub fn router(state: Arc) -> Router { ) .route("/v1/metrics", post(write_otlp).layer(write_body_limit)) }; - router.with_state(state) + // Each protocol's query routes, served only with its fallback, so + // without one the path is as before (404, or proxied in forward mode). + let mut router = router.with_state(state.clone()); + if let Some(fallback) = state.clickhouse_fallback.clone() { + let route = FallbackRoute { + plane: state.clone(), + fallback, + }; + router = router.merge( + Router::new() + .route( + "/clickhouse/query", + get(clickhouse_query).post(clickhouse_query), + ) + .with_state(route), + ); + } + if let Some(fallback) = state.elastic_fallback.clone() { + let route = FallbackRoute { + plane: state.clone(), + fallback, + }; + router = router.merge( + Router::new() + .route("/_sql", post(elastic_sql).get(refuse_elastic_get)) + .route("/_search", post(elastic_search).get(refuse_elastic_get)) + .with_state(route), + ); + } + router +} + +/// The state of one protocol's query routes: the data plane, and the +/// server that answers what the plan does not. +#[derive(Clone)] +struct FallbackRoute { + plane: Arc, + fallback: Arc, +} + +/// `GET` or `POST /clickhouse/query` (ASAPQuery's ClickHouse route): the +/// query ([`clickhouse_http::parse_query`]), evaluated now. +/// Answered from the plan as TabSeparated, or forwarded to ClickHouse +/// ([`answer_or_forward`]); 400 without a query. +async fn clickhouse_query( + State(route): State, + RawQuery(query): RawQuery, + headers: HeaderMap, + body: Bytes, +) -> Response { + let now_ms = precompute::ingestion::wall_clock_ms(); + let request = match clickhouse_http::parse_query(query.as_deref(), &body, now_ms) { + Ok(request) => request, + Err(missing) => return (StatusCode::BAD_REQUEST, missing.to_string()).into_response(), + }; + answer_or_forward(&route, &request, &headers, |result| { + let body = clickhouse_http::tab_separated(result).map_err(|e| e.to_string())?; + let content_type = clickhouse_http::TAB_SEPARATED_CONTENT_TYPE; + Ok(([(header::CONTENT_TYPE, content_type)], body).into_response()) + }) + .await +} + +/// `POST /_sql` (ASAPQuery's Elasticsearch SQL route): the body's `query`, +/// evaluated now ([`elastic_query`]). +async fn elastic_sql( + State(route): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + elastic_query( + &route, + elastic_http::parse_sql(&body, precompute::ingestion::wall_clock_ms()), + &headers, + ) + .await +} + +/// `POST /_search` (ASAPQuery's Query DSL route): the body, evaluated now +/// ([`elastic_query`]). +async fn elastic_search( + State(route): State, + headers: HeaderMap, + body: Bytes, +) -> Response { + elastic_query( + &route, + elastic_http::parse_search(&body, precompute::ingestion::wall_clock_ms()), + &headers, + ) + .await +} + +/// Answers a parsed Elasticsearch request from the plan as `_search` hits, +/// or forwards it to Elasticsearch ([`answer_or_forward`]); a body that +/// does not parse is 400 `parsing_exception`. +async fn elastic_query( + route: &FallbackRoute, + parsed: Result, + headers: &HeaderMap, +) -> Response { + let request = match parsed { + Ok(request) => request, + Err(bad) => { + return (StatusCode::BAD_REQUEST, axum::Json(bad.error_body())).into_response(); + } + }; + answer_or_forward(route, &request, headers, |result| { + let body = elastic_http::search_response(result).map_err(|e| e.to_string())?; + Ok(axum::Json(body).into_response()) + }) + .await +} + +/// `GET /_sql` or `/_search`: 400 `illegal_argument_exception`; +/// Elasticsearch queries are posted as JSON. +async fn refuse_elastic_get() -> Response { + let body = elastic_http::get_refused_body(); + (StatusCode::BAD_REQUEST, axum::Json(body)).into_response() +} + +/// Answers `request` from the plan through the dispatcher, written by +/// `encode` (`x-asap-execution: plan`; 501 with the reason when the +/// protocol cannot express the result). Otherwise sends it to the route's +/// fallback with the client's `Authorization` (the one header ASAPQuery +/// forwards) and +/// answers with the server's status, `Content-Type` and body +/// (`x-asap-execution: forwarded`, and `x-asap-forward-reason` for a +/// planned query the plan did not answer); 502 with the reason when the +/// server cannot be reached or its response cannot be read. +async fn answer_or_forward( + route: &FallbackRoute, + request: &QueryRequest, + headers: &HeaderMap, + encode: impl FnOnce(&QueryResult) -> Result, +) -> Response { + let reason = match route.plane.engine.dispatcher().dispatch(request).await { + QueryOutcome::Ready(result) => { + return match encode(&result) { + Ok(mut response) => { + response + .headers_mut() + .insert(EXECUTION_HEADER, HeaderValue::from_static("plan")); + response + } + Err(reason) => (StatusCode::NOT_IMPLEMENTED, reason).into_response(), + }; + } + QueryOutcome::NotAnswerable(reason) => { + match Fallback::new(reason, &request.query, route.plane.no_forward) { + Fallback::Forward { reason } => reason, + // A route with a fallback is never served with --no-forward. + Fallback::Refuse { reason } => return not_answered(&reason), + } + } + }; + let authorization: Vec<(String, String)> = headers + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .map(|value| (header::AUTHORIZATION.to_string(), value.to_string())) + .into_iter() + .collect(); + let upstream = match route.fallback.execute(request, &authorization).await { + Ok(upstream) => upstream, + Err(error) => return (StatusCode::BAD_GATEWAY, error.message).into_response(), + }; + let status = StatusCode::from_u16(upstream.status_code).unwrap_or(StatusCode::BAD_GATEWAY); + let mut response = (status, upstream.body).into_response(); + if let Ok(content_type) = HeaderValue::from_str(&upstream.content_type) { + response + .headers_mut() + .insert(header::CONTENT_TYPE, content_type); + } + response + .headers_mut() + .insert(EXECUTION_HEADER, HeaderValue::from_static("forwarded")); + with_forward_reason(response, reason) } /// Forward mode: proxies a request the data plane does not serve to the raw diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index 66eac7976..f80e55f85 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -110,6 +110,23 @@ struct Args { /// `--no-forward`. #[arg(long, conflicts_with = "no_forward")] raw_store_url: Option, + /// A ClickHouse server's HTTP interface base URL: serves ClickHouse's + /// query route, `/clickhouse/query`, which forwards every query the plan + /// does not answer to it. Cannot be used with `--no-forward`. + #[arg(long, conflicts_with = "no_forward")] + clickhouse_url: Option, + /// The database forwarded ClickHouse queries run in. + #[arg(long, default_value = "default")] + clickhouse_database: String, + /// An Elasticsearch base URL: serves Elasticsearch's query routes, + /// `/_sql` and `/_search`, which forward every query the plan does not + /// answer to it. Cannot be used with `--no-forward`. + #[arg(long, conflicts_with = "no_forward")] + elastic_url: Option, + /// The index (or index pattern) forwarded Query DSL searches read; + /// empty: every index. + #[arg(long, default_value = "")] + elastic_index: 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)] @@ -180,48 +197,64 @@ async fn main() -> anyhow::Result<()> { .init(); let args = Args::parse(); let plan = std::fs::read_to_string(&args.plan)?; - let state = Arc::new( - DataPlane::with_options( - plan, - args.prometheus_url, - EngineOptions { - ingestion: IngestionOptions { - allowed_lateness_ms: args.allowed_lateness_ms, - max_future_ms: args.max_future_ms, - stream_start_ms: args.stream_start_ms, - view_retention_margin_ms: args.view_retention_margin_ms, - }, - max_queued_samples: args.max_queued_samples, - max_precompute_backlog: args.max_precompute_backlog, - ingest_threads: args.ingest_threads, - precompute_threads: args.precompute_threads, - persist_threads: args.persist_threads, - max_persist_backlog_bytes: args.max_persist_backlog_bytes, - no_forward: args.no_forward, - run_memory_limit_bytes: args.run_memory_limit_bytes, - query_threads: args.query_threads, - share_one_evaluation_results: !args.no_shared_results, - query_time_results_retention_ms: args.query_time_results_retention_ms, - query_time_results_max_bytes: args.query_time_results_max_bytes, - result_cache: !args.no_result_cache, - result_cache_max_bytes: args.result_cache_bytes, - view_dir: (!args.no_view_persistence).then_some(args.view_dir), - view_sync_interval_ms: args.view_sync_interval_ms, - view_cache_max_bytes: args.view_cache_max_bytes, - view_cache_idle_ms: args.view_cache_idle_ms, - view_segment_ms: args.view_segment_ms, - view_read: args.view_read, - precompute_mode: args.precompute_mode, - precompute_memory_budget_bytes: args.precompute_memory_budget_bytes, - push_batching: precompute::push::MorselBatching { - max_samples: args.push_batch_samples, - max_age_ms: args.push_batch_max_ms, - }, - ..EngineOptions::default() + let forward_timeout = Duration::from_secs(args.forward_timeout_seconds); + let mut state = DataPlane::with_options( + plan, + args.prometheus_url, + EngineOptions { + ingestion: IngestionOptions { + allowed_lateness_ms: args.allowed_lateness_ms, + max_future_ms: args.max_future_ms, + stream_start_ms: args.stream_start_ms, + view_retention_margin_ms: args.view_retention_margin_ms, + }, + max_queued_samples: args.max_queued_samples, + max_precompute_backlog: args.max_precompute_backlog, + ingest_threads: args.ingest_threads, + precompute_threads: args.precompute_threads, + persist_threads: args.persist_threads, + max_persist_backlog_bytes: args.max_persist_backlog_bytes, + no_forward: args.no_forward, + run_memory_limit_bytes: args.run_memory_limit_bytes, + query_threads: args.query_threads, + share_one_evaluation_results: !args.no_shared_results, + query_time_results_retention_ms: args.query_time_results_retention_ms, + query_time_results_max_bytes: args.query_time_results_max_bytes, + result_cache: !args.no_result_cache, + result_cache_max_bytes: args.result_cache_bytes, + view_dir: (!args.no_view_persistence).then_some(args.view_dir), + view_sync_interval_ms: args.view_sync_interval_ms, + view_cache_max_bytes: args.view_cache_max_bytes, + view_cache_idle_ms: args.view_cache_idle_ms, + view_segment_ms: args.view_segment_ms, + view_read: args.view_read, + precompute_mode: args.precompute_mode, + precompute_memory_budget_bytes: args.precompute_memory_budget_bytes, + push_batching: precompute::push::MorselBatching { + max_samples: args.push_batch_samples, + max_age_ms: args.push_batch_max_ms, }, - )? - .with_forward_timeout(Duration::from_secs(args.forward_timeout_seconds)), - ); + ..EngineOptions::default() + }, + )? + .with_forward_timeout(forward_timeout); + if let Some(url) = &args.clickhouse_url { + let fallback = clickhouse_http::fallback::ClickHouseHttpFallback::new( + url, + &args.clickhouse_database, + forward_timeout, + ); + state = state.with_clickhouse_fallback(fallback)?; + } + if let Some(url) = &args.elastic_url { + let fallback = elastic_http::fallback::ElasticHttpFallback::new( + url, + &args.elastic_index, + forward_timeout, + ); + state = state.with_elastic_fallback(fallback)?; + } + let state = Arc::new(state); let state = match &args.raw_store_url { Some(url) => { let mut options = data_plane::raw_forward::RawForwardOptions::new(url.clone()); diff --git a/crates/data-plane/tests/query_protocols.rs b/crates/data-plane/tests/query_protocols.rs new file mode 100644 index 000000000..0285b1887 --- /dev/null +++ b/crates/data-plane/tests/query_protocols.rs @@ -0,0 +1,386 @@ +//! The ClickHouse (`/clickhouse/query`) and Elasticsearch (`/_sql`, +//! `/_search`) query routes: each request goes through the dispatcher, +//! and what the plan does not answer reaches that protocol's server +//! through its `common::FallbackClient`. The control plane plans PromQL +//! only, so every such query is forwarded, even one whose text is a +//! planned PromQL query. + +mod common; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Body; +use axum::extract::{OriginalUri, State}; +use axum::http::{header, HeaderMap, Request, StatusCode}; +use axum::routing::post; +use axum::Router; +use clickhouse_http::fallback::ClickHouseHttpFallback; +use data_plane::engine::EngineOptions; +use data_plane::{router, DataPlane, EXECUTION_HEADER}; +use elastic_http::fallback::ElasticHttpFallback; +use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; +use prometheus_remote_write::{Label, Sample, TimeSeries}; +use serde_json::{json, Value}; +use tower::ServiceExt; + +const QUERY: &str = "sum by (job) (sum_over_time(data[1m]))"; + +/// What the mock server received: path and query, `Authorization`, body. +type Received = Arc, String)>>>; + +/// One server standing in for ClickHouse (`POST /`: a TabSeparated row, or +/// 404 with ClickHouse's exception for a query on `missing`) and for +/// Elasticsearch (`/_sql`, `//_search`: JSON naming the path). It +/// records each request; its base URL. +async fn upstream(received: Received) -> String { + async fn record( + State(received): State, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + body: String, + ) -> (StatusCode, [(header::HeaderName, &'static str); 1], String) { + let authorization = headers + .get(header::AUTHORIZATION) + .map(|v| v.to_str().unwrap().to_string()); + let answer = if uri.path() != "/" { + let body = format!("{{\"path\":\"{}\"}}", uri.path()); + ( + StatusCode::OK, + [(header::CONTENT_TYPE, "application/json")], + body, + ) + } else if body.contains("missing") { + let exception = "Code: 60. DB::Exception: Table default.missing does not exist."; + ( + StatusCode::NOT_FOUND, + [(header::CONTENT_TYPE, "text/plain; charset=UTF-8")], + exception.into(), + ) + } else { + let tsv = "text/tab-separated-values; charset=UTF-8"; + (StatusCode::OK, [(header::CONTENT_TYPE, tsv)], "1\n".into()) + }; + received + .lock() + .unwrap() + .push((uri.to_string(), authorization, body)); + answer + } + let app = Router::new() + .route("/", post(record)) + .route("/_sql", post(record)) + .route("/:index/_search", post(record)) + .with_state(received); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{address}") +} + +/// Forwarding allowed, every window refreshed. +fn options() -> EngineOptions { + EngineOptions { + ingestion: IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..EngineOptions::default() + } +} + +fn data_plane() -> DataPlane { + DataPlane::with_options( + common::one_query_plan_json(QUERY, 2, json!({})), + "http://127.0.0.1:1".into(), + options(), + ) + .unwrap() +} + +/// A data plane serving both protocols, forwarding to `url`. +fn app(url: &str) -> Router { + let timeout = Duration::from_secs(5); + let state = data_plane() + .with_clickhouse_fallback(ClickHouseHttpFallback::new(url, "metrics", timeout)) + .unwrap() + .with_elastic_fallback(ElasticHttpFallback::new(url, "logs", timeout)) + .unwrap(); + router(Arc::new(state)) +} + +/// The response's status, `Content-Type`, `x-asap-execution` and body. +async fn send( + app: &Router, + request: Request, +) -> (StatusCode, Option, Option, Vec) { + let response = app.clone().oneshot(request).await.unwrap(); + let header = |name: &str| { + response + .headers() + .get(name) + .map(|v| v.to_str().unwrap().to_string()) + }; + let (content_type, execution) = (header("content-type"), header(EXECUTION_HEADER)); + assert!(response.headers().get("x-asap-forward-reason").is_none()); + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + (status, content_type, execution, body.to_vec()) +} + +fn json_post(uri: &str, body: &str) -> Request { + Request::post(uri) + .header(header::CONTENT_TYPE, "application/json") + .header(header::AUTHORIZATION, "ApiKey k") + .body(Body::from(body.to_string())) + .unwrap() +} + +/// A ClickHouse query, from the URL query, a form or a plain SQL body, is +/// posted to +/// ClickHouse with the client's `Authorization`, and its answer, an +/// exception included, is returned unchanged; a request without a query +/// is refused without forwarding. +#[tokio::test] +async fn clickhouse_queries_are_answered_by_clickhouse() { + let received = Received::default(); + let app = app(&upstream(received.clone()).await); + let get = Request::get("/clickhouse/query?query=SELECT%201") + .header(header::AUTHORIZATION, "Basic dTpw") + .body(Body::empty()) + .unwrap(); + let tsv = Some("text/tab-separated-values; charset=UTF-8".to_string()); + let forwarded = Some("forwarded".to_string()); + assert_eq!( + send(&app, get).await, + ( + StatusCode::OK, + tsv.clone(), + forwarded.clone(), + b"1\n".to_vec() + ) + ); + let form = Request::post("/clickhouse/query") + .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") + .body(Body::from("query=SELECT+*+FROM+missing")) + .unwrap(); + let (status, _, execution, body) = send(&app, form).await; + assert_eq!((status, execution), (StatusCode::NOT_FOUND, forwarded)); + assert!(body.starts_with(b"Code: 60. DB::Exception")); + let plain = Request::post("/clickhouse/query") + .body(Body::from("SELECT count() FROM t WHERE a=1")) + .unwrap(); + assert_eq!(send(&app, plain).await.0, StatusCode::OK); + let no_query = Request::get("/clickhouse/query") + .body(Body::empty()) + .unwrap(); + let (status, _, _, body) = send(&app, no_query).await; + assert_eq!( + (status, body), + ( + StatusCode::BAD_REQUEST, + b"missing parameter \"query\"".to_vec() + ) + ); + assert_eq!( + *received.lock().unwrap(), + [ + ( + "/?database=metrics".to_string(), + Some("Basic dTpw".to_string()), + "SELECT 1".to_string() + ), + ( + "/?database=metrics".to_string(), + None, + "SELECT * FROM missing".to_string() + ), + ( + "/?database=metrics".to_string(), + None, + "SELECT count() FROM t WHERE a=1".to_string() + ), + ] + ); +} + +/// With the plan's views stored, the planned PromQL query is answered +/// from them on the Prometheus route, but the same text on the ClickHouse +/// route is not the plan's query: it is forwarded to ClickHouse. +#[tokio::test] +async fn a_planned_promql_text_is_not_answered_as_clickhouse_sql() { + let received = Received::default(); + let app = app(&upstream(received.clone()).await); + let series = |job: &str| TimeSeries { + labels: [("__name__", "data"), ("job", job)] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value: value.into(), + }) + .collect(), + samples: (1..=120) + .map(|second| Sample { + timestamp: second * 1000, + value: 1.0, + }) + .collect(), + }; + common::remote_write(&app, vec![series("a"), series("b")]).await; + common::barrier(&app, 120_000).await; + let (status, execution, body) = common::get(&app, &common::instant_uri(QUERY, 120)).await; + assert_eq!( + (status, execution.as_deref()), + (StatusCode::OK, Some("plan")) + ); + assert_eq!( + common::per_job(&body), + [("a".to_string(), 60.0), ("b".to_string(), 60.0)] + ); + let uri = format!( + "/clickhouse/query?query={}", + form_urlencoded::byte_serialize(QUERY.as_bytes()).collect::() + ); + let (status, _, execution, _) = + send(&app, Request::get(uri).body(Body::empty()).unwrap()).await; + assert_eq!( + (status, execution.as_deref()), + (StatusCode::OK, Some("forwarded")) + ); + assert_eq!(received.lock().unwrap()[0].2, QUERY); +} + +/// An Elasticsearch SQL query is posted to `/_sql` and a Query DSL search +/// to the index's `_search`, as sent, with the client's `Authorization`; +/// a body that does not parse is 400 `parsing_exception` and a `GET` 400 +/// `illegal_argument_exception` (ASAPQuery's error bodies, sent with HTTP +/// 400 as Elasticsearch sends them), without forwarding. +#[tokio::test] +async fn elasticsearch_queries_are_answered_by_elasticsearch() { + let received = Received::default(); + let app = app(&upstream(received.clone()).await); + let json_type = Some("application/json".to_string()); + let forwarded = Some("forwarded".to_string()); + let sql = json_post("/_sql", r#"{"query": "SELECT COUNT(*) FROM logs;"}"#); + assert_eq!( + send(&app, sql).await, + ( + StatusCode::OK, + json_type.clone(), + forwarded.clone(), + br#"{"path":"/_sql"}"#.to_vec() + ) + ); + let search = r#"{"query": {"match_all": {}}}"#; + let (status, _, execution, body) = send(&app, json_post("/_search", search)).await; + assert_eq!( + (status, execution, body), + ( + StatusCode::OK, + forwarded, + br#"{"path":"/logs/_search"}"#.to_vec() + ) + ); + for (request, error_type) in [ + (json_post("/_search", "not json"), "parsing_exception"), + (json_post("/_sql", "{}"), "parsing_exception"), + ( + Request::get("/_search").body(Body::empty()).unwrap(), + "illegal_argument_exception", + ), + ] { + let (status, _, execution, body) = send(&app, request).await; + assert_eq!((status, execution), (StatusCode::BAD_REQUEST, None)); + let body: Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + (&body["error"]["type"], &body["status"]), + (&json!(error_type), &json!(400)) + ); + } + let received = received.lock().unwrap(); + assert_eq!(received.len(), 2); + let (path, authorization, body) = &received[0]; + assert_eq!( + (path.as_str(), authorization.as_deref()), + ("/_sql", Some("ApiKey k")) + ); + assert_eq!( + serde_json::from_str::(body).unwrap(), + json!({"query": "SELECT COUNT(*) FROM logs", "fetch_size": 1000}) + ); + assert_eq!(received[1].0, "/logs/_search"); + assert_eq!(received[1].2, search); +} + +/// Without a server for a protocol its routes are not served (404, as +/// before); `--no-forward` refuses either server; an unreachable server is +/// 502. +#[tokio::test] +async fn protocol_routes_need_their_server() { + let without = router(Arc::new(data_plane())); + for uri in ["/clickhouse/query?query=SELECT%201", "/_sql", "/_search"] { + let request = Request::post(uri).body(Body::empty()).unwrap(); + assert_eq!( + send(&without, request).await.0, + StatusCode::NOT_FOUND, + "{uri}" + ); + } + let refusing = || { + DataPlane::with_options( + common::one_query_plan_json(QUERY, 2, json!({})), + "http://127.0.0.1:1".into(), + common::no_forward_options(), + ) + .unwrap() + }; + let timeout = Duration::from_secs(5); + let clickhouse = ClickHouseHttpFallback::new("http://127.0.0.1:1", "default", timeout); + assert!(refusing().with_clickhouse_fallback(clickhouse).is_err()); + let elastic = ElasticHttpFallback::new("http://127.0.0.1:1", "", timeout); + assert!(refusing().with_elastic_fallback(elastic).is_err()); + let app = app("http://127.0.0.1:1"); + let request = Request::get("/clickhouse/query?query=SELECT%201") + .body(Body::empty()) + .unwrap(); + let (status, _, execution, body) = send(&app, request).await; + assert_eq!((status, execution), (StatusCode::BAD_GATEWAY, None)); + assert!(body.starts_with(b"forwarding to ClickHouse: ")); +} + +/// In forward mode a protocol's routes still go to its own server, and +/// every other path is still proxied to the raw store. +#[tokio::test] +async fn forward_mode_keeps_protocol_routes_and_proxies_the_rest() { + let received = Received::default(); + let url = upstream(received.clone()).await; + let state = data_plane() + .with_raw_forward(data_plane::raw_forward::RawForwardOptions::new(url.clone())) + .unwrap() + .with_elastic_fallback(ElasticHttpFallback::new( + &url, + "logs", + Duration::from_secs(5), + )) + .unwrap(); + let app = router(Arc::new(state)); + let search = r#"{"query": {"match_all": {}}}"#; + let (status, _, execution, body) = send(&app, json_post("/_search", search)).await; + assert_eq!( + (status, execution.as_deref(), body), + ( + StatusCode::OK, + Some("forwarded"), + br#"{"path":"/logs/_search"}"#.to_vec() + ) + ); + // The mock has no such route: its 404, proxied. + let labels = Request::get("/api/v1/labels").body(Body::empty()).unwrap(); + let (status, _, execution, _) = send(&app, labels).await; + assert_eq!( + (status, execution.as_deref()), + (StatusCode::NOT_FOUND, Some("forwarded")) + ); +}