feat(postgres): OTLP binary payload ingest via COPY FROM STDIN (metrics, traces, logs) (#10050)

feat(postgres): OTLP binary payload ingest via COPY FROM STDIN

COPY FROM STDIN WITH (FORMAT otlp [, signal '...'] [, <options>]) ingests
one binary OTLP protobuf message over the postgres wire protocol — the
first binary COPY format (wire format code 1) — for all three signals:

- signal 'metrics' (default): ExportMetricsServiceRequest, completed
  through OpenTelemetryProtocolHandler::metrics with the same context
  preparation as the HTTP route (OtlpMetricCtx from the options); rows
  are accepted data points.
- signal 'traces': ExportTraceServiceRequest through ::traces, with the
  trace table name and pipeline name/version/params from the options
  (an explicit pipeline name is required, exactly like the HTTP traces
  endpoint); rows are accepted spans.
- signal 'logs': ExportLogsServiceRequest through ::logs, with the log
  table name, pipeline options and extract keys from the options, and
  the same OtlpLogDirect default as the HTTP route; rows are affected
  rows.

The WITH options carry what the HTTP endpoints take as request headers,
reusing the HTTP path's own parsing helpers (truthy, SelectInfo,
GreptimePipelineParams, PipelineWay) so the two routes cannot drift;
values already provided by the postgres session (database, user,
permissions) are not repeated. Option semantics match the headers:
promote_all_resource_attrs / resource_attrs (';'-separated include or
exclude list) / promote_scope_attrs / translation_strategy for metrics;
table_name / pipeline_name / pipeline_version / pipeline_params /
extract_keys for traces and logs. Signal-inapplicable options are
rejected.

Like the influxdb format: table-less (a named table is rejected), the
whole payload is buffered until CopyDone exactly like one OTLP/HTTP
request body and bounded by the shared 64 MiB request limit, decoding
uses the same protobuf types, and the server must be wired —
PostgresServer::with_otlp_handler(handler, with_metric_engine) carries
the same metric-engine flag the HTTP wiring passes from its options.
The pipeline handler is derived from the protocol handler via trait
upcasting, as the HTTP routes do.

e2e: chunked binary metrics ingest; traces with table_name and
pipeline_name options; logs on the default table; metrics
promote_all_resource_attrs making a resource attribute queryable;
invalid-payload failure with connection reuse.

Signed-off-by: Ning Sun <sunning@greptime.com>
This commit is contained in:
Ning Sun
2026-11-02 08:57:05 +00:00
committed by GitHub
parent 94d71196cf
commit a09ebc70e6
8 changed files with 935 additions and 13 deletions
+2
View File
@@ -409,6 +409,7 @@ where
if opts.postgres.enable {
// Init PosgresSQL Server
let with_metric_engine = effective_prom_store_options(&opts).with_metric_engine;
let opts = &opts.postgres;
let pg_addr = parse_addr(&opts.addr)?;
@@ -430,6 +431,7 @@ where
Some(self.instance.process_manager().clone()),
)
.with_influxdb_handler(instance.clone())
.with_otlp_handler(instance.clone(), with_metric_engine)
.with_batching_enabled(postgres_batching),
) as Box<dyn Server>;
+15 -1
View File
@@ -44,7 +44,9 @@ use session::context::Channel;
use self::auth_handler::{PgUserProviderSource, ZeroPidSecretKeyGenerator};
use self::handler::DefaultQueryParser;
use crate::query_handler::sql::ServerSqlQueryHandlerRef;
use crate::query_handler::{CopyInHandlerRef, InfluxdbLineProtocolHandlerRef};
use crate::query_handler::{
CopyInHandlerRef, InfluxdbLineProtocolHandlerRef, OpenTelemetryProtocolHandlerRef,
};
pub(crate) struct GreptimeDBStartupParameters {
version: String,
@@ -86,6 +88,12 @@ pub struct PostgresServerHandlerInner {
/// Absent on servers not wired for it; such connections reject the
/// influxdb format when a copy starts.
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
/// Executes the OTLP payload flushed by a table-less
/// `COPY FROM STDIN WITH (FORMAT otlp)` — the same handler the
/// OTLP/HTTP endpoints use — plus the with-metric-engine flag the
/// HTTP wiring passes from its options.
otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
otlp_with_metric_engine: bool,
force_tls: bool,
auth_driver: AuthDriver<Arc<GreptimeDBStartupParameters>, UserInfoRef>,
/// SCRAM selected; failures get the uniform metric label.
@@ -106,6 +114,10 @@ pub(crate) struct MakePostgresServerHandler {
copy_in_handler: CopyInHandlerRef,
#[builder(default)]
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
#[builder(default)]
otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
#[builder(default)]
otlp_with_metric_engine: bool,
user_provider: Option<UserProviderRef>,
#[builder(default = "Arc::new(GreptimeDBStartupParameters::new())")]
param_provider: Arc<GreptimeDBStartupParameters>,
@@ -157,6 +169,8 @@ impl MakePostgresServerHandler {
.map(|p| Arc::new(PgUserProviderSource::new(p))),
copy_in_handler: self.copy_in_handler.clone(),
influxdb_handler: self.influxdb_handler.clone(),
otlp_handler: self.otlp_handler.clone(),
otlp_with_metric_engine: self.otlp_with_metric_engine,
force_tls: self.force_tls,
auth_driver: AuthDriver::new(self.param_provider.clone())
.with_pid_secret_key_generator(Arc::new(ZeroPidSecretKeyGenerator)),
@@ -55,6 +55,7 @@ use pgwire::error::PgWireResult;
use crate::postgres::copy_in::csv::CsvCodec;
use crate::postgres::copy_in::influxdb::InfluxdbOptions;
use crate::postgres::copy_in::otlp::OtlpOptions;
/// A resolved COPY FROM STDIN format with its validated options.
#[derive(Debug, Clone)]
@@ -67,6 +68,12 @@ pub(super) enum CopyFormat {
/// pipeline the HTTP write endpoints use (one COPY statement is one
/// ingestion request; streaming ingest is not supported).
Influxdb(InfluxdbOptions),
/// Table-less, **binary** OTLP: one `ExportMetricsServiceRequest`,
/// `ExportTraceServiceRequest` or `ExportLogsServiceRequest`
/// protobuf message, buffered whole and completed through the
/// matching OTLP pipeline the OTLP/HTTP endpoints use. Advertises
/// wire format code 1.
Otlp(OtlpOptions),
}
/// A parsed, insertable row: one gRPC value per targeted column, in COPY
+222 -9
View File
@@ -35,12 +35,14 @@ mod codec;
mod csv;
mod influxdb;
mod options;
mod otlp;
mod parse;
use std::fmt::Debug;
use std::sync::Arc;
use crate::influxdb::InfluxdbRequest;
use crate::query_handler::PipelineHandlerRef;
use api::helper::ColumnDataTypeWrapper;
use api::v1::column_def::options_from_column_schema;
use api::v1::{
@@ -48,6 +50,7 @@ use api::v1::{
};
use async_trait::async_trait;
use codec::{CopyFormat, RecordParser};
use common_catalog::consts::{TRACE_TABLE_NAME, TRACE_TABLE_NAME_SESSION_KEY};
use common_grpc::precision::Precision;
use common_query::OutputData;
use common_telemetry::{info, warn};
@@ -57,12 +60,15 @@ use datatypes::data_type::DataType;
use datatypes::schema::{ColumnSchema, SchemaRef};
use futures::{Sink, SinkExt, stream};
use influxdb::InfluxdbOptions;
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
use otlp::{OtlpOptions, OtlpSignal};
use pgwire::api::copy::CopyHandler;
use pgwire::api::results::{CopyResponse, Response, Tag};
use pgwire::api::{ClientInfo, PgWireConnectionState};
use pgwire::error::{ErrorInfo, PgWireError, PgWireResult};
use pgwire::messages::PgWireBackendMessage;
use pgwire::messages::copy::{CopyData, CopyDone, CopyFail};
use prost::Message;
use session::context::QueryContextRef;
use table::metadata::TableInfo;
@@ -84,11 +90,10 @@ use crate::postgres::utils::convert_err;
/// the per-batch fixed costs negligible.
pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768;
/// Upper bound of an influxdb COPY FROM STDIN payload. One COPY
/// statement is one bounded ingestion request (the whole payload is
/// buffered like one HTTP write body); a larger import is multiple COPY
/// statements. Streaming ingest may arrive later, with framing owned by
/// the shared line-protocol parser rather than the COPY layer.
/// Upper bound of a table-less COPY FROM STDIN payload (influxdb line
/// protocol, OTLP). One COPY statement is one bounded ingestion request
/// (the whole payload is buffered like one HTTP request body); a larger
/// import is multiple COPY statements.
pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
/// Builds a format from the format-neutral option set.
@@ -102,6 +107,8 @@ const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[
("csv", csv::build_csv_codec),
("influxdb", influxdb::build_influxdb_codec),
("influxdb_line", influxdb::build_influxdb_codec),
("otlp", otlp::build_otlp_codec),
("otlp_metrics", otlp::build_otlp_codec),
("text", build_unimplemented_text_codec),
("txt", build_unimplemented_text_codec),
("binary", build_unimplemented_binary_codec),
@@ -268,6 +275,10 @@ enum Payload {
data: Vec<u8>,
precision: Option<Precision>,
},
/// The whole buffered OTLP payload with its validated options,
/// decoded and completed as one request at `CopyDone` through the
/// matching OTLP pipeline.
Otlp { data: Vec<u8>, options: OtlpOptions },
}
impl CopyInState {
@@ -327,6 +338,22 @@ impl CopyInState {
}
}
/// State for the OTLP format: the whole binary payload is buffered
/// and completed once at `CopyDone` through the matching OTLP
/// pipeline. Binary: the advertised wire format code is 1.
fn new_otlp(options: &OtlpOptions, query_ctx: QueryContextRef) -> Self {
Self {
query_ctx,
payload: Payload::Otlp {
data: Vec::new(),
options: options.clone(),
},
codec_name: "otlp",
codec_format_code: 1,
rows_written: 0,
}
}
/// The wire format code advertised to the client.
pub(crate) fn format_code(&self) -> i8 {
self.codec_format_code
@@ -337,7 +364,7 @@ impl CopyInState {
fn feed(&mut self, data: &[u8]) -> PgWireResult<()> {
match &mut self.payload {
Payload::Table { parser, rows, .. } => rows.extend(parser.feed(data)?),
Payload::Influxdb { data: buffered, .. } => {
Payload::Influxdb { data: buffered, .. } | Payload::Otlp { data: buffered, .. } => {
if buffered.len() + data.len() > COPY_IN_MAX_PAYLOAD_BYTES {
return Err(bad_copy_data(format!(
"COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements",
@@ -356,7 +383,7 @@ impl CopyInState {
match &mut self.payload {
Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?),
// The whole payload is one request body; nothing to finalize.
Payload::Influxdb { .. } => {}
Payload::Influxdb { .. } | Payload::Otlp { .. } => {}
}
Ok(())
}
@@ -365,7 +392,7 @@ impl CopyInState {
match &self.payload {
Payload::Table { rows, .. } => rows.len() >= COPY_IN_FLUSH_ROWS,
// Completed once at CopyDone, not mid-stream.
Payload::Influxdb { .. } => false,
Payload::Influxdb { .. } | Payload::Otlp { .. } => false,
}
}
@@ -395,6 +422,17 @@ impl CopyInState {
})
}
/// Takes the buffered OTLP payload and its options, if any.
fn take_otlp(&mut self) -> Option<(OtlpOptions, Vec<u8>)> {
let Payload::Otlp { options, data } = &mut self.payload else {
return None;
};
if data.is_empty() {
return None;
}
Some((options.clone(), std::mem::take(data)))
}
/// Takes the buffered payload as one line-protocol request body, if
/// any — the same bytes an HTTP write of the same records would
/// carry.
@@ -558,11 +596,26 @@ impl PostgresServerHandlerInner {
}
CopyInState::new_influxdb(options, query_ctx)
}
// OTLP forbids a target table too — the payload's resource
// metrics route to their own tables — and completes through
// the OTLP metrics pipeline; the server must be wired.
CopyFormat::Otlp(options) => {
if !stmt.table.is_empty() {
return Err(unsupported(format!(
"format otlp routes each record to its own table; \"COPY {} FROM STDIN\" must not name one",
stmt.table.join(".")
)));
}
if self.otlp_handler.is_none() {
return Err(unsupported("this server is not wired for the otlp format"));
}
CopyInState::new_otlp(options, query_ctx)
}
};
let num_columns = match &state.payload {
Payload::Table { grpc_schema, .. } => grpc_schema.len(),
// No fixed column set: the format routes per record.
Payload::Influxdb { .. } => 0,
Payload::Influxdb { .. } | Payload::Otlp { .. } => 0,
};
let format_code = state.format_code();
@@ -585,6 +638,14 @@ impl PostgresServerHandlerInner {
// timestamp alignment and inserts are identical to an HTTP
// write of the same bytes. The context stays this connection's
// postgres context.
if let Some((options, bytes)) = state.take_otlp() {
let Some(otlp_handler) = &self.otlp_handler else {
return Err(unsupported("this server is not wired for the otlp format"));
};
return self
.flush_otlp(otlp_handler, options, bytes, query_ctx)
.await;
}
if let Some(request) = state.take_lines()? {
let Some(influxdb_handler) = &self.influxdb_handler else {
return Err(unsupported(
@@ -616,6 +677,158 @@ impl PostgresServerHandlerInner {
}
}
}
/// Completes an OTLP copy through the pipeline the matching
/// OTLP/HTTP endpoint uses — the payload is decoded with the same
/// protobuf types and handed to the same handler methods with the
/// same context preparation, so both ingestion routes are
/// identical. The context stays this connection's postgres context
/// apart from the signal-specific preparation below.
async fn flush_otlp(
&self,
otlp_handler: &crate::query_handler::OpenTelemetryProtocolHandlerRef,
options: OtlpOptions,
bytes: Vec<u8>,
query_ctx: QueryContextRef,
) -> PgWireResult<u64> {
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use pipeline::{GreptimePipelineParams, PipelineWay, SelectInfo};
use session::protocol_ctx::{MetricType, OtlpMetricCtx, ProtocolCtx};
// The HTTP routes derive the pipeline handler from the same
// protocol handler via trait upcasting; so does the copy.
let pipeline_handler: PipelineHandlerRef = otlp_handler.clone();
match options.signal {
OtlpSignal::Metrics {
promote_all_resource_attrs,
resource_attrs,
promote_scope_attrs,
translation_strategy,
} => {
// Same context preparation as the HTTP metrics route.
let mut ctx = (*query_ctx).clone();
ctx.set_protocol_ctx(ProtocolCtx::OtlpMetric(OtlpMetricCtx {
promote_all_resource_attrs,
resource_attrs,
promote_scope_attrs,
with_metric_engine: self.otlp_with_metric_engine,
// Set by the frontend from its config.
resource_info: false,
metric_type: MetricType::Init,
metric_translation_strategy: translation_strategy,
}));
let request = ExportMetricsServiceRequest::decode(bytes.as_slice())
.map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
let outcome = otlp_handler
.metrics(request, Arc::new(ctx))
.await
.map_err(convert_err)?;
// Same failure semantics as the HTTP route: a payload
// whose points were all rejected is an error, not a
// successful `COPY 0`.
if outcome.accepted_data_points == 0 && outcome.rejected_data_points > 0 {
return Err(all_rejected_error(
"data points",
outcome.rejected_data_points,
outcome.error_message.as_deref(),
));
}
// Rows are the accepted data points.
Ok(outcome.accepted_data_points.max(0) as u64)
}
OtlpSignal::Traces {
table_name,
pipeline_name,
pipeline_version,
pipeline_params,
} => {
let table_name = table_name.unwrap_or_else(|| TRACE_TABLE_NAME.to_string());
// Same context preparation as the HTTP traces route.
let mut ctx = (*query_ctx).clone();
ctx.set_extension(TRACE_TABLE_NAME_SESSION_KEY, &table_name);
let pipeline = PipelineWay::from_name_and_default(
pipeline_name.as_deref(),
pipeline_version.as_deref(),
None,
)
.map_err(convert_err)?;
let request = ExportTraceServiceRequest::decode(bytes.as_slice())
.map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
let outcome = otlp_handler
.traces(
pipeline_handler,
request,
pipeline,
GreptimePipelineParams::from_params(pipeline_params.as_deref()),
table_name,
Arc::new(ctx),
)
.await
.map_err(convert_err)?;
// Same failure semantics as the HTTP route.
if outcome.accepted_spans == 0 && outcome.rejected_spans > 0 {
return Err(all_rejected_error(
"spans",
outcome.rejected_spans as i64,
outcome.error_message.as_deref(),
));
}
// Rows are the accepted spans.
Ok(outcome.accepted_spans as u64)
}
OtlpSignal::Logs {
table_name,
pipeline_name,
pipeline_version,
pipeline_params,
extract_keys,
} => {
let table_name = table_name.unwrap_or_else(|| "opentelemetry_logs".to_string());
// Same select semantics as the HTTP extract-keys header.
let select_info = match extract_keys.as_deref() {
Some(keys) if !keys.is_empty() => SelectInfo::from(keys.to_string()),
_ => Default::default(),
};
let pipeline = PipelineWay::from_name_and_default(
pipeline_name.as_deref(),
pipeline_version.as_deref(),
Some(PipelineWay::OtlpLogDirect(Box::new(select_info))),
)
.map_err(convert_err)?;
let request = ExportLogsServiceRequest::decode(bytes.as_slice())
.map_err(|e| bad_copy_data(format!("invalid OTLP payload: {e}")))?;
let outputs = otlp_handler
.logs(
pipeline_handler,
request,
pipeline,
GreptimePipelineParams::from_params(pipeline_params.as_deref()),
table_name,
query_ctx,
)
.await
.map_err(convert_err)?;
// Rows are the affected rows across the outputs.
Ok(outputs
.iter()
.map(|o| match &o.data {
OutputData::AffectedRows(rows) => *rows as u64,
_ => 0,
})
.sum())
}
}
}
}
/// The error for an OTLP payload whose points/spans were all rejected,
/// carrying the pipeline's reason when it provided one.
fn all_rejected_error(kind: &str, rejected: i64, reason: Option<&str>) -> PgWireError {
bad_copy_data(match reason {
Some(reason) => format!("OTLP ingestion rejected all {rejected} {kind}: {reason}"),
None => format!("OTLP ingestion rejected all {rejected} {kind}"),
})
}
fn adjust_query_context(
+307
View File
@@ -0,0 +1,307 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The `otlp` format for COPY FROM STDIN: one binary OTLP payload for
//! any of the three signals — `ExportMetricsServiceRequest`,
//! `ExportTraceServiceRequest` or `ExportLogsServiceRequest`.
//!
//! `COPY FROM STDIN WITH (FORMAT otlp [, signal 'traces'] [, <options>])`
//! is a GreptimeDB-specific, **binary** format (wire format code 1).
//! Like the influxdb format it is table-less and does not decode here:
//! the whole payload is buffered until `CopyDone` — exactly like an
//! OTLP/HTTP request body — then decoded and completed through the
//! frontend's `OpenTelemetryProtocolHandler`, the same path the
//! `/v1/otlp/v1/{metrics,traces,logs}` endpoints use, under the
//! connection's regular postgres query context.
//!
//! The `WITH` options carry what the HTTP endpoints take as request
//! headers; values already provided by the postgres session (database,
//! user, permissions) are not repeated. Option semantics, defaults and
//! parsing helpers are shared with the HTTP extractors (`truthy`,
//! `SelectInfo`, `GreptimePipelineParams`, `PipelineWay`), so the two
//! ingestion routes cannot drift.
//!
//! One COPY statement is one bounded ingestion request (see
//! [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`]).
use ahash::HashSet;
use pgwire::error::PgWireResult;
use pipeline::truthy;
use session::protocol_ctx::OtlpMetricTranslationStrategy;
use crate::postgres::copy_in::bad_copy_data;
use crate::postgres::copy_in::codec::CopyFormat;
use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue};
/// The format's validated options: the signal and its header-equivalent
/// configuration, carried to the flush that completes the copy.
#[derive(Debug, Clone)]
pub(super) struct OtlpOptions {
pub(super) signal: OtlpSignal,
}
#[derive(Debug, Clone)]
pub(super) enum OtlpSignal {
/// Metric options mirroring the `x-greptime-otlp-metric-*` headers.
Metrics {
/// Persist all resource attributes; `resource_attrs` then acts
/// as an exclude list, otherwise as an include list.
promote_all_resource_attrs: bool,
resource_attrs: HashSet<String>,
promote_scope_attrs: bool,
translation_strategy: OtlpMetricTranslationStrategy,
},
/// Trace options mirroring `x-greptime-trace-table-name` and the
/// pipeline headers. The raw pipeline-params string is parsed by the
/// shared `GreptimePipelineParams::from_params` when the copy
/// completes, like the HTTP request does.
Traces {
table_name: Option<String>,
pipeline_name: Option<String>,
pipeline_version: Option<String>,
pipeline_params: Option<String>,
},
/// Log options mirroring `x-greptime-log-table-name`,
/// `x-greptime-log-extract-keys` and the pipeline headers.
Logs {
table_name: Option<String>,
pipeline_name: Option<String>,
pipeline_version: Option<String>,
pipeline_params: Option<String>,
extract_keys: Option<String>,
},
}
pub(super) fn build_otlp_codec(mut options: CopyOptionSet) -> PgWireResult<CopyFormat> {
let signal = options.take_string("signal")?;
let metric_options = (
take_truthy(&mut options, "promote_all_resource_attrs")?,
options.take_string("resource_attrs")?,
take_truthy(&mut options, "promote_scope_attrs")?,
options.take_string("translation_strategy")?,
);
let trace_log_options = (
options.take_string("table_name")?,
options.take_string("pipeline_name")?,
options.take_string("pipeline_version")?,
options.take_string("pipeline_params")?,
);
let extract_keys = options.take_string("extract_keys")?;
options.reject_leftovers("otlp")?;
let unexpected = |option: &str| {
bad_copy_data(format!(
"COPY option \"{option}\" does not apply to the selected signal"
))
};
let signal = match signal.as_deref() {
None | Some("metrics") => {
if trace_log_options != (None, None, None, None) || extract_keys.is_some() {
return Err(unexpected("table_name/pipeline/extract_keys"));
}
let (promote_all, resource_attrs, promote_scope, strategy) = metric_options;
let promote_all = promote_all.unwrap_or(false);
let promote_scope = promote_scope.unwrap_or(false);
let translation_strategy = match strategy.as_deref() {
None => OtlpMetricTranslationStrategy::default(),
// Same values as the HTTP header (`VALUES`), parsed by
// the same `FromStr`.
Some(value) => value.parse().map_err(|_| {
bad_copy_data(format!(
"invalid translation_strategy \"{value}\", expected one of: {}",
OtlpMetricTranslationStrategy::VALUES.join(", ")
))
})?,
};
let resource_attrs = resource_attrs
// Same ';'-separated list and trimming as the header
// extractor.
.map(|s| s.split(';').map(|s| s.trim().to_string()).collect())
.unwrap_or_default();
OtlpSignal::Metrics {
promote_all_resource_attrs: promote_all,
resource_attrs,
promote_scope_attrs: promote_scope,
translation_strategy,
}
}
Some("traces") | Some("logs") => {
if metric_options != (None, None, None, None) {
return Err(unexpected("promote_*/resource_attrs/translation_strategy"));
}
let (table_name, pipeline_name, pipeline_version, pipeline_params) = trace_log_options;
if signal.as_deref() == Some("traces") {
if extract_keys.is_some() {
// `extract_keys` only applies to logs.
return Err(unexpected("extract_keys"));
}
OtlpSignal::Traces {
table_name,
pipeline_name,
pipeline_version,
pipeline_params,
}
} else {
OtlpSignal::Logs {
table_name,
pipeline_name,
pipeline_version,
pipeline_params,
extract_keys,
}
}
}
Some(unknown) => {
return Err(bad_copy_data(format!(
"invalid signal \"{unknown}\", expected one of: metrics, traces, logs"
)));
}
};
Ok(CopyFormat::Otlp(OtlpOptions { signal }))
}
/// Takes a boolean option with the HTTP header's exact truthy
/// spellings (`true`, `1`, `yes`, `on`, `t`), plus the COPY forms
/// (bare flag or `TRUE`/`FALSE`), so both routes accept the same values.
fn take_truthy(options: &mut CopyOptionSet, key: &str) -> PgWireResult<Option<bool>> {
match options.take_value(key) {
None => Ok(None),
Some(CopyOptionValue::Flag) => Ok(Some(true)),
Some(CopyOptionValue::Boolean(b)) => Ok(Some(b)),
Some(CopyOptionValue::String(v)) | Some(CopyOptionValue::Ident(v)) => Ok(Some(truthy(v))),
Some(other) => Err(bad_copy_data(format!(
"COPY option {key} requires a boolean value, got {}",
other.kind()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::postgres::copy_in::options::CopyOptionValue;
fn opts(entries: &[(&str, CopyOptionValue)]) -> CopyOptionSet {
let mut set = CopyOptionSet::default();
for (k, v) in entries {
set.insert((*k).into(), v.clone()).unwrap();
}
set
}
#[test]
fn test_signal_defaults_and_options() {
// Default signal is metrics.
assert!(matches!(
build_otlp_codec(CopyOptionSet::default()).unwrap(),
CopyFormat::Otlp(OtlpOptions {
signal: OtlpSignal::Metrics { .. }
})
));
// Metric options parse like the headers.
let format = build_otlp_codec(opts(&[
("promote_all_resource_attrs", CopyOptionValue::Flag),
(
"resource_attrs",
CopyOptionValue::String("service.name; host.id ".into()),
),
("promote_scope_attrs", CopyOptionValue::Flag),
(
"translation_strategy",
CopyOptionValue::String("NoTranslation".into()),
),
]))
.unwrap();
let CopyFormat::Otlp(OtlpOptions {
signal:
OtlpSignal::Metrics {
promote_all_resource_attrs,
resource_attrs,
promote_scope_attrs,
translation_strategy,
},
}) = format
else {
panic!("expected metrics");
};
assert!(promote_all_resource_attrs && promote_scope_attrs);
assert_eq!(
resource_attrs,
["service.name", "host.id"]
.into_iter()
.map(String::from)
.collect()
);
assert!(matches!(
translation_strategy,
OtlpMetricTranslationStrategy::NoTranslation
));
// Traces and logs accept their header equivalents.
assert!(matches!(
build_otlp_codec(opts(&[(
"signal",
CopyOptionValue::String("traces".into())
)]))
.unwrap(),
CopyFormat::Otlp(OtlpOptions {
signal: OtlpSignal::Traces { .. }
})
));
assert!(matches!(
build_otlp_codec(opts(&[
("signal", CopyOptionValue::String("logs".into())),
("table_name", CopyOptionValue::String("my_logs".into())),
("extract_keys", CopyOptionValue::String("a,b".into())),
]))
.unwrap(),
CopyFormat::Otlp(OtlpOptions {
signal: OtlpSignal::Logs { .. }
})
));
}
#[test]
fn test_rejects_unknown_and_mismatched_options() {
// Unknown signal.
let set = opts(&[("signal", CopyOptionValue::String("spans".into()))]);
assert!(build_otlp_codec(set).is_err());
// Unknown option.
let set = opts(&[("precision", CopyOptionValue::String("ns".into()))]);
assert!(build_otlp_codec(set).is_err());
// Signal-specific options do not cross.
let set = opts(&[
("signal", CopyOptionValue::String("traces".into())),
("promote_scope_attrs", CopyOptionValue::Flag),
]);
assert!(build_otlp_codec(set).is_err());
let set = opts(&[
("signal", CopyOptionValue::String("metrics".into())),
("table_name", CopyOptionValue::String("t".into())),
]);
assert!(build_otlp_codec(set).is_err());
let set = opts(&[
("signal", CopyOptionValue::String("traces".into())),
(
"extract_keys",
CopyOptionValue::String("attributes.foo".into()),
),
]);
assert!(build_otlp_codec(set).is_err());
}
}
+22
View File
@@ -31,6 +31,7 @@ use crate::error::Result;
use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder};
use crate::query_handler::CopyInHandlerRef;
use crate::query_handler::InfluxdbLineProtocolHandlerRef;
use crate::query_handler::OpenTelemetryProtocolHandlerRef;
use crate::query_handler::sql::ServerSqlQueryHandlerRef;
use crate::server::{AbortableStream, BaseTcpServer, Server};
use crate::tls::ReloadableTlsServerConfig;
@@ -42,6 +43,8 @@ pub struct PostgresServer {
keep_alive_secs: u64,
batching_enabled: bool,
influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
otlp_with_metric_engine: bool,
bind_addr: Option<SocketAddr>,
process_manager: Option<ProcessManagerRef>,
}
@@ -80,6 +83,8 @@ impl PostgresServer {
keep_alive_secs,
batching_enabled: false,
influxdb_handler: None,
otlp_handler: None,
otlp_with_metric_engine: false,
bind_addr: None,
process_manager,
}
@@ -100,6 +105,21 @@ impl PostgresServer {
self
}
/// Wires the OTLP handler used by table-less
/// `COPY FROM STDIN WITH (FORMAT otlp)` — the same handler the
/// OTLP/HTTP endpoints use, so the payload runs through the
/// identical pipeline. `with_metric_engine` carries the same flag
/// the HTTP wiring passes from its options.
pub fn with_otlp_handler(
mut self,
handler: OpenTelemetryProtocolHandlerRef,
with_metric_engine: bool,
) -> Self {
self.otlp_handler = Some(handler);
self.otlp_with_metric_engine = with_metric_engine;
self
}
fn accept(
&self,
io_runtime: Runtime,
@@ -115,6 +135,8 @@ impl PostgresServer {
query_handler: make_handler.query_handler.clone(),
copy_in_handler: make_handler.copy_in_handler.clone(),
influxdb_handler: self.influxdb_handler.clone(),
otlp_handler: self.otlp_handler.clone(),
otlp_with_metric_engine: self.otlp_with_metric_engine,
user_provider: make_handler.user_provider.clone(),
param_provider: make_handler.param_provider.clone(),
force_tls: make_handler.force_tls,
+6 -3
View File
@@ -1216,7 +1216,8 @@ pub async fn setup_pg_server_with_slow_query_threshold(
None,
None,
)
.with_influxdb_handler(fe_instance_ref.clone()),
.with_influxdb_handler(fe_instance_ref.clone())
.with_otlp_handler(fe_instance_ref.clone(), true),
);
pg_server
@@ -1263,7 +1264,8 @@ pub async fn setup_pg_server_with_user_provider(
user_provider,
None,
)
.with_influxdb_handler(fe_instance_ref.clone()),
.with_influxdb_handler(fe_instance_ref.clone())
.with_otlp_handler(fe_instance_ref.clone(), true),
);
pg_server
@@ -1322,7 +1324,8 @@ pub async fn setup_pg_server_with_prom_native_histogram(
None,
None,
)
.with_influxdb_handler(instance.fe_instance().clone()),
.with_influxdb_handler(instance.fe_instance().clone())
.with_otlp_handler(instance.fe_instance().clone(), true),
);
pg_server
@@ -819,3 +819,357 @@ async fn test_postgres_copy_in_influxdb_invalid_utf8_and_trailing_record() {
server.shutdown().await.unwrap();
}
/// `COPY FROM STDIN WITH (FORMAT otlp)` ingests one binary OTLP
/// ExportMetricsServiceRequest through the same pipeline as the OTLP/HTTP
/// endpoint — and validates binary (format code 1) COPY support, including
/// payloads split across CopyData chunks.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_postgres_copy_in_otlp_binary() {
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
use otel_arrow_rust::proto::opentelemetry::common::v1::any_value;
use otel_arrow_rust::proto::opentelemetry::common::v1::{AnyValue, KeyValue};
use otel_arrow_rust::proto::opentelemetry::metrics::v1::number_data_point::Value;
use otel_arrow_rust::proto::opentelemetry::metrics::v1::{
Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, metric,
};
use prost::Message;
init_default_ut_logging();
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_otlp").await;
let port = server.bind_addr().unwrap().port();
let client = connect(port).await;
let request = ExportMetricsServiceRequest {
resource_metrics: vec![ResourceMetrics {
scope_metrics: vec![ScopeMetrics {
metrics: vec![Metric {
name: "copy_otlp_gauge".into(),
data: Some(metric::Data::Gauge(Gauge {
data_points: vec![
NumberDataPoint {
time_unix_nano: 1_700_000_000_000_000_000,
value: Some(Value::AsDouble(1.5)),
attributes: vec![KeyValue {
key: "host".into(),
value: Some(AnyValue {
value: Some(any_value::Value::StringValue("a".into())),
}),
}],
..Default::default()
},
NumberDataPoint {
time_unix_nano: 1_700_000_001_000_000_000,
value: Some(Value::AsDouble(2.5)),
attributes: vec![KeyValue {
key: "host".into(),
value: Some(AnyValue {
value: Some(any_value::Value::StringValue("b".into())),
}),
}],
..Default::default()
},
],
})),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
};
let body = request.encode_to_vec();
// Feed the binary payload in small chunks: the message spans CopyData
// boundaries exactly like a large text payload would.
let rows = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp)",
body.chunks(9).map(Bytes::copy_from_slice).collect(),
)
.await
.unwrap();
assert_eq!(rows, 2);
let messages = client
.simple_query("SELECT host, greptime_value FROM copy_otlp_gauge ORDER BY host")
.await
.unwrap();
let rows: Vec<(String, String)> = messages
.iter()
.filter_map(|m| {
let tokio_postgres::SimpleQueryMessage::Row(row) = m else {
return None;
};
Some((
row.get(0).unwrap_or("").to_string(),
row.get(1).unwrap_or("").to_string(),
))
})
.collect();
assert_eq!(
rows,
vec![("a".into(), "1.5".into()), ("b".into(), "2.5".into())]
);
// Garbage bytes fail the copy and the connection stays usable.
let error = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp)",
vec![Bytes::from_static(b"\xff\xff\xff\xff")],
)
.await
.unwrap_err();
assert!(
error
.as_db_error()
.map(|d| d.message().contains("invalid OTLP payload"))
.unwrap_or(false),
"unexpected error: {error}"
);
let messages = client.simple_query("SELECT 1").await.unwrap();
assert!(!messages.is_empty());
server.shutdown().await.unwrap();
}
/// `COPY FROM STDIN WITH (FORMAT otlp, signal 'traces')` ingests one
/// binary ExportTraceServiceRequest through the same pipeline as the
/// OTLP/HTTP traces endpoint, honoring the trace-table-name option.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_postgres_copy_in_otlp_traces() {
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use prost::Message;
use serde_json::json;
init_default_ut_logging();
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_otlp_traces").await;
let port = server.bind_addr().unwrap().port();
let client = connect(port).await;
let request: ExportTraceServiceRequest = serde_json::from_value(json!({
"resourceSpans": [{
"resource": {"attributes": [
{"key": "service.name", "value": {"stringValue": "copy-svc"}}
]},
"scopeSpans": [{"spans": [{
"traceId": "c05d7a4ec8e1f231f02ed6e8da8655b4",
"spanId": "9630f2916e2f7909",
"name": "copy-op",
"kind": 2,
"startTimeUnixNano": "1736480942444376000",
"endTimeUnixNano": "1736480942444499000"
}]}]
}]
}))
.unwrap();
let rows = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp, signal 'traces', table_name 'copy_traces', pipeline_name 'greptime_trace_v2')",
vec![Bytes::from(request.encode_to_vec())],
)
.await
.unwrap();
assert_eq!(rows, 1);
let messages = client
.simple_query("SELECT count(*) FROM copy_traces WHERE service_name = 'copy-svc'")
.await
.unwrap();
let count: Vec<String> = messages
.iter()
.filter_map(|m| match m {
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
_ => None,
})
.collect();
assert_eq!(count, vec!["1".to_string()]);
server.shutdown().await.unwrap();
}
/// `COPY FROM STDIN WITH (FORMAT otlp, signal 'logs')` ingests one
/// binary ExportLogsServiceRequest through the same pipeline as the
/// OTLP/HTTP logs endpoint, with the default log table.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_postgres_copy_in_otlp_logs() {
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use prost::Message;
use serde_json::json;
init_default_ut_logging();
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_otlp_logs").await;
let port = server.bind_addr().unwrap().port();
let client = connect(port).await;
let request: ExportLogsServiceRequest = serde_json::from_value(json!({
"resourceLogs": [{
"resource": {"attributes": []},
"scopeLogs": [{"logRecords": [{
"timeUnixNano": "1736413568497632000",
"severityNumber": 9,
"severityText": "Info",
"body": {"stringValue": "copied via postgres"},
"traceId": "f665100a612542b69cc362fe2ae9d3bf",
"spanId": "e58f01c4c69f4488"
}]}]
}]
}))
.unwrap();
let rows = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp, signal 'logs')",
vec![Bytes::from(request.encode_to_vec())],
)
.await
.unwrap();
assert_eq!(rows, 1);
let messages = client
.simple_query("SELECT count(*) FROM opentelemetry_logs WHERE body = 'copied via postgres'")
.await
.unwrap();
let count: Vec<String> = messages
.iter()
.filter_map(|m| match m {
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
_ => None,
})
.collect();
assert_eq!(count, vec!["1".to_string()]);
server.shutdown().await.unwrap();
}
/// A metrics COPY honors the header-equivalent options: promoting all
/// resource attributes adds them as columns.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_postgres_copy_in_otlp_metrics_options() {
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
use prost::Message;
init_default_ut_logging();
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_otlp_mopts").await;
let port = server.bind_addr().unwrap().port();
let client = connect(port).await;
let request = ExportMetricsServiceRequest {
resource_metrics: vec![otel_arrow_rust::proto::opentelemetry::metrics::v1::ResourceMetrics {
resource: Some(otel_arrow_rust::proto::opentelemetry::resource::v1::Resource {
attributes: vec![otel_arrow_rust::proto::opentelemetry::common::v1::KeyValue {
key: "deployment.environment".into(),
value: Some(otel_arrow_rust::proto::opentelemetry::common::v1::AnyValue {
value: Some(
otel_arrow_rust::proto::opentelemetry::common::v1::any_value::Value::StringValue("prod".into()),
),
}),
}],
..Default::default()
}),
scope_metrics: vec![otel_arrow_rust::proto::opentelemetry::metrics::v1::ScopeMetrics {
metrics: vec![otel_arrow_rust::proto::opentelemetry::metrics::v1::Metric {
name: "copy_opt_gauge".into(),
data: Some(otel_arrow_rust::proto::opentelemetry::metrics::v1::metric::Data::Gauge(
otel_arrow_rust::proto::opentelemetry::metrics::v1::Gauge {
data_points: vec![otel_arrow_rust::proto::opentelemetry::metrics::v1::NumberDataPoint {
time_unix_nano: 1_700_000_000_000_000_000,
value: Some(otel_arrow_rust::proto::opentelemetry::metrics::v1::number_data_point::Value::AsDouble(42.0)),
..Default::default()
}],
},
)),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
};
let rows = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp, signal 'metrics', promote_all_resource_attrs)",
vec![Bytes::from(request.encode_to_vec())],
)
.await
.unwrap();
assert_eq!(rows, 1);
let messages = client
.simple_query("SELECT count(*) FROM copy_opt_gauge WHERE deployment_environment = 'prod'")
.await
.unwrap();
let count: Vec<String> = messages
.iter()
.filter_map(|m| match m {
tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string),
_ => None,
})
.collect();
assert_eq!(count, vec!["1".to_string()]);
server.shutdown().await.unwrap();
}
/// A payload whose data points are all rejected fails the copy with the
/// pipeline's reason — the same failure semantics as the HTTP route —
/// and the connection stays usable.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_postgres_copy_in_otlp_all_rejected() {
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
use otel_arrow_rust::proto::opentelemetry::metrics::v1::{
AggregationTemporality, Histogram, HistogramDataPoint, Metric, ResourceMetrics,
ScopeMetrics, metric,
};
use prost::Message;
init_default_ut_logging();
let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_otlp_rej").await;
let port = server.bind_addr().unwrap().port();
let client = connect(port).await;
// A delta histogram cannot be stored as-is: its single point is
// rejected — the same trigger the OTLP suite uses for the HTTP
// route's failure outcome.
let request = ExportMetricsServiceRequest {
resource_metrics: vec![ResourceMetrics {
scope_metrics: vec![ScopeMetrics {
metrics: vec![Metric {
name: "copy_rejected_histogram".into(),
data: Some(metric::Data::Histogram(Histogram {
data_points: vec![HistogramDataPoint {
count: 1,
bucket_counts: vec![1],
explicit_bounds: vec![1.0, 2.0],
..Default::default()
}],
aggregation_temporality: AggregationTemporality::Delta as i32,
})),
..Default::default()
}],
..Default::default()
}],
..Default::default()
}],
};
let error = feed_copy_in(
&client,
"COPY FROM STDIN WITH (FORMAT otlp)",
vec![Bytes::from(request.encode_to_vec())],
)
.await
.unwrap_err();
assert!(
error
.as_db_error()
.map(|d| d.message().contains("rejected all"))
.unwrap_or(false),
"unexpected error: {error}"
);
let messages = client.simple_query("SELECT 1").await.unwrap();
assert!(!messages.is_empty());
server.shutdown().await.unwrap();
}