1use std::collections::HashMap;
16use std::convert::Infallible;
17use std::fmt::Display;
18use std::net::SocketAddr;
19use std::sync::{Arc, Mutex as StdMutex};
20use std::time::Duration;
21
22use async_trait::async_trait;
23use auth::{PermissionCheckerRef, UserProviderRef};
24use axum::extract::{DefaultBodyLimit, Request, State};
25use axum::http::StatusCode as HttpStatusCode;
26use axum::middleware::Next;
27use axum::response::{IntoResponse, Response};
28use axum::routing::Route;
29use axum::serve::ListenerExt;
30use axum::{Extension, Router, middleware, routing};
31use common_base::readable_size::ReadableSize;
32use common_recordbatch::RecordBatch;
33use common_telemetry::{error, info};
34use common_time::Timestamp;
35use common_time::timestamp::TimeUnit;
36use datatypes::data_type::DataType;
37use datatypes::schema::SchemaRef;
38use event::{LogState, LogValidatorRef};
39use futures::FutureExt;
40use http::{HeaderValue, Method};
41use serde::{Deserialize, Serialize};
42use serde_json::Value;
43use session::context::QueryContext;
44use snafu::{ResultExt, ensure};
45use tokio::sync::Mutex;
46use tokio::sync::oneshot::{self, Sender};
47use tonic::codegen::Service;
48use tower::{Layer, ServiceBuilder};
49use tower_http::compression::CompressionLayer;
50use tower_http::cors::{AllowOrigin, Any, CorsLayer};
51use tower_http::decompression::RequestDecompressionLayer;
52use tower_http::trace::TraceLayer;
53
54use self::authorize::AuthState;
55use self::result::table_result::TableResponse;
56use crate::batcher::BatchingProtocol;
57use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
58use crate::elasticsearch;
59use crate::error::{AlreadyStartedSnafu, Error, InternalIoSnafu, InvalidHeaderValueSnafu, Result};
60use crate::http::influxdb::{influxdb_health, influxdb_ping, influxdb_write_v1, influxdb_write_v2};
61use crate::http::listener::HttpListener;
62use crate::http::otlp::OtlpState;
63use crate::http::prom_store::PromStoreState;
64use crate::http::prometheus::{
65 build_info_query, format_query, instant_query, label_values_query, labels_query,
66 metadata_query, parse_query, query_exemplars, range_query, series_query,
67};
68use crate::http::result::arrow_result::ArrowResponse;
69use crate::http::result::csv_result::CsvResponse;
70use crate::http::result::error_result::ErrorResponse;
71use crate::http::result::greptime_result_v1::GreptimedbV1Response;
72use crate::http::result::influxdb_result_v1::InfluxdbV1Response;
73use crate::http::result::json_result::JsonResponse;
74use crate::http::result::null_result::NullResponse;
75use crate::interceptor::LogIngestInterceptorRef;
76use crate::metrics::http_metrics_layer;
77use crate::metrics_handler::MetricsHandler;
78use crate::prometheus_handler::PrometheusHandlerRef;
79use crate::query_handler::sql::ServerSqlQueryHandlerRef;
80use crate::query_handler::{
81 DashboardHandlerRef, InfluxdbLineProtocolHandlerRef, JaegerQueryHandlerRef, LogQueryHandlerRef,
82 OpenTelemetryProtocolHandlerRef, OpentsdbProtocolHandlerRef, PipelineHandlerRef,
83 PromStoreProtocolHandlerRef,
84};
85use crate::request_memory_limiter::ServerMemoryLimiter;
86use crate::server::Server;
87use crate::tls::TlsOption;
88
89pub mod authorize;
90#[cfg(feature = "dashboard")]
91mod dashboard;
92pub mod dyn_log;
93pub mod dyn_trace;
94pub mod event;
95pub mod extractor;
96pub mod handler;
97pub mod header;
98pub mod influxdb;
99pub mod jaeger;
100mod listener;
101pub mod logs;
102pub mod loki;
103pub mod mem_prof;
104mod memory_limit;
105pub mod opentsdb;
106pub mod otlp;
107pub mod pprof;
108pub mod prom_store;
109pub mod prometheus;
110pub mod result;
111pub mod splunk;
112mod timeout;
113pub mod utils;
114mod workload_scheduler;
115
116pub use memory_limit::decoded_body_accounting_middleware;
117pub(crate) use memory_limit::memory_limit_middleware;
118use result::HttpOutputWriter;
119pub(crate) use timeout::DynamicTimeoutLayer;
120
121mod client_ip;
122use crate::prom_remote_write::validation::PromValidationMode;
123mod hints;
124mod read_preference;
125mod skip_wal;
126#[cfg(any(test, feature = "testing"))]
127pub mod test_helpers;
128
129pub const HTTP_API_VERSION: &str = "v1";
130pub const HTTP_API_PREFIX: &str = "/v1/";
131pub const HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH: &str = "/v1";
132
133pub trait ExtraHttpRouterProvider: Send + Sync {
135 fn router(&self) -> Router;
137}
138
139pub type ExtraHttpRouterProviderRef = Arc<dyn ExtraHttpRouterProvider>;
140
141#[derive(Clone, Default)]
143pub struct ExtraHttpRouterProviders {
144 providers: Vec<ExtraHttpRouterProviderRef>,
145}
146
147impl ExtraHttpRouterProviders {
148 pub fn new() -> Self {
150 Self::default()
151 }
152
153 pub fn add(&mut self, provider: ExtraHttpRouterProviderRef) {
155 self.providers.push(provider);
156 }
157
158 pub fn iter(&self) -> impl Iterator<Item = &dyn ExtraHttpRouterProvider> {
160 self.providers.iter().map(|x| x.as_ref())
161 }
162}
163
164const DEFAULT_BODY_LIMIT: ReadableSize = ReadableSize::mb(64);
166const DEFAULT_HTTP_API_ADDR_PORT: u16 = 4006;
168
169pub const AUTHORIZATION_HEADER: &str = "x-greptime-auth";
171
172pub static PUBLIC_API_PREFIX: [&str; 5] = [
175 "/v1/auth/config",
176 "/v1/influxdb/ping",
177 "/v1/influxdb/health",
178 "/v1/health",
179 "/v1/splunk/services/collector/health",
180];
181
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
188pub(crate) enum HttpServerKind {
189 #[default]
192 Full,
193 Api,
195}
196
197#[derive(Default)]
198pub struct HttpServer {
199 router: StdMutex<Router>,
200 shutdown_tx: Mutex<Option<Sender<()>>>,
201 user_provider: Option<UserProviderRef>,
202 admin_checker: Option<PermissionCheckerRef>,
203 memory_limiter: ServerMemoryLimiter,
204
205 options: HttpOptions,
207 batching_protocols: Vec<BatchingProtocol>,
208 logical_batching_protocols: Vec<BatchingProtocol>,
209 bind_addr: Option<SocketAddr>,
210 kind: HttpServerKind,
212}
213
214pub(crate) fn is_namespace(path: &str, root: &str) -> bool {
218 path == root
219 || path
220 .strip_prefix(root)
221 .is_some_and(|suffix| suffix.starts_with('/'))
222}
223
224pub fn is_api_listener_path(path: &str) -> bool {
226 is_namespace(path, HTTP_API_PREFIX_WITHOUT_TRAILING_SLASH) || is_namespace(path, "/dashboard")
227}
228
229#[derive(Clone)]
230struct LogicalBatchingProtocols(Vec<BatchingProtocol>);
231
232pub async fn set_http_write_batching(
234 State(protocol): State<BatchingProtocol>,
235 mut req: Request,
236 next: Next,
237) -> Response {
238 let enabled = req
239 .extensions()
240 .get::<Arc<Vec<BatchingProtocol>>>()
241 .is_some_and(|protocols| protocols.contains(&protocol));
242 let logical_enabled = req
243 .extensions()
244 .get::<LogicalBatchingProtocols>()
245 .is_some_and(|protocols| protocols.0.contains(&protocol));
246 let body_memory_bytes = req
247 .extensions()
248 .get::<memory_limit::BodyMemoryAccounting>()
249 .map(memory_limit::BodyMemoryAccounting::reserved_bytes_counter);
250 if let Some(ctx) = req.extensions_mut().get_mut::<QueryContext>() {
251 ctx.set_batching_enabled(enabled);
252 ctx.set_logical_batching_enabled(logical_enabled);
253 if let Some(bytes) = body_memory_bytes {
254 ctx.set_body_memory_bytes(bytes);
255 }
256 }
257 next.run(req).await
258}
259
260async fn enforce_api_surface(req: Request, next: Next) -> Response {
264 if !is_api_listener_path(req.uri().path()) {
265 return HttpStatusCode::NOT_FOUND.into_response();
266 }
267 next.run(req).await
268}
269
270impl HttpServer {
271 fn kind(&self) -> &'static str {
273 match self.kind {
274 HttpServerKind::Api => "HTTP API",
275 HttpServerKind::Full => "HTTP",
276 }
277 }
278}
279
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(default)]
282pub struct HttpOptions {
283 pub addr: String,
284
285 pub tls: TlsOption,
287
288 #[serde(with = "humantime_serde")]
291 pub timeout: Duration,
292
293 #[serde(skip)]
294 pub disable_dashboard: bool,
295
296 pub body_limit: ReadableSize,
297
298 pub cors_allowed_origins: Vec<String>,
299
300 pub enable_cors: bool,
301
302 pub enable_api_server: bool,
307 pub api_server_addr: String,
310}
311
312impl Default for HttpOptions {
313 fn default() -> Self {
314 Self {
315 addr: "127.0.0.1:4000".to_string(),
316 tls: TlsOption::default(),
317 timeout: Duration::from_secs(0),
318 disable_dashboard: false,
319 body_limit: DEFAULT_BODY_LIMIT,
320 cors_allowed_origins: Vec::new(),
321 enable_cors: true,
322 enable_api_server: false,
323 api_server_addr: format!("127.0.0.1:{}", DEFAULT_HTTP_API_ADDR_PORT),
324 }
325 }
326}
327
328#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
329pub struct ColumnSchema {
330 name: String,
331 data_type: String,
332}
333
334impl ColumnSchema {
335 pub fn new(name: String, data_type: String) -> ColumnSchema {
336 ColumnSchema { name, data_type }
337 }
338}
339
340#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
341pub struct OutputSchema {
342 column_schemas: Vec<ColumnSchema>,
343}
344
345impl OutputSchema {
346 pub fn new(columns: Vec<ColumnSchema>) -> OutputSchema {
347 OutputSchema {
348 column_schemas: columns,
349 }
350 }
351}
352
353impl From<SchemaRef> for OutputSchema {
354 fn from(schema: SchemaRef) -> OutputSchema {
355 OutputSchema {
356 column_schemas: schema
357 .column_schemas()
358 .iter()
359 .map(|cs| ColumnSchema {
360 name: cs.name.clone(),
361 data_type: cs.data_type.name(),
362 })
363 .collect(),
364 }
365 }
366}
367
368#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
369pub struct HttpRecordsOutput {
370 schema: OutputSchema,
371 rows: Vec<Vec<Value>>,
372 #[serde(default)]
375 total_rows: usize,
376
377 #[serde(skip_serializing_if = "HashMap::is_empty")]
379 #[serde(default)]
380 metrics: HashMap<String, Value>,
381}
382
383impl HttpRecordsOutput {
384 pub fn num_rows(&self) -> usize {
385 self.rows.len()
386 }
387
388 pub fn num_cols(&self) -> usize {
389 self.schema.column_schemas.len()
390 }
391
392 pub fn schema(&self) -> &OutputSchema {
393 &self.schema
394 }
395
396 pub fn rows(&self) -> &Vec<Vec<Value>> {
397 &self.rows
398 }
399}
400
401impl HttpRecordsOutput {
402 pub fn try_new(
403 schema: SchemaRef,
404 recordbatches: Vec<RecordBatch>,
405 ) -> std::result::Result<HttpRecordsOutput, Error> {
406 if recordbatches.is_empty() {
407 Ok(HttpRecordsOutput {
408 schema: OutputSchema::from(schema),
409 rows: vec![],
410 total_rows: 0,
411 metrics: Default::default(),
412 })
413 } else {
414 let num_rows = recordbatches.iter().map(|r| r.num_rows()).sum::<usize>();
415 let mut rows = Vec::with_capacity(num_rows);
416
417 for recordbatch in recordbatches {
418 let mut writer = HttpOutputWriter::new(schema.num_columns(), None);
419 writer.write(recordbatch, &mut rows)?;
420 }
421
422 Ok(HttpRecordsOutput {
423 schema: OutputSchema::from(schema),
424 total_rows: rows.len(),
425 rows,
426 metrics: Default::default(),
427 })
428 }
429 }
430}
431
432#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
433#[serde(rename_all = "lowercase")]
434pub enum GreptimeQueryOutput {
435 AffectedRows(usize),
436 Records(HttpRecordsOutput),
437}
438
439#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
441pub enum ResponseFormat {
442 Arrow,
443 Csv(bool, bool),
445 Table,
446 #[default]
447 GreptimedbV1,
448 InfluxdbV1,
449 Json,
450 Null,
451}
452
453impl ResponseFormat {
454 pub fn parse(s: &str) -> Option<Self> {
455 match s {
456 "arrow" => Some(ResponseFormat::Arrow),
457 "csv" => Some(ResponseFormat::Csv(false, false)),
458 "csvwithnames" => Some(ResponseFormat::Csv(true, false)),
459 "csvwithnamesandtypes" => Some(ResponseFormat::Csv(true, true)),
460 "table" => Some(ResponseFormat::Table),
461 "greptimedb_v1" => Some(ResponseFormat::GreptimedbV1),
462 "influxdb_v1" => Some(ResponseFormat::InfluxdbV1),
463 "json" => Some(ResponseFormat::Json),
464 "null" => Some(ResponseFormat::Null),
465 _ => None,
466 }
467 }
468
469 pub fn as_str(&self) -> &'static str {
470 match self {
471 ResponseFormat::Arrow => "arrow",
472 ResponseFormat::Csv(_, _) => "csv",
473 ResponseFormat::Table => "table",
474 ResponseFormat::GreptimedbV1 => "greptimedb_v1",
475 ResponseFormat::InfluxdbV1 => "influxdb_v1",
476 ResponseFormat::Json => "json",
477 ResponseFormat::Null => "null",
478 }
479 }
480}
481
482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
483pub enum Epoch {
484 Nanosecond,
485 Microsecond,
486 Millisecond,
487 Second,
488}
489
490impl Epoch {
491 pub fn parse(s: &str) -> Option<Epoch> {
492 match s {
497 "ns" => Some(Epoch::Nanosecond),
498 "u" | "µ" => Some(Epoch::Microsecond),
499 "ms" => Some(Epoch::Millisecond),
500 "s" => Some(Epoch::Second),
501 _ => None, }
503 }
504
505 pub fn convert_timestamp(&self, ts: Timestamp) -> Option<Timestamp> {
506 match self {
507 Epoch::Nanosecond => ts.convert_to(TimeUnit::Nanosecond),
508 Epoch::Microsecond => ts.convert_to(TimeUnit::Microsecond),
509 Epoch::Millisecond => ts.convert_to(TimeUnit::Millisecond),
510 Epoch::Second => ts.convert_to(TimeUnit::Second),
511 }
512 }
513}
514
515impl Display for Epoch {
516 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
517 match self {
518 Epoch::Nanosecond => write!(f, "Epoch::Nanosecond"),
519 Epoch::Microsecond => write!(f, "Epoch::Microsecond"),
520 Epoch::Millisecond => write!(f, "Epoch::Millisecond"),
521 Epoch::Second => write!(f, "Epoch::Second"),
522 }
523 }
524}
525
526#[derive(Serialize, Deserialize, Debug)]
527pub enum HttpResponse {
528 Arrow(ArrowResponse),
529 Csv(CsvResponse),
530 Table(TableResponse),
531 Error(ErrorResponse),
532 GreptimedbV1(GreptimedbV1Response),
533 InfluxdbV1(InfluxdbV1Response),
534 Json(JsonResponse),
535 Null(NullResponse),
536}
537
538impl HttpResponse {
539 pub fn with_execution_time(self, execution_time: u64) -> Self {
540 match self {
541 HttpResponse::Arrow(resp) => resp.with_execution_time(execution_time).into(),
542 HttpResponse::Csv(resp) => resp.with_execution_time(execution_time).into(),
543 HttpResponse::Table(resp) => resp.with_execution_time(execution_time).into(),
544 HttpResponse::GreptimedbV1(resp) => resp.with_execution_time(execution_time).into(),
545 HttpResponse::InfluxdbV1(resp) => resp.with_execution_time(execution_time).into(),
546 HttpResponse::Json(resp) => resp.with_execution_time(execution_time).into(),
547 HttpResponse::Null(resp) => resp.with_execution_time(execution_time).into(),
548 HttpResponse::Error(resp) => resp.with_execution_time(execution_time).into(),
549 }
550 }
551
552 pub fn with_limit(self, limit: usize) -> Self {
553 match self {
554 HttpResponse::Csv(resp) => resp.with_limit(limit).into(),
555 HttpResponse::Table(resp) => resp.with_limit(limit).into(),
556 HttpResponse::GreptimedbV1(resp) => resp.with_limit(limit).into(),
557 HttpResponse::Json(resp) => resp.with_limit(limit).into(),
558 _ => self,
559 }
560 }
561}
562
563pub fn process_with_limit(
564 mut outputs: Vec<GreptimeQueryOutput>,
565 limit: usize,
566) -> Vec<GreptimeQueryOutput> {
567 outputs
568 .drain(..)
569 .map(|data| match data {
570 GreptimeQueryOutput::Records(mut records) => {
571 if records.rows.len() > limit {
572 records.rows.truncate(limit);
573 records.total_rows = limit;
574 }
575 GreptimeQueryOutput::Records(records)
576 }
577 _ => data,
578 })
579 .collect()
580}
581
582impl IntoResponse for HttpResponse {
583 fn into_response(self) -> Response {
584 match self {
585 HttpResponse::Arrow(resp) => resp.into_response(),
586 HttpResponse::Csv(resp) => resp.into_response(),
587 HttpResponse::Table(resp) => resp.into_response(),
588 HttpResponse::GreptimedbV1(resp) => resp.into_response(),
589 HttpResponse::InfluxdbV1(resp) => resp.into_response(),
590 HttpResponse::Json(resp) => resp.into_response(),
591 HttpResponse::Null(resp) => resp.into_response(),
592 HttpResponse::Error(resp) => resp.into_response(),
593 }
594 }
595}
596
597impl From<ArrowResponse> for HttpResponse {
598 fn from(value: ArrowResponse) -> Self {
599 HttpResponse::Arrow(value)
600 }
601}
602
603impl From<CsvResponse> for HttpResponse {
604 fn from(value: CsvResponse) -> Self {
605 HttpResponse::Csv(value)
606 }
607}
608
609impl From<TableResponse> for HttpResponse {
610 fn from(value: TableResponse) -> Self {
611 HttpResponse::Table(value)
612 }
613}
614
615impl From<ErrorResponse> for HttpResponse {
616 fn from(value: ErrorResponse) -> Self {
617 HttpResponse::Error(value)
618 }
619}
620
621impl From<GreptimedbV1Response> for HttpResponse {
622 fn from(value: GreptimedbV1Response) -> Self {
623 HttpResponse::GreptimedbV1(value)
624 }
625}
626
627impl From<InfluxdbV1Response> for HttpResponse {
628 fn from(value: InfluxdbV1Response) -> Self {
629 HttpResponse::InfluxdbV1(value)
630 }
631}
632
633impl From<JsonResponse> for HttpResponse {
634 fn from(value: JsonResponse) -> Self {
635 HttpResponse::Json(value)
636 }
637}
638
639impl From<NullResponse> for HttpResponse {
640 fn from(value: NullResponse) -> Self {
641 HttpResponse::Null(value)
642 }
643}
644
645#[derive(Clone)]
646pub struct ApiState {
647 pub sql_handler: ServerSqlQueryHandlerRef,
648}
649
650#[derive(Clone)]
651pub struct GreptimeOptionsConfigState {
652 pub greptime_config_options: String,
653}
654
655#[derive(Clone)]
656pub struct DashboardState {
657 pub handler: DashboardHandlerRef,
658}
659
660pub struct HttpServerBuilder {
661 options: HttpOptions,
662 batching_protocols: Vec<BatchingProtocol>,
663 logical_batching_protocols: Vec<BatchingProtocol>,
664 user_provider: Option<UserProviderRef>,
665 admin_checker: Option<PermissionCheckerRef>,
666 router: Router,
667 memory_limiter: ServerMemoryLimiter,
668}
669
670impl HttpServerBuilder {
671 pub fn new(options: HttpOptions) -> Self {
672 Self {
673 options,
674 batching_protocols: Vec::new(),
675 logical_batching_protocols: Vec::new(),
676 user_provider: None,
677 admin_checker: None,
678 router: Router::new(),
679 memory_limiter: ServerMemoryLimiter::default(),
680 }
681 }
682
683 pub fn with_logical_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
685 self.logical_batching_protocols = protocols;
686 self
687 }
688
689 pub fn with_batching_protocols(mut self, protocols: Vec<BatchingProtocol>) -> Self {
691 self.batching_protocols = protocols;
692 self
693 }
694
695 pub fn with_memory_limiter(mut self, limiter: ServerMemoryLimiter) -> Self {
697 self.memory_limiter = limiter;
698 self
699 }
700
701 pub fn with_sql_handler(self, sql_handler: ServerSqlQueryHandlerRef) -> Self {
702 let batch_body_limit = if self.options.body_limit.0 == 0 {
703 4 * 1024 * 1024
704 } else {
705 (self.options.body_limit.0 as usize).min(4 * 1024 * 1024)
706 };
707 let sql_router = HttpServer::route_sql(ApiState { sql_handler }, batch_body_limit);
708
709 Self {
710 router: self
711 .router
712 .nest(&format!("/{HTTP_API_VERSION}"), sql_router),
713 ..self
714 }
715 }
716
717 pub fn with_logs_handler(self, logs_handler: LogQueryHandlerRef) -> Self {
718 let logs_router = HttpServer::route_logs(logs_handler);
719
720 Self {
721 router: self
722 .router
723 .nest(&format!("/{HTTP_API_VERSION}"), logs_router),
724 ..self
725 }
726 }
727
728 pub fn with_opentsdb_handler(self, handler: OpentsdbProtocolHandlerRef) -> Self {
729 Self {
730 router: self.router.nest(
731 &format!("/{HTTP_API_VERSION}/opentsdb"),
732 HttpServer::route_opentsdb(handler),
733 ),
734 ..self
735 }
736 }
737
738 pub fn with_influxdb_handler(self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
739 Self {
740 router: self.router.nest(
741 &format!("/{HTTP_API_VERSION}/influxdb"),
742 HttpServer::route_influxdb(handler, self.memory_limiter.clone()),
743 ),
744 ..self
745 }
746 }
747
748 pub fn with_prom_handler(
749 self,
750 handler: PromStoreProtocolHandlerRef,
751 pipeline_handler: Option<PipelineHandlerRef>,
752 prom_store_with_metric_engine: bool,
753 prom_validation_mode: PromValidationMode,
754 pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
755 ) -> Self {
756 let state = PromStoreState {
757 prom_store_handler: handler,
758 pipeline_handler,
759 prom_store_with_metric_engine,
760 prom_validation_mode,
761 pending_rows_batcher,
762 memory_limiter: self.memory_limiter.clone(),
763 };
764
765 Self {
766 router: self.router.nest(
767 &format!("/{HTTP_API_VERSION}/prometheus"),
768 HttpServer::route_prom(state),
769 ),
770 ..self
771 }
772 }
773
774 pub fn with_prometheus_handler(self, handler: PrometheusHandlerRef) -> Self {
775 Self {
776 router: self.router.nest(
777 &format!("/{HTTP_API_VERSION}/prometheus/api/v1"),
778 HttpServer::route_prometheus(handler),
779 ),
780 ..self
781 }
782 }
783
784 pub fn with_otlp_handler(
785 self,
786 handler: OpenTelemetryProtocolHandlerRef,
787 with_metric_engine: bool,
788 ) -> Self {
789 Self {
790 router: self.router.nest(
791 &format!("/{HTTP_API_VERSION}/otlp"),
792 HttpServer::route_otlp(handler, with_metric_engine, self.memory_limiter.clone()),
793 ),
794 ..self
795 }
796 }
797
798 pub fn with_user_provider(self, user_provider: UserProviderRef) -> Self {
799 Self {
800 user_provider: Some(user_provider),
801 ..self
802 }
803 }
804
805 pub fn with_metrics_handler(self, handler: MetricsHandler) -> Self {
806 Self {
807 router: self.router.merge(HttpServer::route_metrics(handler)),
808 ..self
809 }
810 }
811
812 pub fn with_log_ingest_handler(
813 self,
814 handler: PipelineHandlerRef,
815 validator: Option<LogValidatorRef>,
816 ingest_interceptor: Option<LogIngestInterceptorRef<Error>>,
817 ) -> Self {
818 let log_state = LogState {
819 log_handler: handler,
820 log_validator: validator,
821 ingest_interceptor,
822 };
823
824 let router = self.router.nest(
825 &format!("/{HTTP_API_VERSION}"),
826 HttpServer::route_pipelines(log_state.clone(), self.memory_limiter.clone()),
827 );
828 let router = router.nest(
830 &format!("/{HTTP_API_VERSION}/events"),
831 #[allow(deprecated)]
832 HttpServer::route_log_deprecated(log_state.clone(), self.memory_limiter.clone()),
833 );
834
835 let router = router.nest(
836 &format!("/{HTTP_API_VERSION}/loki"),
837 HttpServer::route_loki(log_state.clone(), self.memory_limiter.clone()),
838 );
839
840 let router = router.nest(
841 &format!("/{HTTP_API_VERSION}/elasticsearch"),
842 HttpServer::route_elasticsearch(log_state.clone(), self.memory_limiter.clone()),
843 );
844
845 let router = router.nest(
846 &format!("/{HTTP_API_VERSION}/elasticsearch/"),
847 Router::new()
848 .route("/", routing::get(elasticsearch::handle_get_version))
849 .with_state(log_state.clone()),
850 );
851
852 let router = router.nest(
853 &format!("/{HTTP_API_VERSION}/splunk"),
854 HttpServer::route_splunk(log_state, self.memory_limiter.clone()),
855 );
856
857 Self { router, ..self }
858 }
859
860 pub fn with_greptime_config_options(self, opts: String) -> Self {
861 let config_router = HttpServer::route_config(GreptimeOptionsConfigState {
862 greptime_config_options: opts,
863 });
864
865 Self {
866 router: self.router.merge(config_router),
867 ..self
868 }
869 }
870
871 pub fn with_jaeger_handler(self, handler: JaegerQueryHandlerRef) -> Self {
872 Self {
873 router: self.router.nest(
874 &format!("/{HTTP_API_VERSION}/jaeger"),
875 HttpServer::route_jaeger(handler),
876 ),
877 ..self
878 }
879 }
880
881 pub fn with_dashboard_handler(self, handler: DashboardHandlerRef) -> Self {
882 Self {
883 router: self.router.nest(
884 &format!("/{HTTP_API_VERSION}/dashboards"),
885 HttpServer::route_dashboard(handler, self.memory_limiter.clone()),
886 ),
887 ..self
888 }
889 }
890
891 pub fn with_admin_checker(mut self, checker: PermissionCheckerRef) -> Self {
893 self.admin_checker = Some(checker);
894 self
895 }
896
897 pub fn with_extra_router(self, router: Router) -> Self {
898 Self {
899 router: self.router.merge(router),
900 ..self
901 }
902 }
903
904 pub fn add_layer<L>(self, layer: L) -> Self
905 where
906 L: Layer<Route> + Clone + Send + Sync + 'static,
907 L::Service: Service<Request> + Clone + Send + Sync + 'static,
908 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
909 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
910 <L::Service as Service<Request>>::Future: Send + 'static,
911 {
912 Self {
913 router: self.router.layer(layer),
914 ..self
915 }
916 }
917
918 pub fn build(self) -> HttpServer {
919 HttpServer {
920 options: self.options,
921 batching_protocols: self.batching_protocols.clone(),
922 logical_batching_protocols: self.logical_batching_protocols.clone(),
923 user_provider: self.user_provider,
924 admin_checker: self.admin_checker,
925 shutdown_tx: Mutex::new(None),
926 router: StdMutex::new(self.router),
927 bind_addr: None,
928 memory_limiter: self.memory_limiter,
929 kind: HttpServerKind::Full,
930 }
931 }
932
933 pub fn build_servers(self) -> (HttpServer, Option<HttpServer>) {
952 let api_enabled = self.options.enable_api_server;
953 let api_addr = self.options.api_server_addr.clone();
954
955 let internal = HttpServer {
956 options: self.options,
957 batching_protocols: self.batching_protocols.clone(),
958 logical_batching_protocols: self.logical_batching_protocols.clone(),
959 user_provider: self.user_provider.clone(),
960 admin_checker: self.admin_checker.clone(),
961 shutdown_tx: Mutex::new(None),
962 router: StdMutex::new(self.router.clone()),
963 bind_addr: None,
964 memory_limiter: self.memory_limiter.clone(),
965 kind: HttpServerKind::Full,
966 };
967
968 let api = if api_enabled {
969 let api_options = HttpOptions {
972 addr: api_addr,
973 ..internal.options.clone()
974 };
975 Some(HttpServer {
976 options: api_options,
977 batching_protocols: self.batching_protocols,
978 logical_batching_protocols: self.logical_batching_protocols,
979 user_provider: self.user_provider.clone(),
980 admin_checker: self.admin_checker.clone(),
981 shutdown_tx: Mutex::new(None),
982 router: StdMutex::new(self.router),
983 bind_addr: None,
984 memory_limiter: self.memory_limiter,
985 kind: HttpServerKind::Api,
986 })
987 } else {
988 None
989 };
990
991 (internal, api)
992 }
993}
994
995impl HttpServer {
996 pub fn make_app(&self) -> Router {
1006 let mut router = self.router.lock().unwrap().clone();
1007 let auth_router = Router::new()
1008 .route("/v1/auth/config", routing::get(authorize::auth_config))
1009 .with_state(AuthState::new(self.user_provider.clone()));
1010
1011 router = router
1012 .merge(auth_router)
1013 .route(
1014 &format!("/{HTTP_API_VERSION}/health"),
1015 routing::get(handler::health).post(handler::health),
1016 )
1017 .route("/", routing::get(handler::index))
1018 .route(
1019 "/health",
1020 routing::get(handler::health).post(handler::health),
1021 )
1022 .route(
1023 "/ready",
1024 routing::get(handler::health).post(handler::health),
1025 )
1026 .route("/status", routing::get(handler::status));
1027
1028 #[cfg(feature = "dashboard")]
1031 {
1032 if !self.options.disable_dashboard {
1033 info!("Enable dashboard service at '/dashboard'");
1034 router = router.route(
1036 "/dashboard",
1037 routing::get(|uri: axum::http::uri::Uri| async move {
1038 let path = uri.path();
1039 let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
1040
1041 let new_uri = format!("{}/{}", path, query);
1042 axum::response::Redirect::permanent(&new_uri)
1043 }),
1044 );
1045
1046 router = router
1050 .route(
1051 "/dashboard/",
1052 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1053 )
1054 .route(
1055 "/dashboard/{*x}",
1056 routing::get(dashboard::static_handler).post(dashboard::static_handler),
1057 );
1058 }
1059 }
1060
1061 if let Some(checker) = &self.admin_checker {
1062 let state = AuthState::new(self.user_provider.clone())
1063 .with_permission_checker(Some(checker.clone()));
1064 router = router.route_layer(middleware::from_fn_with_state(
1065 state,
1066 authorize::check_admin_auth,
1067 ));
1068 }
1069
1070 router = router.route_layer(middleware::from_fn(http_metrics_layer));
1072
1073 router
1074 }
1075
1076 pub fn build(&self, router: Router) -> Result<Router> {
1079 let timeout_layer = ServiceBuilder::new().layer(
1080 DynamicTimeoutLayer::new(self.options.timeout)
1081 .with_status_code_fn(Self::request_timeout_status_code),
1082 );
1083 let body_limit_layer = if self.options.body_limit != ReadableSize(0) {
1084 Some(
1085 ServiceBuilder::new()
1086 .layer(DefaultBodyLimit::max(self.options.body_limit.0 as usize)),
1087 )
1088 } else {
1089 info!("HTTP server body limit is disabled");
1090 None
1091 };
1092 let cors_layer = if self.options.enable_cors {
1093 Some(
1094 CorsLayer::new()
1095 .allow_methods([
1096 Method::GET,
1097 Method::POST,
1098 Method::PUT,
1099 Method::DELETE,
1100 Method::HEAD,
1101 ])
1102 .allow_origin(cors_allow_origin(&self.options.cors_allowed_origins)?)
1103 .allow_headers(Any),
1104 )
1105 } else {
1106 info!("HTTP server cross-origin is disabled");
1107 None
1108 };
1109
1110 let router = router
1111 .layer(
1113 ServiceBuilder::new()
1114 .layer(TraceLayer::new_for_http().on_failure(()))
1117 .option_layer(cors_layer)
1118 .layer(timeout_layer)
1119 .option_layer(body_limit_layer)
1120 .layer(middleware::from_fn_with_state(
1122 self.memory_limiter.clone(),
1123 memory_limit_middleware,
1124 ))
1125 .layer(middleware::from_fn_with_state(
1127 AuthState::new(self.user_provider.clone()),
1128 authorize::check_http_auth,
1129 ))
1130 .layer(Extension(Arc::new(self.batching_protocols.clone())))
1131 .layer(Extension(LogicalBatchingProtocols(
1132 self.logical_batching_protocols.clone(),
1133 )))
1134 .layer(middleware::from_fn(hints::extract_hints))
1135 .layer(middleware::from_fn(client_ip::log_error_with_client_ip))
1136 .layer(middleware::from_fn(
1137 read_preference::extract_read_preference,
1138 ))
1139 .layer(middleware::from_fn(skip_wal::extract_skip_wal)),
1140 );
1141
1142 let debug_router = Router::new().nest(
1147 "/debug",
1148 Router::new()
1149 .route("/log_level", routing::post(dyn_log::dyn_log_handler))
1151 .route(
1152 "/workload_scheduler",
1153 routing::get(workload_scheduler::get_status_handler),
1154 )
1155 .route(
1156 "/workload_scheduler/enabled",
1157 routing::post(workload_scheduler::set_enabled_handler),
1158 )
1159 .route(
1160 "/workload_scheduler/weights",
1161 routing::post(workload_scheduler::set_weights_handler),
1162 )
1163 .route("/enable_trace", routing::post(dyn_trace::dyn_trace_handler))
1164 .nest(
1165 "/prof",
1166 Router::new()
1167 .route("/cpu", routing::post(pprof::pprof_handler))
1168 .route("/mem", routing::post(mem_prof::mem_prof_handler))
1169 .route("/mem/symbol", routing::post(mem_prof::symbolicate_handler))
1170 .route(
1171 "/mem/activate",
1172 routing::post(mem_prof::activate_heap_prof_handler),
1173 )
1174 .route(
1175 "/mem/deactivate",
1176 routing::post(mem_prof::deactivate_heap_prof_handler),
1177 )
1178 .route(
1179 "/mem/status",
1180 routing::get(mem_prof::heap_prof_status_handler),
1181 ) .route(
1183 "/mem/gdump",
1184 routing::get(mem_prof::gdump_status_handler)
1185 .post(mem_prof::gdump_toggle_handler),
1186 ),
1187 ),
1188 );
1189 let router = debug_router
1192 .layer(middleware::from_fn_with_state(
1193 AuthState::new(self.user_provider.clone()),
1194 authorize::check_http_auth,
1195 ))
1196 .merge(router);
1197
1198 if self.kind == HttpServerKind::Api {
1203 Ok(router.layer(middleware::from_fn(enforce_api_surface)))
1204 } else {
1205 Ok(router)
1206 }
1207 }
1208
1209 fn request_timeout_status_code(request: &Request) -> HttpStatusCode {
1210 if request.uri().path() == "/v1/prometheus/write" {
1211 HttpStatusCode::GATEWAY_TIMEOUT
1212 } else {
1213 HttpStatusCode::REQUEST_TIMEOUT
1214 }
1215 }
1216
1217 fn route_metrics<S>(metrics_handler: MetricsHandler) -> Router<S> {
1218 Router::new()
1219 .route("/metrics", routing::get(handler::metrics))
1220 .with_state(metrics_handler)
1221 }
1222
1223 fn route_loki<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1224 Router::new()
1225 .route("/api/v1/push", routing::post(loki::loki_ingest))
1226 .layer(middleware::from_fn_with_state(
1227 memory_limiter,
1228 memory_limit::decoded_body_accounting_middleware,
1229 ))
1230 .layer(
1231 ServiceBuilder::new()
1232 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1233 )
1234 .layer(middleware::from_fn_with_state(
1235 BatchingProtocol::Loki,
1236 set_http_write_batching,
1237 ))
1238 .with_state(log_state)
1239 }
1240
1241 fn route_splunk<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1242 Router::new()
1243 .route(
1244 "/services/collector/health",
1245 routing::get(splunk::handle_health),
1246 )
1247 .route(
1248 "/services/collector/health/1.0",
1249 routing::get(splunk::handle_health),
1250 )
1251 .route(
1254 "/services/collector/event",
1255 routing::post(splunk::handle_event),
1256 )
1257 .route("/services/collector", routing::post(splunk::handle_event))
1258 .route(
1259 "/services/collector/event/1.0",
1260 routing::post(splunk::handle_event),
1261 )
1262 .route("/services/collector/raw", routing::post(splunk::handle_raw))
1265 .route(
1266 "/services/collector/raw/1.0",
1267 routing::post(splunk::handle_raw),
1268 )
1269 .layer(middleware::from_fn_with_state(
1270 memory_limiter,
1271 memory_limit::decoded_body_accounting_middleware,
1272 ))
1273 .layer(
1274 ServiceBuilder::new()
1275 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1276 )
1277 .layer(middleware::from_fn_with_state(
1278 BatchingProtocol::Splunk,
1279 set_http_write_batching,
1280 ))
1281 .with_state(log_state)
1282 }
1283
1284 fn route_elasticsearch<S>(
1285 log_state: LogState,
1286 memory_limiter: ServerMemoryLimiter,
1287 ) -> Router<S> {
1288 Router::new()
1289 .route(
1291 "/",
1292 routing::head((HttpStatusCode::OK, elasticsearch::elasticsearch_headers())),
1293 )
1294 .route("/", routing::get(elasticsearch::handle_get_version))
1296 .route("/_license", routing::get(elasticsearch::handle_get_license))
1298 .route("/_bulk", routing::post(elasticsearch::handle_bulk_api))
1299 .route(
1300 "/{index}/_bulk",
1301 routing::post(elasticsearch::handle_bulk_api_with_index),
1302 )
1303 .route(
1305 "/_ilm/policy/{*path}",
1306 routing::any((
1307 HttpStatusCode::OK,
1308 elasticsearch::elasticsearch_headers(),
1309 axum::Json(serde_json::json!({})),
1310 )),
1311 )
1312 .route(
1314 "/_index_template/{*path}",
1315 routing::any((
1316 HttpStatusCode::OK,
1317 elasticsearch::elasticsearch_headers(),
1318 axum::Json(serde_json::json!({})),
1319 )),
1320 )
1321 .route(
1324 "/_ingest/{*path}",
1325 routing::any((
1326 HttpStatusCode::OK,
1327 elasticsearch::elasticsearch_headers(),
1328 axum::Json(serde_json::json!({})),
1329 )),
1330 )
1331 .route(
1334 "/_nodes/{*path}",
1335 routing::any((
1336 HttpStatusCode::OK,
1337 elasticsearch::elasticsearch_headers(),
1338 axum::Json(serde_json::json!({})),
1339 )),
1340 )
1341 .route(
1344 "/logstash/{*path}",
1345 routing::any((
1346 HttpStatusCode::OK,
1347 elasticsearch::elasticsearch_headers(),
1348 axum::Json(serde_json::json!({})),
1349 )),
1350 )
1351 .route(
1352 "/_logstash/{*path}",
1353 routing::any((
1354 HttpStatusCode::OK,
1355 elasticsearch::elasticsearch_headers(),
1356 axum::Json(serde_json::json!({})),
1357 )),
1358 )
1359 .layer(middleware::from_fn_with_state(
1360 memory_limiter,
1361 memory_limit::decoded_body_accounting_middleware,
1362 ))
1363 .layer(ServiceBuilder::new().layer(RequestDecompressionLayer::new()))
1364 .layer(middleware::from_fn_with_state(
1365 BatchingProtocol::Elasticsearch,
1366 set_http_write_batching,
1367 ))
1368 .with_state(log_state)
1369 }
1370
1371 #[deprecated(since = "0.11.0", note = "Use `route_pipelines()` instead.")]
1372 fn route_log_deprecated<S>(
1373 log_state: LogState,
1374 memory_limiter: ServerMemoryLimiter,
1375 ) -> Router<S> {
1376 Router::new()
1377 .route("/logs", routing::post(event::log_ingester))
1378 .route(
1379 "/pipelines/{pipeline_name}",
1380 routing::get(event::query_pipeline),
1381 )
1382 .route(
1383 "/pipelines/{pipeline_name}",
1384 routing::post(event::add_pipeline),
1385 )
1386 .route(
1387 "/pipelines/{pipeline_name}",
1388 routing::delete(event::delete_pipeline),
1389 )
1390 .route("/pipelines/dryrun", routing::post(event::pipeline_dryrun))
1391 .layer(middleware::from_fn_with_state(
1392 memory_limiter,
1393 memory_limit::decoded_body_accounting_middleware,
1394 ))
1395 .layer(
1396 ServiceBuilder::new()
1397 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1398 )
1399 .layer(middleware::from_fn_with_state(
1400 BatchingProtocol::Logs,
1401 set_http_write_batching,
1402 ))
1403 .with_state(log_state)
1404 }
1405
1406 fn route_pipelines<S>(log_state: LogState, memory_limiter: ServerMemoryLimiter) -> Router<S> {
1407 Router::new()
1408 .route("/ingest", routing::post(event::log_ingester))
1409 .route(
1410 "/pipelines/{pipeline_name}",
1411 routing::get(event::query_pipeline),
1412 )
1413 .route(
1414 "/pipelines/{pipeline_name}/ddl",
1415 routing::get(event::query_pipeline_ddl),
1416 )
1417 .route(
1418 "/pipelines/{pipeline_name}",
1419 routing::post(event::add_pipeline),
1420 )
1421 .route(
1422 "/pipelines/{pipeline_name}",
1423 routing::delete(event::delete_pipeline),
1424 )
1425 .route("/pipelines/_dryrun", routing::post(event::pipeline_dryrun))
1426 .layer(middleware::from_fn_with_state(
1427 memory_limiter,
1428 memory_limit::decoded_body_accounting_middleware,
1429 ))
1430 .layer(
1431 ServiceBuilder::new()
1432 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1433 )
1434 .layer(middleware::from_fn_with_state(
1435 BatchingProtocol::Logs,
1436 set_http_write_batching,
1437 ))
1438 .with_state(log_state)
1439 }
1440
1441 fn route_sql<S>(api_state: ApiState, batch_body_limit: usize) -> Router<S> {
1442 Router::new()
1443 .route(
1444 "/capabilities",
1445 routing::get(|State(state): State<ApiState>| async move {
1446 let mut capabilities =
1447 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1});
1448 if state.sql_handler.supports_metric_batch_ddl() {
1449 capabilities["metric_batch_ddl"] = serde_json::json!(1);
1450 }
1451 axum::Json(capabilities)
1452 }),
1453 )
1454 .route(
1455 "/ddl/logical-tables",
1456 routing::post(handler::create_logical_tables)
1457 .layer(DefaultBodyLimit::max(batch_body_limit)),
1458 )
1459 .route(
1460 "/sql",
1461 routing::get(handler::sql).post(handler::sql).layer(
1462 middleware::from_fn_with_state(
1463 BatchingProtocol::HttpSql,
1464 set_http_write_batching,
1465 ),
1466 ),
1467 )
1468 .route(
1469 "/sql/parse",
1470 routing::get(handler::sql_parse).post(handler::sql_parse),
1471 )
1472 .route(
1473 "/sql/format",
1474 routing::get(handler::sql_format).post(handler::sql_format),
1475 )
1476 .route(
1477 "/promql",
1478 routing::get(handler::promql).post(handler::promql),
1479 )
1480 .route(
1481 "/sql/analyze/stream",
1482 routing::post(handler::sql_analyze_stream),
1483 )
1484 .with_state(api_state)
1485 }
1486
1487 fn route_logs<S>(log_handler: LogQueryHandlerRef) -> Router<S> {
1488 Router::new()
1489 .route("/logs", routing::get(logs::logs).post(logs::logs))
1490 .with_state(log_handler)
1491 }
1492
1493 pub fn route_prometheus<S>(prometheus_handler: PrometheusHandlerRef) -> Router<S> {
1497 Router::new()
1498 .route(
1499 "/format_query",
1500 routing::post(format_query).get(format_query),
1501 )
1502 .route("/status/buildinfo", routing::get(build_info_query))
1503 .route("/query", routing::post(instant_query).get(instant_query))
1504 .route("/query_range", routing::post(range_query).get(range_query))
1505 .route(
1506 "/query_exemplars",
1507 routing::post(query_exemplars).get(query_exemplars),
1508 )
1509 .route("/labels", routing::post(labels_query).get(labels_query))
1510 .route("/metadata", routing::get(metadata_query))
1511 .route("/series", routing::post(series_query).get(series_query))
1512 .route("/parse_query", routing::post(parse_query).get(parse_query))
1513 .route(
1514 "/label/{label_name}/values",
1515 routing::get(label_values_query),
1516 )
1517 .layer(ServiceBuilder::new().layer(CompressionLayer::new()))
1518 .with_state(prometheus_handler)
1519 }
1520
1521 fn route_prom<S>(state: PromStoreState) -> Router<S> {
1527 let write = routing::post(prom_store::remote_write);
1528 let write = if state.prom_store_with_metric_engine {
1529 write
1530 } else {
1531 write.layer(middleware::from_fn_with_state(
1532 BatchingProtocol::Prom,
1533 set_http_write_batching,
1534 ))
1535 };
1536 Router::new()
1537 .route("/read", routing::post(prom_store::remote_read))
1538 .route("/write", write)
1539 .with_state(state)
1540 }
1541
1542 fn route_influxdb<S>(
1543 influxdb_handler: InfluxdbLineProtocolHandlerRef,
1544 memory_limiter: ServerMemoryLimiter,
1545 ) -> Router<S> {
1546 Router::new()
1547 .route("/write", routing::post(influxdb_write_v1))
1548 .route("/api/v2/write", routing::post(influxdb_write_v2))
1549 .layer(middleware::from_fn_with_state(
1550 memory_limiter,
1551 memory_limit::decoded_body_accounting_middleware,
1552 ))
1553 .layer(
1554 ServiceBuilder::new()
1555 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1556 )
1557 .route("/ping", routing::get(influxdb_ping))
1558 .route("/health", routing::get(influxdb_health))
1559 .layer(middleware::from_fn_with_state(
1560 BatchingProtocol::Influxdb,
1561 set_http_write_batching,
1562 ))
1563 .with_state(influxdb_handler)
1564 }
1565
1566 fn route_opentsdb<S>(opentsdb_handler: OpentsdbProtocolHandlerRef) -> Router<S> {
1567 Router::new()
1568 .route("/api/put", routing::post(opentsdb::put))
1569 .layer(middleware::from_fn_with_state(
1570 BatchingProtocol::Opentsdb,
1571 set_http_write_batching,
1572 ))
1573 .with_state(opentsdb_handler)
1574 }
1575
1576 fn route_otlp<S>(
1577 otlp_handler: OpenTelemetryProtocolHandlerRef,
1578 with_metric_engine: bool,
1579 memory_limiter: ServerMemoryLimiter,
1580 ) -> Router<S> {
1581 Router::new()
1582 .route("/v1/metrics", routing::post(otlp::metrics))
1583 .route("/v1/traces", routing::post(otlp::traces))
1584 .route("/v1/logs", routing::post(otlp::logs))
1585 .layer(middleware::from_fn_with_state(
1586 memory_limiter,
1587 memory_limit::decoded_body_accounting_middleware,
1588 ))
1589 .layer(
1590 ServiceBuilder::new()
1591 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1592 )
1593 .layer(middleware::from_fn_with_state(
1594 BatchingProtocol::Otlp,
1595 set_http_write_batching,
1596 ))
1597 .with_state(OtlpState {
1598 with_metric_engine,
1599 handler: otlp_handler,
1600 })
1601 }
1602
1603 fn route_config<S>(state: GreptimeOptionsConfigState) -> Router<S> {
1604 Router::new()
1605 .route("/config", routing::get(handler::config))
1606 .with_state(state)
1607 }
1608
1609 fn route_jaeger<S>(handler: JaegerQueryHandlerRef) -> Router<S> {
1610 Router::new()
1611 .route("/api/services", routing::get(jaeger::handle_get_services))
1612 .route(
1613 "/api/services/{service_name}/operations",
1614 routing::get(jaeger::handle_get_operations_by_service),
1615 )
1616 .route(
1617 "/api/operations",
1618 routing::get(jaeger::handle_get_operations),
1619 )
1620 .route("/api/traces", routing::get(jaeger::handle_find_traces))
1621 .route(
1622 "/api/traces/{trace_id}",
1623 routing::get(jaeger::handle_get_trace),
1624 )
1625 .route(
1626 "/api/v3/services",
1627 routing::get(jaeger::v3::handle_get_services),
1628 )
1629 .route(
1630 "/api/v3/operations",
1631 routing::get(jaeger::v3::handle_get_operations),
1632 )
1633 .route(
1634 "/api/v3/traces",
1635 routing::get(jaeger::v3::handle_find_traces),
1636 )
1637 .route(
1638 "/api/v3/trace-summaries",
1639 routing::get(jaeger::v3::handle_find_trace_summaries),
1640 )
1641 .route(
1642 "/api/v3/traces/{trace_id}",
1643 routing::get(jaeger::v3::handle_get_trace),
1644 )
1645 .with_state(handler)
1646 }
1647
1648 #[cfg(feature = "dashboard")]
1649 fn route_dashboard<S>(
1650 handler: DashboardHandlerRef,
1651 memory_limiter: ServerMemoryLimiter,
1652 ) -> Router<S> {
1653 use crate::http::dashboard::{add_dashboard, delete_dashboard, list_dashboards};
1654
1655 Router::new()
1656 .route("/", routing::get(list_dashboards))
1657 .route("/{dashboard_name}", routing::post(add_dashboard))
1658 .route("/{dashboard_name}", routing::delete(delete_dashboard))
1659 .layer(middleware::from_fn_with_state(
1660 memory_limiter,
1661 memory_limit::decoded_body_accounting_middleware,
1662 ))
1663 .layer(
1664 ServiceBuilder::new()
1665 .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true)),
1666 )
1667 .with_state(DashboardState { handler })
1668 }
1669
1670 #[cfg(not(feature = "dashboard"))]
1671 fn route_dashboard<S>(
1672 handler: DashboardHandlerRef,
1673 _memory_limiter: ServerMemoryLimiter,
1674 ) -> Router<S> {
1675 Router::new().with_state(DashboardState { handler })
1676 }
1677}
1678
1679pub const HTTP_SERVER: &str = "HTTP_SERVER";
1680pub const HTTP_API_SERVER: &str = "HTTP_API_SERVER";
1681
1682pub(crate) fn cors_allow_origin(origins: &[String]) -> Result<AllowOrigin> {
1684 if origins.is_empty() {
1685 return Ok(AllowOrigin::any());
1686 }
1687 let origins = origins
1688 .iter()
1689 .map(|origin| HeaderValue::from_str(origin).context(InvalidHeaderValueSnafu))
1690 .collect::<Result<Vec<_>>>()?;
1691 Ok(AllowOrigin::list(origins))
1692}
1693
1694#[async_trait]
1695impl Server for HttpServer {
1696 async fn shutdown(&self) -> Result<()> {
1697 let mut shutdown_tx = self.shutdown_tx.lock().await;
1698 if let Some(tx) = shutdown_tx.take()
1699 && tx.send(()).is_err()
1700 {
1701 info!("Receiver dropped, the HTTP server has already exited");
1702 }
1703 info!("Shutdown {}", self.kind());
1704
1705 Ok(())
1706 }
1707
1708 async fn start(&mut self, listening: SocketAddr) -> Result<()> {
1709 let (tx, rx) = oneshot::channel();
1710 let serve = {
1711 let mut shutdown_tx = self.shutdown_tx.lock().await;
1712 ensure!(
1713 shutdown_tx.is_none(),
1714 AlreadyStartedSnafu {
1715 server: self.kind()
1716 }
1717 );
1718
1719 let app = self.build(self.make_app())?;
1720 let listener = HttpListener::bind(listening, &self.options.tls)
1721 .await?
1722 .tap_io(|_| {});
1724 let serve = axum::serve(
1725 listener,
1726 app.into_make_service_with_connect_info::<SocketAddr>(),
1727 );
1728
1729 *shutdown_tx = Some(tx);
1746
1747 serve
1748 };
1749 let listening = serve.local_addr().context(InternalIoSnafu)?;
1750 info!("{} server is bound to {}", self.kind(), listening);
1751
1752 common_runtime::spawn_global(async move {
1753 if let Err(e) = serve
1754 .with_graceful_shutdown(rx.map(drop))
1755 .await
1756 .context(InternalIoSnafu)
1757 {
1758 error!(e; "Failed to shutdown http server");
1759 }
1760 });
1761
1762 self.bind_addr = Some(listening);
1763 Ok(())
1764 }
1765
1766 fn name(&self) -> &str {
1767 match self.kind {
1768 HttpServerKind::Api => HTTP_API_SERVER,
1769 HttpServerKind::Full => HTTP_SERVER,
1770 }
1771 }
1772
1773 fn bind_addr(&self) -> Option<SocketAddr> {
1774 self.bind_addr
1775 }
1776
1777 fn as_any(&self) -> &dyn std::any::Any {
1778 self
1779 }
1780}
1781
1782#[cfg(test)]
1783mod test {
1784 use std::future::pending;
1785 use std::io::Cursor;
1786 use std::sync::Arc;
1787
1788 use arrow_ipc::reader::StreamReader;
1789 use arrow_schema::DataType;
1790 use axum::http::StatusCode;
1791 use axum::routing::{get, post};
1792 use common_query::{Output, OutputData};
1793 use common_recordbatch::RecordBatches;
1794 use datafusion_expr::LogicalPlan;
1795 use datatypes::prelude::*;
1796 use datatypes::schema::{ColumnSchema, Schema};
1797 use datatypes::vectors::{StringVector, UInt32Vector};
1798 use header::constants::GREPTIME_DB_HEADER_TIMEOUT;
1799 use query::parser::PromQuery;
1800 use query::query_engine::DescribeResult;
1801 use session::context::QueryContextRef;
1802 use sql::statements::statement::Statement;
1803 use tokio::sync::mpsc;
1804 use tokio::time::Instant;
1805
1806 use crate::http::test_helpers::TestClient;
1807 use crate::http::*;
1808 use crate::prom_remote_write::validation::validate_label_name;
1809 use crate::query_handler::sql::SqlQueryHandler;
1810
1811 struct DummyInstance {
1812 _tx: mpsc::Sender<(String, Vec<u8>)>,
1813 }
1814
1815 #[async_trait]
1816 impl SqlQueryHandler for DummyInstance {
1817 async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1818 unimplemented!()
1819 }
1820
1821 async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1822 let stream = common_recordbatch::RecordBatches::empty().as_stream();
1823 Ok(Output::new(OutputData::Stream(stream), Default::default()))
1824 }
1825
1826 async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1827 unimplemented!()
1828 }
1829
1830 async fn do_exec_plan(
1831 &self,
1832 _plan: LogicalPlan,
1833 _stmt: Option<Statement>,
1834 _query_ctx: QueryContextRef,
1835 ) -> Result<Output> {
1836 unimplemented!()
1837 }
1838
1839 async fn do_describe(
1840 &self,
1841 _stmt: sql::statements::statement::Statement,
1842 _query_ctx: QueryContextRef,
1843 ) -> Result<Option<DescribeResult>> {
1844 unimplemented!()
1845 }
1846
1847 async fn is_valid_schema(&self, _catalog: &str, _schema: &str) -> Result<bool> {
1848 Ok(true)
1849 }
1850 }
1851
1852 async fn forever() {
1853 pending().await
1854 }
1855
1856 fn make_test_app(tx: mpsc::Sender<(String, Vec<u8>)>) -> Router {
1857 make_test_app_custom(tx, HttpOptions::default())
1858 }
1859
1860 fn make_test_app_custom(tx: mpsc::Sender<(String, Vec<u8>)>, options: HttpOptions) -> Router {
1861 let instance = Arc::new(DummyInstance { _tx: tx });
1862 let server = HttpServerBuilder::new(options)
1863 .with_sql_handler(instance.clone())
1864 .build();
1865 let app = server
1866 .make_app()
1867 .route("/test/timeout", get(forever))
1868 .route("/v1/prometheus/write", post(forever));
1869 server.build(app).unwrap()
1870 }
1871
1872 fn make_split_builder() -> HttpServerBuilder {
1873 let (tx, _rx) = mpsc::channel(100);
1874 let instance = Arc::new(DummyInstance { _tx: tx });
1875 let options = HttpOptions {
1877 enable_api_server: true,
1878 ..HttpOptions::default()
1879 };
1880 HttpServerBuilder::new(options)
1881 .with_sql_handler(instance)
1882 .with_metrics_handler(MetricsHandler)
1883 .with_greptime_config_options("dummy = \"value\"".to_string())
1884 }
1885
1886 #[tokio::test]
1887 pub async fn test_http_api_options_defaults() {
1888 let opts = HttpOptions::default();
1889 assert!(!opts.enable_api_server);
1891 assert_eq!(opts.api_server_addr, "127.0.0.1:4006");
1892 }
1893
1894 #[tokio::test]
1895 async fn test_auth_config_without_provider_disables_auth() {
1896 let server = HttpServerBuilder::new(HttpOptions::default()).build();
1897 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1898 let response = client.get("/v1/auth/config").send().await;
1899
1900 assert_eq!(response.status(), StatusCode::OK);
1901 assert_eq!(
1902 response.json::<serde_json::Value>().await,
1903 serde_json::json!({"auth_required": false, "methods": []})
1904 );
1905 }
1906
1907 #[tokio::test]
1908 async fn test_auth_config_with_provider_is_public() {
1909 let provider =
1910 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
1911 .unwrap();
1912 let server = HttpServerBuilder::new(HttpOptions::default())
1913 .with_user_provider(Arc::new(provider))
1914 .build();
1915 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
1916 let response = client.get("/v1/auth/config").send().await;
1917
1918 assert_eq!(response.status(), StatusCode::OK);
1919 assert_eq!(
1920 response.json::<serde_json::Value>().await,
1921 serde_json::json!({
1922 "auth_required": true,
1923 "methods": [{"type": "password"}]
1924 })
1925 );
1926 }
1927
1928 #[tokio::test]
1929 pub async fn test_build_serves_all_routes() {
1930 let server = make_split_builder().build();
1934 assert_eq!(server.name(), HTTP_SERVER);
1935
1936 let app = server.build(server.make_app()).unwrap();
1937 let client = TestClient::new(app).await;
1938
1939 for path in ["/v1/health", "/health", "/status", "/metrics", "/config"] {
1940 let res = client.get(path).send().await;
1941 assert_eq!(
1942 res.status(),
1943 StatusCode::OK,
1944 "internal/full server should serve {path}"
1945 );
1946 }
1947 }
1948
1949 #[tokio::test]
1950 pub async fn test_build_servers_separates_api_and_internal_routes() {
1951 let (internal, api) = make_split_builder().build_servers();
1954 let api = api.expect("API server is explicitly enabled in make_split_builder");
1955 assert_eq!(internal.name(), HTTP_SERVER);
1956 assert_eq!(api.name(), HTTP_API_SERVER);
1957
1958 let internal_app = internal.build(internal.make_app()).unwrap();
1959 let api_app = api.build(api.make_app()).unwrap();
1960
1961 let internal_client = TestClient::new(internal_app).await;
1962 let api_client = TestClient::new(api_app).await;
1963
1964 assert_eq!(
1966 internal_client.get("/v1/health").send().await.status(),
1967 StatusCode::OK
1968 );
1969 assert_eq!(
1970 api_client.get("/v1/health").send().await.status(),
1971 StatusCode::OK
1972 );
1973
1974 for path in ["/health", "/status", "/metrics", "/config"] {
1976 assert_eq!(
1977 internal_client.get(path).send().await.status(),
1978 StatusCode::OK,
1979 "internal/full server should serve {path}"
1980 );
1981 assert_eq!(
1983 api_client.get(path).send().await.status(),
1984 StatusCode::NOT_FOUND,
1985 "API server should NOT serve {path}"
1986 );
1987 }
1988 }
1989
1990 #[test]
1991 fn test_build_servers_api_inherits_http_options() {
1992 let http_opts = HttpOptions {
1994 timeout: Duration::from_secs(42),
1995 body_limit: ReadableSize::mb(128),
1996 cors_allowed_origins: vec!["https://example.com".to_string()],
1997 enable_api_server: true,
1998 ..HttpOptions::default()
1999 };
2000 let (internal, api) = HttpServerBuilder::new(http_opts.clone()).build_servers();
2001 let api = api.expect("API server is explicitly enabled");
2002
2003 assert_eq!(internal.options.addr, http_opts.addr);
2005 assert_eq!(api.options.addr, "127.0.0.1:4006");
2006 assert_eq!(api.options.timeout, http_opts.timeout);
2008 assert_eq!(api.options.body_limit, http_opts.body_limit);
2009 assert_eq!(
2010 api.options.cors_allowed_origins,
2011 http_opts.cors_allowed_origins
2012 );
2013 }
2014
2015 #[test]
2016 fn test_is_api_listener_path() {
2017 assert!(is_api_listener_path("/v1"));
2019 assert!(is_api_listener_path("/v1/"));
2020 assert!(is_api_listener_path("/v1/sql"));
2021 assert!(!is_api_listener_path("/v10/sql"));
2022 assert!(!is_api_listener_path("/v1-internal"));
2023 assert!(is_api_listener_path("/dashboard"));
2025 assert!(is_api_listener_path("/dashboard/app.js"));
2026 assert!(!is_api_listener_path("/dashboard-admin"));
2027 assert!(!is_api_listener_path("/metrics"));
2029 assert!(!is_api_listener_path("/status/plugin"));
2030 assert!(!is_api_listener_path("/health"));
2031 }
2032
2033 #[tokio::test]
2034 async fn debug_routes_require_auth_when_provider_is_configured() {
2035 let server = HttpServerBuilder::new(HttpOptions::default()).build();
2036 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2037 assert_eq!(
2038 client
2039 .get("/debug/workload_scheduler")
2040 .send()
2041 .await
2042 .status(),
2043 StatusCode::OK
2044 );
2045 let response = client
2046 .get("/no_such_path")
2047 .header("Origin", "https://example.com")
2048 .send()
2049 .await;
2050 assert_eq!(response.status(), StatusCode::NOT_FOUND);
2051 assert!(
2052 response
2053 .headers()
2054 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2055 );
2056
2057 let provider =
2058 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
2059 .unwrap();
2060 let server = HttpServerBuilder::new(HttpOptions::default())
2061 .with_user_provider(Arc::new(provider))
2062 .build();
2063 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2064 assert_eq!(
2065 client
2066 .get("/debug/workload_scheduler")
2067 .send()
2068 .await
2069 .status(),
2070 StatusCode::UNAUTHORIZED
2071 );
2072 assert_eq!(
2073 client
2074 .post("/debug/log_level")
2075 .body("info")
2076 .send()
2077 .await
2078 .status(),
2079 StatusCode::UNAUTHORIZED
2080 );
2081 assert_eq!(
2082 client
2083 .get("/debug/workload_scheduler")
2084 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
2085 .send()
2086 .await
2087 .status(),
2088 StatusCode::OK
2089 );
2090 }
2091
2092 #[tokio::test]
2093 async fn admin_auth_is_independent_of_debug_database_access() {
2094 let provider = auth::tests::MockUserProvider {
2095 schema: "operations".to_string(),
2096 ..Default::default()
2097 };
2098 let server = HttpServerBuilder::new(HttpOptions::default())
2099 .with_user_provider(Arc::new(provider))
2100 .with_admin_checker(auth::DefaultPermissionChecker::arc())
2101 .with_extra_router(
2102 Router::new().route("/admin/plugin", routing::get(|| async { StatusCode::OK })),
2103 )
2104 .build();
2105 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2106 for (path, expected) in [
2107 ("/admin/plugin", StatusCode::OK),
2108 ("/debug/workload_scheduler", StatusCode::UNAUTHORIZED),
2109 ("/debug/workload_scheduler?db=operations", StatusCode::OK),
2110 ] {
2111 assert_eq!(
2112 client
2113 .get(path)
2114 .header("Authorization", "Basic Z3JlcHRpbWU6Z3JlcHRpbWU=")
2115 .send()
2116 .await
2117 .status(),
2118 expected,
2119 "{path}"
2120 );
2121 }
2122 }
2123
2124 #[tokio::test]
2125 async fn packed_capability_requires_auth_on_full_and_api_listeners() {
2126 let (tx, _rx) = mpsc::channel(1);
2127 let provider =
2128 auth::static_user_provider_from_option("static_user_provider:cmd:user=password")
2129 .unwrap();
2130 let (full, api) = HttpServerBuilder::new(HttpOptions {
2131 enable_api_server: true,
2132 ..Default::default()
2133 })
2134 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
2135 .with_user_provider(Arc::new(provider))
2136 .build_servers();
2137 for server in [full, api.unwrap()] {
2138 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2139 assert_eq!(
2140 client.get("/v1/capabilities").send().await.status(),
2141 StatusCode::UNAUTHORIZED
2142 );
2143 assert_eq!(
2144 client
2145 .post("/v1/ddl/logical-tables")
2146 .form(&[("sql", "SELECT 1")])
2147 .send()
2148 .await
2149 .status(),
2150 StatusCode::UNAUTHORIZED
2151 );
2152 let response = client
2153 .get("/v1/capabilities")
2154 .header("Authorization", "Basic dXNlcjpwYXNzd29yZA==")
2155 .send()
2156 .await;
2157 assert_eq!(response.status(), StatusCode::OK);
2158 assert_eq!(
2159 response.json::<serde_json::Value>().await,
2160 serde_json::json!({"metric_packed_import": 1, "metric_packed_export": 1})
2161 );
2162 }
2163 }
2164
2165 #[tokio::test]
2166 async fn logical_ddl_form_limits_and_unsupported_handler() {
2167 use axum::body::{Body, to_bytes};
2168 use tower::ServiceExt;
2169
2170 async fn post_form(app: Router, body: String) -> (StatusCode, serde_json::Value) {
2171 let response = app
2172 .oneshot(
2173 Request::builder()
2174 .method(Method::POST)
2175 .uri("/v1/ddl/logical-tables")
2176 .header("Content-Type", "application/x-www-form-urlencoded")
2177 .body(Body::from(body))
2178 .unwrap(),
2179 )
2180 .await
2181 .unwrap();
2182 let status = response.status();
2183 let body = to_bytes(response.into_body(), 4096).await.unwrap();
2184 (status, serde_json::from_slice(&body).unwrap())
2185 }
2186
2187 for limit in [0, 64] {
2188 let (tx, _rx) = mpsc::channel(1);
2189 let server = HttpServerBuilder::new(HttpOptions {
2190 body_limit: ReadableSize(limit),
2191 ..Default::default()
2192 })
2193 .with_sql_handler(Arc::new(DummyInstance { _tx: tx }))
2194 .build();
2195 let app = server.build(server.make_app()).unwrap();
2196 let client = TestClient::new(app.clone()).await;
2197 assert_eq!(
2198 client.get("/v1/ddl/logical-tables").send().await.status(),
2199 StatusCode::METHOD_NOT_ALLOWED
2200 );
2201 let small = client
2202 .post("/v1/ddl/logical-tables")
2203 .form(&[("sql", "CREATE TABLE t")])
2204 .send()
2205 .await;
2206 assert_eq!(
2207 small.json::<serde_json::Value>().await["code"],
2208 common_error::status_code::StatusCode::Unsupported as u32
2209 );
2210 let (_, body) = post_form(
2211 app.clone(),
2212 if limit == 0 {
2213 format!("sql={}", "%20".repeat(1024 * 1024))
2214 } else {
2215 "sql=".to_string() + &" ".repeat(65)
2216 },
2217 )
2218 .await;
2219 let code = body["code"].clone();
2220 assert_eq!(
2221 code,
2222 if limit == 0 {
2223 common_error::status_code::StatusCode::Unsupported as u32
2224 } else {
2225 common_error::status_code::StatusCode::InvalidArguments as u32
2226 }
2227 );
2228 for body in [
2229 format!("sql={}", "x".repeat(1024 * 1024 + 1)),
2230 format!("sql={}", "%C3%A9".repeat(512 * 1024 + 1)),
2231 format!("sql=CREATE+TABLE+t&padding={}", "x".repeat(4 * 1024 * 1024)),
2232 ] {
2233 let (status, body) = post_form(app.clone(), body).await;
2234 assert_eq!(status, StatusCode::BAD_REQUEST);
2235 assert_eq!(
2236 body["code"],
2237 common_error::status_code::StatusCode::InvalidArguments as u32
2238 );
2239 }
2240 }
2241 }
2242
2243 #[tokio::test]
2244 pub async fn test_extra_router_respects_api_surface() {
2245 let (tx, _rx) = mpsc::channel(100);
2251 let instance = Arc::new(DummyInstance { _tx: tx });
2252 let options = HttpOptions {
2253 enable_api_server: true,
2254 ..HttpOptions::default()
2255 };
2256 let builder = HttpServerBuilder::new(options)
2257 .with_sql_handler(instance)
2258 .with_extra_router(
2259 Router::new()
2260 .route("/status/plugin", routing::get(|| async { "ok" }))
2261 .route("/v1/plugin", routing::get(|| async { "ok" })),
2262 );
2263 let (full, api) = builder.build_servers();
2264 let api = api.expect("API server is explicitly enabled");
2265
2266 let full_client = TestClient::new(full.build(full.make_app()).unwrap()).await;
2267 let api_client = TestClient::new(api.build(api.make_app()).unwrap()).await;
2268
2269 assert_eq!(
2271 full_client.get("/status/plugin").send().await.status(),
2272 StatusCode::OK
2273 );
2274 assert_eq!(
2276 api_client.get("/status/plugin").send().await.status(),
2277 StatusCode::NOT_FOUND
2278 );
2279
2280 assert_eq!(
2282 full_client.get("/v1/plugin").send().await.status(),
2283 StatusCode::OK
2284 );
2285 assert_eq!(
2286 api_client.get("/v1/plugin").send().await.status(),
2287 StatusCode::OK
2288 );
2289
2290 assert_eq!(
2292 api_client.get("/v10/plugin").send().await.status(),
2293 StatusCode::NOT_FOUND
2294 );
2295 }
2296
2297 #[test]
2298 fn test_build_servers_api_disabled_by_default() {
2299 let (_internal, api) = HttpServerBuilder::new(HttpOptions::default()).build_servers();
2302 assert!(api.is_none());
2303 }
2304
2305 #[tokio::test]
2306 pub async fn test_cors() {
2307 let (tx, _rx) = mpsc::channel(100);
2309 let app = make_test_app(tx);
2310 let client = TestClient::new(app).await;
2311
2312 let res = client.get("/health").send().await;
2313
2314 assert_eq!(res.status(), StatusCode::OK);
2315 assert_eq!(
2316 res.headers()
2317 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2318 .expect("expect cors header origin"),
2319 "*"
2320 );
2321
2322 let res = client.get("/v1/health").send().await;
2323
2324 assert_eq!(res.status(), StatusCode::OK);
2325 assert_eq!(
2326 res.headers()
2327 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2328 .expect("expect cors header origin"),
2329 "*"
2330 );
2331
2332 let res = client
2333 .options("/health")
2334 .header("Access-Control-Request-Headers", "x-greptime-auth")
2335 .header("Access-Control-Request-Method", "DELETE")
2336 .header("Origin", "https://example.com")
2337 .send()
2338 .await;
2339 assert_eq!(res.status(), StatusCode::OK);
2340 assert_eq!(
2341 res.headers()
2342 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2343 .expect("expect cors header origin"),
2344 "*"
2345 );
2346 assert_eq!(
2347 res.headers()
2348 .get(http::header::ACCESS_CONTROL_ALLOW_HEADERS)
2349 .expect("expect cors header headers"),
2350 "*"
2351 );
2352 assert_eq!(
2353 res.headers()
2354 .get(http::header::ACCESS_CONTROL_ALLOW_METHODS)
2355 .expect("expect cors header methods"),
2356 "GET,POST,PUT,DELETE,HEAD"
2357 );
2358 }
2359
2360 #[tokio::test]
2361 pub async fn test_cors_custom_origins() {
2362 let (tx, _rx) = mpsc::channel(100);
2364 let origin = "https://example.com";
2365
2366 let options = HttpOptions {
2367 cors_allowed_origins: vec![origin.to_string()],
2368 ..Default::default()
2369 };
2370
2371 let app = make_test_app_custom(tx, options);
2372 let client = TestClient::new(app).await;
2373
2374 let res = client.get("/health").header("Origin", origin).send().await;
2375
2376 assert_eq!(res.status(), StatusCode::OK);
2377 assert_eq!(
2378 res.headers()
2379 .get(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2380 .expect("expect cors header origin"),
2381 origin
2382 );
2383
2384 let res = client
2385 .get("/health")
2386 .header("Origin", "https://notallowed.com")
2387 .send()
2388 .await;
2389
2390 assert_eq!(res.status(), StatusCode::OK);
2391 assert!(
2392 !res.headers()
2393 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2394 );
2395 }
2396
2397 #[tokio::test]
2398 pub async fn test_cors_disabled() {
2399 let (tx, _rx) = mpsc::channel(100);
2401
2402 let options = HttpOptions {
2403 enable_cors: false,
2404 ..Default::default()
2405 };
2406
2407 let app = make_test_app_custom(tx, options);
2408 let client = TestClient::new(app).await;
2409
2410 let res = client.get("/health").send().await;
2411
2412 assert_eq!(res.status(), StatusCode::OK);
2413 assert!(
2414 !res.headers()
2415 .contains_key(http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
2416 );
2417 }
2418
2419 #[test]
2420 fn test_http_options_default() {
2421 let default = HttpOptions::default();
2422 assert_eq!("127.0.0.1:4000".to_string(), default.addr);
2423 assert_eq!(Duration::from_secs(0), default.timeout)
2424 }
2425
2426 #[tokio::test]
2427 async fn test_http_options_legacy_analyze_stream_config_is_ignored() {
2428 let options: HttpOptions = serde_json::from_value(serde_json::json!({
2429 "addr": "127.0.0.1:4000",
2430 "timeout": "0s",
2431 "body_limit": "64MiB",
2432 "cors_allowed_origins": [],
2433 "enable_cors": true,
2434 "experimental_enable_explain_analyze_stream": false,
2435 "enable_api_server": false,
2436 "api_server_addr": "127.0.0.1:4006"
2437 }))
2438 .unwrap();
2439 let serialized = serde_json::to_string(&options).unwrap();
2440 assert!(!serialized.contains("experimental_enable_explain_analyze_stream"));
2441
2442 let (tx, _rx) = mpsc::channel(100);
2443 let app = make_test_app_custom(tx, options);
2444 let client = TestClient::new(app).await;
2445 let response = client
2446 .post("/v1/sql/analyze/stream")
2447 .form(&handler::SqlQuery {
2448 sql: Some("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2449 ..Default::default()
2450 })
2451 .send()
2452 .await;
2453 assert_ne!(response.status(), StatusCode::NOT_FOUND);
2454 }
2455
2456 #[tokio::test]
2457 async fn test_http_server_request_timeout() {
2458 common_telemetry::init_default_ut_logging();
2459
2460 let (tx, _rx) = mpsc::channel(100);
2461 let options = HttpOptions {
2462 timeout: Duration::from_millis(10),
2463 ..Default::default()
2464 };
2465 let app = make_test_app_custom(tx, options);
2466 let client = TestClient::new(app).await;
2467 let res = client.get("/test/timeout").send().await;
2468 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2469
2470 let res = client.post("/v1/prometheus/write").send().await;
2471 assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT);
2472
2473 let now = Instant::now();
2474 let res = client
2475 .get("/test/timeout")
2476 .header(GREPTIME_DB_HEADER_TIMEOUT, "20ms")
2477 .send()
2478 .await;
2479 assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
2480 let elapsed = now.elapsed();
2481 assert!(elapsed > Duration::from_millis(15));
2482
2483 tokio::time::timeout(
2484 Duration::from_millis(15),
2485 client
2486 .get("/test/timeout")
2487 .header(GREPTIME_DB_HEADER_TIMEOUT, "0s")
2488 .send(),
2489 )
2490 .await
2491 .unwrap_err();
2492
2493 tokio::time::timeout(
2494 Duration::from_millis(15),
2495 client
2496 .get("/test/timeout")
2497 .header(
2498 GREPTIME_DB_HEADER_TIMEOUT,
2499 humantime::format_duration(Duration::default()).to_string(),
2500 )
2501 .send(),
2502 )
2503 .await
2504 .unwrap_err();
2505 }
2506
2507 #[tokio::test]
2508 async fn test_schema_for_empty_response() {
2509 let column_schemas = vec![
2510 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2511 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2512 ];
2513 let schema = Arc::new(Schema::new(column_schemas));
2514
2515 let recordbatches = RecordBatches::try_new(schema.clone(), vec![]).unwrap();
2516 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2517
2518 let json_resp = GreptimedbV1Response::from_output(outputs).await;
2519 if let HttpResponse::GreptimedbV1(json_resp) = json_resp {
2520 let json_output = &json_resp.output[0];
2521 if let GreptimeQueryOutput::Records(r) = json_output {
2522 assert_eq!(r.num_rows(), 0);
2523 assert_eq!(r.num_cols(), 2);
2524 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2525 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2526 } else {
2527 panic!("invalid output type");
2528 }
2529 } else {
2530 panic!("invalid format")
2531 }
2532 }
2533
2534 #[tokio::test]
2535 async fn test_recordbatches_conversion() {
2536 let column_schemas = vec![
2537 ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
2538 ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
2539 ];
2540 let schema = Arc::new(Schema::new(column_schemas));
2541 let columns: Vec<VectorRef> = vec![
2542 Arc::new(UInt32Vector::from_slice(vec![1, 2, 3, 4])),
2543 Arc::new(StringVector::from(vec![
2544 None,
2545 Some("hello"),
2546 Some("greptime"),
2547 None,
2548 ])),
2549 ];
2550 let recordbatch = RecordBatch::new(schema.clone(), columns).unwrap();
2551
2552 for format in [
2553 ResponseFormat::GreptimedbV1,
2554 ResponseFormat::InfluxdbV1,
2555 ResponseFormat::Csv(true, true),
2556 ResponseFormat::Table,
2557 ResponseFormat::Arrow,
2558 ResponseFormat::Json,
2559 ResponseFormat::Null,
2560 ] {
2561 let recordbatches =
2562 RecordBatches::try_new(schema.clone(), vec![recordbatch.clone()]).unwrap();
2563 let outputs = vec![Ok(Output::new_with_record_batches(recordbatches))];
2564 let json_resp = match format {
2565 ResponseFormat::Arrow => ArrowResponse::from_output(outputs, None).await,
2566 ResponseFormat::Csv(with_names, with_types) => {
2567 CsvResponse::from_output(outputs, with_names, with_types).await
2568 }
2569 ResponseFormat::Table => TableResponse::from_output(outputs).await,
2570 ResponseFormat::GreptimedbV1 => GreptimedbV1Response::from_output(outputs).await,
2571 ResponseFormat::InfluxdbV1 => InfluxdbV1Response::from_output(outputs, None).await,
2572 ResponseFormat::Json => JsonResponse::from_output(outputs).await,
2573 ResponseFormat::Null => NullResponse::from_output(outputs).await,
2574 };
2575
2576 match json_resp {
2577 HttpResponse::GreptimedbV1(resp) => {
2578 let json_output = &resp.output[0];
2579 if let GreptimeQueryOutput::Records(r) = json_output {
2580 assert_eq!(r.num_rows(), 4);
2581 assert_eq!(r.num_cols(), 2);
2582 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2583 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2584 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2585 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2586 } else {
2587 panic!("invalid output type");
2588 }
2589 }
2590 HttpResponse::InfluxdbV1(resp) => {
2591 let json_output = &resp.results()[0];
2592 assert_eq!(json_output.num_rows(), 4);
2593 assert_eq!(json_output.num_cols(), 2);
2594 assert_eq!(json_output.series[0].columns.clone()[0], "numbers");
2595 assert_eq!(
2596 json_output.series[0].values[0][0],
2597 serde_json::Value::from(1)
2598 );
2599 assert_eq!(json_output.series[0].values[0][1], serde_json::Value::Null);
2600 }
2601 HttpResponse::Csv(resp) => {
2602 let output = &resp.output()[0];
2603 if let GreptimeQueryOutput::Records(r) = output {
2604 assert_eq!(r.num_rows(), 4);
2605 assert_eq!(r.num_cols(), 2);
2606 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2607 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2608 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2609 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2610 } else {
2611 panic!("invalid output type");
2612 }
2613 }
2614
2615 HttpResponse::Table(resp) => {
2616 let output = &resp.output()[0];
2617 if let GreptimeQueryOutput::Records(r) = output {
2618 assert_eq!(r.num_rows(), 4);
2619 assert_eq!(r.num_cols(), 2);
2620 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2621 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2622 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2623 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2624 } else {
2625 panic!("invalid output type");
2626 }
2627 }
2628
2629 HttpResponse::Arrow(resp) => {
2630 let output = resp.data;
2631 let mut reader = StreamReader::try_new(Cursor::new(output), None)
2632 .expect("Arrow reader error");
2633 let schema = reader.schema();
2634 assert_eq!(schema.fields[0].name(), "numbers");
2635 assert_eq!(schema.fields[0].data_type(), &DataType::UInt32);
2636 assert_eq!(schema.fields[1].name(), "strings");
2637 assert_eq!(schema.fields[1].data_type(), &DataType::Utf8);
2638
2639 let rb = reader.next().unwrap().expect("read record batch failed");
2640 assert_eq!(rb.num_columns(), 2);
2641 assert_eq!(rb.num_rows(), 4);
2642 }
2643
2644 HttpResponse::Json(resp) => {
2645 let output = &resp.output()[0];
2646 if let GreptimeQueryOutput::Records(r) = output {
2647 assert_eq!(r.num_rows(), 4);
2648 assert_eq!(r.num_cols(), 2);
2649 assert_eq!(r.schema.column_schemas[0].name, "numbers");
2650 assert_eq!(r.schema.column_schemas[0].data_type, "UInt32");
2651 assert_eq!(r.rows[0][0], serde_json::Value::from(1));
2652 assert_eq!(r.rows[0][1], serde_json::Value::Null);
2653 } else {
2654 panic!("invalid output type");
2655 }
2656 }
2657
2658 HttpResponse::Null(resp) => {
2659 assert_eq!(resp.rows(), 4);
2660 }
2661
2662 HttpResponse::Error(err) => unreachable!("{err:?}"),
2663 }
2664 }
2665 }
2666
2667 #[test]
2668 fn test_response_format_misc() {
2669 assert_eq!(ResponseFormat::default(), ResponseFormat::GreptimedbV1);
2670 assert_eq!(ResponseFormat::parse("arrow"), Some(ResponseFormat::Arrow));
2671 assert_eq!(
2672 ResponseFormat::parse("csv"),
2673 Some(ResponseFormat::Csv(false, false))
2674 );
2675 assert_eq!(
2676 ResponseFormat::parse("csvwithnames"),
2677 Some(ResponseFormat::Csv(true, false))
2678 );
2679 assert_eq!(
2680 ResponseFormat::parse("csvwithnamesandtypes"),
2681 Some(ResponseFormat::Csv(true, true))
2682 );
2683 assert_eq!(ResponseFormat::parse("table"), Some(ResponseFormat::Table));
2684 assert_eq!(
2685 ResponseFormat::parse("greptimedb_v1"),
2686 Some(ResponseFormat::GreptimedbV1)
2687 );
2688 assert_eq!(
2689 ResponseFormat::parse("influxdb_v1"),
2690 Some(ResponseFormat::InfluxdbV1)
2691 );
2692 assert_eq!(ResponseFormat::parse("json"), Some(ResponseFormat::Json));
2693 assert_eq!(ResponseFormat::parse("null"), Some(ResponseFormat::Null));
2694
2695 assert_eq!(ResponseFormat::parse("invalid"), None);
2697 assert_eq!(ResponseFormat::parse(""), None);
2698 assert_eq!(ResponseFormat::parse("CSV"), None); assert_eq!(ResponseFormat::Arrow.as_str(), "arrow");
2702 assert_eq!(ResponseFormat::Csv(false, false).as_str(), "csv");
2703 assert_eq!(ResponseFormat::Csv(true, true).as_str(), "csv");
2704 assert_eq!(ResponseFormat::Table.as_str(), "table");
2705 assert_eq!(ResponseFormat::GreptimedbV1.as_str(), "greptimedb_v1");
2706 assert_eq!(ResponseFormat::InfluxdbV1.as_str(), "influxdb_v1");
2707 assert_eq!(ResponseFormat::Json.as_str(), "json");
2708 assert_eq!(ResponseFormat::Null.as_str(), "null");
2709 assert_eq!(ResponseFormat::default().as_str(), "greptimedb_v1");
2710 }
2711
2712 #[test]
2713 fn test_decode_label_name_strict() {
2714 let strict = PromValidationMode::Strict;
2715
2716 assert!(strict.decode_label_name(b"__name__").is_ok());
2718 assert!(strict.decode_label_name(b"job").is_ok());
2719 assert!(strict.decode_label_name(b"instance").is_ok());
2720 assert!(strict.decode_label_name(b"_private").is_ok());
2721 assert!(strict.decode_label_name(b"label_with_underscores").is_ok());
2722 assert!(strict.decode_label_name(b"abc123").is_ok());
2723 assert!(strict.decode_label_name(b"A").is_ok());
2724 assert!(strict.decode_label_name(b"_").is_ok());
2725
2726 assert!(strict.decode_label_name(b"0abc").is_err());
2728 assert!(strict.decode_label_name(b"123").is_err());
2729
2730 assert!(strict.decode_label_name(b"label-name").is_err());
2732 assert!(strict.decode_label_name(b"label.name").is_err());
2733 assert!(strict.decode_label_name(b"label name").is_err());
2734 assert!(strict.decode_label_name(b"label/name").is_err());
2735
2736 assert!(strict.decode_label_name(b"").is_err());
2738
2739 assert!(strict.decode_label_name("ラベル".as_bytes()).is_err());
2741
2742 assert!(strict.decode_label_name(&[0xff, 0xfe]).is_err());
2744 }
2745
2746 #[test]
2747 fn test_decode_label_name_lossy() {
2748 let lossy = PromValidationMode::Lossy;
2749
2750 assert!(lossy.decode_label_name(b"__name__").is_ok());
2752 assert!(lossy.decode_label_name(b"label-name").is_err());
2753 assert!(lossy.decode_label_name(b"0abc").is_err());
2754
2755 assert!(lossy.decode_label_name(&[0xff, 0xfe]).is_err());
2757 }
2758
2759 #[test]
2760 fn test_decode_label_name_unchecked() {
2761 let unchecked = PromValidationMode::Unchecked;
2762
2763 assert!(unchecked.decode_label_name(b"__name__").is_ok());
2765 assert!(unchecked.decode_label_name(b"label-name").is_err());
2766 assert!(unchecked.decode_label_name(b"0abc").is_err());
2767 }
2768
2769 #[test]
2770 fn test_is_valid_prom_label_name_bytes() {
2771 assert!(validate_label_name(b"__name__"));
2772 assert!(validate_label_name(b"job"));
2773 assert!(validate_label_name(b"_"));
2774 assert!(validate_label_name(b"A"));
2775 assert!(validate_label_name(b"abc123"));
2776 assert!(validate_label_name(b"_leading_underscore"));
2777
2778 assert!(!validate_label_name(b""));
2779 assert!(!validate_label_name(b"0starts_with_digit"));
2780 assert!(!validate_label_name(b"has-dash"));
2781 assert!(!validate_label_name(b"has.dot"));
2782 assert!(!validate_label_name(b"has space"));
2783 assert!(!validate_label_name(&[0xff, 0xfe]));
2784 }
2785}
2786
2787#[cfg(test)]
2788mod batching_tests {
2789 use std::sync::{Arc, Mutex};
2790
2791 use axum::http::StatusCode;
2792 use common_query::Output;
2793 use session::context::QueryContextRef;
2794
2795 use crate::batcher::BatchingProtocol;
2796 use crate::error::Result as ServerResult;
2797 use crate::http::test_helpers::TestClient;
2798 use crate::http::{HttpOptions, HttpServerBuilder};
2799 use crate::influxdb::InfluxdbRequest;
2800 use crate::opentsdb::codec::DataPoint;
2801 use crate::query_handler::{InfluxdbLineProtocolHandler, OpentsdbProtocolHandler};
2802
2803 #[tokio::test]
2804 async fn test_batching_selectors_are_independent() {
2805 use axum::routing::post;
2806 use axum::{Extension, Json, Router, middleware};
2807 use session::context::{QueryContext, QueryContextBuilder};
2808
2809 use crate::http::{LogicalBatchingProtocols, set_http_write_batching};
2810 for table in [false, true] {
2811 for logical in [false, true] {
2812 let app = Router::new()
2813 .route(
2814 "/",
2815 post(|Extension(ctx): Extension<QueryContext>| async move {
2816 Json([ctx.batching_enabled(), ctx.logical_batching_enabled()])
2817 }),
2818 )
2819 .route_layer(middleware::from_fn_with_state(
2820 BatchingProtocol::Otlp,
2821 set_http_write_batching,
2822 ))
2823 .layer(Extension(QueryContextBuilder::default().build()))
2824 .layer(Extension(Arc::new(if table {
2825 vec![BatchingProtocol::Otlp]
2826 } else {
2827 vec![]
2828 })))
2829 .layer(Extension(LogicalBatchingProtocols(if logical {
2830 vec![BatchingProtocol::Otlp]
2831 } else {
2832 vec![]
2833 })));
2834 let client = TestClient::new(app).await;
2835 let actual: [bool; 2] = client.post("/").send().await.json().await;
2836 assert_eq!(actual, [table, logical]);
2837 }
2838 }
2839 }
2840
2841 #[derive(Default)]
2842 struct RecordingWriteHandler {
2843 selections: Mutex<Vec<bool>>,
2844 }
2845
2846 #[async_trait::async_trait]
2847 impl OpentsdbProtocolHandler for RecordingWriteHandler {
2848 async fn preflight(&self, _: &[DataPoint], _: QueryContextRef) -> ServerResult<()> {
2849 Ok(())
2850 }
2851
2852 async fn exec(&self, points: Vec<DataPoint>, ctx: QueryContextRef) -> ServerResult<usize> {
2853 self.selections.lock().unwrap().push(ctx.batching_enabled());
2854 Ok(points.len())
2855 }
2856 }
2857
2858 #[async_trait::async_trait]
2859 impl InfluxdbLineProtocolHandler for RecordingWriteHandler {
2860 async fn exec(&self, _: InfluxdbRequest, ctx: QueryContextRef) -> ServerResult<Output> {
2861 self.selections.lock().unwrap().push(ctx.batching_enabled());
2862 Ok(Output::new_with_affected_rows(1))
2863 }
2864 }
2865
2866 #[tokio::test]
2867 async fn test_real_influx_and_opentsdb_routes_keep_selection() {
2868 for protocols in [
2869 vec![],
2870 vec![BatchingProtocol::Influxdb],
2871 vec![BatchingProtocol::Opentsdb],
2872 vec![BatchingProtocol::Influxdb, BatchingProtocol::Opentsdb],
2873 ] {
2874 let handler = Arc::new(RecordingWriteHandler::default());
2875 let influx_enabled = protocols.contains(&BatchingProtocol::Influxdb);
2876 let opentsdb_enabled = protocols.contains(&BatchingProtocol::Opentsdb);
2877 let server = HttpServerBuilder::new(HttpOptions::default())
2878 .with_batching_protocols(protocols)
2879 .with_influxdb_handler(handler.clone())
2880 .with_opentsdb_handler(handler.clone())
2881 .build();
2882 let client = TestClient::new(server.build(server.make_app()).unwrap()).await;
2883 for path in [
2884 "/v1/influxdb/write",
2885 "/v1/influxdb/api/v2/write?bucket=public",
2886 ] {
2887 assert_eq!(
2888 client
2889 .post(path)
2890 .body("cpu value=1 42")
2891 .send()
2892 .await
2893 .status(),
2894 StatusCode::NO_CONTENT
2895 );
2896 }
2897 let point =
2898 serde_json::json!({"metric":"cpu", "timestamp":42, "value":1, "tags":{"host":"a"}});
2899 for query in ["", "?summary", "?details"] {
2900 let response = client
2901 .post(&format!("/v1/opentsdb/api/put{query}"))
2902 .json(&point)
2903 .send()
2904 .await;
2905 assert_eq!(
2906 response.status(),
2907 if query.is_empty() {
2908 StatusCode::NO_CONTENT
2909 } else {
2910 StatusCode::OK
2911 }
2912 );
2913 }
2914 assert_eq!(
2915 *handler.selections.lock().unwrap(),
2916 vec![
2917 influx_enabled,
2918 influx_enabled,
2919 opentsdb_enabled,
2920 opentsdb_enabled,
2921 opentsdb_enabled
2922 ]
2923 );
2924 }
2925 }
2926}