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_time::util::current_time_rfc3339;
28use promql_parser::parser::value::ValueType;
29use query::parser::PromQuery;
30use session::context::{Channel, QueryContext};
31use snafu::OptionExt;
32use tonic::{Request, Response};
33
34use crate::error::InvalidQuerySnafu;
35use crate::grpc::greptime_handler::{auth, create_query_context};
36use crate::grpc::TonicResult;
37use crate::http::prometheus::{retrieve_metric_name_and_result_type, PrometheusJsonResponse};
38use crate::prometheus_handler::PrometheusHandlerRef;
39
40pub struct PrometheusGatewayService {
41    handler: PrometheusHandlerRef,
42    user_provider: Option<UserProviderRef>,
43}
44
45#[async_trait]
46impl PrometheusGateway for PrometheusGatewayService {
47    async fn handle(&self, req: Request<PromqlRequest>) -> TonicResult<Response<PromqlResponse>> {
48        let mut is_range_query = false;
49        let inner = req.into_inner();
50        let prom_query = match inner.promql.context(InvalidQuerySnafu {
51            reason: "Expecting non-empty PromqlRequest.",
52        })? {
53            Promql::RangeQuery(range_query) => {
54                is_range_query = true;
55                PromQuery {
56                    query: range_query.query,
57                    start: range_query.start,
58                    end: range_query.end,
59                    step: range_query.step,
60                    lookback: range_query.lookback,
61                }
62            }
63            Promql::InstantQuery(instant_query) => {
64                let time = if instant_query.time.is_empty() {
65                    current_time_rfc3339()
66                } else {
67                    instant_query.time
68                };
69                PromQuery {
70                    query: instant_query.query,
71                    start: time.clone(),
72                    end: time,
73                    step: String::from("1s"),
74                    lookback: instant_query.lookback,
75                }
76            }
77        };
78
79        let header = inner.header.as_ref();
80        let query_ctx = create_query_context(Channel::Promql, header, Default::default())?;
81
82        let user_info = auth(self.user_provider.clone(), header, &query_ctx).await?;
83        query_ctx.set_current_user(user_info);
84
85        let json_response = self
86            .handle_inner(prom_query, query_ctx, is_range_query)
87            .await;
88        let json_bytes = serde_json::to_string(&json_response).unwrap().into_bytes();
89
90        let response = Response::new(PromqlResponse {
91            header: Some(ResponseHeader {
92                status: Some(api::v1::Status {
93                    status_code: StatusCode::Success as _,
94                    ..Default::default()
95                }),
96            }),
97            body: json_bytes,
98        });
99        Ok(response)
100    }
101}
102
103impl PrometheusGatewayService {
104    pub fn new(handler: PrometheusHandlerRef, user_provider: Option<UserProviderRef>) -> Self {
105        Self {
106            handler,
107            user_provider,
108        }
109    }
110
111    async fn handle_inner(
112        &self,
113        query: PromQuery,
114        ctx: Arc<QueryContext>,
115        is_range_query: bool,
116    ) -> PrometheusJsonResponse {
117        let db = ctx.get_db_string();
118        let _timer = crate::metrics::METRIC_SERVER_GRPC_PROM_REQUEST_TIMER
119            .with_label_values(&[db.as_str()])
120            .start_timer();
121
122        let result = self.handler.do_query(&query, ctx).await;
123        let (metric_name, mut result_type) =
124            match retrieve_metric_name_and_result_type(&query.query) {
125                Ok((metric_name, result_type)) => (metric_name, result_type),
126                Err(err) => {
127                    return PrometheusJsonResponse::error(err.status_code(), err.output_msg())
128                }
129            };
130        // range query only returns matrix
131        if is_range_query {
132            result_type = ValueType::Matrix;
133        };
134
135        PrometheusJsonResponse::from_query_result(result, metric_name, result_type).await
136    }
137}