Skip to main content

servers/grpc/
prom_query_gateway.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
15//! PrometheusGateway provides a gRPC interface to query Prometheus metrics
16//! by PromQL. The behavior is similar to the Prometheus HTTP API.
17
18use std::sync::Arc;
19
20use api::v1::prometheus_gateway_server::PrometheusGateway;
21use api::v1::promql_request::Promql;
22use api::v1::{PromqlRequest, PromqlResponse, ResponseHeader};
23use async_trait::async_trait;
24use auth::UserProviderRef;
25use common_error::ext::ErrorExt;
26use common_error::status_code::StatusCode;
27use common_query::promql_annotations::promql_annotation_collector;
28use common_time::util::current_time_rfc3339;
29use promql_parser::parser::value::ValueType;
30use query::parser::PromQuery;
31use session::context::{Channel, QueryContext};
32use snafu::OptionExt;
33use tonic::{Request, Response};
34
35use crate::error::InvalidQuerySnafu;
36use crate::grpc::TonicResult;
37use crate::grpc::context_auth::auth;
38use crate::grpc::greptime_handler::create_query_context;
39use crate::http::prometheus::{PrometheusJsonResponse, retrieve_metric_name_and_result_type};
40use crate::prometheus_handler::{ParsedPromQuery, PrometheusHandlerRef};
41
42pub struct PrometheusGatewayService {
43    handler: PrometheusHandlerRef,
44    user_provider: Option<UserProviderRef>,
45}
46
47#[async_trait]
48impl PrometheusGateway for PrometheusGatewayService {
49    async fn handle(&self, req: Request<PromqlRequest>) -> TonicResult<Response<PromqlResponse>> {
50        let mut is_range_query = false;
51        let channel = req
52            .extensions()
53            .get::<Channel>()
54            .copied()
55            .unwrap_or(Channel::Promql);
56        let inner = req.into_inner();
57        let prom_query = match inner.promql.context(InvalidQuerySnafu {
58            reason: "Expecting non-empty PromqlRequest.",
59        })? {
60            Promql::RangeQuery(range_query) => {
61                is_range_query = true;
62                PromQuery {
63                    query: range_query.query,
64                    start: range_query.start,
65                    end: range_query.end,
66                    step: range_query.step,
67                    lookback: range_query.lookback,
68                    alias: None,
69                }
70            }
71            Promql::InstantQuery(instant_query) => {
72                let time = if instant_query.time.is_empty() {
73                    current_time_rfc3339()
74                } else {
75                    instant_query.time
76                };
77                PromQuery {
78                    query: instant_query.query,
79                    start: time.clone(),
80                    end: time,
81                    step: String::from("1s"),
82                    lookback: instant_query.lookback,
83                    alias: None,
84                }
85            }
86        };
87
88        let header = inner.header.as_ref();
89        let query_ctx =
90            create_query_context(channel, header, Default::default(), Default::default())?;
91
92        let user_info = auth(self.user_provider.clone(), header, &query_ctx).await?;
93        query_ctx.set_current_user(user_info);
94
95        let json_response = self
96            .handle_inner(prom_query, query_ctx, is_range_query)
97            .await;
98        let json_bytes = serde_json::to_string(&json_response).unwrap().into_bytes();
99
100        let response = Response::new(PromqlResponse {
101            header: Some(ResponseHeader {
102                status: Some(api::v1::Status {
103                    status_code: StatusCode::Success as _,
104                    ..Default::default()
105                }),
106            }),
107            body: json_bytes,
108        });
109        Ok(response)
110    }
111}
112
113impl PrometheusGatewayService {
114    pub fn new(handler: PrometheusHandlerRef, user_provider: Option<UserProviderRef>) -> Self {
115        Self {
116            handler,
117            user_provider,
118        }
119    }
120
121    async fn handle_inner(
122        &self,
123        query: PromQuery,
124        ctx: Arc<QueryContext>,
125        is_range_query: bool,
126    ) -> PrometheusJsonResponse {
127        let db = ctx.get_db_string();
128        let _timer = crate::metrics::METRIC_SERVER_GRPC_PROM_REQUEST_TIMER
129            .with_label_values(&[db.as_str()])
130            .start_timer();
131
132        let query = match ParsedPromQuery::parse(query, &ctx) {
133            Ok(query) => query,
134            Err(err) => {
135                return PrometheusJsonResponse::error(err.status_code(), err.output_msg());
136            }
137        };
138        let (metric_name, mut result_type) = retrieve_metric_name_and_result_type(query.expr());
139        // Create the collector here so one strong reference spans planning, execution and the response;
140        // the planner and executor find it by query id through the registry.
141        let collector = ctx.remote_query_id().map(promql_annotation_collector);
142        // A range query only returns a matrix, and matrix serialization sorts
143        // samples and series, so execution order never reaches the response.
144        let query = if is_range_query {
145            result_type = ValueType::Matrix;
146            query.with_unordered_output()
147        } else {
148            query
149        };
150        let result = self.handler.do_query_parsed(query, ctx).await;
151
152        PrometheusJsonResponse::from_query_result(result, metric_name, result_type, collector).await
153    }
154}