Skip to main content

servers/http/
otlp.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16
17use axum::Extension;
18use axum::extract::State;
19use axum::http::{StatusCode, header};
20use axum::response::IntoResponse;
21use axum_extra::TypedHeader;
22use bytes::Bytes;
23use common_catalog::consts::{TRACE_TABLE_NAME, TRACE_TABLE_NAME_SESSION_KEY};
24use common_telemetry::tracing;
25use headers::ContentType;
26use mime_guess::mime;
27use opentelemetry_proto::tonic::collector::logs::v1::{
28    ExportLogsServiceRequest, ExportLogsServiceResponse,
29};
30use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceResponse;
31use opentelemetry_proto::tonic::collector::trace::v1::{
32    ExportTracePartialSuccess, ExportTraceServiceRequest, ExportTraceServiceResponse,
33};
34use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
35use pipeline::PipelineWay;
36use prost::Message;
37use session::context::{Channel, QueryContext};
38use session::protocol_ctx::{MetricType, OtlpMetricCtx, ProtocolCtx};
39use snafu::prelude::*;
40
41use crate::error::{self, PipelineSnafu, Result};
42use crate::http::extractor::{
43    LogTableName, OtlpMetricOptions, PipelineInfo, SelectInfoWrapper, TraceTableName,
44};
45use crate::http::header::{CONTENT_TYPE_PROTOBUF, write_cost_header_map};
46use crate::metrics::METRIC_HTTP_OPENTELEMETRY_LOGS_ELAPSED;
47use crate::query_handler::{OpenTelemetryProtocolHandlerRef, PipelineHandler, TraceIngestOutcome};
48
49#[derive(Clone, prost::Message)]
50pub struct GoogleRpcStatus {
51    #[prost(int32, tag = "1")]
52    pub code: i32,
53    #[prost(string, tag = "2")]
54    pub message: String,
55}
56
57fn is_json_content_type(content_type: Option<&ContentType>) -> bool {
58    match content_type {
59        None => false,
60        Some(ct) => {
61            let mime: mime::Mime = ct.clone().into();
62            mime.subtype() == mime::JSON
63        }
64    }
65}
66
67fn content_type_to_string(content_type: Option<&TypedHeader<ContentType>>) -> String {
68    content_type
69        .map(|h| h.0.to_string())
70        .unwrap_or_else(|| "not specified".to_string())
71}
72
73#[derive(Clone)]
74pub struct OtlpState {
75    pub with_metric_engine: bool,
76    pub handler: OpenTelemetryProtocolHandlerRef,
77}
78
79#[axum_macros::debug_handler]
80#[tracing::instrument(skip_all, fields(protocol = "otlp", request_type = "metrics"))]
81pub async fn metrics(
82    State(state): State<OtlpState>,
83    Extension(mut query_ctx): Extension<QueryContext>,
84    http_opts: OtlpMetricOptions,
85    content_type: Option<TypedHeader<ContentType>>,
86    bytes: Bytes,
87) -> Result<OtlpResponse<ExportMetricsServiceResponse>> {
88    if is_json_content_type(content_type.as_ref().map(|h| &h.0)) {
89        return error::UnsupportedJsonContentTypeSnafu {}.fail();
90    }
91
92    let db = query_ctx.get_db_string();
93    query_ctx.set_channel(Channel::Otlp);
94
95    let _timer = crate::metrics::METRIC_HTTP_OPENTELEMETRY_METRICS_ELAPSED
96        .with_label_values(&[db.as_str()])
97        .start_timer();
98    let request = ExportMetricsServiceRequest::decode(bytes).with_context(|_| {
99        error::DecodeOtlpRequestSnafu {
100            content_type: content_type_to_string(content_type.as_ref()),
101        }
102    })?;
103
104    let OtlpState {
105        with_metric_engine,
106        handler,
107    } = state;
108
109    query_ctx.set_protocol_ctx(ProtocolCtx::OtlpMetric(OtlpMetricCtx {
110        promote_all_resource_attrs: http_opts.promote_all_resource_attrs,
111        resource_attrs: http_opts.resource_attrs,
112        promote_scope_attrs: http_opts.promote_scope_attrs,
113        with_metric_engine,
114        // set is_legacy later
115        is_legacy: false,
116        metric_type: MetricType::Init,
117    }));
118    let query_ctx = Arc::new(query_ctx);
119
120    handler
121        .metrics(request, query_ctx)
122        .await
123        .map(|o| OtlpResponse {
124            resp_body: ExportMetricsServiceResponse {
125                partial_success: None,
126            },
127            write_cost: o.meta.cost,
128        })
129}
130
131#[axum_macros::debug_handler]
132#[tracing::instrument(skip_all, fields(protocol = "otlp", request_type = "traces"))]
133pub async fn traces(
134    State(state): State<OtlpState>,
135    TraceTableName(table_name): TraceTableName,
136    pipeline_info: PipelineInfo,
137    Extension(mut query_ctx): Extension<QueryContext>,
138    content_type: Option<TypedHeader<ContentType>>,
139    bytes: Bytes,
140) -> Result<OtlpTraceResponse> {
141    if is_json_content_type(content_type.as_ref().map(|h| &h.0)) {
142        return error::UnsupportedJsonContentTypeSnafu {}.fail();
143    }
144
145    let db = query_ctx.get_db_string();
146    let table_name = table_name.unwrap_or_else(|| TRACE_TABLE_NAME.to_string());
147
148    query_ctx.set_channel(Channel::Otlp);
149    query_ctx.set_extension(TRACE_TABLE_NAME_SESSION_KEY, &table_name);
150
151    let query_ctx = Arc::new(query_ctx);
152    let _timer = crate::metrics::METRIC_HTTP_OPENTELEMETRY_TRACES_ELAPSED
153        .with_label_values(&[db.as_str()])
154        .start_timer();
155    let request = ExportTraceServiceRequest::decode(bytes).with_context(|_| {
156        error::DecodeOtlpRequestSnafu {
157            content_type: content_type_to_string(content_type.as_ref()),
158        }
159    })?;
160
161    let pipeline = PipelineWay::from_name_and_default(
162        pipeline_info.pipeline_name.as_deref(),
163        pipeline_info.pipeline_version.as_deref(),
164        None,
165    )
166    .context(PipelineSnafu)?;
167
168    let pipeline_params = pipeline_info.pipeline_params;
169
170    let OtlpState { handler, .. } = state;
171
172    // here we use nightly feature `trait_upcasting` to convert handler to
173    // pipeline_handler
174    let pipeline_handler: Arc<dyn PipelineHandler + Send + Sync> = handler.clone();
175
176    handler
177        .traces(
178            pipeline_handler,
179            request,
180            pipeline,
181            pipeline_params,
182            table_name,
183            query_ctx,
184        )
185        .await
186        .map(|outcome| {
187            if outcome.accepted_spans == 0 && outcome.rejected_spans > 0 {
188                OtlpTraceResponse::Failure(outcome)
189            } else if outcome.rejected_spans > 0 || outcome.error_message.is_some() {
190                OtlpTraceResponse::PartialSuccess(outcome)
191            } else {
192                OtlpTraceResponse::FullSuccess(outcome)
193            }
194        })
195}
196
197#[axum_macros::debug_handler]
198#[tracing::instrument(skip_all, fields(protocol = "otlp", request_type = "logs"))]
199pub async fn logs(
200    State(state): State<OtlpState>,
201    Extension(mut query_ctx): Extension<QueryContext>,
202    pipeline_info: PipelineInfo,
203    LogTableName(tablename): LogTableName,
204    SelectInfoWrapper(select_info): SelectInfoWrapper,
205    content_type: Option<TypedHeader<ContentType>>,
206    bytes: Bytes,
207) -> Result<OtlpResponse<ExportLogsServiceResponse>> {
208    if is_json_content_type(content_type.as_ref().map(|h| &h.0)) {
209        return error::UnsupportedJsonContentTypeSnafu {}.fail();
210    }
211
212    let tablename = tablename.unwrap_or_else(|| "opentelemetry_logs".to_string());
213    let db = query_ctx.get_db_string();
214    query_ctx.set_channel(Channel::Otlp);
215    let query_ctx = Arc::new(query_ctx);
216    let _timer = METRIC_HTTP_OPENTELEMETRY_LOGS_ELAPSED
217        .with_label_values(&[db.as_str()])
218        .start_timer();
219    let request = ExportLogsServiceRequest::decode(bytes).with_context(|_| {
220        error::DecodeOtlpRequestSnafu {
221            content_type: content_type_to_string(content_type.as_ref()),
222        }
223    })?;
224
225    let pipeline = PipelineWay::from_name_and_default(
226        pipeline_info.pipeline_name.as_deref(),
227        pipeline_info.pipeline_version.as_deref(),
228        Some(PipelineWay::OtlpLogDirect(Box::new(select_info))),
229    )
230    .context(PipelineSnafu)?;
231    let pipeline_params = pipeline_info.pipeline_params;
232
233    let OtlpState { handler, .. } = state;
234
235    // here we use nightly feature `trait_upcasting` to convert handler to
236    // pipeline_handler
237    let pipeline_handler: Arc<dyn PipelineHandler + Send + Sync> = handler.clone();
238    handler
239        .logs(
240            pipeline_handler,
241            request,
242            pipeline,
243            pipeline_params,
244            tablename,
245            query_ctx,
246        )
247        .await
248        .map(|o| OtlpResponse {
249            resp_body: ExportLogsServiceResponse {
250                partial_success: None,
251            },
252            write_cost: o.iter().map(|o| o.meta.cost).sum(),
253        })
254}
255
256pub struct OtlpResponse<T: Message> {
257    resp_body: T,
258    write_cost: usize,
259}
260
261impl<T: Message> IntoResponse for OtlpResponse<T> {
262    fn into_response(self) -> axum::response::Response {
263        let mut header_map = write_cost_header_map(self.write_cost);
264        header_map.insert(header::CONTENT_TYPE, CONTENT_TYPE_PROTOBUF.clone());
265
266        (header_map, self.resp_body.encode_to_vec()).into_response()
267    }
268}
269
270pub enum OtlpTraceResponse {
271    FullSuccess(TraceIngestOutcome),
272    PartialSuccess(TraceIngestOutcome),
273    Failure(TraceIngestOutcome),
274}
275
276impl IntoResponse for OtlpTraceResponse {
277    fn into_response(self) -> axum::response::Response {
278        match self {
279            OtlpTraceResponse::FullSuccess(outcome) => {
280                let mut header_map = write_cost_header_map(outcome.write_cost);
281                header_map.insert(header::CONTENT_TYPE, CONTENT_TYPE_PROTOBUF.clone());
282                let body = ExportTraceServiceResponse {
283                    partial_success: None,
284                };
285                (header_map, body.encode_to_vec()).into_response()
286            }
287            OtlpTraceResponse::PartialSuccess(outcome) => {
288                let mut header_map = write_cost_header_map(outcome.write_cost);
289                header_map.insert(header::CONTENT_TYPE, CONTENT_TYPE_PROTOBUF.clone());
290                let body = ExportTraceServiceResponse {
291                    partial_success: outcome.error_message.map(|error_message| {
292                        ExportTracePartialSuccess {
293                            rejected_spans: outcome.rejected_spans as i64,
294                            error_message,
295                        }
296                    }),
297                };
298                (header_map, body.encode_to_vec()).into_response()
299            }
300            OtlpTraceResponse::Failure(outcome) => {
301                let status = GoogleRpcStatus {
302                    code: 0,
303                    message: outcome.error_message.unwrap_or_default(),
304                };
305                (
306                    StatusCode::BAD_REQUEST,
307                    [(header::CONTENT_TYPE, CONTENT_TYPE_PROTOBUF.as_ref())],
308                    status.encode_to_vec(),
309                )
310                    .into_response()
311            }
312        }
313    }
314}