mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 08:25:29 +00:00
* chore!: remove unused mysql and postgres runtime_size options `mysql.runtime_size` and `postgres.runtime_size` have not been read since #4436. Remove them from the option structs, example configs and generated config docs. BREAKING CHANGE: `mysql.runtime_size` and `postgres.runtime_size` are no longer part of the frontend/standalone configuration. Existing config files that still set them load unchanged, since the option structs do not deny unknown fields; the keys are ignored as before. The serialized config (e.g. the `/config` HTTP API) no longer lists them. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(servers)!: describe SHOW statements with their execution schema The PostgreSQL extended-protocol Describe hand-wrote result columns for several SHOW statements, and the names did not match what execution returns. pgwire does not resend RowDescription on Execute, so clients reading columns by name saw the wrong names: - SHOW CREATE TABLE/DATABASE/VIEW/FLOW were described as `name` and `create_statement`; execution returns e.g. `Table` and `Create Table`. - SHOW TRIGGERS was described as `name`; execution returns `Triggers`. - SHOW VARIABLES for a query option was described upper-cased; execution keeps the option's spelling. Describe SHOW CREATE from the static schemas execution uses, route SHOW TRIGGERS through the same dataframe path as SHOW FLOWS, and share the SHOW VARIABLES column-name rule with execution. BREAKING CHANGE: extended-protocol PostgreSQL clients now see the same column names for these statements as MySQL and simple-protocol clients. Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
8518 lines
319 KiB
Rust
8518 lines
319 KiB
Rust
// Copyright 2023 Greptime Team
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
pub mod builder;
|
|
mod copy_in;
|
|
mod dashboard;
|
|
mod entity_graph;
|
|
mod exemplar;
|
|
mod export_database;
|
|
mod grpc;
|
|
mod import_packed;
|
|
mod influxdb;
|
|
mod jaeger;
|
|
mod log_handler;
|
|
mod logical_batcher;
|
|
mod logs;
|
|
mod opentsdb;
|
|
mod otlp;
|
|
pub mod prom_store;
|
|
mod promql;
|
|
mod promql_rollup_cache;
|
|
mod region_query;
|
|
mod schema_selection;
|
|
|
|
use std::collections::HashSet;
|
|
use std::pin::Pin;
|
|
use std::sync::atomic::AtomicBool;
|
|
use std::sync::{Arc, OnceLock, atomic};
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
use async_stream::stream;
|
|
use async_trait::async_trait;
|
|
use auth::{
|
|
COPY_TO, PROMQL_QUERY, PermissionChecker, PermissionCheckerRef, PermissionReq,
|
|
PermissionTableTarget, PermissionTableTargets, TableTargetPrecheck,
|
|
};
|
|
use catalog::CatalogManagerRef;
|
|
use catalog::process_manager::{
|
|
ProcessManagerRef, QueryStatement as CatalogQueryStatement, SlowQueryRecorder, SlowQueryTimer,
|
|
Ticket,
|
|
};
|
|
use client::OutputData;
|
|
use common_base::Plugins;
|
|
use common_base::cancellation::CancellableFuture;
|
|
use common_batcher::request_limiter::RequestLimiter;
|
|
use common_error::ext::{BoxedError, ErrorExt};
|
|
use common_event_recorder::EventRecorderRef;
|
|
use common_meta::cache::TableFlownodeSetCacheRef;
|
|
use common_meta::cache_invalidator::CacheInvalidatorRef;
|
|
use common_meta::key::TableMetadataManagerRef;
|
|
use common_meta::node_manager::NodeManagerRef;
|
|
use common_meta::procedure_executor::ProcedureExecutorRef;
|
|
use common_query::{Output, OutputMeta};
|
|
use common_recordbatch::error::StreamTimeoutSnafu;
|
|
use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
|
|
use common_telemetry::logging::SlowQueryOptions;
|
|
use common_telemetry::{debug, error, tracing};
|
|
use common_time::timestamp::TimeUnit;
|
|
use datafusion::dataframe::DataFrame;
|
|
use datafusion::physical_plan::ExecutionPlan;
|
|
use datafusion_expr::LogicalPlan;
|
|
use futures::TryStreamExt;
|
|
use futures::{Stream, StreamExt, future};
|
|
use operator::delete::DeleterRef;
|
|
use operator::insert::InserterRef;
|
|
use operator::statement::{StatementExecutor, StatementExecutorRef};
|
|
use partition::manager::PartitionRuleManagerRef;
|
|
use pipeline::pipeline_operator::PipelineOperator;
|
|
use prometheus::HistogramTimer;
|
|
// The absolute path names the `promql` crate, not this module's `promql` submodule.
|
|
use promql_parser::label::{METRIC_NAME, MatchOp, Matcher};
|
|
use promql_parser::util::{ExprVisitor, walk_expr};
|
|
use query::QueryEngineRef;
|
|
use query::metrics::OnDone;
|
|
use query::parser::{PromQuery, QueryStatement};
|
|
use query::query_engine::DescribeResult;
|
|
use query::query_engine::options::{QueryOptions, validate_catalog_and_schema};
|
|
use servers::batcher::logical_table::LogicalTablePendingRowsBatcher;
|
|
use servers::error::{self as server_error, AuthSnafu, ExecuteQuerySnafu};
|
|
use servers::interceptor::{
|
|
PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, SqlQueryInterceptorRef,
|
|
};
|
|
use servers::prometheus_handler::{
|
|
ParsedPromQuery, PrometheusHandler, resolve_schema_from_matchers,
|
|
};
|
|
use servers::query_handler::sql::SqlQueryHandler;
|
|
use servers::request_memory_limiter::ServerMemoryLimiter;
|
|
use session::context::{Channel, MetricDiscoveryScope, QueryContextRef};
|
|
use session::table_name::table_idents_to_full_name;
|
|
use snafu::prelude::*;
|
|
use sql::ast::ObjectNamePartExt;
|
|
use sql::dialect::Dialect;
|
|
use sql::parser::{ParseOptions, ParserContext};
|
|
use sql::statements::comment::CommentObject;
|
|
use sql::statements::copy::{Copy, CopyDatabase, CopyTable};
|
|
use sql::statements::statement::Statement;
|
|
use sql::statements::tql::Tql;
|
|
use sql::util::{
|
|
extract_tables_from_prom_expr_checked, extract_tables_from_prom_expr_partial,
|
|
extract_tables_from_statement_checked, extract_tables_from_statement_partial,
|
|
extract_tql_exprs_from_statement,
|
|
};
|
|
use sqlparser::ast::{AnalyzeFormat, ObjectName};
|
|
use tracing::Span;
|
|
|
|
use crate::error::{
|
|
self, CatalogSnafu, CollectRecordbatchSnafu, Error, ExecLogicalPlanSnafu, ExecutePromqlSnafu,
|
|
ExternalSnafu, InvalidSqlSnafu, ParseSqlSnafu, PermissionSnafu, PlanStatementSnafu, Result,
|
|
SqlExecInterceptedSnafu, StatementTimeoutSnafu, TableOperationSnafu,
|
|
};
|
|
use crate::promql_query_cache::PromqlRollupCache;
|
|
use crate::service_config::InfluxdbMergeMode;
|
|
use crate::stream_wrapper::CancellableStreamWrapper;
|
|
|
|
fn deduplicate_permission_targets(targets: PermissionTableTargets) -> PermissionTableTargets {
|
|
let PermissionTableTargets::Resolved(mut targets) = targets else {
|
|
return PermissionTableTargets::Unresolved;
|
|
};
|
|
if targets.len() > 1 {
|
|
let mut seen = HashSet::with_capacity(targets.len());
|
|
targets.retain(|target| seen.insert(target.clone()));
|
|
}
|
|
PermissionTableTargets::resolved(targets)
|
|
}
|
|
|
|
/// The frontend instance contains necessary components, and implements many
|
|
/// traits, like [`servers::query_handler::grpc::GrpcQueryHandler`],
|
|
/// [`servers::query_handler::sql::SqlQueryHandler`], etc.
|
|
#[derive(Clone)]
|
|
pub struct Instance {
|
|
server_memory_limiter: ServerMemoryLimiter,
|
|
frontend_peer_addr: String,
|
|
catalog_manager: CatalogManagerRef,
|
|
pipeline_operator: Arc<PipelineOperator>,
|
|
statement_executor: Arc<StatementExecutor>,
|
|
query_engine: QueryEngineRef,
|
|
plugins: Plugins,
|
|
inserter: InserterRef,
|
|
logical_batcher: Arc<OnceLock<Option<Arc<LogicalTablePendingRowsBatcher>>>>,
|
|
deleter: DeleterRef,
|
|
table_metadata_manager: TableMetadataManagerRef,
|
|
event_recorder: EventRecorderRef,
|
|
slow_query_recorder: EventRecorderRef,
|
|
process_manager: ProcessManagerRef,
|
|
slow_query_options: SlowQueryOptions,
|
|
influxdb_default_merge_mode: InfluxdbMergeMode,
|
|
/// Time index unit for physical metric tables created by auto table creation
|
|
/// through the frontend instance (e.g., batched logical-table flushes).
|
|
auto_create_physical_table_timestamp_unit: TimeUnit,
|
|
trace_ingest_chunk_size: usize,
|
|
trace_aux_cache: otlp::TraceAuxCache,
|
|
trace_aux_limiter: Option<RequestLimiter>,
|
|
otlp_resource_info: bool,
|
|
suspend: Arc<AtomicBool>,
|
|
/// The frontend-local rollup cache of PromQL range queries, when one is
|
|
/// installed.
|
|
///
|
|
/// Disabled by default. [`crate::frontend::FrontendOptions::promql_rollup_cache`]
|
|
/// installs it; a request that misses fills it itself, so nothing else has to run
|
|
/// for it to serve.
|
|
promql_rollup_cache: Option<Arc<PromqlRollupCache>>,
|
|
}
|
|
|
|
impl Instance {
|
|
/// Returns the memory pool shared by protocol admission and table-batch conversion.
|
|
pub fn server_memory_limiter(&self) -> &ServerMemoryLimiter {
|
|
&self.server_memory_limiter
|
|
}
|
|
|
|
pub fn frontend_peer_addr(&self) -> &str {
|
|
&self.frontend_peer_addr
|
|
}
|
|
|
|
pub fn catalog_manager(&self) -> &CatalogManagerRef {
|
|
&self.catalog_manager
|
|
}
|
|
|
|
pub fn query_engine(&self) -> &QueryEngineRef {
|
|
&self.query_engine
|
|
}
|
|
|
|
pub fn plugins(&self) -> &Plugins {
|
|
&self.plugins
|
|
}
|
|
|
|
fn check_permission(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
req: PermissionReq<'_>,
|
|
) -> server_error::Result<()> {
|
|
self.plugins
|
|
.get::<PermissionCheckerRef>()
|
|
.as_ref()
|
|
.check_permission(ctx.current_user(), req)
|
|
.context(AuthSnafu)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn statement_executor(&self) -> &StatementExecutorRef {
|
|
&self.statement_executor
|
|
}
|
|
|
|
pub fn table_metadata_manager(&self) -> &TableMetadataManagerRef {
|
|
&self.table_metadata_manager
|
|
}
|
|
|
|
pub fn inserter(&self) -> &InserterRef {
|
|
&self.inserter
|
|
}
|
|
|
|
pub fn process_manager(&self) -> &ProcessManagerRef {
|
|
&self.process_manager
|
|
}
|
|
|
|
/// Returns the event recorder configured for this frontend instance.
|
|
pub fn event_recorder(&self) -> EventRecorderRef {
|
|
self.event_recorder.clone()
|
|
}
|
|
|
|
pub fn node_manager(&self) -> &NodeManagerRef {
|
|
self.inserter.node_manager()
|
|
}
|
|
|
|
pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
|
|
self.inserter.partition_manager()
|
|
}
|
|
|
|
pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
|
|
self.inserter.table_flownode_set_cache()
|
|
}
|
|
|
|
pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
|
|
self.statement_executor.cache_invalidator()
|
|
}
|
|
|
|
pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
|
|
self.statement_executor.procedure_executor()
|
|
}
|
|
|
|
/// The rollup cache a range query may be served from, when one is installed.
|
|
pub fn promql_rollup_cache(&self) -> Option<&Arc<PromqlRollupCache>> {
|
|
self.promql_rollup_cache.as_ref()
|
|
}
|
|
|
|
/// Empties this frontend's local rollup cache.
|
|
///
|
|
/// The cache is process-local. This does not affect other frontends, source
|
|
/// data, or in-flight queries; those either finish with their own plan or
|
|
/// refill the cache on their next read.
|
|
pub fn clear_promql_rollup_cache(&self) {
|
|
if let Some(cache) = self.promql_rollup_cache.as_ref() {
|
|
cache.clear();
|
|
}
|
|
}
|
|
|
|
pub fn suspend_state(&self) -> Arc<AtomicBool> {
|
|
self.suspend.clone()
|
|
}
|
|
|
|
pub(crate) fn is_suspended(&self) -> bool {
|
|
self.suspend.load(atomic::Ordering::Relaxed)
|
|
}
|
|
}
|
|
|
|
fn parse_stmt(sql: &str, dialect: &(dyn Dialect + Send + Sync)) -> Result<Vec<Statement>> {
|
|
ParserContext::create_with_dialect(sql, dialect, ParseOptions::default()).context(ParseSqlSnafu)
|
|
}
|
|
|
|
fn is_explain_analyze_verbose(stmt: &Statement) -> bool {
|
|
matches!(stmt, Statement::Explain(explain) if explain.analyze && explain.verbose)
|
|
|| matches!(stmt, Statement::Tql(Tql::Analyze(analyze)) if analyze.is_verbose)
|
|
}
|
|
|
|
fn validate_analyze_stream_statement(stmt: &mut Statement) -> Result<()> {
|
|
let (is_verbose, format) = match stmt {
|
|
Statement::Explain(explain) => (explain.analyze && explain.verbose, &mut explain.format),
|
|
Statement::Tql(Tql::Analyze(analyze)) => (analyze.is_verbose, &mut analyze.format),
|
|
_ => {
|
|
return InvalidSqlSnafu {
|
|
err_msg: "only EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE statement is supported",
|
|
}
|
|
.fail();
|
|
}
|
|
};
|
|
|
|
ensure!(
|
|
is_verbose,
|
|
InvalidSqlSnafu {
|
|
err_msg: "statement must be EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE"
|
|
}
|
|
);
|
|
match format {
|
|
None | Some(AnalyzeFormat::JSON) => {
|
|
// Keep explicit FORMAT JSON accepted, but pass JSON through
|
|
// QueryContext.explain_format instead of the statement to avoid
|
|
// the planner's current `EXPLAIN VERBOSE with FORMAT` limitation.
|
|
*format = None;
|
|
Ok(())
|
|
}
|
|
Some(_) => InvalidSqlSnafu {
|
|
err_msg: "only FORMAT JSON is supported for EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE",
|
|
}
|
|
.fail(),
|
|
}
|
|
}
|
|
|
|
impl Instance {
|
|
fn slow_query_timer(
|
|
&self,
|
|
statement: impl FnOnce() -> CatalogQueryStatement,
|
|
query_ctx: &QueryContextRef,
|
|
) -> Option<SlowQueryTimer> {
|
|
self.slow_query_options.enable.then(|| {
|
|
SlowQueryTimer::new(
|
|
statement(),
|
|
query_ctx.current_schema(),
|
|
self.slow_query_options.threshold,
|
|
self.slow_query_options.sample_ratio,
|
|
self.slow_query_options.record_type,
|
|
self.slow_query_recorder.clone(),
|
|
)
|
|
})
|
|
}
|
|
|
|
fn register_query(
|
|
&self,
|
|
query_ctx: &QueryContextRef,
|
|
schemas: Vec<String>,
|
|
query: String,
|
|
slow_query_timer: Option<SlowQueryTimer>,
|
|
) -> Ticket {
|
|
self.process_manager.register_query(
|
|
query_ctx.current_catalog().to_string(),
|
|
schemas,
|
|
query,
|
|
query_ctx.conn_info().to_string(),
|
|
Some(query_ctx.process_id()),
|
|
slow_query_timer,
|
|
)
|
|
}
|
|
|
|
async fn query_statement(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
|
|
check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
|
|
let query_ctx = if matches!(&stmt, Statement::SetVariables(_)) {
|
|
query_ctx
|
|
} else {
|
|
Arc::new(
|
|
query_ctx
|
|
.query_option_snapshot()
|
|
.map_err(|error| {
|
|
query::error::InvalidQueryContextExtensionSnafu {
|
|
reason: error.to_string(),
|
|
}
|
|
.build()
|
|
})
|
|
.context(PlanStatementSnafu)?,
|
|
)
|
|
};
|
|
|
|
let query_interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
|
let query_interceptor = query_interceptor.as_ref();
|
|
|
|
let timeout = derive_timeout(stmt.is_readonly(), &query_ctx);
|
|
if should_track_statement_process(&stmt) {
|
|
let slow_query_timer =
|
|
self.slow_query_timer(|| CatalogQueryStatement::Sql(stmt.clone()), &query_ctx);
|
|
let timeout_recorder = is_explain_analyze_verbose(&stmt)
|
|
.then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
|
|
.flatten();
|
|
let ticket = self.register_query(
|
|
&query_ctx,
|
|
vec![query_ctx.current_schema()],
|
|
stmt.to_string(),
|
|
slow_query_timer,
|
|
);
|
|
|
|
let exec = Box::pin(self.exec_statement(stmt, query_ctx, query_interceptor));
|
|
let query_fut = exec_with_timeout(timeout, exec, timeout_recorder);
|
|
exec_tracked(ticket, query_fut, CancellableStreamWrapper::new).await
|
|
} else {
|
|
let exec = Box::pin(self.exec_statement(stmt, query_ctx, query_interceptor));
|
|
exec_with_timeout(timeout, exec, None).await
|
|
}
|
|
}
|
|
|
|
async fn exec_statement(
|
|
&self,
|
|
stmt: Statement,
|
|
query_ctx: QueryContextRef,
|
|
query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
|
|
) -> Result<Output> {
|
|
match stmt {
|
|
Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
|
|
// TODO: remove this when format is supported in datafusion
|
|
if let Statement::Explain(explain) = &stmt
|
|
&& let Some(format) = explain.format()
|
|
{
|
|
query_ctx.set_explain_format(format.to_string());
|
|
}
|
|
|
|
self.plan_and_exec_sql(stmt, &query_ctx, query_interceptor)
|
|
.await
|
|
}
|
|
Statement::Tql(tql) => {
|
|
self.plan_and_exec_tql(&query_ctx, query_interceptor, tql)
|
|
.await
|
|
}
|
|
_ => {
|
|
query_interceptor.pre_execute(Some(&stmt), None, query_ctx.clone())?;
|
|
if let Statement::SetVariables(set) = &stmt
|
|
&& query_ctx.channel() == Channel::Postgres
|
|
&& let Some(schemas) = set.search_path()
|
|
{
|
|
return self.set_search_path(schemas, query_ctx).await;
|
|
}
|
|
if let Statement::Use(schema) = &stmt {
|
|
self.authorize_database(query_ctx.current_catalog(), schema, &query_ctx)
|
|
.await?;
|
|
}
|
|
if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(
|
|
CopyDatabase::From(arg),
|
|
)) = &stmt
|
|
&& arg.with.get("metric_data_layout").is_some()
|
|
{
|
|
return self
|
|
.copy_packed_database(arg.clone(), &stmt, query_ctx)
|
|
.await;
|
|
}
|
|
if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(CopyDatabase::To(
|
|
arg,
|
|
))) = &stmt
|
|
&& export_database::parse_metric_export_requested(&arg.with)?
|
|
{
|
|
return self.copy_metric_database(arg.clone(), query_ctx).await;
|
|
}
|
|
if let Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy)) = &stmt {
|
|
return self.copy_database(copy.clone(), &stmt, query_ctx).await;
|
|
}
|
|
if let Statement::CreateFlow(stmt) = stmt {
|
|
let (catalog, schema, table) = session::table_name::table_idents_to_full_name(
|
|
&stmt.sink_table_name,
|
|
&query_ctx,
|
|
)
|
|
.map_err(BoxedError::new)
|
|
.context(crate::error::ExternalSnafu)?;
|
|
let allow_sink_create = self
|
|
.can_create_flow_sinks(
|
|
&query_ctx,
|
|
catalog,
|
|
schema,
|
|
table,
|
|
stmt.flow_options.get("incremental"),
|
|
stmt.flow_options.get("incremental_result_view"),
|
|
)
|
|
.await?;
|
|
return self
|
|
.statement_executor
|
|
.create_flow_with_sink_create_permission(stmt, allow_sink_create, query_ctx)
|
|
.await
|
|
.context(TableOperationSnafu);
|
|
}
|
|
self.statement_executor
|
|
.execute_sql(stmt, query_ctx)
|
|
.await
|
|
.context(TableOperationSnafu)
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn plan_and_exec_sql(
|
|
&self,
|
|
stmt: Statement,
|
|
query_ctx: &QueryContextRef,
|
|
query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
|
|
) -> Result<Output> {
|
|
let stmt = QueryStatement::Sql(stmt);
|
|
let plan = self
|
|
.statement_executor
|
|
.plan(&stmt, query_ctx.clone())
|
|
.await?;
|
|
let QueryStatement::Sql(stmt) = stmt else {
|
|
unreachable!()
|
|
};
|
|
query_interceptor.pre_execute(Some(&stmt), Some(&plan), query_ctx.clone())?;
|
|
|
|
self.statement_executor
|
|
.exec_plan(plan, query_ctx.clone())
|
|
.await
|
|
.context(TableOperationSnafu)
|
|
}
|
|
|
|
async fn plan_and_exec_tql(
|
|
&self,
|
|
query_ctx: &QueryContextRef,
|
|
query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
|
|
tql: Tql,
|
|
) -> Result<Output> {
|
|
let plan = self
|
|
.statement_executor
|
|
.plan_tql(tql.clone(), query_ctx)
|
|
.await?;
|
|
query_interceptor.pre_execute(
|
|
Some(&Statement::Tql(tql)),
|
|
Some(&plan),
|
|
query_ctx.clone(),
|
|
)?;
|
|
self.statement_executor
|
|
.exec_plan(plan, query_ctx.clone())
|
|
.await
|
|
.context(TableOperationSnafu)
|
|
}
|
|
}
|
|
|
|
/// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements.
|
|
/// For MySQL, it applies only to read-only statements.
|
|
fn derive_timeout(readonly: bool, query_ctx: &QueryContextRef) -> Option<Duration> {
|
|
let query_timeout = query_ctx.query_timeout()?;
|
|
if query_timeout.is_zero() {
|
|
return None;
|
|
}
|
|
match query_ctx.channel() {
|
|
Channel::Mysql if readonly => Some(query_timeout),
|
|
Channel::Postgres => Some(query_timeout),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Runs `exec` within `timeout`, which also bounds reading a stream output.
|
|
///
|
|
/// `exec` is boxed because an async fn keeps its future argument and the awaited copy
|
|
/// side by side, and the statement futures are large enough to overflow the stack in
|
|
/// debug builds.
|
|
async fn exec_with_timeout(
|
|
timeout: Option<Duration>,
|
|
exec: Pin<Box<impl Future<Output = Result<Output>>>>,
|
|
timeout_recorder: Option<SlowQueryRecorder>,
|
|
) -> Result<Output> {
|
|
let Some(timeout) = timeout else {
|
|
return exec.await.and_then(map_query_output);
|
|
};
|
|
let start = tokio::time::Instant::now();
|
|
let output = tokio::time::timeout(timeout, exec)
|
|
.await
|
|
.map_err(|_| StatementTimeoutSnafu.build())??;
|
|
let output = map_query_output(output)?;
|
|
let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
|
|
attach_timeout(output, remaining_timeout, timeout_recorder)
|
|
}
|
|
|
|
/// Runs a query registered under `ticket` so that killing it cancels the run. A
|
|
/// stream output takes the ticket, keeping the query listed until the stream is dropped.
|
|
async fn exec_tracked(
|
|
ticket: Ticket,
|
|
query: impl Future<Output = Result<Output>>,
|
|
wrap_stream: fn(SendableRecordBatchStream, Ticket) -> CancellableStreamWrapper,
|
|
) -> Result<Output> {
|
|
let Output { meta, data } = CancellableFuture::new(query, ticket.cancellation_handle.clone())
|
|
.await
|
|
.map_err(|_| error::CancelledSnafu.build())??;
|
|
let data = match data {
|
|
OutputData::Stream(stream) => OutputData::Stream(Box::pin(wrap_stream(stream, ticket))),
|
|
other => other,
|
|
};
|
|
Ok(Output { data, meta })
|
|
}
|
|
|
|
fn record_explain_analyze_timeout(
|
|
recorder: Option<&SlowQueryRecorder>,
|
|
plan: Option<&Arc<dyn ExecutionPlan>>,
|
|
) {
|
|
let Some(recorder) = recorder else {
|
|
return;
|
|
};
|
|
let metrics = plan
|
|
.and_then(|plan| query::analyze_plan_metrics_to_json_value(plan, true).ok())
|
|
.unwrap_or_else(|| serde_json::json!([]));
|
|
recorder.force_record_with_payload(serde_json::json!({
|
|
"timed_out": true,
|
|
"metrics": metrics,
|
|
}));
|
|
}
|
|
|
|
fn attach_timeout(
|
|
output: Output,
|
|
mut timeout: Duration,
|
|
timeout_recorder: Option<SlowQueryRecorder>,
|
|
) -> Result<Output> {
|
|
if timeout.is_zero() {
|
|
return StatementTimeoutSnafu.fail();
|
|
}
|
|
|
|
let plan = timeout_recorder
|
|
.as_ref()
|
|
.and_then(|_| output.meta.plan.clone());
|
|
let output = match output.data {
|
|
OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
|
|
OutputData::Stream(mut stream) => {
|
|
let schema = stream.schema();
|
|
let s = Box::pin(stream! {
|
|
let mut start = tokio::time::Instant::now();
|
|
while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.map_err(|_| {
|
|
record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
|
|
StreamTimeoutSnafu.build()
|
|
})? {
|
|
yield item;
|
|
|
|
let now = tokio::time::Instant::now();
|
|
timeout = timeout.checked_sub(now - start).unwrap_or(Duration::ZERO);
|
|
start = now;
|
|
// tokio::time::timeout may not return an error immediately when timeout is 0.
|
|
if timeout.is_zero() {
|
|
record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
|
|
StreamTimeoutSnafu.fail()?;
|
|
}
|
|
}
|
|
}) as Pin<Box<dyn Stream<Item = _> + Send>>;
|
|
let stream = RecordBatchStreamWrapper {
|
|
schema,
|
|
stream: s,
|
|
output_ordering: None,
|
|
metrics: Default::default(),
|
|
span: Span::current(),
|
|
};
|
|
Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
|
|
}
|
|
};
|
|
|
|
Ok(output)
|
|
}
|
|
|
|
impl Instance {
|
|
async fn copy_database(
|
|
&self,
|
|
copy: CopyDatabase,
|
|
stmt: &Statement,
|
|
ctx: QueryContextRef,
|
|
) -> Result<Output> {
|
|
self.plugins
|
|
.get::<PermissionCheckerRef>()
|
|
.as_ref()
|
|
.check_permission_with_context(
|
|
ctx.current_user(),
|
|
PermissionReq::SqlStatement(stmt),
|
|
Some(&ctx.current_schema()),
|
|
)
|
|
.context(PermissionSnafu)?;
|
|
match copy {
|
|
CopyDatabase::To(arg) => {
|
|
let req = operator::statement::to_copy_database_request(arg, &ctx)?;
|
|
let tables = self
|
|
.statement_executor
|
|
.capture_database_export_tables(&req, None, &ctx)
|
|
.await?;
|
|
let targets = PermissionTableTargets::resolved(
|
|
tables
|
|
.iter()
|
|
.map(|table| {
|
|
let info = table.table_info();
|
|
PermissionTableTarget::new(
|
|
&info.catalog_name,
|
|
&info.schema_name,
|
|
&info.name,
|
|
)
|
|
})
|
|
.collect(),
|
|
);
|
|
self.check_table_permission(
|
|
&ctx,
|
|
PermissionReq::SqlStatement(stmt),
|
|
targets.clone(),
|
|
)
|
|
.context(PermissionSnafu)?;
|
|
self.check_table_permission(&ctx, PermissionReq::Action(COPY_TO), targets)
|
|
.context(PermissionSnafu)?;
|
|
self.statement_executor
|
|
.copy_database_to_tables(req, tables, ctx)
|
|
.await
|
|
.context(TableOperationSnafu)
|
|
}
|
|
CopyDatabase::From(arg) => {
|
|
let req = operator::statement::to_copy_database_request(arg, &ctx)?;
|
|
let requests = self
|
|
.statement_executor
|
|
.prepare_database_import(&req)
|
|
.await?;
|
|
let targets = PermissionTableTargets::resolved(
|
|
requests
|
|
.iter()
|
|
.map(|request| {
|
|
PermissionTableTarget::new(
|
|
&request.catalog_name,
|
|
&request.schema_name,
|
|
&request.table_name,
|
|
)
|
|
})
|
|
.collect(),
|
|
);
|
|
self.check_resolved_table_permission(
|
|
&ctx,
|
|
PermissionReq::SqlStatement(stmt),
|
|
targets,
|
|
)
|
|
.await?;
|
|
self.statement_executor
|
|
.copy_database_from_requests(req, requests, ctx)
|
|
.await
|
|
.context(TableOperationSnafu)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Authorizes `stmt` and returns the context to plan it with: the one given, carrying the
|
|
/// metric discovery scope this authorization resolved when the statement evaluates TQL.
|
|
async fn check_sql_permission(
|
|
&self,
|
|
stmt: &Statement,
|
|
query_ctx: &QueryContextRef,
|
|
) -> Result<QueryContextRef> {
|
|
self.check_unselected_mysql_database(stmt, query_ctx)
|
|
.await?;
|
|
self.plugins
|
|
.get::<PermissionCheckerRef>()
|
|
.as_ref()
|
|
.check_permission_with_context(
|
|
query_ctx.current_user(),
|
|
PermissionReq::SqlStatement(stmt),
|
|
Some(&query_ctx.current_schema()),
|
|
)
|
|
.context(PermissionSnafu)?;
|
|
|
|
// Database COPY needs the full table set before table-target authorization.
|
|
if matches!(stmt, Statement::Copy(Copy::CopyDatabase(_))) {
|
|
return Ok(query_ctx.clone());
|
|
}
|
|
|
|
let full_names = |names: Vec<ObjectName>, query_ctx: &QueryContextRef| {
|
|
names
|
|
.into_iter()
|
|
.map(|name| {
|
|
table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| {
|
|
PermissionTableTarget::new(catalog, schema, table)
|
|
})
|
|
})
|
|
.collect::<std::result::Result<Vec<_>, _>>()
|
|
.map_err(BoxedError::new)
|
|
.context(ExternalSnafu)
|
|
};
|
|
let mut targets = match extract_tables_from_statement_checked(stmt) {
|
|
Some(tables) => {
|
|
PermissionTableTargets::resolved(full_names(tables.collect(), query_ctx)?)
|
|
}
|
|
None => PermissionTableTargets::Unresolved,
|
|
};
|
|
let req = PermissionReq::SqlStatement(stmt);
|
|
let mut query_ctx = query_ctx.clone();
|
|
// TQL discovers metrics the way the Prometheus handler does, bounded by the tables this
|
|
// statement's own permission request may read.
|
|
if let Some(exprs) = extract_tql_exprs_from_statement(stmt)
|
|
&& !exprs.is_empty()
|
|
{
|
|
self.prepare_metric_discovery_scope_with(&exprs, req.clone(), &mut query_ctx)
|
|
.await?;
|
|
if matches!(targets, PermissionTableTargets::Unresolved)
|
|
&& let Some(discovered) =
|
|
MetricDiscoveryVisitor::walk(&exprs, query_ctx.current_schema())
|
|
.discovery_targets(query_ctx.metric_discovery_scope())
|
|
{
|
|
let mut resolved =
|
|
full_names(extract_tables_from_statement_partial(stmt), &query_ctx)?;
|
|
resolved.extend(discovered);
|
|
targets = PermissionTableTargets::resolved(resolved);
|
|
}
|
|
}
|
|
if matches!(
|
|
stmt,
|
|
Statement::Copy(Copy::CopyTable(CopyTable::To(_)) | Copy::CopyQueryTo(_))
|
|
) {
|
|
// COPY retains its write permission requirement and also reads source data.
|
|
self.check_resolved_table_permissions(
|
|
&query_ctx,
|
|
[PermissionReq::Action(COPY_TO), req],
|
|
targets,
|
|
)
|
|
.await?;
|
|
} else {
|
|
self.check_resolved_table_permission(&query_ctx, req, targets)
|
|
.await?;
|
|
}
|
|
Ok(query_ctx)
|
|
}
|
|
|
|
#[tracing::instrument(skip_all, name = "SqlQueryHandler::do_analyze_stream_query")]
|
|
async fn do_analyze_stream_query_inner(
|
|
&self,
|
|
query: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> Result<Output> {
|
|
ensure!(!self.is_suspended(), error::SuspendedSnafu);
|
|
|
|
let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
|
let query_interceptor = query_interceptor_opt.as_ref();
|
|
let query = query_interceptor.pre_parsing(query, query_ctx.clone())?;
|
|
let mut stmts = parse_stmt(query.as_ref(), query_ctx.sql_dialect())
|
|
.and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))?;
|
|
|
|
ensure!(
|
|
stmts.len() == 1,
|
|
InvalidSqlSnafu {
|
|
err_msg: "only a single EXPLAIN ANALYZE VERBOSE or TQL ANALYZE VERBOSE statement is supported"
|
|
}
|
|
);
|
|
let mut stmt = stmts.remove(0);
|
|
validate_analyze_stream_statement(&mut stmt)?;
|
|
query_ctx.set_explain_format(AnalyzeFormat::JSON.to_string());
|
|
|
|
let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?;
|
|
check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
|
|
let slow_query_timer = should_track_statement_process(&stmt)
|
|
.then(|| self.slow_query_timer(|| CatalogQueryStatement::Sql(stmt.clone()), &query_ctx))
|
|
.flatten();
|
|
let ticket = self.register_query(
|
|
&query_ctx,
|
|
vec![query_ctx.current_schema()],
|
|
stmt.to_string(),
|
|
slow_query_timer,
|
|
);
|
|
let query_fut = exec_with_timeout(
|
|
derive_timeout(stmt.is_readonly(), &query_ctx),
|
|
Box::pin(self.exec_statement(stmt, query_ctx.clone(), query_interceptor)),
|
|
None,
|
|
);
|
|
let output = exec_tracked(
|
|
ticket,
|
|
query_fut,
|
|
CancellableStreamWrapper::new_cancel_on_drop,
|
|
)
|
|
.await?;
|
|
query_interceptor.post_execute(output, query_ctx)
|
|
}
|
|
|
|
async fn batch_create_logical_tables(
|
|
&self,
|
|
query: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> Result<Vec<Output>> {
|
|
use servers::query_handler::sql::{
|
|
MAX_LOGICAL_TABLE_DDL_BYTES, MAX_LOGICAL_TABLE_DDL_STATEMENTS,
|
|
};
|
|
ensure!(!self.is_suspended(), error::SuspendedSnafu);
|
|
ensure!(
|
|
query.len() <= MAX_LOGICAL_TABLE_DDL_BYTES,
|
|
InvalidSqlSnafu {
|
|
err_msg: "logical-table DDL exceeds 1 MiB"
|
|
}
|
|
);
|
|
let interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
|
let interceptor = interceptor.as_ref();
|
|
let query = interceptor.pre_parsing(query, query_ctx.clone())?;
|
|
ensure!(
|
|
query.len() <= MAX_LOGICAL_TABLE_DDL_BYTES,
|
|
InvalidSqlSnafu {
|
|
err_msg: "logical-table DDL exceeds 1 MiB"
|
|
}
|
|
);
|
|
let statements = parse_stmt(query.as_ref(), query_ctx.sql_dialect()).map_err(|_| {
|
|
InvalidSqlSnafu {
|
|
err_msg: "invalid logical-table DDL",
|
|
}
|
|
.build()
|
|
})?;
|
|
ensure!(
|
|
!statements.is_empty() && statements.len() <= MAX_LOGICAL_TABLE_DDL_STATEMENTS,
|
|
InvalidSqlSnafu {
|
|
err_msg: "logical-table batch requires 1 to 128 statements"
|
|
}
|
|
);
|
|
let original_statements = interceptor.map(|_| statements.clone());
|
|
let statements = interceptor.post_parsing(statements, query_ctx.clone())?;
|
|
ensure!(
|
|
!statements.is_empty() && statements.len() <= MAX_LOGICAL_TABLE_DDL_STATEMENTS,
|
|
InvalidSqlSnafu {
|
|
err_msg: "logical-table batch requires 1 to 128 statements"
|
|
}
|
|
);
|
|
let measure_rewritten_sql = || {
|
|
let mut remaining = MAX_LOGICAL_TABLE_DDL_BYTES - (statements.len() - 1);
|
|
statements.iter().all(|statement| {
|
|
matches!(statement, Statement::CreateTable(create) if create.consume_sql_size_budget(&mut remaining))
|
|
})
|
|
};
|
|
ensure!(
|
|
original_statements
|
|
.as_ref()
|
|
.is_none_or(|original| original == &statements)
|
|
|| measure_rewritten_sql(),
|
|
InvalidSqlSnafu {
|
|
err_msg: "invalid or oversized rewritten logical-table DDL"
|
|
}
|
|
);
|
|
for statement in &statements {
|
|
ensure!(
|
|
matches!(statement, Statement::CreateTable(_)),
|
|
InvalidSqlSnafu {
|
|
err_msg: "batch requires explicit Metric logical CREATE TABLE statements"
|
|
}
|
|
);
|
|
interceptor.pre_execute(Some(statement), None, query_ctx.clone())?;
|
|
}
|
|
for statement in &statements {
|
|
self.check_sql_permission(statement, &query_ctx).await?;
|
|
check_permission(self.plugins.clone(), statement, &query_ctx)?;
|
|
}
|
|
let count = statements.len();
|
|
let creates = statements
|
|
.into_iter()
|
|
.filter_map(|statement| {
|
|
if let Statement::CreateTable(create) = statement {
|
|
Some(create)
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
self.statement_executor
|
|
.batch_create_logical_tables(creates, query_ctx.clone())
|
|
.await
|
|
.context(TableOperationSnafu)?;
|
|
(0..count)
|
|
.map(|_| interceptor.post_execute(Output::new_with_affected_rows(0), query_ctx.clone()))
|
|
.collect()
|
|
}
|
|
|
|
#[tracing::instrument(skip_all, name = "SqlQueryHandler::do_query")]
|
|
async fn do_query_inner(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
|
|
if self.is_suspended() {
|
|
return vec![error::SuspendedSnafu {}.fail()];
|
|
}
|
|
|
|
let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
|
let query_interceptor = query_interceptor_opt.as_ref();
|
|
let query = match query_interceptor.pre_parsing(query, query_ctx.clone()) {
|
|
Ok(q) => q,
|
|
Err(e) => return vec![Err(e)],
|
|
};
|
|
|
|
match parse_stmt(query.as_ref(), query_ctx.sql_dialect())
|
|
.and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))
|
|
{
|
|
Ok(stmts) => {
|
|
if stmts.is_empty() {
|
|
return vec![
|
|
InvalidSqlSnafu {
|
|
err_msg: "empty statements",
|
|
}
|
|
.fail(),
|
|
];
|
|
}
|
|
|
|
let mut results = Vec::with_capacity(stmts.len());
|
|
for stmt in stmts {
|
|
let stmt_ctx = match self.check_sql_permission(&stmt, &query_ctx).await {
|
|
Ok(stmt_ctx) => stmt_ctx,
|
|
Err(e) => {
|
|
results.push(Err(e));
|
|
break;
|
|
}
|
|
};
|
|
|
|
match self.query_statement(stmt.clone(), stmt_ctx).await {
|
|
Ok(output) => {
|
|
let output_result =
|
|
query_interceptor.post_execute(output, query_ctx.clone());
|
|
results.push(output_result);
|
|
}
|
|
Err(e) => {
|
|
if e.status_code().should_log_error() {
|
|
error!(e; user = query_ctx.current_user().username(), protocol = %query_ctx.channel(),
|
|
catalog = query_ctx.current_catalog(), schema = %query_ctx.current_schema(),
|
|
process_id = query_ctx.process_id(), "Failed to execute query: {stmt}");
|
|
} else {
|
|
debug!("Failed to execute query: {stmt}, {e}");
|
|
}
|
|
results.push(Err(e));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
results
|
|
}
|
|
Err(e) => {
|
|
vec![Err(e)]
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
|
|
self.query_engine
|
|
.execute(plan, query_ctx)
|
|
.await
|
|
.context(ExecLogicalPlanSnafu)
|
|
}
|
|
|
|
async fn do_exec_plan_inner(
|
|
&self,
|
|
plan: LogicalPlan,
|
|
stmt: Option<Statement>,
|
|
query_ctx: QueryContextRef,
|
|
) -> Result<Output> {
|
|
ensure!(!self.is_suspended(), error::SuspendedSnafu);
|
|
if let Some(stmt) = &stmt {
|
|
self.check_unselected_mysql_database(stmt, &query_ctx)
|
|
.await?;
|
|
} else if query_ctx.channel() == Channel::Mysql && query_ctx.current_schema().is_empty() {
|
|
return Err(BoxedError::new(
|
|
session::SessionError::NoDatabaseSelected {},
|
|
))
|
|
.context(ExternalSnafu);
|
|
}
|
|
|
|
let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
|
|
let query_interceptor = query_interceptor_opt.as_ref();
|
|
|
|
query_interceptor.pre_execute(stmt.as_ref(), Some(&plan), query_ctx.clone())?;
|
|
|
|
// TQL EXPLAIN/ANALYZE formats are consumed from the query context at
|
|
// execution time (see `optimize_physical_plan`); re-apply the side
|
|
// effect of `plan_tql` that was lost when the plan was built during
|
|
// Describe. `explain_format` is per-query state, so this never
|
|
// overwrites anything.
|
|
if let Some(Statement::Tql(tql)) = &stmt {
|
|
let format = match tql {
|
|
Tql::Explain(explain) => explain.format.as_ref(),
|
|
Tql::Analyze(analyze) => analyze.format.as_ref(),
|
|
Tql::Eval(_) => None,
|
|
};
|
|
if let Some(format) = format {
|
|
query_ctx.set_explain_format(format.to_string());
|
|
}
|
|
}
|
|
|
|
let query = stmt
|
|
.as_ref()
|
|
.map(|s| s.to_string())
|
|
.unwrap_or_else(|| plan.display_indent().to_string());
|
|
|
|
let timeout = derive_timeout(is_readonly_plan(&plan), &query_ctx);
|
|
let result = if should_track_plan_process(stmt.as_ref(), &plan) {
|
|
let slow_query_timer =
|
|
self.slow_query_timer(|| CatalogQueryStatement::Plan(query.clone()), &query_ctx);
|
|
let timeout_recorder = stmt
|
|
.as_ref()
|
|
.is_some_and(is_explain_analyze_verbose)
|
|
.then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
|
|
.flatten();
|
|
let ticket = self.register_query(
|
|
&query_ctx,
|
|
vec![query_ctx.current_schema()],
|
|
query,
|
|
slow_query_timer,
|
|
);
|
|
|
|
let exec = Box::pin(self.exec_plan(plan, query_ctx.clone()));
|
|
let query_fut = exec_with_timeout(timeout, exec, timeout_recorder);
|
|
exec_tracked(ticket, query_fut, CancellableStreamWrapper::new).await
|
|
} else {
|
|
let exec = Box::pin(self.exec_plan(plan, query_ctx.clone()));
|
|
exec_with_timeout(timeout, exec, None).await
|
|
};
|
|
|
|
result.and_then(|output| query_interceptor.post_execute(output, query_ctx))
|
|
}
|
|
|
|
#[tracing::instrument(skip_all, name = "SqlQueryHandler::do_promql_query")]
|
|
async fn do_promql_query_inner(
|
|
&self,
|
|
query: &PromQuery,
|
|
query_ctx: QueryContextRef,
|
|
) -> Vec<Result<Output>> {
|
|
if self.is_suspended() {
|
|
return vec![error::SuspendedSnafu {}.fail()];
|
|
}
|
|
|
|
// check will be done in prometheus handler's do_query
|
|
let result = PrometheusHandler::do_query(self, query, query_ctx)
|
|
.await
|
|
.with_context(|_| ExecutePromqlSnafu {
|
|
query: format!("{query:?}"),
|
|
});
|
|
vec![result]
|
|
}
|
|
|
|
/// Builds the [`DataFrame`] for an information-schema-backed `SHOW`
|
|
/// statement; `None` for other statements. The future is boxed to keep
|
|
/// `do_describe_inner`'s state machine small.
|
|
fn show_statement_dataframe<'a>(
|
|
&'a self,
|
|
stmt: &'a Statement,
|
|
query_ctx: &'a QueryContextRef,
|
|
) -> Pin<Box<dyn Future<Output = Option<query::error::Result<DataFrame>>> + Send + 'a>> {
|
|
Box::pin(async move {
|
|
let engine = &self.query_engine;
|
|
let catalog_manager = self.catalog_manager();
|
|
let ctx = query_ctx.clone();
|
|
let dataframe = match stmt {
|
|
Statement::ShowDatabases(show) => {
|
|
query::sql::show_databases_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowTables(show) => {
|
|
query::sql::show_tables_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowViews(show) => {
|
|
query::sql::show_views_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowFlows(show) => {
|
|
query::sql::show_flows_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowColumns(show) => {
|
|
query::sql::show_columns_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowTableStatus(show) => {
|
|
query::sql::show_table_status_dataframe(show, engine, catalog_manager, ctx)
|
|
.await
|
|
}
|
|
Statement::ShowCharset(kind) => {
|
|
query::sql::show_charsets_dataframe(kind, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowCollation(kind) => {
|
|
query::sql::show_collations_dataframe(kind, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowIndex(show) => {
|
|
query::sql::show_index_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowRegion(show) => {
|
|
query::sql::show_region_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
Statement::ShowProcesslist(show) => {
|
|
query::sql::show_processlist_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::ShowTriggers(show) => {
|
|
query::sql::show_triggers_dataframe(show, engine, catalog_manager, ctx).await
|
|
}
|
|
_ => return None,
|
|
};
|
|
Some(dataframe)
|
|
})
|
|
}
|
|
|
|
async fn do_describe_inner(
|
|
&self,
|
|
stmt: Statement,
|
|
query_ctx: QueryContextRef,
|
|
) -> Result<Option<DescribeResult>> {
|
|
ensure!(!self.is_suspended(), error::SuspendedSnafu);
|
|
self.check_unselected_mysql_database(&stmt, &query_ctx)
|
|
.await?;
|
|
|
|
// EXPLAIN / EXPLAIN ANALYZE wrap an inner statement; describe them when the
|
|
// wrapped statement is something we already plan (so that bind parameters
|
|
// in the inner query get their types inferred). See #8029.
|
|
let is_inner_plannable = |s: &Statement| {
|
|
matches!(
|
|
s,
|
|
Statement::Insert(_) | Statement::Query(_) | Statement::Delete(_)
|
|
)
|
|
};
|
|
let plannable = is_inner_plannable(&stmt)
|
|
|| matches!(&stmt, Statement::Explain(explain) if is_inner_plannable(explain.statement.as_ref()));
|
|
|
|
if let Statement::Tql(tql) = stmt {
|
|
// TQL produces a logical plan; describe it from the plan so the
|
|
// extended-protocol RowDescription matches the executed DataRows.
|
|
let query_ctx = self
|
|
.check_sql_permission(&Statement::Tql(tql.clone()), &query_ctx)
|
|
.await?;
|
|
let plan = self.statement_executor.plan_tql(tql, &query_ctx).await?;
|
|
return self
|
|
.query_engine
|
|
.describe(plan, query_ctx)
|
|
.await
|
|
.map(Some)
|
|
.context(error::DescribeStatementSnafu);
|
|
}
|
|
|
|
// Describe SHOW statements from the same projection the executor builds.
|
|
if let Some(dataframe) = self
|
|
.show_statement_dataframe(&stmt, &query_ctx)
|
|
.await
|
|
.transpose()
|
|
.context(PlanStatementSnafu)?
|
|
{
|
|
self.check_sql_permission(&stmt, &query_ctx).await?;
|
|
let plan = dataframe.into_unoptimized_plan();
|
|
return self
|
|
.query_engine
|
|
.describe(plan, query_ctx)
|
|
.await
|
|
.map(Some)
|
|
.context(error::DescribeStatementSnafu);
|
|
}
|
|
|
|
if plannable {
|
|
let query_ctx = self.check_sql_permission(&stmt, &query_ctx).await?;
|
|
|
|
let plan = self
|
|
.query_engine
|
|
.planner()
|
|
.plan(&QueryStatement::Sql(stmt), query_ctx.clone())
|
|
.await
|
|
.context(PlanStatementSnafu)?;
|
|
self.query_engine
|
|
.describe(plan, query_ctx)
|
|
.await
|
|
.map(Some)
|
|
.context(error::DescribeStatementSnafu)
|
|
} else {
|
|
Ok(None)
|
|
}
|
|
}
|
|
|
|
async fn is_valid_schema_inner(&self, catalog: &str, schema: &str) -> Result<bool> {
|
|
self.catalog_manager
|
|
.schema_exists(catalog, schema, None)
|
|
.await
|
|
.context(error::CatalogSnafu)
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl SqlQueryHandler for Instance {
|
|
fn supports_metric_batch_ddl(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
async fn create_logical_tables(
|
|
&self,
|
|
query: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Vec<Output>> {
|
|
self.batch_create_logical_tables(query, query_ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
|
|
async fn do_query(
|
|
&self,
|
|
query: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> Vec<server_error::Result<Output>> {
|
|
self.do_query_inner(query, query_ctx)
|
|
.await
|
|
.into_iter()
|
|
.map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
|
|
.collect()
|
|
}
|
|
|
|
async fn do_analyze_stream_query(
|
|
&self,
|
|
query: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Output> {
|
|
self.do_analyze_stream_query_inner(query, query_ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
|
|
async fn do_exec_plan(
|
|
&self,
|
|
plan: LogicalPlan,
|
|
stmt: Option<Statement>,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Output> {
|
|
// Prepared statements reach here with a plan built before their current execution.
|
|
let plan = query::plan::refresh_partition_columns(plan, &self.catalog_manager, &query_ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(server_error::ExecutePlanSnafu)?;
|
|
self.do_exec_plan_inner(plan, stmt, query_ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(server_error::ExecutePlanSnafu)
|
|
}
|
|
|
|
async fn do_promql_query(
|
|
&self,
|
|
query: &PromQuery,
|
|
query_ctx: QueryContextRef,
|
|
) -> Vec<server_error::Result<Output>> {
|
|
self.do_promql_query_inner(query, query_ctx)
|
|
.await
|
|
.into_iter()
|
|
.map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
|
|
.collect()
|
|
}
|
|
|
|
async fn do_describe(
|
|
&self,
|
|
stmt: Statement,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Option<DescribeResult>> {
|
|
self.do_describe_inner(stmt, query_ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(server_error::DescribeStatementSnafu)
|
|
}
|
|
|
|
async fn is_valid_schema(&self, catalog: &str, schema: &str) -> server_error::Result<bool> {
|
|
self.is_valid_schema_inner(catalog, schema)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(server_error::CheckDatabaseValiditySnafu)
|
|
}
|
|
}
|
|
|
|
/// Expands scan-time dictionaries only when a query result leaves the frontend.
|
|
pub(crate) fn map_query_output(output: Output) -> Result<Output> {
|
|
output
|
|
.map_dictionary_to_values()
|
|
.context(CollectRecordbatchSnafu)
|
|
}
|
|
|
|
/// Attaches a timer to the output and observes it once the output is exhausted.
|
|
pub fn attach_timer(output: Output, timer: HistogramTimer) -> Output {
|
|
match output.data {
|
|
OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
|
|
OutputData::Stream(stream) => {
|
|
let stream = OnDone::new(stream, move || {
|
|
timer.observe_duration();
|
|
});
|
|
Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Instance {
|
|
fn check_prom_query_privilege(&self, query_ctx: &QueryContextRef) -> server_error::Result<()> {
|
|
self.plugins
|
|
.get::<PermissionCheckerRef>()
|
|
.as_ref()
|
|
.check_permission(
|
|
query_ctx.current_user(),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
)
|
|
.context(AuthSnafu)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn prom_expr_permission_targets(
|
|
&self,
|
|
expr: &promql_parser::parser::Expr,
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<Option<Vec<PermissionTableTarget>>> {
|
|
extract_tables_from_prom_expr_checked(expr)
|
|
.map(|tables| {
|
|
tables
|
|
.map(|name| {
|
|
table_idents_to_full_name(&name, query_ctx).map(
|
|
|(catalog, schema, table)| {
|
|
PermissionTableTarget::new(catalog, schema, table)
|
|
},
|
|
)
|
|
})
|
|
.collect::<std::result::Result<Vec<_>, _>>()
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
})
|
|
.transpose()
|
|
}
|
|
|
|
async fn is_physical_query_permission_target(
|
|
&self,
|
|
target: &PermissionTableTarget,
|
|
query_ctx: &QueryContextRef,
|
|
) -> Result<bool> {
|
|
self.catalog_manager
|
|
.table(
|
|
&target.catalog,
|
|
&target.schema,
|
|
&target.table,
|
|
Some(query_ctx),
|
|
)
|
|
.await
|
|
.map(|table| table.is_some_and(|table| table.table_info().is_physical_table()))
|
|
.context(CatalogSnafu)
|
|
}
|
|
|
|
pub(crate) async fn check_resolved_table_permission(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
req: PermissionReq<'_>,
|
|
targets: PermissionTableTargets,
|
|
) -> Result<()> {
|
|
self.check_resolved_table_permissions(ctx, [req], targets)
|
|
.await
|
|
}
|
|
|
|
pub(crate) async fn can_create_flow_sink(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
catalog: String,
|
|
schema: String,
|
|
table: String,
|
|
) -> Result<bool> {
|
|
let req = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateTable(
|
|
api::v1::CreateTableExpr {
|
|
catalog_name: catalog.clone(),
|
|
schema_name: schema.clone(),
|
|
table_name: table.clone(),
|
|
..Default::default()
|
|
},
|
|
)),
|
|
});
|
|
let targets = PermissionTableTargets::Resolved(vec![PermissionTableTarget {
|
|
catalog,
|
|
schema,
|
|
table,
|
|
is_physical_metric_table: false,
|
|
}]);
|
|
match self
|
|
.check_resolved_table_permission(ctx, PermissionReq::GrpcRequest(&req), targets)
|
|
.await
|
|
{
|
|
Ok(()) => Ok(true),
|
|
Err(Error::Permission { source, .. })
|
|
if source.status_code()
|
|
== common_error::status_code::StatusCode::PermissionDenied =>
|
|
{
|
|
Ok(false)
|
|
}
|
|
Err(err) => Err(err),
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn can_create_flow_sinks(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
catalog: String,
|
|
schema: String,
|
|
sink_table: String,
|
|
incremental_flag: Option<&str>,
|
|
incremental_result_view: Option<&str>,
|
|
) -> Result<bool> {
|
|
if !self
|
|
.can_create_flow_sink(ctx, catalog.clone(), schema.clone(), sink_table.clone())
|
|
.await?
|
|
{
|
|
return Ok(false);
|
|
}
|
|
let is_incremental =
|
|
incremental_flag.is_some_and(|value| value.trim().eq_ignore_ascii_case("true"));
|
|
if !is_incremental {
|
|
return Ok(true);
|
|
}
|
|
let result_view = incremental_result_view
|
|
.map(str::trim)
|
|
.filter(|value| !value.is_empty())
|
|
.map(ToString::to_string)
|
|
.unwrap_or_else(|| format!("{sink_table}_result"));
|
|
self.can_create_flow_sink(ctx, catalog, schema, result_view)
|
|
.await
|
|
}
|
|
|
|
async fn check_resolved_table_permissions<const N: usize>(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
requests: [PermissionReq<'_>; N],
|
|
targets: PermissionTableTargets,
|
|
) -> Result<()> {
|
|
let checker = self.plugins.get::<PermissionCheckerRef>();
|
|
if checker.is_none() {
|
|
return Ok(());
|
|
}
|
|
let checker = checker.as_ref();
|
|
let mut targets = if checker.uses_table_targets() {
|
|
deduplicate_permission_targets(targets)
|
|
} else {
|
|
targets
|
|
};
|
|
|
|
let user = ctx.current_user();
|
|
let current_schema = ctx.current_schema();
|
|
let check = |req, targets| {
|
|
checker
|
|
.check_permission_with_table_targets(
|
|
user.clone(),
|
|
req,
|
|
targets,
|
|
Some(current_schema.as_str()),
|
|
)
|
|
.map(|_| ())
|
|
.context(PermissionSnafu)
|
|
};
|
|
let mut looked_up = HashSet::new();
|
|
for (i, req) in requests.into_iter().enumerate() {
|
|
match checker
|
|
.precheck_table_targets(
|
|
user.clone(),
|
|
req.clone(),
|
|
&targets,
|
|
Some(current_schema.as_str()),
|
|
)
|
|
.context(PermissionSnafu)?
|
|
{
|
|
TableTargetPrecheck::Allow => continue,
|
|
TableTargetPrecheck::Reject => {
|
|
unreachable!("Option<&PermissionCheckerRef> maps Reject to PermissionDenied")
|
|
}
|
|
TableTargetPrecheck::NeedsPhysicalResolution(indices) => {
|
|
self.resolve_physical_permission_targets(
|
|
ctx,
|
|
&mut targets,
|
|
indices,
|
|
&mut looked_up,
|
|
)
|
|
.await?;
|
|
}
|
|
}
|
|
|
|
if i + 1 == N {
|
|
return check(req, targets);
|
|
}
|
|
check(req, targets.clone())?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn resolve_physical_permission_targets(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
targets: &mut PermissionTableTargets,
|
|
mut indices: Vec<usize>,
|
|
looked_up: &mut HashSet<usize>,
|
|
) -> Result<()> {
|
|
const CONCURRENCY: usize = 8;
|
|
|
|
if let PermissionTableTargets::Resolved(resolved) = targets {
|
|
if let Some(index) = indices.iter().find(|&&index| index >= resolved.len()) {
|
|
return auth::error::InternalStateSnafu {
|
|
msg: format!(
|
|
"permission target precheck returned out-of-bounds index {index} for {} targets",
|
|
resolved.len()
|
|
),
|
|
}
|
|
.fail()
|
|
.context(PermissionSnafu);
|
|
}
|
|
indices.retain(|index| looked_up.insert(*index));
|
|
// Bound catalog load and inspect results in target order to preserve serial semantics.
|
|
for chunk in indices.chunks(CONCURRENCY) {
|
|
let results =
|
|
future::join_all(chunk.iter().map(|&index| {
|
|
self.is_physical_query_permission_target(&resolved[index], ctx)
|
|
}))
|
|
.await;
|
|
for (&index, result) in chunk.iter().zip(results) {
|
|
if result? {
|
|
resolved[index].is_physical_metric_table = true;
|
|
}
|
|
}
|
|
}
|
|
} else if !indices.is_empty() {
|
|
return auth::error::InternalStateSnafu {
|
|
msg: "permission target precheck returned indices for unresolved targets"
|
|
.to_string(),
|
|
}
|
|
.fail()
|
|
.context(PermissionSnafu);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) async fn check_server_table_permission(
|
|
&self,
|
|
ctx: &QueryContextRef,
|
|
req: PermissionReq<'_>,
|
|
targets: PermissionTableTargets,
|
|
) -> server_error::Result<()> {
|
|
match self
|
|
.check_resolved_table_permission(ctx, req, targets)
|
|
.await
|
|
{
|
|
Ok(()) => Ok(()),
|
|
Err(Error::Permission { source, .. }) => Err(source).context(AuthSnafu),
|
|
Err(err) => Err(BoxedError::new(err)).context(ExecuteQuerySnafu),
|
|
}
|
|
}
|
|
|
|
fn prom_queries_permission_targets(
|
|
&self,
|
|
queries: &[ParsedPromQuery],
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<PermissionTableTargets> {
|
|
let mut targets = Vec::new();
|
|
let mut resolved = true;
|
|
|
|
for query in queries {
|
|
let QueryStatement::Promql(eval_stmt, _) = query.statement() else {
|
|
unreachable!("query is parsed from promql");
|
|
};
|
|
|
|
if let Some(query_targets) =
|
|
self.prom_expr_permission_targets(&eval_stmt.expr, query_ctx)?
|
|
{
|
|
targets.extend(query_targets);
|
|
} else {
|
|
resolved = false;
|
|
}
|
|
}
|
|
|
|
Ok(if resolved {
|
|
PermissionTableTargets::resolved(targets)
|
|
} else {
|
|
PermissionTableTargets::Unresolved
|
|
})
|
|
}
|
|
}
|
|
|
|
/// What one PromQL expression needs in order to be answered by discovering metrics.
|
|
#[derive(Default)]
|
|
struct MetricDiscoveryVisitor {
|
|
needs_discovery: bool,
|
|
/// True only while every selector that names no exact table is one discovery can answer. If
|
|
/// any selector is not discoverable, the check must stay unresolved rather than be replaced by
|
|
/// a set that silently stops naming a table the query reads.
|
|
all_unresolved_are_discoverable: bool,
|
|
schemas: HashSet<String>,
|
|
current_schema: String,
|
|
/// Addresses of the label selectors of `info` calls, which the walk reaches after their call.
|
|
/// Compared only, never read through; plain integers keep the visitor `Send` across awaits.
|
|
info_label_selectors: Vec<usize>,
|
|
}
|
|
|
|
impl MetricDiscoveryVisitor {
|
|
fn new(current_schema: String) -> Self {
|
|
Self {
|
|
all_unresolved_are_discoverable: true,
|
|
current_schema,
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
fn walk(exprs: &[promql_parser::parser::Expr], current_schema: String) -> Self {
|
|
let mut visitor = Self::new(current_schema);
|
|
for expr in exprs {
|
|
let _ = walk_expr(&mut visitor, expr);
|
|
}
|
|
visitor
|
|
}
|
|
|
|
/// The tables discovery adds to the statically named ones of a query whose table extraction
|
|
/// is unresolved, or `None` when something other than discovery left it unresolved.
|
|
fn discovery_targets(
|
|
&self,
|
|
scope: &MetricDiscoveryScope,
|
|
) -> Option<Vec<PermissionTableTarget>> {
|
|
if !self.needs_discovery || !self.all_unresolved_are_discoverable {
|
|
return None;
|
|
}
|
|
match scope {
|
|
MetricDiscoveryScope::Allowed(allowed) => Some(allowed.iter().cloned().collect()),
|
|
// The named tables alone, because a selector that cannot be resolved statically is
|
|
// what left the query unresolved: the complete extraction would answer "no tables",
|
|
// dropping the named ones that the same query also reads.
|
|
MetricDiscoveryScope::Unrestricted => Some(Vec::new()),
|
|
MetricDiscoveryScope::Unavailable => None,
|
|
}
|
|
}
|
|
|
|
/// The planner reads the info table this selector stands for and never discovers with it, so
|
|
/// it must not authorize a schema here. A shape the table extractor leaves unresolved keeps
|
|
/// the whole expression unresolved.
|
|
fn inspect_info_labels(&mut self, labels: &promql_parser::parser::VectorSelector) {
|
|
self.info_label_selectors
|
|
.push(std::ptr::from_ref(labels) as usize);
|
|
let names = labels.matchers.find_matchers(METRIC_NAME);
|
|
let exact_name =
|
|
labels.name.is_some() || (names.len() == 1 && names[0].op == MatchOp::Equal);
|
|
self.all_unresolved_are_discoverable &=
|
|
exact_name || sql::util::reads_default_info_metric(labels);
|
|
}
|
|
|
|
/// Whether this selector is answered by enumerating the schema's metric tables.
|
|
///
|
|
/// The planner decides the same thing before it scans anything, and the two answers have to
|
|
/// match: this walk authorizes what the planner will scan, so a selector the planner declines
|
|
/// must not authorize a whole schema here. It is one function in `query`, called from both.
|
|
fn is_discovery_selector(selector: &promql_parser::parser::VectorSelector) -> bool {
|
|
query::promql::planner::discovers_metric_name(selector)
|
|
}
|
|
|
|
fn inspect_selector(&mut self, selector: &promql_parser::parser::VectorSelector) {
|
|
let names = selector.matchers.find_matchers(METRIC_NAME);
|
|
let exact_name =
|
|
selector.name.is_some() || (names.len() == 1 && names[0].op == MatchOp::Equal);
|
|
let discover = Self::is_discovery_selector(selector);
|
|
if !exact_name {
|
|
self.all_unresolved_are_discoverable &= discover;
|
|
}
|
|
if !discover {
|
|
return;
|
|
}
|
|
self.needs_discovery = true;
|
|
let effective_schema = selector
|
|
.matchers
|
|
.matchers
|
|
.iter()
|
|
.rev()
|
|
.find(|m| {
|
|
(m.name == "__schema__" || m.name == "__database__") && m.op == MatchOp::Equal
|
|
})
|
|
.map(|m| m.value.clone())
|
|
.unwrap_or_else(|| self.current_schema.clone());
|
|
self.schemas.insert(effective_schema);
|
|
}
|
|
}
|
|
|
|
impl ExprVisitor for MetricDiscoveryVisitor {
|
|
type Error = std::convert::Infallible;
|
|
|
|
fn pre_visit(
|
|
&mut self,
|
|
expr: &promql_parser::parser::Expr,
|
|
) -> std::result::Result<bool, Self::Error> {
|
|
match expr {
|
|
promql_parser::parser::Expr::Call(call) if call.func.name == "info" => {
|
|
if let Some(promql_parser::parser::Expr::VectorSelector(labels)) =
|
|
call.args.args.get(1).map(|labels| labels.as_ref())
|
|
{
|
|
self.inspect_info_labels(labels);
|
|
}
|
|
}
|
|
promql_parser::parser::Expr::VectorSelector(selector)
|
|
if !self
|
|
.info_label_selectors
|
|
.contains(&(std::ptr::from_ref(selector) as usize)) =>
|
|
{
|
|
self.inspect_selector(selector);
|
|
}
|
|
promql_parser::parser::Expr::MatrixSelector(selector) => {
|
|
self.inspect_selector(&selector.vs);
|
|
}
|
|
_ => {}
|
|
}
|
|
Ok(true)
|
|
}
|
|
}
|
|
|
|
impl Instance {
|
|
/// Bounds the metric tables this request may discover by the caller's grants, before anything
|
|
/// reads the catalog. `Unavailable` would make the planner decline discovery entirely, so this
|
|
/// always resolves to something explicit.
|
|
async fn prepare_metric_discovery_scope(
|
|
&self,
|
|
expr: &promql_parser::parser::Expr,
|
|
query_ctx: &mut QueryContextRef,
|
|
) -> server_error::Result<()> {
|
|
self.prepare_metric_discovery_scope_with(
|
|
std::slice::from_ref(expr),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
query_ctx,
|
|
)
|
|
.await
|
|
.or_else(|error| match error {
|
|
Error::Permission { source, .. } => Err(source).context(AuthSnafu),
|
|
error => Err(BoxedError::new(error)).context(ExecuteQuerySnafu),
|
|
})
|
|
}
|
|
|
|
/// [`Self::prepare_metric_discovery_scope`] for the expressions one request evaluates, keeping
|
|
/// each discovered table that `req` may read.
|
|
async fn prepare_metric_discovery_scope_with(
|
|
&self,
|
|
exprs: &[promql_parser::parser::Expr],
|
|
req: PermissionReq<'_>,
|
|
query_ctx: &mut QueryContextRef,
|
|
) -> Result<()> {
|
|
// Discovery scope is read by the native PromQL route only, so a query that does not ask
|
|
// for it pays nothing here beyond resolving the switch: the value is read through the
|
|
// query engine's own resolver, which takes what the query states (a request hint, or the
|
|
// session `SET` it inherits) over the engine default - the same two sources planning
|
|
// reads, so the two cannot disagree. A route that is off leaves discovery unrestricted,
|
|
// which is what it was before the switch existed; a route that is on is bounded below
|
|
// whether or not the fallback option later keeps the plan on the existing route.
|
|
let native_requested = query::promql::planner::native_promql_resolved(
|
|
query_ctx,
|
|
self.query_engine
|
|
.engine_state()
|
|
.experimental_native_promql(),
|
|
)
|
|
.map_err(BoxedError::new)
|
|
.context(ExternalSnafu)?;
|
|
if !native_requested {
|
|
Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted);
|
|
return Ok(());
|
|
}
|
|
let checker = self.plugins.get::<PermissionCheckerRef>();
|
|
if !checker.as_ref().uses_table_targets() {
|
|
Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Unrestricted);
|
|
return Ok(());
|
|
}
|
|
let visitor = MetricDiscoveryVisitor::walk(exprs, query_ctx.current_schema());
|
|
if !visitor.needs_discovery {
|
|
return Ok(());
|
|
}
|
|
let schemas = visitor.schemas;
|
|
let mut allowed = HashSet::new();
|
|
for schema in schemas {
|
|
let mut tables = self
|
|
.catalog_manager
|
|
.tables(query_ctx.current_catalog(), &schema, Some(query_ctx))
|
|
.try_collect::<Vec<_>>()
|
|
.await
|
|
.context(CatalogSnafu)?;
|
|
tables.sort_by_key(|table| table.table_info().name.clone());
|
|
for table in tables {
|
|
let info = table.table_info();
|
|
if info.meta.engine != store_api::metric_engine_consts::METRIC_ENGINE_NAME
|
|
|| info.is_physical_table()
|
|
{
|
|
continue;
|
|
}
|
|
if info.catalog_name != query_ctx.current_catalog() || info.schema_name != schema {
|
|
continue;
|
|
}
|
|
let target = PermissionTableTarget::new(
|
|
query_ctx.current_catalog(),
|
|
&schema,
|
|
info.name.as_str(),
|
|
);
|
|
match checker.as_ref().check_permission_with_table_targets(
|
|
query_ctx.current_user(),
|
|
req.clone(),
|
|
PermissionTableTargets::resolved(vec![target.clone()]),
|
|
Some(schema.as_str()),
|
|
) {
|
|
Ok(_) => {
|
|
allowed.insert(target);
|
|
}
|
|
// A rejected metric is skipped rather than failing the query, which is what
|
|
// makes discovery mean "every metric you can see": a table the caller cannot
|
|
// read is one the expression never mentions, the same way a query naming it
|
|
// would be rejected only where it names it. The split route instead rejects a
|
|
// query whose name matchers reach a denied table, so the same regex query
|
|
// answers with the readable metrics here and with `PermissionDenied` there.
|
|
Err(error)
|
|
if error.status_code()
|
|
== common_error::status_code::StatusCode::PermissionDenied => {}
|
|
Err(error) => return Err(error).context(PermissionSnafu),
|
|
}
|
|
}
|
|
}
|
|
Arc::make_mut(query_ctx).set_metric_discovery_scope(MetricDiscoveryScope::Allowed(allowed));
|
|
Ok(())
|
|
}
|
|
|
|
/// Fails closed: a path that must have set the scope and did not is an internal error, not a
|
|
/// silent return to an unfiltered discovery.
|
|
fn validate_metric_discovery_scope(
|
|
expr: &promql_parser::parser::Expr,
|
|
scope: &MetricDiscoveryScope,
|
|
) -> server_error::Result<()> {
|
|
let mut visitor = MetricDiscoveryVisitor::new(String::new());
|
|
let _ = walk_expr(&mut visitor, expr);
|
|
if visitor.needs_discovery && matches!(scope, MetricDiscoveryScope::Unavailable) {
|
|
return Err(server_error::Error::Internal {
|
|
err_msg: "Metric discovery reached without an authorization scope".to_string(),
|
|
});
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The statically named tables of an expression, kept even when another selector cannot be
|
|
/// resolved. The complete extractor would answer "no tables at all" for that expression and
|
|
/// drop these, which is how a mixed query lost the tables it names explicitly.
|
|
fn prom_expr_permission_targets_partial(
|
|
&self,
|
|
expr: &promql_parser::parser::Expr,
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<PermissionTableTarget>> {
|
|
extract_tables_from_prom_expr_partial(expr)
|
|
.into_iter()
|
|
.map(|name| {
|
|
table_idents_to_full_name(&name, query_ctx).map(|(catalog, schema, table)| {
|
|
PermissionTableTarget::new(catalog, schema, table)
|
|
})
|
|
})
|
|
.collect::<std::result::Result<Vec<_>, _>>()
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl PrometheusHandler for Instance {
|
|
async fn query_exemplars(
|
|
&self,
|
|
query: servers::exemplar::query::Query,
|
|
ctx: QueryContextRef,
|
|
) -> server_error::Result<Vec<servers::exemplar::query::Series>> {
|
|
self.query_exemplars_inner(query, ctx).await
|
|
}
|
|
|
|
#[tracing::instrument(skip_all)]
|
|
async fn do_query(
|
|
&self,
|
|
query: &PromQuery,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Output> {
|
|
let query = ParsedPromQuery::parse(query.clone(), &query_ctx)?;
|
|
self.do_query_parsed(query, query_ctx).await
|
|
}
|
|
|
|
#[tracing::instrument(skip_all)]
|
|
async fn do_query_parsed(
|
|
&self,
|
|
query: ParsedPromQuery,
|
|
query_ctx: QueryContextRef,
|
|
) -> server_error::Result<Output> {
|
|
let interceptor = self
|
|
.plugins
|
|
.get::<PromQueryInterceptorRef<server_error::Error>>();
|
|
|
|
self.check_prom_query_privilege(&query_ctx)?;
|
|
|
|
let parsed_expr = match query.statement() {
|
|
QueryStatement::Promql(eval_stmt, _) => &eval_stmt.expr,
|
|
_ => unreachable!("query is parsed from promql"),
|
|
};
|
|
// Authorization precedes any catalog read for discovery, so a denied name never reaches
|
|
// the plan, an error message, or an output column.
|
|
let mut scoped_ctx = query_ctx.clone();
|
|
self.prepare_metric_discovery_scope(parsed_expr, &mut scoped_ctx)
|
|
.await?;
|
|
let query_ctx = scoped_ctx;
|
|
Self::validate_metric_discovery_scope(parsed_expr, query_ctx.metric_discovery_scope())?;
|
|
let mut targets =
|
|
self.prom_queries_permission_targets(std::slice::from_ref(&query), &query_ctx)?;
|
|
if matches!(targets, PermissionTableTargets::Unresolved)
|
|
&& let Some(discovered) = MetricDiscoveryVisitor::walk(
|
|
std::slice::from_ref(parsed_expr),
|
|
query_ctx.current_schema(),
|
|
)
|
|
.discovery_targets(query_ctx.metric_discovery_scope())
|
|
{
|
|
let mut resolved =
|
|
self.prom_expr_permission_targets_partial(parsed_expr, &query_ctx)?;
|
|
resolved.extend(discovered);
|
|
targets = PermissionTableTargets::resolved(resolved);
|
|
}
|
|
self.check_query_target_permission(targets, &query_ctx)
|
|
.await?;
|
|
|
|
let requires_output_ordering = query.requires_output_ordering();
|
|
let (query, stmt) = query.into_parts();
|
|
|
|
let QueryStatement::Promql(eval_stmt, alias) = &stmt else {
|
|
unreachable!("query is parsed from promql");
|
|
};
|
|
let cached_alias = alias.clone();
|
|
|
|
let plan = self
|
|
.statement_executor
|
|
.plan(&stmt, query_ctx.clone())
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)?;
|
|
|
|
let plan = if requires_output_ordering {
|
|
plan
|
|
} else {
|
|
promql::remove_output_sort(plan)
|
|
};
|
|
|
|
interceptor.pre_execute(&query, &eval_stmt.expr, Some(&plan), query_ctx.clone())?;
|
|
|
|
// Take the EvalStmt from the original QueryStatement and use it to create the
|
|
// CatalogQueryStatement. It is copied rather than moved, because the statement
|
|
// passed the `let else` above and the range path may still read it below.
|
|
let query_statement = CatalogQueryStatement::Promql(eval_stmt.clone(), alias.clone());
|
|
let raw_query = query_statement.to_string();
|
|
|
|
let slow_query_timer = self.slow_query_timer(|| query_statement, &query_ctx);
|
|
let ticket = self.register_query(
|
|
&query_ctx,
|
|
vec![query_ctx.current_schema()],
|
|
raw_query,
|
|
slow_query_timer,
|
|
);
|
|
|
|
// A range query over a whole evaluation grid is the one shape the rollup cache
|
|
// serves. It is consulted after authorization, after `pre_execute`, and under the
|
|
// same process-list ticket, so a cached answer passes exactly the checks an
|
|
// executed one does; anything the cache declines keeps the original plan below.
|
|
let cached = self
|
|
.cached_range_output(
|
|
&query,
|
|
eval_stmt,
|
|
cached_alias,
|
|
requires_output_ordering,
|
|
&plan,
|
|
&query_ctx,
|
|
ticket.cancellation_handle.clone(),
|
|
)
|
|
.await?;
|
|
|
|
let output = match cached {
|
|
Some(rows) => Output {
|
|
data: OutputData::RecordBatches(rows),
|
|
// Every row was read into memory above, so the merged answer carries no
|
|
// stretches of one plan to point at.
|
|
meta: OutputMeta::default(),
|
|
},
|
|
None => {
|
|
let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone());
|
|
|
|
let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
|
|
.await
|
|
.map_err(|_| servers::error::CancelledSnafu.build())?
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)?;
|
|
map_query_output(output)
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)?
|
|
}
|
|
};
|
|
let Output { meta, data } = output;
|
|
let data = match data {
|
|
OutputData::Stream(stream) => {
|
|
OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
|
|
}
|
|
other => other,
|
|
};
|
|
let output = Output { data, meta };
|
|
Ok(interceptor.post_execute(output, query_ctx)?)
|
|
}
|
|
|
|
async fn check_query_permission(
|
|
&self,
|
|
queries: &[PromQuery],
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<()> {
|
|
let queries = queries
|
|
.iter()
|
|
.cloned()
|
|
.map(|query| ParsedPromQuery::parse(query, query_ctx))
|
|
.collect::<server_error::Result<Vec<_>>>()?;
|
|
self.check_query_permission_parsed(&queries, query_ctx)
|
|
.await
|
|
}
|
|
|
|
async fn check_query_permission_parsed(
|
|
&self,
|
|
queries: &[ParsedPromQuery],
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<()> {
|
|
self.check_prom_query_privilege(query_ctx)?;
|
|
let targets = self.prom_queries_permission_targets(queries, query_ctx)?;
|
|
self.check_query_target_permission(targets, query_ctx).await
|
|
}
|
|
|
|
async fn check_query_target_permission(
|
|
&self,
|
|
targets: PermissionTableTargets,
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<()> {
|
|
self.check_server_table_permission(query_ctx, PermissionReq::Action(PROMQL_QUERY), targets)
|
|
.await
|
|
}
|
|
|
|
async fn filter_metadata_metric_names(
|
|
&self,
|
|
metric_names: Vec<String>,
|
|
schema: &str,
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<String>> {
|
|
let checker = self.plugins.get::<PermissionCheckerRef>();
|
|
if !checker.as_ref().uses_table_targets() {
|
|
let Some(metric) = metric_names.first() else {
|
|
return Ok(metric_names);
|
|
};
|
|
let target =
|
|
PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
|
|
let result = checker
|
|
.as_ref()
|
|
.check_permission_with_table_targets(
|
|
query_ctx.current_user(),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![target]),
|
|
Some(schema),
|
|
)
|
|
.context(AuthSnafu);
|
|
return match result {
|
|
Ok(_) => Ok(metric_names),
|
|
Err(error)
|
|
if error.status_code()
|
|
== common_error::status_code::StatusCode::PermissionDenied =>
|
|
{
|
|
Ok(Vec::new())
|
|
}
|
|
Err(error) => Err(error),
|
|
};
|
|
}
|
|
|
|
let mut allowed = Vec::with_capacity(metric_names.len());
|
|
for metric in metric_names {
|
|
let target =
|
|
PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
|
|
match checker
|
|
.as_ref()
|
|
.check_permission_with_table_targets(
|
|
query_ctx.current_user(),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![target]),
|
|
Some(schema),
|
|
)
|
|
.context(AuthSnafu)
|
|
{
|
|
Ok(_) => allowed.push(metric),
|
|
Err(error)
|
|
if error.status_code()
|
|
== common_error::status_code::StatusCode::PermissionDenied => {}
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(allowed)
|
|
}
|
|
|
|
async fn filter_metadata_schema_names(
|
|
&self,
|
|
schema_names: Vec<String>,
|
|
query_ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<String>> {
|
|
let checker = self.plugins.get::<PermissionCheckerRef>();
|
|
let mut allowed = Vec::with_capacity(schema_names.len());
|
|
for schema in schema_names {
|
|
match checker
|
|
.as_ref()
|
|
.check_permission(
|
|
query_ctx.current_user(),
|
|
PermissionReq::SchemaRead {
|
|
catalog: query_ctx.current_catalog(),
|
|
schema: &schema,
|
|
},
|
|
)
|
|
.context(AuthSnafu)
|
|
{
|
|
Ok(_) => allowed.push(schema),
|
|
Err(error)
|
|
if error.status_code()
|
|
== common_error::status_code::StatusCode::PermissionDenied => {}
|
|
Err(error) => return Err(error),
|
|
}
|
|
}
|
|
Ok(allowed)
|
|
}
|
|
|
|
async fn query_metric_names(
|
|
&self,
|
|
matchers: Vec<Matcher>,
|
|
schema: &str,
|
|
ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<String>> {
|
|
self.handle_query_metric_names(matchers, schema, ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
|
|
async fn query_metric_names_by_labels(
|
|
&self,
|
|
matchers: Vec<Matcher>,
|
|
schema: &str,
|
|
start: SystemTime,
|
|
end: SystemTime,
|
|
ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<String>> {
|
|
self.handle_query_metric_names_by_labels(matchers, schema, start, end, ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
|
|
async fn query_label_values(
|
|
&self,
|
|
metric: String,
|
|
label_name: String,
|
|
matchers: Vec<Matcher>,
|
|
start: SystemTime,
|
|
end: SystemTime,
|
|
ctx: &QueryContextRef,
|
|
) -> server_error::Result<Vec<String>> {
|
|
let schema =
|
|
resolve_schema_from_matchers(&matchers)?.unwrap_or_else(|| ctx.current_schema());
|
|
let target = PermissionTableTarget::new(ctx.current_catalog(), schema.as_str(), &metric);
|
|
self.check_query_target_permission(
|
|
PermissionTableTargets::resolved(vec![target.clone()]),
|
|
ctx,
|
|
)
|
|
.await?;
|
|
|
|
self.handle_query_label_values(target, label_name, matchers, start, end, ctx)
|
|
.await
|
|
.map_err(BoxedError::new)
|
|
.context(ExecuteQuerySnafu)
|
|
}
|
|
|
|
fn catalog_manager(&self) -> CatalogManagerRef {
|
|
self.catalog_manager.clone()
|
|
}
|
|
}
|
|
|
|
/// Validate `stmt.database` permission if it's presented.
|
|
macro_rules! validate_db_permission {
|
|
($stmt: expr, $query_ctx: expr) => {
|
|
if let Some(database) = &$stmt.database {
|
|
validate_catalog_and_schema($query_ctx.current_catalog(), database, $query_ctx)
|
|
.map_err(BoxedError::new)
|
|
.context(SqlExecInterceptedSnafu)?;
|
|
}
|
|
};
|
|
}
|
|
|
|
pub fn check_permission(
|
|
plugins: Plugins,
|
|
stmt: &Statement,
|
|
query_ctx: &QueryContextRef,
|
|
) -> Result<()> {
|
|
let need_validate = plugins
|
|
.get::<QueryOptions>()
|
|
.map(|opts| opts.disallow_cross_catalog_query)
|
|
.unwrap_or_default();
|
|
|
|
if !need_validate {
|
|
return Ok(());
|
|
}
|
|
|
|
match stmt {
|
|
// Will be checked in execution.
|
|
// TODO(dennis): add a hook for admin commands.
|
|
Statement::Admin(_) => {}
|
|
// These are executed by query engine, and will be checked there.
|
|
Statement::Query(_)
|
|
| Statement::Explain(_)
|
|
| Statement::Tql(_)
|
|
| Statement::Delete(_)
|
|
| Statement::DeclareCursor(_)
|
|
| Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(_)) => {}
|
|
// database ops won't be checked
|
|
Statement::CreateDatabase(_)
|
|
| Statement::ShowDatabases(_)
|
|
| Statement::DropDatabase(_)
|
|
| Statement::AlterDatabase(_)
|
|
| Statement::DropFlow(_)
|
|
| Statement::Use(_) => {}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::DropTrigger(_) => {}
|
|
Statement::ShowCreateDatabase(stmt) => {
|
|
validate_database(&stmt.database_name, query_ctx)?;
|
|
}
|
|
Statement::ShowCreateTable(stmt) => {
|
|
validate_param(&stmt.table_name, query_ctx)?;
|
|
}
|
|
Statement::ShowCreateFlow(stmt) => {
|
|
validate_flow(&stmt.flow_name, query_ctx)?;
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::ShowCreateTrigger(stmt) => {
|
|
validate_param(&stmt.trigger_name, query_ctx)?;
|
|
}
|
|
Statement::ShowCreateView(stmt) => {
|
|
validate_param(&stmt.view_name, query_ctx)?;
|
|
}
|
|
Statement::CreateExternalTable(stmt) => {
|
|
validate_param(&stmt.name, query_ctx)?;
|
|
}
|
|
Statement::CreateFlow(stmt) => {
|
|
// TODO: should also validate source table name here?
|
|
validate_param(&stmt.sink_table_name, query_ctx)?;
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::CreateTrigger(stmt) => {
|
|
validate_param(&stmt.trigger_name, query_ctx)?;
|
|
}
|
|
Statement::CreateView(stmt) => {
|
|
validate_param(&stmt.name, query_ctx)?;
|
|
}
|
|
Statement::AlterTable(stmt) => {
|
|
validate_param(stmt.table_name(), query_ctx)?;
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::AlterTrigger(_) => {}
|
|
// set/show variable now only alter/show variable in session
|
|
Statement::SetVariables(_) | Statement::ShowVariables(_) => {}
|
|
// show charset and show collation won't be checked
|
|
Statement::ShowCharset(_) | Statement::ShowCollation(_) => {}
|
|
|
|
Statement::Comment(comment) => match &comment.object {
|
|
CommentObject::Table(table) => validate_param(table, query_ctx)?,
|
|
CommentObject::Column { table, .. } => validate_param(table, query_ctx)?,
|
|
CommentObject::Flow(flow) => validate_flow(flow, query_ctx)?,
|
|
},
|
|
|
|
Statement::Insert(insert) => {
|
|
let name = insert.table_name().context(ParseSqlSnafu)?;
|
|
validate_param(name, query_ctx)?;
|
|
}
|
|
Statement::CreateTable(stmt) => {
|
|
validate_param(&stmt.name, query_ctx)?;
|
|
}
|
|
Statement::CreateTableLike(stmt) => {
|
|
validate_param(&stmt.table_name, query_ctx)?;
|
|
validate_param(&stmt.source_name, query_ctx)?;
|
|
}
|
|
Statement::DropTable(drop_stmt) => {
|
|
for table_name in drop_stmt.table_names() {
|
|
validate_param(table_name, query_ctx)?;
|
|
}
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::UndropTable(stmt) => {
|
|
validate_param(stmt.table_name(), query_ctx)?;
|
|
}
|
|
Statement::DropView(stmt) => {
|
|
validate_param(&stmt.view_name, query_ctx)?;
|
|
}
|
|
Statement::ShowTables(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowTableStatus(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowColumns(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowIndex(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowRegion(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowViews(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowFlows(stmt) => {
|
|
validate_db_permission!(stmt, query_ctx);
|
|
}
|
|
Statement::ShowFlowStatus(_stmt) => {
|
|
// Flow statistics are organized based on the catalog dimension and
|
|
// filtered by the current catalog, so there is no need to check the
|
|
// permission of the database(schema).
|
|
}
|
|
#[cfg(feature = "enterprise")]
|
|
Statement::ShowTriggers(_stmt) => {
|
|
// The trigger is organized based on the catalog dimension, so there
|
|
// is no need to check the permission of the database(schema).
|
|
}
|
|
Statement::ShowStatus(_stmt) => {}
|
|
Statement::ShowSearchPath(_stmt) => {}
|
|
Statement::DescribeTable(stmt) => {
|
|
validate_param(stmt.name(), query_ctx)?;
|
|
}
|
|
Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => match stmt {
|
|
CopyTable::To(copy_table_to) => validate_param(©_table_to.table_name, query_ctx)?,
|
|
CopyTable::From(copy_table_from) => {
|
|
validate_param(©_table_from.table_name, query_ctx)?
|
|
}
|
|
},
|
|
Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
|
|
match copy_database {
|
|
CopyDatabase::To(stmt) => validate_database(&stmt.database_name, query_ctx)?,
|
|
CopyDatabase::From(stmt) => validate_database(&stmt.database_name, query_ctx)?,
|
|
}
|
|
}
|
|
Statement::TruncateTable(stmt) => {
|
|
validate_param(stmt.table_name(), query_ctx)?;
|
|
}
|
|
// cursor operations are always allowed once it's created
|
|
Statement::FetchCursor(_) | Statement::CloseCursor(_) => {}
|
|
// User can only kill process in their own catalog.
|
|
Statement::Kill(_) => {}
|
|
// SHOW PROCESSLIST
|
|
Statement::ShowProcesslist(_) => {}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn validate_param(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
|
|
let (catalog, schema, _) = table_idents_to_full_name(name, query_ctx)
|
|
.map_err(BoxedError::new)
|
|
.context(ExternalSnafu)?;
|
|
|
|
validate_catalog_and_schema(&catalog, &schema, query_ctx)
|
|
.map_err(BoxedError::new)
|
|
.context(SqlExecInterceptedSnafu)
|
|
}
|
|
|
|
fn validate_flow(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
|
|
let catalog = match &name.0[..] {
|
|
[_flow] => query_ctx.current_catalog().to_string(),
|
|
[catalog, _flow] => catalog.to_string_unquoted(),
|
|
_ => {
|
|
return InvalidSqlSnafu {
|
|
err_msg: format!(
|
|
"expect flow name to be <catalog>.<flow_name> or <flow_name>, actual: {name}",
|
|
),
|
|
}
|
|
.fail();
|
|
}
|
|
};
|
|
|
|
let schema = query_ctx.current_schema();
|
|
|
|
validate_catalog_and_schema(&catalog, &schema, query_ctx)
|
|
.map_err(BoxedError::new)
|
|
.context(SqlExecInterceptedSnafu)
|
|
}
|
|
|
|
fn validate_database(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
|
|
let (catalog, schema) = match &name.0[..] {
|
|
[schema] => (
|
|
query_ctx.current_catalog().to_string(),
|
|
schema.to_string_unquoted(),
|
|
),
|
|
[catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
|
|
_ => InvalidSqlSnafu {
|
|
err_msg: format!(
|
|
"expect database name to be <catalog>.<schema> or <schema>, actual: {name}",
|
|
),
|
|
}
|
|
.fail()?,
|
|
};
|
|
|
|
validate_catalog_and_schema(&catalog, &schema, query_ctx)
|
|
.map_err(BoxedError::new)
|
|
.context(SqlExecInterceptedSnafu)
|
|
}
|
|
|
|
fn is_readonly_plan(plan: &LogicalPlan) -> bool {
|
|
!matches!(plan, LogicalPlan::Dml(_) | LogicalPlan::Ddl(_))
|
|
}
|
|
|
|
fn should_track_statement_process(stmt: &Statement) -> bool {
|
|
stmt.is_readonly()
|
|
|| matches!(stmt, Statement::Insert(insert) if insert.has_non_values_query_source())
|
|
}
|
|
|
|
fn should_track_plan_process(stmt: Option<&Statement>, plan: &LogicalPlan) -> bool {
|
|
is_readonly_plan(plan)
|
|
|| matches!(stmt, Some(Statement::Insert(insert)) if insert.has_non_values_query_source())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::any::Any;
|
|
use std::collections::HashMap;
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
use std::sync::Arc;
|
|
use std::task::{Context, Poll};
|
|
use std::time::Duration;
|
|
|
|
use api::prom_store::remote::label_matcher::Type as PromMatcherType;
|
|
use api::prom_store::remote::{
|
|
Label, LabelMatcher, Query as RemoteQuery, ReadRequest, ReadResponse, Sample,
|
|
};
|
|
use api::v1::greptime_request::Request;
|
|
use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse};
|
|
use api::v1::query_request::Query;
|
|
use auth::{
|
|
DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE, JAEGER_QUERY, PIPELINE_DELETE,
|
|
PIPELINE_INSERT, PIPELINE_QUERY, PermissionAction, PermissionResp, UserInfo, UserInfoRef,
|
|
};
|
|
use catalog::process_manager::{ProcessManager, QueryStatement, SlowQueryTimer};
|
|
use common_base::Plugins;
|
|
use common_base::cancellation::CancellationHandle;
|
|
use common_catalog::consts::DEFAULT_PRIVATE_SCHEMA_NAME;
|
|
use common_error::ext::{BoxedError, ErrorExt, PlainError};
|
|
use common_error::status_code::StatusCode;
|
|
use common_event_recorder::{Event, EventRecorder, EventTypeFilter, EventTypeFilterRef};
|
|
use common_frontend::metrics::{CACHE_HIT, CACHE_MISS};
|
|
use common_frontend::slow_query_event::SlowQueryEvent;
|
|
use common_meta::cache::LayeredCacheRegistryBuilder;
|
|
use common_meta::kv_backend::memory::MemoryKvBackend;
|
|
use common_meta::procedure_executor::{ExecutorContext, ProcedureExecutor};
|
|
use common_meta::rpc::ddl::{DdlTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse};
|
|
use common_meta::rpc::procedure::{
|
|
MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse,
|
|
};
|
|
use common_query::prelude::greptime_value;
|
|
use common_query::{Output, OutputMeta};
|
|
use common_recordbatch::{
|
|
OrderOption, RecordBatch, RecordBatchStream, RecordBatches, SendableRecordBatchStream,
|
|
};
|
|
use common_telemetry::logging::SlowQueriesRecordType;
|
|
use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
|
|
use datafusion::physical_plan::empty::EmptyExec;
|
|
use datafusion_expr::dml::InsertOp;
|
|
use datafusion_expr::{LogicalPlanBuilder, LogicalTableSource};
|
|
use datatypes::prelude::ConcreteDataType;
|
|
use datatypes::schema::{ColumnSchema, Schema as GtSchema, SchemaRef as GtSchemaRef};
|
|
use datatypes::vectors::{
|
|
Float64Vector, StringVector, TimestampMillisecondVector, TimestampNanosecondVector,
|
|
VectorRef,
|
|
};
|
|
use log_query::LogQuery;
|
|
use promql_parser::parser::EvalStmt;
|
|
use prost::Message;
|
|
use query::query_engine::options::QueryOptions;
|
|
use servers::query_handler::{
|
|
DashboardHandler, JaegerQueryHandler, LogQueryHandler, PipelineHandler, PipelineHandlerRef,
|
|
PromStoreProtocolHandler,
|
|
};
|
|
use session::context::{Channel, ConnInfo, QueryContext, QueryContextBuilder};
|
|
use snafu::{Location, Snafu};
|
|
use sql::dialect::GreptimeDbDialect;
|
|
use store_api::data_source::DataSource;
|
|
use store_api::metric_engine_consts::{
|
|
LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
|
|
};
|
|
use store_api::storage::ScanRequest;
|
|
use strfmt::Format;
|
|
use table::metadata::{
|
|
FilterPushDownType, TableId, TableInfo, TableInfoBuilder, TableMetaBuilder, TableType,
|
|
};
|
|
use table::table_name::TableName;
|
|
use table::test_util::{EmptyTable, MemTable};
|
|
use table::{Table, TableRef};
|
|
use tokio::sync::{mpsc, oneshot};
|
|
use tower::ServiceExt;
|
|
|
|
use crate::frontend::FrontendOptions;
|
|
use crate::instance::builder::FrontendBuilder;
|
|
use crate::instance::*;
|
|
|
|
/// The id the `cpu` metric table of [`metric_instance`] is registered under.
|
|
const CPU_TABLE_ID: TableId = 1024;
|
|
|
|
fn parse_test_sql(sql: &str) -> Vec<Statement> {
|
|
parse_stmt(sql, &GreptimeDbDialect {}).unwrap()
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
struct RecordingSlowQueryEventRecorder {
|
|
queries: std::sync::Mutex<Vec<String>>,
|
|
payloads: std::sync::Mutex<Vec<serde_json::Value>>,
|
|
}
|
|
|
|
impl EventRecorder for RecordingSlowQueryEventRecorder {
|
|
fn record(&self, event: Box<dyn Event>) {
|
|
let event = event
|
|
.as_any()
|
|
.downcast_ref::<SlowQueryEvent>()
|
|
.expect("expected a slow query event");
|
|
self.queries.lock().unwrap().push(event.query.clone());
|
|
self.payloads.lock().unwrap().push(event.payload.clone());
|
|
}
|
|
|
|
fn event_type_filter(&self) -> EventTypeFilterRef {
|
|
Arc::new(EventTypeFilter::All)
|
|
}
|
|
|
|
fn close(&self) {}
|
|
}
|
|
|
|
#[test]
|
|
fn test_validate_analyze_stream_statement_strictness() {
|
|
for sql in [
|
|
"select 1",
|
|
"explain analyze select 1",
|
|
"explain analyze verbose format text select 1",
|
|
"explain analyze verbose format graphviz select 1",
|
|
"TQL ANALYZE (0, 10, '5s') physical_metric",
|
|
"TQL EXPLAIN VERBOSE (0, 10, '5s') physical_metric",
|
|
"TQL ANALYZE VERBOSE FORMAT TEXT (0, 10, '5s') physical_metric",
|
|
] {
|
|
let mut stmts = parse_test_sql(sql);
|
|
assert!(
|
|
validate_analyze_stream_statement(&mut stmts[0]).is_err(),
|
|
"{sql}"
|
|
);
|
|
}
|
|
|
|
for sql in [
|
|
"explain analyze verbose select 1",
|
|
"explain analyze verbose format json select 1",
|
|
"TQL ANALYZE VERBOSE (0, 10, '5s') physical_metric",
|
|
"TQL ANALYZE VERBOSE FORMAT JSON (0, 10, '5s') physical_metric",
|
|
] {
|
|
let mut stmts = parse_test_sql(sql);
|
|
assert!(
|
|
validate_analyze_stream_statement(&mut stmts[0]).is_ok(),
|
|
"{sql}"
|
|
);
|
|
match &stmts[0] {
|
|
Statement::Explain(explain) => assert!(explain.format.is_none()),
|
|
Statement::Tql(Tql::Analyze(analyze)) => assert!(analyze.format.is_none()),
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
|
|
assert_eq!(
|
|
parse_test_sql("explain analyze verbose select 1; select 2").len(),
|
|
2
|
|
);
|
|
|
|
assert!(is_explain_analyze_verbose(
|
|
&parse_test_sql("explain analyze verbose select 1")[0]
|
|
));
|
|
assert!(is_explain_analyze_verbose(
|
|
&parse_test_sql("TQL ANALYZE VERBOSE (0, 10, '5s') physical_metric")[0]
|
|
));
|
|
for sql in [
|
|
"select 1",
|
|
"explain select 1",
|
|
"explain analyze select 1",
|
|
"explain verbose select 1",
|
|
"TQL ANALYZE (0, 10, '5s') physical_metric",
|
|
"TQL EXPLAIN VERBOSE (0, 10, '5s') physical_metric",
|
|
] {
|
|
assert!(
|
|
!is_explain_analyze_verbose(&parse_test_sql(sql)[0]),
|
|
"{sql}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Snafu)]
|
|
enum TestError {
|
|
#[snafu(display("Failed to build test cache registry"))]
|
|
BuildCacheRegistry {
|
|
source: cache::error::Error,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to build test table meta for table: {table_name}"))]
|
|
BuildTableMeta {
|
|
table_name: String,
|
|
source: table::metadata::TableMetaBuilderError,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to build test table info for table: {table_name}"))]
|
|
BuildTableInfo {
|
|
table_name: String,
|
|
source: table::metadata::TableInfoBuilderError,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to register test table: {table_name}"))]
|
|
RegisterTable {
|
|
table_name: String,
|
|
source: catalog::error::Error,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to build test frontend instance"))]
|
|
BuildFrontend {
|
|
source: crate::error::Error,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Expected exactly one output for SQL `{sql}`, got {actual}"))]
|
|
UnexpectedOutputCount {
|
|
sql: String,
|
|
actual: usize,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to execute SQL `{sql}`"))]
|
|
ExecuteSql {
|
|
sql: String,
|
|
source: crate::error::Error,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Timed out waiting for insert-select start notification"))]
|
|
InsertStartTimeout {
|
|
source: tokio::time::error::Elapsed,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Insert-select start notification channel closed"))]
|
|
InsertStartChannelClosed {
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Failed to release blocking insert-select interceptor"))]
|
|
ReleaseBlockedInsert {
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Timed out waiting for insert-select source to be polled"))]
|
|
SourcePollTimeout {
|
|
source: tokio::time::error::Elapsed,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Insert-select source poll notification channel closed"))]
|
|
SourcePollChannelClosed {
|
|
source: oneshot::error::RecvError,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Timed out waiting for insert task to finish"))]
|
|
InsertTaskTimeout {
|
|
source: tokio::time::error::Elapsed,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Insert task panicked"))]
|
|
InsertTaskPanic {
|
|
source: tokio::task::JoinError,
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
|
|
#[snafu(display("Expected insert-select to be cancelled"))]
|
|
InsertSelectNotCancelled {
|
|
#[snafu(implicit)]
|
|
location: Location,
|
|
},
|
|
}
|
|
|
|
type TestResult<T> = std::result::Result<T, TestError>;
|
|
|
|
fn parse_one_sql(sql: &str) -> Statement {
|
|
parse_stmt(sql, &GreptimeDbDialect {}).unwrap().remove(0)
|
|
}
|
|
|
|
fn test_query_ctx(process_id: u32) -> QueryContextRef {
|
|
Arc::new(
|
|
QueryContextBuilder::default()
|
|
.channel(Channel::Mysql)
|
|
.conn_info(ConnInfo::new(None, Channel::Mysql))
|
|
.process_id(process_id)
|
|
.build(),
|
|
)
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct AdminUserInfo;
|
|
|
|
impl UserInfo for AdminUserInfo {
|
|
fn as_any(&self) -> &dyn Any {
|
|
self
|
|
}
|
|
|
|
fn username(&self) -> &str {
|
|
"admin"
|
|
}
|
|
|
|
fn is_admin(&self) -> bool {
|
|
true
|
|
}
|
|
}
|
|
|
|
/// A checker that authorizes per table and counts the grants it was asked for, so a test can
|
|
/// state that a path did (or did not) ask.
|
|
#[derive(Default)]
|
|
struct CountingPermissionChecker {
|
|
table_target_checks: atomic::AtomicUsize,
|
|
}
|
|
|
|
impl CountingPermissionChecker {
|
|
fn table_target_checks(&self) -> usize {
|
|
self.table_target_checks.load(atomic::Ordering::Relaxed)
|
|
}
|
|
}
|
|
|
|
impl PermissionChecker for CountingPermissionChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
_targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.table_target_checks
|
|
.fetch_add(1, atomic::Ordering::Relaxed);
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn uses_table_targets(&self) -> bool {
|
|
true
|
|
}
|
|
}
|
|
|
|
struct RejectUnresolvedPermissionChecker;
|
|
|
|
impl PermissionChecker for RejectUnresolvedPermissionChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let reject = match targets {
|
|
PermissionTableTargets::Unresolved => true,
|
|
PermissionTableTargets::Resolved(targets) => targets
|
|
.iter()
|
|
.any(|target| target.table == "denied" || target.is_physical_metric_table),
|
|
};
|
|
Ok(if reject {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
struct CheckedAction {
|
|
action: PermissionAction,
|
|
targets: Option<PermissionTableTargets>,
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct RejectEndpointPermissionChecker {
|
|
checks: std::sync::Mutex<Vec<CheckedAction>>,
|
|
}
|
|
|
|
impl RejectEndpointPermissionChecker {
|
|
fn reject(
|
|
&self,
|
|
action: PermissionAction,
|
|
targets: Option<PermissionTableTargets>,
|
|
) -> PermissionResp {
|
|
self.checks
|
|
.lock()
|
|
.unwrap()
|
|
.push(CheckedAction { action, targets });
|
|
PermissionResp::Reject
|
|
}
|
|
|
|
fn take_check(&self) -> CheckedAction {
|
|
let mut checks = self.checks.lock().unwrap();
|
|
assert_eq!(1, checks.len());
|
|
checks.pop().unwrap()
|
|
}
|
|
}
|
|
|
|
impl PermissionChecker for RejectEndpointPermissionChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(match req {
|
|
PermissionReq::Action(action) => self.reject(action, None),
|
|
_ => PermissionResp::Allow,
|
|
})
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(match req {
|
|
PermissionReq::Action(action) => self.reject(action, Some(targets)),
|
|
_ => PermissionResp::Allow,
|
|
})
|
|
}
|
|
}
|
|
|
|
struct WriteOnlyPermissionChecker;
|
|
|
|
impl PermissionChecker for WriteOnlyPermissionChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(if req.is_readonly() {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
_targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.check_permission(user_info, req)
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct TargetIndependentPermissionChecker {
|
|
checks: atomic::AtomicUsize,
|
|
}
|
|
|
|
impl PermissionChecker for TargetIndependentPermissionChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.checks.fetch_add(1, atomic::Ordering::Relaxed);
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn uses_table_targets(&self) -> bool {
|
|
false
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
_targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.check_permission(user_info, req)
|
|
}
|
|
}
|
|
|
|
struct BlockingInsertSelectInterceptor {
|
|
started_tx: mpsc::UnboundedSender<()>,
|
|
finish_rx: std::sync::Mutex<Option<oneshot::Receiver<()>>>,
|
|
}
|
|
|
|
impl BlockingInsertSelectInterceptor {
|
|
fn new(started_tx: mpsc::UnboundedSender<()>, finish_rx: oneshot::Receiver<()>) -> Self {
|
|
Self {
|
|
started_tx,
|
|
finish_rx: std::sync::Mutex::new(Some(finish_rx)),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl SqlQueryInterceptor for BlockingInsertSelectInterceptor {
|
|
type Error = Error;
|
|
|
|
fn pre_execute(
|
|
&self,
|
|
statement: Option<&Statement>,
|
|
_plan: Option<&LogicalPlan>,
|
|
_query_ctx: QueryContextRef,
|
|
) -> Result<()> {
|
|
let Some(Statement::Insert(insert)) = statement else {
|
|
return Ok(());
|
|
};
|
|
if !insert.has_non_values_query_source() {
|
|
return Ok(());
|
|
}
|
|
|
|
let finish_rx = self.finish_rx.lock().unwrap().take().unwrap();
|
|
let _ = self.started_tx.send(());
|
|
tokio::task::block_in_place(|| {
|
|
tokio::runtime::Handle::current()
|
|
.block_on(finish_rx)
|
|
.unwrap();
|
|
});
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
struct PendingRecordBatchStream {
|
|
schema: GtSchemaRef,
|
|
polled_tx: Option<oneshot::Sender<()>>,
|
|
_finish_tx: oneshot::Sender<()>,
|
|
finish_rx: Pin<Box<oneshot::Receiver<()>>>,
|
|
}
|
|
|
|
impl RecordBatchStream for PendingRecordBatchStream {
|
|
fn schema(&self) -> GtSchemaRef {
|
|
self.schema.clone()
|
|
}
|
|
|
|
fn output_ordering(&self) -> Option<&[OrderOption]> {
|
|
None
|
|
}
|
|
|
|
fn metrics(&self) -> Option<common_recordbatch::adapter::RecordBatchMetrics> {
|
|
None
|
|
}
|
|
}
|
|
|
|
impl Stream for PendingRecordBatchStream {
|
|
type Item = common_recordbatch::error::Result<RecordBatch>;
|
|
|
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
|
if let Some(polled_tx) = self.polled_tx.take() {
|
|
let _ = polled_tx.send(());
|
|
}
|
|
|
|
match self.finish_rx.as_mut().poll(cx) {
|
|
Poll::Ready(_) => Poll::Ready(None),
|
|
Poll::Pending => Poll::Pending,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Unpin for PendingRecordBatchStream {}
|
|
|
|
#[test]
|
|
fn test_record_explain_analyze_timeout_uses_empty_metrics_without_plan() {
|
|
let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
|
|
let timer = SlowQueryTimer::new(
|
|
QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
|
|
"public".to_string(),
|
|
Duration::from_secs(3600),
|
|
0.0,
|
|
SlowQueriesRecordType::SystemTable,
|
|
event_recorder.clone(),
|
|
);
|
|
let timeout_recorder = timer.recorder();
|
|
|
|
record_explain_analyze_timeout(Some(&timeout_recorder), None);
|
|
drop(timer);
|
|
|
|
let payloads = event_recorder.payloads.lock().unwrap();
|
|
assert_eq!(payloads.len(), 1);
|
|
assert_eq!(payloads[0]["timed_out"], true);
|
|
assert_eq!(payloads[0]["metrics"], serde_json::json!([]));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_attach_timeout_records_explain_analyze_metrics() {
|
|
let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
|
|
let timer = SlowQueryTimer::new(
|
|
QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
|
|
"public".to_string(),
|
|
Duration::from_secs(3600),
|
|
0.0,
|
|
SlowQueriesRecordType::SystemTable,
|
|
event_recorder.clone(),
|
|
);
|
|
let timeout_recorder = timer.recorder();
|
|
let plan: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::new(Schema::empty())));
|
|
let (finish_tx, finish_rx) = oneshot::channel();
|
|
let stream = PendingRecordBatchStream {
|
|
schema: Arc::new(GtSchema::new(vec![])),
|
|
polled_tx: None,
|
|
_finish_tx: finish_tx,
|
|
finish_rx: Box::pin(finish_rx),
|
|
};
|
|
let output = Output::new(
|
|
OutputData::Stream(Box::pin(stream)),
|
|
OutputMeta::new_with_plan(plan),
|
|
);
|
|
let output =
|
|
attach_timeout(output, Duration::from_millis(10), Some(timeout_recorder)).unwrap();
|
|
let OutputData::Stream(mut stream) = output.data else {
|
|
unreachable!();
|
|
};
|
|
|
|
let err = stream.next().await.unwrap().unwrap_err();
|
|
assert_eq!(err.to_string(), "Stream timeout");
|
|
drop(stream);
|
|
drop(timer);
|
|
|
|
let payloads = event_recorder.payloads.lock().unwrap();
|
|
assert_eq!(payloads.len(), 1);
|
|
assert_eq!(payloads[0]["timed_out"], true);
|
|
assert!(
|
|
payloads[0]["metrics"]
|
|
.as_array()
|
|
.is_some_and(|metrics| !metrics.is_empty())
|
|
);
|
|
}
|
|
|
|
struct PendingDataSource {
|
|
schema: GtSchemaRef,
|
|
polled_tx: std::sync::Mutex<Option<oneshot::Sender<()>>>,
|
|
}
|
|
|
|
impl DataSource for PendingDataSource {
|
|
fn get_stream(
|
|
&self,
|
|
_request: ScanRequest,
|
|
) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
|
|
let (finish_tx, finish_rx) = oneshot::channel();
|
|
let mut polled_tx = self.polled_tx.lock().map_err(|_| {
|
|
BoxedError::new(PlainError::new(
|
|
"pending data source lock poisoned".to_string(),
|
|
StatusCode::Unexpected,
|
|
))
|
|
})?;
|
|
Ok(Box::pin(PendingRecordBatchStream {
|
|
schema: self.schema.clone(),
|
|
polled_tx: polled_tx.take(),
|
|
_finish_tx: finish_tx,
|
|
finish_rx: Box::pin(finish_rx),
|
|
}))
|
|
}
|
|
}
|
|
|
|
struct NoopProcedureExecutor;
|
|
|
|
#[async_trait::async_trait]
|
|
impl ProcedureExecutor for NoopProcedureExecutor {
|
|
async fn submit_ddl_task(
|
|
&self,
|
|
_ctx: ExecutorContext,
|
|
_request: SubmitDdlTaskRequest,
|
|
) -> common_meta::error::Result<SubmitDdlTaskResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "submit_ddl_task",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn migrate_region(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_request: MigrateRegionRequest,
|
|
) -> common_meta::error::Result<MigrateRegionResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "migrate_region",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn reconcile(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_request: ReconcileRequest,
|
|
) -> common_meta::error::Result<ReconcileResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "reconcile",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn query_procedure_state(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_pid: &str,
|
|
) -> common_meta::error::Result<ProcedureStateResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "query_procedure_state",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn list_procedures(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
) -> common_meta::error::Result<ProcedureDetailResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "list_procedures",
|
|
}
|
|
.fail()
|
|
}
|
|
}
|
|
|
|
/// A test [`ProcedureExecutor`] that completes create/drop DDL tasks against the
|
|
/// in-memory catalog, mimicking what the meta DDL procedures do in production.
|
|
/// This allows happy-path DDL requests (create/drop table/view) to be exercised
|
|
/// end to end through the gRPC ingress.
|
|
struct MockProcedureExecutor {
|
|
catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
|
|
next_table_id: std::sync::atomic::AtomicU32,
|
|
submitted: std::sync::Mutex<Vec<DdlTask>>,
|
|
}
|
|
|
|
impl MockProcedureExecutor {
|
|
fn new(catalog_manager: Arc<catalog::memory::MemoryCatalogManager>) -> Self {
|
|
Self {
|
|
catalog_manager,
|
|
next_table_id: std::sync::atomic::AtomicU32::new(1026),
|
|
submitted: std::sync::Mutex::new(Vec::new()),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl ProcedureExecutor for MockProcedureExecutor {
|
|
async fn submit_ddl_task(
|
|
&self,
|
|
_ctx: ExecutorContext,
|
|
request: SubmitDdlTaskRequest,
|
|
) -> common_meta::error::Result<SubmitDdlTaskResponse> {
|
|
self.submitted.lock().unwrap().push(request.task.clone());
|
|
match request.task {
|
|
DdlTask::CreateTable(task) => {
|
|
let table_id = self
|
|
.next_table_id
|
|
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
let mut table_info = task.table_info;
|
|
table_info.ident.table_id = table_id;
|
|
self.catalog_manager
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: table_info.catalog_name.clone(),
|
|
schema: table_info.schema_name.clone(),
|
|
table_name: table_info.name.clone(),
|
|
table_id,
|
|
table: table::dist_table::DistTable::table(Arc::new(table_info)),
|
|
})
|
|
.map_err(BoxedError::new)
|
|
.context(common_meta::error::ExternalSnafu)?;
|
|
Ok(SubmitDdlTaskResponse {
|
|
key: Vec::new(),
|
|
table_ids: vec![table_id],
|
|
})
|
|
}
|
|
DdlTask::CreateView(task) => {
|
|
let view_id = self
|
|
.next_table_id
|
|
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
let mut view_info = task.view_info;
|
|
view_info.ident.table_id = view_id;
|
|
self.catalog_manager
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: task.create_view.catalog_name.clone(),
|
|
schema: task.create_view.schema_name.clone(),
|
|
table_name: task.create_view.view_name.clone(),
|
|
table_id: view_id,
|
|
table: table::dist_table::DistTable::table(Arc::new(view_info)),
|
|
})
|
|
.map_err(BoxedError::new)
|
|
.context(common_meta::error::ExternalSnafu)?;
|
|
Ok(SubmitDdlTaskResponse {
|
|
key: Vec::new(),
|
|
table_ids: vec![view_id],
|
|
})
|
|
}
|
|
DdlTask::DropView(task) => {
|
|
self.catalog_manager
|
|
.deregister_table_sync(catalog::DeregisterTableRequest {
|
|
catalog: task.catalog.clone(),
|
|
schema: task.schema.clone(),
|
|
table_name: task.view.clone(),
|
|
})
|
|
.map_err(BoxedError::new)
|
|
.context(common_meta::error::ExternalSnafu)?;
|
|
Ok(SubmitDdlTaskResponse::default())
|
|
}
|
|
DdlTask::CreateFlow(_) => Ok(SubmitDdlTaskResponse::default()),
|
|
other => common_meta::error::UnsupportedSnafu {
|
|
operation: format!("mock submit_ddl_task: {other:?}"),
|
|
}
|
|
.fail(),
|
|
}
|
|
}
|
|
|
|
async fn migrate_region(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_request: MigrateRegionRequest,
|
|
) -> common_meta::error::Result<MigrateRegionResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "migrate_region",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn reconcile(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_request: ReconcileRequest,
|
|
) -> common_meta::error::Result<ReconcileResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "reconcile",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn query_procedure_state(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
_pid: &str,
|
|
) -> common_meta::error::Result<ProcedureStateResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "query_procedure_state",
|
|
}
|
|
.fail()
|
|
}
|
|
|
|
async fn list_procedures(
|
|
&self,
|
|
_ctx: &ExecutorContext,
|
|
) -> common_meta::error::Result<ProcedureDetailResponse> {
|
|
common_meta::error::UnsupportedSnafu {
|
|
operation: "list_procedures",
|
|
}
|
|
.fail()
|
|
}
|
|
}
|
|
|
|
fn test_cache_registry(
|
|
kv_backend: common_meta::kv_backend::KvBackendRef,
|
|
) -> TestResult<common_meta::cache::LayeredCacheRegistryRef> {
|
|
Ok(Arc::new(
|
|
cache::with_default_composite_cache_registry(
|
|
LayeredCacheRegistryBuilder::default()
|
|
.add_cache_registry(cache::build_fundamental_cache_registry(kv_backend)),
|
|
)
|
|
.context(BuildCacheRegistrySnafu)?
|
|
.build(),
|
|
))
|
|
}
|
|
|
|
fn test_table_info(table_id: u32, table_name: &str) -> TestResult<TableInfo> {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new("id", ConcreteDataType::int32_datatype(), false),
|
|
ColumnSchema::new(
|
|
"ts",
|
|
ConcreteDataType::timestamp_millisecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
]));
|
|
let table_meta = TableMetaBuilder::empty()
|
|
.schema(schema)
|
|
.primary_key_indices(vec![0])
|
|
.value_indices(vec![1])
|
|
.next_column_id(1024)
|
|
.build()
|
|
.with_context(|_| BuildTableMetaSnafu {
|
|
table_name: table_name.to_string(),
|
|
})?;
|
|
|
|
TableInfoBuilder::new(table_name, table_meta)
|
|
.table_id(table_id)
|
|
.build()
|
|
.with_context(|_| BuildTableInfoSnafu {
|
|
table_name: table_name.to_string(),
|
|
})
|
|
}
|
|
|
|
fn test_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
|
|
let table_info = test_table_info(table_id, table_name)?;
|
|
Ok(EmptyTable::from_table_info(&table_info))
|
|
}
|
|
|
|
fn test_physical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
|
|
let mut table_info = test_table_info(table_id, table_name)?;
|
|
table_info
|
|
.meta
|
|
.options
|
|
.extra_options
|
|
.insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), String::new());
|
|
Ok(EmptyTable::from_table_info(&table_info))
|
|
}
|
|
|
|
fn test_logical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
|
|
let mut table_info = test_table_info(table_id, table_name)?;
|
|
table_info.meta.engine = METRIC_ENGINE_NAME.to_string();
|
|
table_info.meta.options.extra_options.insert(
|
|
LOGICAL_TABLE_METADATA_KEY.to_string(),
|
|
"physical_metric".to_string(),
|
|
);
|
|
Ok(EmptyTable::from_table_info(&table_info))
|
|
}
|
|
|
|
/// A metric table of one series whose rows are exactly `rows`.
|
|
///
|
|
/// A PromQL range query reads a table through its time index and its value
|
|
/// columns, which a table's metadata names, so the fixture states both: the
|
|
/// `ts` column is the time index and `cpu` is the single value column. Every
|
|
/// scan sees the same rows, which is what makes a cached answer and an executed
|
|
/// one comparable.
|
|
fn test_metric_table_with_rows(rows: Vec<(i64, f64)>) -> TableRef {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new(
|
|
"ts",
|
|
ConcreteDataType::timestamp_millisecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
ColumnSchema::new("cpu", ConcreteDataType::float64_datatype(), false),
|
|
]));
|
|
let (timestamps, values): (Vec<_>, Vec<_>) = rows.into_iter().unzip();
|
|
let recordbatch = RecordBatch::new(
|
|
schema.clone(),
|
|
vec![
|
|
Arc::new(TimestampMillisecondVector::from_vec(timestamps)) as VectorRef,
|
|
Arc::new(Float64Vector::from_vec(values)) as VectorRef,
|
|
],
|
|
)
|
|
.unwrap();
|
|
let table_meta = TableMetaBuilder::empty()
|
|
.schema(schema)
|
|
// No tag columns: the fixture is one series.
|
|
.primary_key_indices(vec![])
|
|
.value_indices(vec![1])
|
|
.next_column_id(1024)
|
|
.build()
|
|
.unwrap();
|
|
let table_info = TableInfoBuilder::new("cpu", table_meta)
|
|
.table_id(1024)
|
|
.catalog_name("greptime")
|
|
.schema_name("public")
|
|
.build()
|
|
.unwrap();
|
|
Arc::new(Table::new(
|
|
Arc::new(table_info),
|
|
FilterPushDownType::Unsupported,
|
|
Arc::new(StaticRowsDataSource { recordbatch }),
|
|
))
|
|
}
|
|
|
|
/// A data source that answers every scan with the same rows.
|
|
struct StaticRowsDataSource {
|
|
recordbatch: RecordBatch,
|
|
}
|
|
|
|
impl StaticRowsDataSource {
|
|
/// The fixture has no storage error of its own, so a failure to lay its one
|
|
/// batch out is reported as the test bug it is.
|
|
fn boxed(error: impl std::fmt::Display) -> BoxedError {
|
|
BoxedError::new(PlainError::new(error.to_string(), StatusCode::Unexpected))
|
|
}
|
|
}
|
|
|
|
impl DataSource for StaticRowsDataSource {
|
|
fn get_stream(
|
|
&self,
|
|
request: ScanRequest,
|
|
) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
|
|
let projected = match request.projection.as_deref() {
|
|
Some(indices) => self
|
|
.recordbatch
|
|
.df_record_batch()
|
|
.project(indices)
|
|
.map_err(Self::boxed)?,
|
|
None => self.recordbatch.df_record_batch().clone(),
|
|
};
|
|
let schema = Arc::new(GtSchema::try_from(projected.schema()).map_err(Self::boxed)?);
|
|
let recordbatch = RecordBatch::from_df_record_batch(schema.clone(), projected);
|
|
Ok(RecordBatches::try_new(schema, vec![recordbatch])
|
|
.map_err(Self::boxed)?
|
|
.as_stream())
|
|
}
|
|
}
|
|
|
|
/// Runs one PromQL request and returns the rows it answered with, in order.
|
|
async fn promql_rows(
|
|
instance: &Instance,
|
|
query: &PromQuery,
|
|
ctx: QueryContextRef,
|
|
) -> TestResult<RecordBatches> {
|
|
let output = PrometheusHandler::do_query(instance, query, ctx)
|
|
.await
|
|
.with_context(|_| ExecutePromqlSnafu {
|
|
query: query.query.clone(),
|
|
})
|
|
.with_context(|_| ExecuteSqlSnafu {
|
|
sql: query.query.clone(),
|
|
})?;
|
|
match output.data {
|
|
OutputData::RecordBatches(rows) => Ok(rows),
|
|
OutputData::Stream(stream) => RecordBatches::try_collect(stream)
|
|
.await
|
|
.context(CollectRecordbatchSnafu)
|
|
.with_context(|_| ExecuteSqlSnafu {
|
|
sql: query.query.clone(),
|
|
}),
|
|
OutputData::AffectedRows(_) => unreachable!("a PromQL query returns rows"),
|
|
}
|
|
}
|
|
|
|
/// The rows of a result, in order, as one printed table.
|
|
///
|
|
/// The spans of a chunked request read into several batches while a request that
|
|
/// executed its whole plan reads into one, so comparing batch by batch would
|
|
/// compare layouts rather than rows; one table prints the rows either way.
|
|
fn printed(rows: &RecordBatches) -> String {
|
|
rows.pretty_print().unwrap()
|
|
}
|
|
|
|
/// How many rows a result holds.
|
|
///
|
|
/// A test that compares two answers states with it that the answer they agree on is
|
|
/// not empty, which two empty answers would satisfy vacuously.
|
|
fn row_count(rows: &RecordBatches) -> usize {
|
|
rows.iter().map(|batch| batch.num_rows()).sum()
|
|
}
|
|
|
|
/// A range cache configured with a five-minute chunk target, with no tail, so a
|
|
/// request over whole chunks is cacheable in a test that runs at wall-clock time.
|
|
///
|
|
/// The target is below the twenty-step floor of a one-minute query, so the chunk
|
|
/// these tests plan with is twenty minutes wide, not five.
|
|
fn test_promql_rollup_cache() -> Arc<crate::promql_query_cache::PromqlRollupCache> {
|
|
let config = crate::promql_query_cache::PromqlRollupCacheConfig::new(
|
|
1 << 20,
|
|
Duration::ZERO,
|
|
Duration::from_secs(300),
|
|
Duration::from_secs(3_600),
|
|
)
|
|
.unwrap();
|
|
Arc::new(crate::promql_query_cache::PromqlRollupCache::new(config))
|
|
}
|
|
|
|
/// One-minute steps from 10:00, with a gap between minutes 12 and 19: a
|
|
/// lookback of one minute leaves the points inside the gap without a sample.
|
|
fn metric_rows() -> Vec<(i64, f64)> {
|
|
const HEAD_MS: i64 = 36_000_000;
|
|
(0..60i64)
|
|
.filter(|minute| !(13..19).contains(minute))
|
|
.map(|minute| (HEAD_MS + minute * 60_000, minute as f64))
|
|
.collect()
|
|
}
|
|
|
|
/// The range query `expr` asks for: 10:00 to 10:59, one-minute steps, a
|
|
/// one-minute lookback.
|
|
fn metric_range_query(expr: &str) -> PromQuery {
|
|
PromQuery {
|
|
query: expr.to_string(),
|
|
start: "36000".to_string(),
|
|
end: "39540".to_string(),
|
|
step: "60".to_string(),
|
|
lookback: "60".to_string(),
|
|
alias: None,
|
|
}
|
|
}
|
|
|
|
/// An instance over [`test_metric_table_with_rows`], with `cache` installed
|
|
/// when one is given.
|
|
async fn metric_instance(
|
|
promql_rollup_cache: Option<Arc<crate::promql_query_cache::PromqlRollupCache>>,
|
|
) -> TestResult<Instance> {
|
|
let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table(
|
|
test_metric_table_with_rows(metric_rows()),
|
|
);
|
|
test_instance_with_catalog_manager_and_cache(
|
|
catalog_manager,
|
|
test_table(1025, "target")?,
|
|
Plugins::default(),
|
|
None,
|
|
Arc::new(NoopProcedureExecutor),
|
|
promql_rollup_cache,
|
|
)
|
|
.await
|
|
}
|
|
|
|
#[test]
|
|
fn range_query_identity_uses_source_from_the_statement_across_sliding_windows() {
|
|
let mut query = metric_range_query("sum(rate(cpu[5m]))");
|
|
let stmt = EvalStmt {
|
|
expr: promql_parser::parser::parse(&query.query).unwrap(),
|
|
start: std::time::UNIX_EPOCH + Duration::from_secs(36_000),
|
|
end: std::time::UNIX_EPOCH + Duration::from_secs(37_740),
|
|
interval: Duration::from_secs(60),
|
|
lookback_delta: Duration::from_secs(60),
|
|
};
|
|
let context = test_query_ctx(1);
|
|
let plan = LogicalPlanBuilder::empty(false).build().unwrap();
|
|
let first =
|
|
Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID)
|
|
.expect("the expression names one admitted table");
|
|
assert_eq!(first.source_table, "cpu");
|
|
assert_eq!(first.table_id, CPU_TABLE_ID);
|
|
|
|
query.start = "36300".to_string();
|
|
query.end = "38040".to_string();
|
|
let mut sliding = stmt.clone();
|
|
sliding.start += Duration::from_secs(300);
|
|
sliding.end += Duration::from_secs(300);
|
|
let second =
|
|
Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID)
|
|
.expect("the sliding expression names the same table");
|
|
assert_eq!(first, second);
|
|
assert_eq!(second.source_table, "cpu");
|
|
|
|
// The statement expression, not the original query text, is authoritative.
|
|
sliding.expr = promql_parser::parser::parse("sum(rate(memory[5m]))").unwrap();
|
|
let other =
|
|
Instance::range_query_identity(&query, &sliding, None, &plan, &context, CPU_TABLE_ID)
|
|
.expect("the statement names a table");
|
|
assert_eq!(other.source_table, "memory");
|
|
assert_ne!(first, other);
|
|
}
|
|
|
|
#[test]
|
|
fn range_query_identity_bypasses_when_the_source_is_unknown() {
|
|
let context = test_query_ctx(1);
|
|
let plan = LogicalPlanBuilder::empty(false).build().unwrap();
|
|
for text in ["cpu + memory", "avg(cpu)", "{host=\"a\"}"] {
|
|
let query = metric_range_query(text);
|
|
let stmt = EvalStmt {
|
|
expr: promql_parser::parser::parse(text).unwrap(),
|
|
start: std::time::UNIX_EPOCH,
|
|
end: std::time::UNIX_EPOCH + Duration::from_secs(300),
|
|
interval: Duration::from_secs(60),
|
|
lookback_delta: Duration::from_secs(60),
|
|
};
|
|
assert!(
|
|
Instance::range_query_identity(&query, &stmt, None, &plan, &context, CPU_TABLE_ID)
|
|
.is_none(),
|
|
"{text}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn promql_rollup_cache_is_disabled_by_default() -> TestResult<()> {
|
|
let instance = metric_instance(None).await?;
|
|
|
|
assert!(instance.promql_rollup_cache().is_none());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Runs the cached range path of `instance` the way a Prometheus range request
|
|
/// reaches it: the statement is planned exactly as the original path plans it, and
|
|
/// that plan is what the cache is consulted with.
|
|
///
|
|
/// Answers the rows the cache served, or `None` when it declined and the original
|
|
/// plan has to run. The ordering flag is the one the HTTP and gRPC Prometheus
|
|
/// handlers mark: a request that demands execution order keeps its own plan.
|
|
async fn run_cached_range(
|
|
instance: &Instance,
|
|
query: &PromQuery,
|
|
ctx: QueryContextRef,
|
|
requires_output_ordering: bool,
|
|
) -> TestResult<Option<RecordBatches>> {
|
|
let parsed = ParsedPromQuery::parse(query.clone(), &ctx)
|
|
.expect("the test query is a parsable PromQL statement");
|
|
let (query, statement) = parsed.into_parts();
|
|
let query::parser::QueryStatement::Promql(eval_stmt, alias) = &statement else {
|
|
unreachable!("a PromQL query parses into a PromQL statement");
|
|
};
|
|
let plan = instance
|
|
.statement_executor()
|
|
.plan(&statement, ctx.clone())
|
|
.await
|
|
.expect("the test statement plans");
|
|
instance
|
|
.cached_range_output(
|
|
&query,
|
|
eval_stmt,
|
|
alias.clone(),
|
|
requires_output_ordering,
|
|
&plan,
|
|
&ctx,
|
|
Arc::new(CancellationHandle::default()),
|
|
)
|
|
.await
|
|
.context(ExecutePromqlSnafu {
|
|
query: query.query.clone(),
|
|
})
|
|
.with_context(|_| ExecuteSqlSnafu {
|
|
sql: query.query.clone(),
|
|
})
|
|
}
|
|
|
|
/// [`run_cached_range`] on a request the cache must serve.
|
|
async fn cached_rows(instance: &Instance, query: &PromQuery) -> TestResult<RecordBatches> {
|
|
Ok(run_cached_range(instance, query, test_query_ctx(1), false)
|
|
.await?
|
|
.expect("the cache served the request"))
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_range_query_fills_the_cache_and_the_next_one_is_served() -> TestResult<()> {
|
|
let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
|
|
let cache = cached.promql_rollup_cache().unwrap().clone();
|
|
let plain = metric_instance(None).await?;
|
|
// A `rate` rather than a bare selector, which bypasses the cache before it is
|
|
// ever consulted.
|
|
let query = metric_range_query("rate(cpu[5m])");
|
|
|
|
let cold = cached_rows(&cached, &query).await?;
|
|
assert_eq!(
|
|
3,
|
|
cache.entry_count(),
|
|
"sixty one-minute points are three twenty-step chunks"
|
|
);
|
|
assert_eq!(0, cache.hit_count(), "the first request filled every chunk");
|
|
let warm = cached_rows(&cached, &query).await?;
|
|
let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?;
|
|
|
|
// The gap is in the answer: the points inside it have no pair of samples the
|
|
// `rate` can fold, so the range query holds fewer rows than the sixty grid
|
|
// points it evaluates, and more than none.
|
|
let rows = row_count(&cold);
|
|
assert!(
|
|
rows > 0 && rows < 60,
|
|
"the gap leaves points unanswered: {rows}"
|
|
);
|
|
assert_eq!(printed(&uncached), printed(&cold));
|
|
assert_eq!(printed(&uncached), printed(&warm));
|
|
assert_eq!(3, cache.hit_count(), "the warm request served every chunk");
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn every_bypass_reason_keeps_the_original_plan() -> TestResult<()> {
|
|
let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
|
|
let cache = cached.promql_rollup_cache().unwrap().clone();
|
|
let plain = metric_instance(None).await?;
|
|
let cacheable = metric_range_query("rate(cpu[5m])");
|
|
|
|
// One row per reason a range request keeps its own plan. `nocache` is the client's
|
|
// request and the rest are what the request carries, so each row states the flag
|
|
// and the context it needs and nothing else.
|
|
let nocache = QueryContextBuilder::default()
|
|
.set_extension(
|
|
session::hints::PROMQL_ROLLUP_CACHE_NOCACHE.to_string(),
|
|
"true".to_string(),
|
|
)
|
|
.build();
|
|
let mut instant = cacheable.clone();
|
|
instant.start = "36300".to_string();
|
|
instant.end = instant.start.clone();
|
|
let snapshot = QueryContext::with_db_name(None);
|
|
snapshot.set_snapshot(1, 42);
|
|
let sst_bounded = QueryContextBuilder::default()
|
|
.sst_min_sequences(Arc::new(std::sync::RwLock::new(HashMap::from([(1, 90)]))))
|
|
.build();
|
|
let flow = QueryContextBuilder::default()
|
|
.set_extension("flow.incremental_start".to_string(), "1".to_string())
|
|
.build();
|
|
|
|
for (reason, query, ctx, ordering) in [
|
|
("nocache", &cacheable, Arc::new(nocache), false),
|
|
("instant query", &instant, test_query_ctx(1), false),
|
|
("output ordering", &cacheable, test_query_ctx(1), true),
|
|
("snapshot", &cacheable, Arc::new(snapshot), false),
|
|
("SST bound", &cacheable, Arc::new(sst_bounded), false),
|
|
("flow bound", &cacheable, Arc::new(flow), false),
|
|
] {
|
|
assert!(
|
|
run_cached_range(&cached, query, ctx.clone(), ordering)
|
|
.await?
|
|
.is_none(),
|
|
"{reason}: the cache must decline"
|
|
);
|
|
// The request still answers what the ordinary path answers, and it fills
|
|
// nothing on the way.
|
|
let answer = promql_rows(&cached, query, ctx.clone()).await?;
|
|
let uncached = promql_rows(&plain, query, ctx).await?;
|
|
assert!(
|
|
row_count(&answer) > 0,
|
|
"{reason}: the answers compared are not empty"
|
|
);
|
|
assert_eq!(printed(&uncached), printed(&answer), "{reason}");
|
|
assert_eq!(0, cache.entry_count(), "{reason}: nothing may be filled");
|
|
assert_eq!(0, cache.hit_count(), "{reason}: nothing may be served");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_schema_override_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> {
|
|
let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
|
|
let cache = cached.promql_rollup_cache().unwrap().clone();
|
|
let plain = metric_instance(None).await?;
|
|
|
|
// `__schema__` makes the planner read another schema, and the cache key only
|
|
// names the current one. The expression is a `rate` around a named selector, so
|
|
// what bypasses is the override leaving the window allowlist rather than the
|
|
// bare-selector heuristic.
|
|
let overridden = metric_range_query(r#"rate(cpu{__schema__="public"}[5m])"#);
|
|
let answer = promql_rows(&cached, &overridden, test_query_ctx(1)).await?;
|
|
let uncached = promql_rows(&plain, &overridden, test_query_ctx(2)).await?;
|
|
assert!(row_count(&answer) > 0, "the answers compared are not empty");
|
|
assert_eq!(printed(&uncached), printed(&answer));
|
|
assert!(
|
|
run_cached_range(&cached, &overridden, test_query_ctx(3), false)
|
|
.await?
|
|
.is_none(),
|
|
"a schema override is never planned into chunks"
|
|
);
|
|
assert_eq!(0, cache.entry_count(), "schema override fills nothing");
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_bare_selector_range_query_bypasses_the_promql_rollup_cache() -> TestResult<()> {
|
|
// A bare selector is scan- and serialize-dominated, so a chunk served from memory
|
|
// costs a copy and a merge of the cached payload (and the fill pays for both) on
|
|
// top of a read that was already cheap: the cached path measured ~23% slower in a
|
|
// local benchmark on a 2048-series selector. Such a request therefore keeps its
|
|
// original plan and fills nothing. Parentheses only group, so they do not make a
|
|
// selector cacheable again.
|
|
let cached = metric_instance(Some(test_promql_rollup_cache())).await?;
|
|
let cache = cached.promql_rollup_cache().unwrap().clone();
|
|
let plain = metric_instance(None).await?;
|
|
|
|
for expr in ["cpu", "((cpu))"] {
|
|
let query = metric_range_query(expr);
|
|
let cold = promql_rows(&cached, &query, test_query_ctx(1)).await?;
|
|
let repeated = promql_rows(&cached, &query, test_query_ctx(2)).await?;
|
|
let uncached = promql_rows(&plain, &query, test_query_ctx(3)).await?;
|
|
|
|
assert_eq!(printed(&uncached), printed(&cold), "{expr}");
|
|
assert_eq!(printed(&uncached), printed(&repeated), "{expr}");
|
|
assert!(
|
|
row_count(&cold) > 0,
|
|
"{expr}: the answers compared are not empty"
|
|
);
|
|
assert!(
|
|
run_cached_range(&cached, &query, test_query_ctx(4), false)
|
|
.await?
|
|
.is_none(),
|
|
"{expr}: a bare selector keeps its own plan"
|
|
);
|
|
}
|
|
assert_eq!(0, cache.entry_count(), "a bare selector fills nothing");
|
|
assert_eq!(0, cache.hit_count(), "a bare selector is never served");
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_annotations_of_a_merged_answer_are_replayed_once() {
|
|
// The response path reads the collector the request opened, so everything the
|
|
// chunked execution recorded has to be replayed into it — once, however many
|
|
// spans recorded the same message.
|
|
let query_ctx = Arc::new(QueryContext::with("greptime", "public"));
|
|
let annotations = crate::promql_query_cache::CachedAnnotations::new(
|
|
vec![
|
|
"b-warning".to_string(),
|
|
"a-warning".to_string(),
|
|
"a-warning".to_string(),
|
|
],
|
|
vec!["an-info".to_string()],
|
|
);
|
|
|
|
// The response path holds the collector across the call, which is what keeps
|
|
// the registry entry alive for the replay to write into.
|
|
let collector = common_query::promql_annotations::promql_annotation_collector(
|
|
query_ctx.remote_query_id().unwrap(),
|
|
);
|
|
Instance::record_annotations(&query_ctx, &annotations);
|
|
Instance::record_annotations(&query_ctx, &annotations);
|
|
|
|
let (mut warnings, mut infos) = (Vec::new(), Vec::new());
|
|
collector.append_to(&mut warnings, &mut infos);
|
|
assert_eq!(
|
|
vec!["a-warning".to_string(), "b-warning".to_string()],
|
|
warnings
|
|
);
|
|
assert_eq!(vec!["an-info".to_string()], infos);
|
|
|
|
// The replay is per request: another request's collector is untouched, and a
|
|
// request with nothing to report writes nothing.
|
|
let other = Arc::new(QueryContext::with("greptime", "public"));
|
|
let other_collector = common_query::promql_annotations::promql_annotation_collector(
|
|
other.remote_query_id().unwrap(),
|
|
);
|
|
Instance::record_annotations(
|
|
&other,
|
|
&crate::promql_query_cache::CachedAnnotations::default(),
|
|
);
|
|
let (mut other_warnings, mut other_infos) = (Vec::new(), Vec::new());
|
|
other_collector.append_to(&mut other_warnings, &mut other_infos);
|
|
assert!(other_warnings.is_empty() && other_infos.is_empty());
|
|
}
|
|
|
|
fn test_metric_names_table() -> TableRef {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new("table_catalog", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("table_schema", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("table_name", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("engine", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("create_options", ConcreteDataType::string_datatype(), false),
|
|
]));
|
|
let columns: Vec<VectorRef> = vec![
|
|
Arc::new(StringVector::from(vec!["greptime", "greptime"])),
|
|
Arc::new(StringVector::from(vec!["public", "public"])),
|
|
Arc::new(StringVector::from(vec!["denied", "target"])),
|
|
Arc::new(StringVector::from(vec!["metric", "metric"])),
|
|
Arc::new(StringVector::from(vec![
|
|
"on_physical_table=physical_metric",
|
|
"on_physical_table=physical_metric",
|
|
])),
|
|
];
|
|
let record_batch = RecordBatch::new(schema, columns).unwrap();
|
|
MemTable::new_with_catalog(
|
|
"tables",
|
|
record_batch,
|
|
2048,
|
|
"greptime".to_string(),
|
|
"information_schema".to_string(),
|
|
)
|
|
}
|
|
|
|
fn test_pipeline_table() -> TableRef {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new("name", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("schema", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("content_type", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new("pipeline", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new(
|
|
"created_at",
|
|
ConcreteDataType::timestamp_nanosecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
]));
|
|
let columns: Vec<VectorRef> = vec![
|
|
Arc::new(StringVector::from(vec!["pipeline"])),
|
|
Arc::new(StringVector::from(vec!["public"])),
|
|
Arc::new(StringVector::from(vec!["application/yaml"])),
|
|
Arc::new(StringVector::from(vec![
|
|
"transform:\n- field: ts\n type: timestamp, ns\n index: time\n",
|
|
])),
|
|
Arc::new(TimestampNanosecondVector::from_values([1])),
|
|
];
|
|
let record_batch = RecordBatch::new(schema, columns).unwrap();
|
|
MemTable::new_with_catalog(
|
|
"pipelines",
|
|
record_batch,
|
|
2049,
|
|
"greptime".to_string(),
|
|
DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
|
|
)
|
|
}
|
|
|
|
struct CancellableExportSource {
|
|
schema: GtSchemaRef,
|
|
channels: std::sync::Mutex<Option<(oneshot::Sender<()>, oneshot::Receiver<()>)>>,
|
|
}
|
|
|
|
impl DataSource for CancellableExportSource {
|
|
fn get_stream(
|
|
&self,
|
|
_request: ScanRequest,
|
|
) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
|
|
let (started, release) = self.channels.lock().unwrap().take().unwrap();
|
|
let schema = self.schema.clone();
|
|
let stream = futures::stream::once(async move {
|
|
started.send(()).unwrap();
|
|
release.await.unwrap();
|
|
Ok(RecordBatch::new_empty(schema))
|
|
});
|
|
Ok(Box::pin(RecordBatchStreamWrapper::new(
|
|
self.schema.clone(),
|
|
Box::pin(stream),
|
|
)))
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_copy_database_enforces_read_and_write_targets() -> TestResult<()> {
|
|
struct DatabaseCopyAcl {
|
|
reject_read: bool,
|
|
}
|
|
impl PermissionChecker for DatabaseCopyAcl {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let applies = match req {
|
|
PermissionReq::Action(action) => action == COPY_TO && self.reject_read,
|
|
PermissionReq::SqlStatement(Statement::Copy(Copy::CopyDatabase(_))) => {
|
|
!self.reject_read
|
|
}
|
|
_ => false,
|
|
};
|
|
let PermissionTableTargets::Resolved(targets) = targets else {
|
|
return Ok(PermissionResp::Reject);
|
|
};
|
|
Ok(
|
|
if applies
|
|
&& targets.iter().any(|target| {
|
|
target.table == "denied" || target.is_physical_metric_table
|
|
})
|
|
{
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
},
|
|
)
|
|
}
|
|
}
|
|
for (table, direction, reject_read) in [
|
|
(test_table(1024, "denied")?, "TO", true),
|
|
(test_table(1024, "denied")?, "TO", false),
|
|
(test_table(1024, "denied")?, "FROM", false),
|
|
(test_physical_table(1024, "physical")?, "FROM", false),
|
|
(test_table(1024, "source")?, "TO", true),
|
|
(test_table(1024, "source")?, "TO", false),
|
|
(test_table(1024, "source")?, "FROM", false),
|
|
] {
|
|
let dir = common_test_util::temp_dir::create_temp_dir("copy_database_permissions");
|
|
let name = table.table_info().name.clone();
|
|
let catalog = catalog::memory::MemoryCatalogManager::new_with_table(table);
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".into(),
|
|
schema: "public".into(),
|
|
table_name: "allowed".into(),
|
|
table_id: 1025,
|
|
table: test_table(1025, "allowed")?,
|
|
})
|
|
.unwrap();
|
|
if direction == "FROM" {
|
|
std::fs::write(dir.path().join("allowed.parquet"), b"not parquet").unwrap();
|
|
std::fs::write(dir.path().join(format!("{name}.parquet")), b"not parquet").unwrap();
|
|
}
|
|
let kv = Arc::new(MemoryKvBackend::new());
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(DatabaseCopyAcl { reject_read }));
|
|
let instance = FrontendBuilder::new(
|
|
FrontendOptions::default(),
|
|
kv.clone(),
|
|
test_cache_registry(kv)?,
|
|
catalog,
|
|
Arc::new(client::client_manager::NodeClients::default()),
|
|
Arc::new(NoopProcedureExecutor),
|
|
Arc::new(ProcessManager::new("copy-permissions".into(), None)),
|
|
)
|
|
.with_plugin(plugins)
|
|
.with_local_file_access(
|
|
common_datasource::object_store::LocalFileAccess::sandboxed(dir.path()).unwrap(),
|
|
)
|
|
.try_build()
|
|
.await
|
|
.context(BuildFrontendSnafu)?;
|
|
let location = reqwest::Url::from_directory_path(dir.path()).unwrap();
|
|
let sql = format!(
|
|
"COPY DATABASE public {direction} '{location}' WITH (continue_on_error='true')"
|
|
);
|
|
let result = instance
|
|
.do_query_inner(&sql, QueryContext::arc())
|
|
.await
|
|
.remove(0);
|
|
if name == "source" {
|
|
assert!(result.is_ok(), "{result:?}");
|
|
} else {
|
|
assert_eq!(
|
|
StatusCode::PermissionDenied,
|
|
result.unwrap_err().status_code()
|
|
);
|
|
if direction == "TO" {
|
|
assert_eq!(0, std::fs::read_dir(dir.path()).unwrap().count());
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_metric_export_http_timeout_cancels_ordinary_source() {
|
|
let destination = common_test_util::temp_dir::create_temp_dir("metric_export_timeout");
|
|
let (started_tx, started_rx) = oneshot::channel();
|
|
let (mut release_tx, release_rx) = oneshot::channel();
|
|
let info = test_table_info(1024, "source").unwrap();
|
|
let source = Arc::new(Table::new(
|
|
Arc::new(info.clone()),
|
|
FilterPushDownType::Unsupported,
|
|
Arc::new(CancellableExportSource {
|
|
schema: info.meta.schema.clone(),
|
|
channels: std::sync::Mutex::new(Some((started_tx, release_rx))),
|
|
}),
|
|
));
|
|
let catalog = catalog::memory::MemoryCatalogManager::new_with_table(source);
|
|
let kv = Arc::new(MemoryKvBackend::new());
|
|
let instance = FrontendBuilder::new(
|
|
FrontendOptions::default(),
|
|
kv.clone(),
|
|
test_cache_registry(kv).unwrap(),
|
|
catalog,
|
|
Arc::new(client::client_manager::NodeClients::default()),
|
|
Arc::new(NoopProcedureExecutor),
|
|
Arc::new(ProcessManager::new("export-timeout".into(), None)),
|
|
)
|
|
.with_local_file_access(
|
|
common_datasource::object_store::LocalFileAccess::sandboxed(destination.path())
|
|
.unwrap(),
|
|
)
|
|
.try_build()
|
|
.await
|
|
.unwrap();
|
|
let server = servers::http::HttpServerBuilder::new(servers::http::HttpOptions {
|
|
timeout: Duration::from_secs(2),
|
|
..Default::default()
|
|
})
|
|
.with_sql_handler(Arc::new(instance))
|
|
.build();
|
|
let app = server.build(server.make_app()).unwrap();
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let addr = listener.local_addr().unwrap();
|
|
let server_task = tokio::spawn(async move {
|
|
axum::serve(listener, app).await.unwrap();
|
|
});
|
|
let uri = reqwest::Url::from_directory_path(destination.path()).unwrap();
|
|
let sql = format!(
|
|
"COPY DATABASE greptime.public TO '{uri}' WITH (experimental_metric_export='true')"
|
|
);
|
|
let request = tokio::spawn(async move {
|
|
reqwest::Client::builder()
|
|
.no_proxy()
|
|
.build()
|
|
.unwrap()
|
|
.post(format!("http://{addr}/v1/sql"))
|
|
.form(&[("sql", sql)])
|
|
.send()
|
|
.await
|
|
.unwrap()
|
|
});
|
|
tokio::time::timeout(Duration::from_secs(5), started_rx)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
let response = request.await.unwrap();
|
|
assert_eq!(response.status(), reqwest::StatusCode::REQUEST_TIMEOUT);
|
|
tokio::time::timeout(Duration::from_secs(5), release_tx.closed())
|
|
.await
|
|
.unwrap();
|
|
assert!(!destination.path().join("source.parquet").exists());
|
|
server_task.abort();
|
|
}
|
|
|
|
fn pending_table(
|
|
table_id: u32,
|
|
table_name: &str,
|
|
polled_tx: oneshot::Sender<()>,
|
|
) -> TestResult<table::TableRef> {
|
|
let table_info = test_table_info(table_id, table_name)?;
|
|
let data_source = Arc::new(PendingDataSource {
|
|
schema: table_info.meta.schema.clone(),
|
|
polled_tx: std::sync::Mutex::new(Some(polled_tx)),
|
|
});
|
|
|
|
Ok(Arc::new(Table::new(
|
|
Arc::new(table_info),
|
|
FilterPushDownType::Unsupported,
|
|
data_source,
|
|
)))
|
|
}
|
|
|
|
async fn test_instance_with_tables(
|
|
source_table: TableRef,
|
|
target_table: TableRef,
|
|
) -> TestResult<Instance> {
|
|
test_instance_with_plugins(source_table, target_table, Plugins::new()).await
|
|
}
|
|
|
|
async fn test_instance_with_insert_select_interceptor(
|
|
interceptor: SqlQueryInterceptorRef<Error>,
|
|
) -> TestResult<Instance> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<SqlQueryInterceptorRef<Error>>(interceptor);
|
|
|
|
test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await
|
|
}
|
|
|
|
async fn test_instance_with_plugins(
|
|
source_table: TableRef,
|
|
target_table: TableRef,
|
|
plugins: Plugins,
|
|
) -> TestResult<Instance> {
|
|
test_instance_with_plugins_and_metric_names(source_table, target_table, plugins, None).await
|
|
}
|
|
|
|
async fn test_instance_with_plugins_and_metric_names(
|
|
source_table: TableRef,
|
|
target_table: TableRef,
|
|
plugins: Plugins,
|
|
metric_names_table: Option<TableRef>,
|
|
) -> TestResult<Instance> {
|
|
let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table(source_table);
|
|
test_instance_with_catalog_manager(
|
|
catalog_manager,
|
|
target_table,
|
|
plugins,
|
|
metric_names_table,
|
|
Arc::new(NoopProcedureExecutor),
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// Builds a test frontend `Instance` over the given (already source-registered)
|
|
/// catalog manager, completing DDL tasks through `procedure_executor`.
|
|
async fn test_instance_with_catalog_manager(
|
|
catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
|
|
target_table: TableRef,
|
|
plugins: Plugins,
|
|
metric_names_table: Option<TableRef>,
|
|
procedure_executor: ProcedureExecutorRef,
|
|
) -> TestResult<Instance> {
|
|
test_instance_with_catalog_manager_and_cache(
|
|
catalog_manager,
|
|
target_table,
|
|
plugins,
|
|
metric_names_table,
|
|
procedure_executor,
|
|
None,
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// [`test_instance_with_catalog_manager`] with the rollup cache the PromQL range
|
|
/// path serves from, when a test installs one.
|
|
async fn test_instance_with_catalog_manager_and_cache(
|
|
catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
|
|
target_table: TableRef,
|
|
plugins: Plugins,
|
|
metric_names_table: Option<TableRef>,
|
|
procedure_executor: ProcedureExecutorRef,
|
|
promql_rollup_cache: Option<Arc<crate::promql_query_cache::PromqlRollupCache>>,
|
|
) -> TestResult<Instance> {
|
|
let kv_backend = Arc::new(MemoryKvBackend::new());
|
|
let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None));
|
|
let target_table_name = "target";
|
|
catalog_manager
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: target_table_name.to_string(),
|
|
table_id: 1025,
|
|
table: target_table,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: target_table_name.to_string(),
|
|
})?;
|
|
if let Some(table) = metric_names_table {
|
|
catalog_manager
|
|
.deregister_table_sync(catalog::DeregisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "information_schema".to_string(),
|
|
table_name: "tables".to_string(),
|
|
})
|
|
.unwrap();
|
|
catalog_manager
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "information_schema".to_string(),
|
|
table_name: "tables".to_string(),
|
|
table_id: 2048,
|
|
table,
|
|
})
|
|
.unwrap();
|
|
}
|
|
catalog_manager.register_process_list_table(process_manager.clone());
|
|
|
|
let cache_registry = test_cache_registry(kv_backend.clone())?;
|
|
|
|
let builder = FrontendBuilder::new(
|
|
FrontendOptions::default(),
|
|
kv_backend,
|
|
cache_registry,
|
|
catalog_manager,
|
|
Arc::new(client::client_manager::NodeClients::default()),
|
|
procedure_executor,
|
|
process_manager,
|
|
)
|
|
.with_plugin(plugins);
|
|
let builder = match promql_rollup_cache {
|
|
Some(cache) => builder.with_promql_rollup_cache(cache),
|
|
None => builder,
|
|
};
|
|
builder.try_build().await.context(BuildFrontendSnafu)
|
|
}
|
|
|
|
async fn execute_sql_maybe_prepared(
|
|
instance: &Instance,
|
|
sql: &str,
|
|
query_ctx: QueryContextRef,
|
|
prepared: bool,
|
|
) -> TestResult<Output> {
|
|
if !prepared {
|
|
return execute_one_sql(instance, sql, query_ctx).await;
|
|
}
|
|
let stmt = parse_one_sql(sql);
|
|
let described = instance
|
|
.do_describe_inner(stmt.clone(), query_ctx.clone())
|
|
.await
|
|
.context(ExecuteSqlSnafu { sql })?
|
|
.unwrap();
|
|
instance
|
|
.do_exec_plan_inner(described.logical_plan, Some(stmt), query_ctx)
|
|
.await
|
|
.context(ExecuteSqlSnafu { sql })
|
|
}
|
|
|
|
async fn execute_one_sql(
|
|
instance: &Instance,
|
|
sql: &str,
|
|
query_ctx: QueryContextRef,
|
|
) -> TestResult<Output> {
|
|
let mut results = instance.do_query_inner(sql, query_ctx).await;
|
|
ensure!(
|
|
results.len() == 1,
|
|
UnexpectedOutputCountSnafu {
|
|
sql: sql.to_string(),
|
|
actual: results.len(),
|
|
}
|
|
);
|
|
results.remove(0).with_context(|_| ExecuteSqlSnafu {
|
|
sql: sql.to_string(),
|
|
})
|
|
}
|
|
|
|
fn assert_permission_denied<T>(result: servers::error::Result<T>) {
|
|
let err = match result {
|
|
Ok(_) => panic!("request should be rejected"),
|
|
Err(err) => err,
|
|
};
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
}
|
|
|
|
fn assert_action_checked(
|
|
checker: &RejectEndpointPermissionChecker,
|
|
action: PermissionAction,
|
|
targets: Option<PermissionTableTargets>,
|
|
) {
|
|
assert_eq!(CheckedAction { action, targets }, checker.take_check());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn database_export_authorizes_all_tables_before_preparation() -> TestResult<()> {
|
|
struct ExportAcl(std::sync::Mutex<Vec<PermissionTableTargets>>);
|
|
impl PermissionChecker for ExportAcl {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
assert!(matches!(
|
|
req,
|
|
PermissionReq::SqlStatement(Statement::Copy(
|
|
sql::statements::copy::Copy::CopyDatabase(
|
|
sql::statements::copy::CopyDatabase::To(_)
|
|
)
|
|
))
|
|
));
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.0.lock().unwrap().push(targets.clone());
|
|
let PermissionTableTargets::Resolved(tables) = targets else {
|
|
panic!("unresolved export")
|
|
};
|
|
if req.is_readonly() {
|
|
assert!(matches!(req, PermissionReq::Action(action) if action == COPY_TO));
|
|
// The first table is readable; the later table has only write access.
|
|
Ok(if tables.iter().any(|t| t.table == "target") {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
} else {
|
|
self.check_permission(QueryContext::arc().current_user(), req)
|
|
}
|
|
}
|
|
}
|
|
let checker = Arc::new(ExportAcl(Default::default()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let instance = test_instance_with_plugins(
|
|
test_logical_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
let req = table::requests::CopyDatabaseRequest {
|
|
catalog_name: "greptime".into(),
|
|
schema_name: "public".into(),
|
|
location: "invalid-destination".into(),
|
|
with: Default::default(),
|
|
connection: Default::default(),
|
|
time_range: None,
|
|
};
|
|
let result = instance
|
|
.export_database_for_test(
|
|
req.clone(),
|
|
None,
|
|
&tokio_util::sync::CancellationToken::new(),
|
|
QueryContext::arc(),
|
|
)
|
|
.await;
|
|
assert!(matches!(result, Err(Error::Permission { .. })));
|
|
let expected = PermissionTableTargets::resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "source"),
|
|
PermissionTableTarget::new("greptime", "public", "target"),
|
|
]);
|
|
assert_eq!(*checker.0.lock().unwrap(), vec![expected.clone(), expected]);
|
|
// An empty selection must still check the operation privilege.
|
|
instance
|
|
.plugins
|
|
.map_mut::<PermissionCheckerRef, _, _>(|checker| {
|
|
*checker.unwrap() = Arc::new(WriteOnlyPermissionChecker)
|
|
});
|
|
let result = instance
|
|
.export_database_for_test(
|
|
req,
|
|
Some(&[]),
|
|
&tokio_util::sync::CancellationToken::new(),
|
|
QueryContext::arc(),
|
|
)
|
|
.await;
|
|
assert!(matches!(result, Err(Error::Permission { .. })));
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_prom_remote_read_with_custom_timestamp_and_value_columns() -> TestResult<()> {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new(
|
|
"custom_ts",
|
|
ConcreteDataType::timestamp_millisecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
ColumnSchema::new("custom_value", ConcreteDataType::float64_datatype(), false),
|
|
]));
|
|
let recordbatch = RecordBatch::new(
|
|
schema,
|
|
vec![
|
|
Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
|
|
Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
|
|
],
|
|
)
|
|
.unwrap();
|
|
let instance = test_instance_with_tables(
|
|
MemTable::table("custom_metric", recordbatch),
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?;
|
|
|
|
let response = PromStoreProtocolHandler::read(
|
|
&instance,
|
|
ReadRequest {
|
|
queries: vec![RemoteQuery {
|
|
start_timestamp_ms: 1500,
|
|
end_timestamp_ms: 2500,
|
|
matchers: vec![LabelMatcher {
|
|
r#type: PromMatcherType::Eq as i32,
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: "custom_metric".to_string(),
|
|
}],
|
|
..Default::default()
|
|
}],
|
|
..Default::default()
|
|
},
|
|
test_query_ctx(1),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
|
|
let response = ReadResponse::decode(body.as_slice()).unwrap();
|
|
|
|
assert_eq!(1, response.results.len());
|
|
assert_eq!(1, response.results[0].timeseries.len());
|
|
let timeseries = &response.results[0].timeseries[0];
|
|
assert_eq!(
|
|
vec![Label {
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: "custom_metric".to_string(),
|
|
}],
|
|
timeseries.labels
|
|
);
|
|
assert_eq!(
|
|
vec![Sample {
|
|
value: 2.0,
|
|
timestamp: 2000,
|
|
}],
|
|
timeseries.samples
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_prom_remote_read_prefers_default_value_column() -> TestResult<()> {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new(
|
|
"custom_ts",
|
|
ConcreteDataType::timestamp_millisecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
ColumnSchema::new("extra_field", ConcreteDataType::string_datatype(), false),
|
|
ColumnSchema::new(
|
|
greptime_value(),
|
|
ConcreteDataType::float64_datatype(),
|
|
false,
|
|
),
|
|
]));
|
|
let recordbatch = RecordBatch::new(
|
|
schema,
|
|
vec![
|
|
Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
|
|
Arc::new(StringVector::from(vec!["99", "99", "99"])) as VectorRef,
|
|
Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
|
|
],
|
|
)
|
|
.unwrap();
|
|
let instance = test_instance_with_tables(
|
|
MemTable::table("multi_field_metric", recordbatch),
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?;
|
|
|
|
let response = PromStoreProtocolHandler::read(
|
|
&instance,
|
|
ReadRequest {
|
|
queries: vec![RemoteQuery {
|
|
start_timestamp_ms: 1500,
|
|
end_timestamp_ms: 2500,
|
|
matchers: vec![LabelMatcher {
|
|
r#type: PromMatcherType::Eq as i32,
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: "multi_field_metric".to_string(),
|
|
}],
|
|
..Default::default()
|
|
}],
|
|
..Default::default()
|
|
},
|
|
test_query_ctx(1),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
|
|
let response = ReadResponse::decode(body.as_slice()).unwrap();
|
|
|
|
assert_eq!(1, response.results.len());
|
|
assert_eq!(1, response.results[0].timeseries.len());
|
|
let timeseries = &response.results[0].timeseries[0];
|
|
assert_eq!(
|
|
vec![
|
|
Label {
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: "multi_field_metric".to_string(),
|
|
},
|
|
Label {
|
|
name: "extra_field".to_string(),
|
|
value: "99".to_string(),
|
|
},
|
|
],
|
|
timeseries.labels
|
|
);
|
|
assert_eq!(
|
|
vec![Sample {
|
|
value: 2.0,
|
|
timestamp: 2000,
|
|
}],
|
|
timeseries.samples
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_prom_remote_read_rejects_ambiguous_value_columns() -> TestResult<()> {
|
|
let schema = Arc::new(GtSchema::new(vec![
|
|
ColumnSchema::new(
|
|
"custom_ts",
|
|
ConcreteDataType::timestamp_millisecond_datatype(),
|
|
false,
|
|
)
|
|
.with_time_index(true),
|
|
ColumnSchema::new("field_a", ConcreteDataType::float64_datatype(), false),
|
|
ColumnSchema::new("field_b", ConcreteDataType::float64_datatype(), false),
|
|
]));
|
|
let recordbatch = RecordBatch::new(
|
|
schema,
|
|
vec![
|
|
Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as VectorRef,
|
|
Arc::new(Float64Vector::from_vec(vec![1.0])) as VectorRef,
|
|
Arc::new(Float64Vector::from_vec(vec![2.0])) as VectorRef,
|
|
],
|
|
)
|
|
.unwrap();
|
|
let instance = test_instance_with_tables(
|
|
MemTable::table("ambiguous_metric", recordbatch),
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?;
|
|
|
|
let err = PromStoreProtocolHandler::read(
|
|
&instance,
|
|
ReadRequest {
|
|
queries: vec![RemoteQuery {
|
|
matchers: vec![LabelMatcher {
|
|
r#type: PromMatcherType::Eq as i32,
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: "ambiguous_metric".to_string(),
|
|
}],
|
|
..Default::default()
|
|
}],
|
|
..Default::default()
|
|
},
|
|
test_query_ctx(1),
|
|
)
|
|
.await
|
|
.err()
|
|
.expect("ambiguous value columns should fail remote read");
|
|
|
|
assert_eq!(StatusCode::InvalidArguments, err.status_code());
|
|
assert!(format!("{err:?}").contains("Ambiguous value column"));
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_restricted_endpoint_handlers_check_permissions() -> TestResult<()> {
|
|
let checker = Arc::new(RejectEndpointPermissionChecker::default());
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "denied")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
let mut ctx = test_query_ctx(1);
|
|
Arc::get_mut(&mut ctx).unwrap().set_extension(
|
|
servers::http::jaeger::JAEGER_QUERY_TABLE_NAME_KEY,
|
|
"denied".to_string(),
|
|
);
|
|
let jaeger_targets = Some(PermissionTableTargets::resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "denied"),
|
|
]));
|
|
|
|
assert_permission_denied(JaegerQueryHandler::get_services(&instance, ctx.clone()).await);
|
|
assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
|
|
assert_permission_denied(
|
|
JaegerQueryHandler::get_operations(&instance, ctx.clone(), "service", None).await,
|
|
);
|
|
assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
|
|
assert_permission_denied(
|
|
JaegerQueryHandler::get_trace(&instance, ctx.clone(), "trace", None, None, None).await,
|
|
);
|
|
assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
|
|
assert_permission_denied(
|
|
JaegerQueryHandler::find_traces(
|
|
&instance,
|
|
ctx.clone(),
|
|
servers::http::jaeger::QueryTraceParams {
|
|
service_name: Some("service".to_string()),
|
|
..Default::default()
|
|
},
|
|
)
|
|
.await,
|
|
);
|
|
assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets);
|
|
|
|
assert_permission_denied(
|
|
PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
|
|
);
|
|
assert_action_checked(&checker, PIPELINE_QUERY, None);
|
|
assert_permission_denied(
|
|
PipelineHandler::insert_pipeline(
|
|
&instance,
|
|
"pipeline",
|
|
"application/yaml",
|
|
"",
|
|
ctx.clone(),
|
|
)
|
|
.await,
|
|
);
|
|
assert_action_checked(&checker, PIPELINE_INSERT, None);
|
|
assert_permission_denied(
|
|
PipelineHandler::delete_pipeline(&instance, "pipeline", None, ctx.clone()).await,
|
|
);
|
|
assert_action_checked(&checker, PIPELINE_DELETE, None);
|
|
let app = axum::Router::new()
|
|
.route(
|
|
"/pipelines/_dryrun",
|
|
axum::routing::post(servers::http::event::pipeline_dryrun),
|
|
)
|
|
.with_state(servers::http::event::LogState {
|
|
log_handler: Arc::new(instance.clone()),
|
|
log_validator: None,
|
|
ingest_interceptor: None,
|
|
})
|
|
.layer(axum::Extension((*ctx).clone()));
|
|
let response = app
|
|
.oneshot(
|
|
axum::http::Request::post("/pipelines/_dryrun")
|
|
.header("content-type", "application/json")
|
|
.body(axum::body::Body::from("{}"))
|
|
.unwrap(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
|
|
assert_action_checked(&checker, PIPELINE_QUERY, None);
|
|
|
|
assert_permission_denied(
|
|
DashboardHandler::save(&instance, "dashboard", "{}", ctx.clone()).await,
|
|
);
|
|
assert_action_checked(&checker, DASHBOARD_SAVE, None);
|
|
assert_permission_denied(DashboardHandler::list(&instance, ctx.clone()).await);
|
|
assert_action_checked(&checker, DASHBOARD_QUERY, None);
|
|
assert_permission_denied(
|
|
DashboardHandler::delete(&instance, "dashboard", ctx.clone()).await,
|
|
);
|
|
assert_action_checked(&checker, DASHBOARD_DELETE, None);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_write_only_ingestion_loads_named_pipeline() -> TestResult<()> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(WriteOnlyPermissionChecker));
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
instance
|
|
.catalog_manager()
|
|
.as_any()
|
|
.downcast_ref::<catalog::memory::MemoryCatalogManager>()
|
|
.unwrap()
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
|
|
table_name: "pipelines".to_string(),
|
|
table_id: 2049,
|
|
table: test_pipeline_table(),
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: "pipelines".to_string(),
|
|
})?;
|
|
let ctx = test_query_ctx(1);
|
|
let handler: PipelineHandlerRef = Arc::new(instance.clone());
|
|
let hits = CACHE_HIT.with_label_values(&["pipeline_table"]);
|
|
let misses = CACHE_MISS.with_label_values(&["pipeline_table"]);
|
|
let before = (hits.get(), misses.get());
|
|
|
|
handler
|
|
.get_pipeline("pipeline", None, ctx.clone())
|
|
.await
|
|
.unwrap();
|
|
assert_eq!((hits.get(), misses.get()), (before.0 + 1, before.1 + 1));
|
|
handler
|
|
.get_pipeline("pipeline", None, ctx.clone())
|
|
.await
|
|
.unwrap();
|
|
assert_eq!((hits.get(), misses.get()), (before.0 + 3, before.1 + 1));
|
|
assert_permission_denied(
|
|
PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
|
|
);
|
|
|
|
let app = axum::Router::new()
|
|
.route(
|
|
"/pipelines/_dryrun",
|
|
axum::routing::post(servers::http::event::pipeline_dryrun),
|
|
)
|
|
.with_state(servers::http::event::LogState {
|
|
log_handler: handler,
|
|
log_validator: None,
|
|
ingest_interceptor: None,
|
|
})
|
|
.layer(axum::Extension((*ctx).clone()));
|
|
let response = app
|
|
.oneshot(
|
|
axum::http::Request::post("/pipelines/_dryrun")
|
|
.header("content-type", "application/json")
|
|
.body(axum::body::Body::from("{}"))
|
|
.unwrap(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_copy_export_read_action_has_source_targets() -> TestResult<()> {
|
|
let checker = Arc::new(RejectEndpointPermissionChecker::default());
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_physical_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
for (sql, name, physical) in [
|
|
("COPY source TO '/unused.parquet'", "source", false),
|
|
(
|
|
"COPY (SELECT * FROM source) TO '/unused.parquet'",
|
|
"source",
|
|
false,
|
|
),
|
|
("COPY target TO '/unused.parquet'", "target", true),
|
|
] {
|
|
assert_eq!(
|
|
StatusCode::PermissionDenied,
|
|
instance
|
|
.check_sql_permission(&parse_one_sql(sql), &QueryContext::arc())
|
|
.await
|
|
.unwrap_err()
|
|
.status_code(),
|
|
);
|
|
assert_action_checked(
|
|
&checker,
|
|
COPY_TO,
|
|
Some(PermissionTableTargets::resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", name)
|
|
.with_physical_metric_table(physical),
|
|
])),
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_copy_export_requires_read_and_write_permission() -> TestResult<()> {
|
|
use auth::UserProvider;
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(auth::DefaultPermissionChecker::arc());
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
let provider = auth::static_user_provider_from_option(
|
|
"static_user_provider:cmd:reader:ro=pwd,writer:wo=pwd,owner:rw=pwd",
|
|
)
|
|
.unwrap();
|
|
for (username, can_export, can_import) in [
|
|
("reader", false, false),
|
|
("writer", false, true),
|
|
("owner", true, true),
|
|
] {
|
|
let ctx = QueryContext::arc();
|
|
ctx.set_current_user(
|
|
provider
|
|
.authenticate(
|
|
auth::Identity::UserId(username, None),
|
|
auth::Password::PlainText("pwd".to_string().into()),
|
|
)
|
|
.await
|
|
.unwrap(),
|
|
);
|
|
for sql in [
|
|
"COPY source TO '/unused.parquet'",
|
|
"COPY (SELECT * FROM source) TO '/unused.parquet'",
|
|
] {
|
|
let result = instance
|
|
.check_sql_permission(&parse_one_sql(sql), &ctx)
|
|
.await;
|
|
if can_export {
|
|
result.unwrap();
|
|
} else {
|
|
assert_eq!(
|
|
StatusCode::PermissionDenied,
|
|
result.unwrap_err().status_code()
|
|
);
|
|
}
|
|
}
|
|
let result = instance
|
|
.check_sql_permission(&parse_one_sql("COPY target FROM '/unused.parquet'"), &ctx)
|
|
.await;
|
|
if can_import {
|
|
result.unwrap();
|
|
} else {
|
|
assert_eq!(
|
|
StatusCode::PermissionDenied,
|
|
result.unwrap_err().status_code()
|
|
);
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_sql_schema_selection_authorizes_before_mutation() -> TestResult<()> {
|
|
struct SchemaProvider;
|
|
#[async_trait::async_trait]
|
|
impl auth::UserProvider for SchemaProvider {
|
|
fn name(&self) -> &str {
|
|
"schema-test"
|
|
}
|
|
async fn authenticate(
|
|
&self,
|
|
_: auth::Identity<'_>,
|
|
_: auth::Password<'_>,
|
|
) -> auth::error::Result<UserInfoRef> {
|
|
unreachable!("the request already has an authenticated user")
|
|
}
|
|
async fn authorize(
|
|
&self,
|
|
_: &str,
|
|
schema: &str,
|
|
_: &UserInfoRef,
|
|
) -> auth::error::Result<()> {
|
|
if schema == "backend_error" {
|
|
return auth::error::InternalStateSnafu {
|
|
msg: "backend unavailable",
|
|
}
|
|
.fail();
|
|
}
|
|
if matches!(schema, "public" | "allowed" | "allowed_missing" | "admin") {
|
|
Ok(())
|
|
} else {
|
|
auth::error::PermissionDeniedSnafu.fail()
|
|
}
|
|
}
|
|
}
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<auth::UserProviderRef>(Arc::new(SchemaProvider));
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
for schema in ["denied", "allowed", "admin"] {
|
|
catalog
|
|
.register_schema_sync(catalog::RegisterSchemaRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: schema.to_string(),
|
|
})
|
|
.unwrap();
|
|
}
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
Arc::new(NoopProcedureExecutor),
|
|
)
|
|
.await?;
|
|
for sql in [
|
|
"Use denied",
|
|
" USE denied",
|
|
"/* switch */ USE denied",
|
|
"USE public; Use denied",
|
|
"USE missing",
|
|
] {
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
let results = instance.do_query_inner(sql, ctx.clone()).await;
|
|
assert_eq!(
|
|
StatusCode::PermissionDenied,
|
|
results.last().unwrap().as_ref().unwrap_err().status_code(),
|
|
"{sql}"
|
|
);
|
|
assert_eq!("public", ctx.current_schema());
|
|
}
|
|
for sql in ["USE allowed", "SET search_path TO allowed"] {
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
assert!(
|
|
instance
|
|
.do_query_inner(sql, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.is_ok()
|
|
);
|
|
assert_eq!("allowed", ctx.current_schema());
|
|
}
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
let error = instance
|
|
.do_query_inner("USE allowed_missing", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::InvalidArguments, error.status_code());
|
|
assert_eq!("public", ctx.current_schema());
|
|
for (sql, expected) in [
|
|
("SET search_path TO denied, public", "public"),
|
|
("SET search_path TO DEFAULT", "admin"),
|
|
("SET search_path TO allowed_missing, allowed", "allowed"),
|
|
(
|
|
"SET search_path TO denied, allowed_missing, public",
|
|
"public",
|
|
),
|
|
(r#"SET search_path TO "$user", public"#, "admin"),
|
|
(r#"SET "search_path" TO denied, allowed"#, "allowed"),
|
|
("SET SEARCH_PATH TO 'denied'", ""),
|
|
("SET search_path TO allowed_missing", ""),
|
|
("SET search_path TO ''", ""),
|
|
("SET search_path TO allowed; SET search_path TO denied", ""),
|
|
] {
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
ctx.set_current_user(Arc::new(AdminUserInfo));
|
|
let results = instance.do_query_inner(sql, ctx.clone()).await;
|
|
assert!(
|
|
results.iter().all(|result| matches!(
|
|
result,
|
|
Ok(Output {
|
|
data: OutputData::AffectedRows(0),
|
|
..
|
|
})
|
|
)),
|
|
"{sql}: {results:?}"
|
|
);
|
|
assert_eq!(expected, ctx.current_schema(), "{sql}");
|
|
}
|
|
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
// The default user's schema is absent or unauthorized, so public remains usable.
|
|
assert!(
|
|
instance
|
|
.do_query_inner(r#"SET search_path TO "$user", public"#, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.is_ok()
|
|
);
|
|
assert_eq!("public", ctx.current_schema());
|
|
assert!(
|
|
instance
|
|
.do_query_inner("SET search_path TO DEFAULT", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.is_ok()
|
|
);
|
|
assert_eq!("public", ctx.current_schema());
|
|
let error = instance
|
|
.do_query_inner("SET search_path TO backend_error, allowed", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::Unexpected, error.status_code());
|
|
assert_eq!("public", ctx.current_schema());
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_mysql_without_selected_database() -> TestResult<()> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<auth::UserProviderRef>(Arc::new(auth::tests::MockUserProvider::default()));
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
let ctx = Arc::new(QueryContext::with_channel("greptime", "", Channel::Mysql));
|
|
for sql in [
|
|
"SELECT * FROM source",
|
|
"INSERT INTO source VALUES (1, 0)",
|
|
"CREATE TABLE t (ts TIMESTAMP TIME INDEX)",
|
|
"SHOW TABLES",
|
|
"TRUNCATE TABLE source",
|
|
"SHOW CREATE TABLE source",
|
|
"COPY source TO '/tmp/out'",
|
|
"SELECT flush_table('public.source')",
|
|
] {
|
|
let result = instance.do_query_inner(sql, ctx.clone()).await.remove(0);
|
|
let error = match result {
|
|
Err(error) => Err::<(), _>(BoxedError::new(error))
|
|
.context(servers::error::ExecuteQuerySnafu)
|
|
.unwrap_err(),
|
|
Ok(output) => {
|
|
let OutputData::Stream(stream) = output.data else {
|
|
panic!("Expected a query stream: {sql}");
|
|
};
|
|
common_recordbatch::util::collect(stream)
|
|
.await
|
|
.context(servers::error::CollectRecordbatchSnafu)
|
|
.unwrap_err()
|
|
}
|
|
};
|
|
let (kind, message) = servers::mysql::writer::handle_err(error, ctx.clone());
|
|
assert_eq!(1046, kind as u16, "{sql}: {message}");
|
|
assert!(message.contains("No database selected"), "{message}");
|
|
}
|
|
let output = instance
|
|
.do_query_inner(
|
|
"SELECT 1, DATABASE() IS NULL AS no_database, SCHEMA() IS NULL AS no_schema",
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
assert_eq!(2, output.data.pretty_print().await.matches("true").count());
|
|
for sql in [
|
|
"SELECT * FROM denied.source",
|
|
"SHOW TABLES FROM denied",
|
|
"USE denied",
|
|
] {
|
|
let error = instance
|
|
.do_query_inner(sql, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert_eq!(
|
|
StatusCode::AccessDenied,
|
|
error.status_code(),
|
|
"{sql}: {error}"
|
|
);
|
|
assert!(ctx.current_schema().is_empty());
|
|
}
|
|
for sql in [
|
|
"SELECT * FROM public.source",
|
|
"SHOW TABLES FROM public",
|
|
"SET time_zone = '+00:00'",
|
|
] {
|
|
assert!(
|
|
instance
|
|
.do_query_inner(sql, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.is_ok(),
|
|
"{sql}"
|
|
);
|
|
}
|
|
let plan = instance
|
|
.do_describe_inner(parse_one_sql("SELECT * FROM public.source"), ctx.clone())
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
.logical_plan;
|
|
instance
|
|
.do_exec_plan_inner(
|
|
plan.clone(),
|
|
Some(parse_one_sql("SELECT * FROM public.source")),
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let error = instance
|
|
.do_describe_inner(parse_one_sql("SELECT * FROM denied.source"), ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::AccessDenied, error.status_code());
|
|
assert!(ctx.current_schema().is_empty());
|
|
let error = instance
|
|
.do_exec_plan_inner(plan.clone(), None, ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::DatabaseNotFound, error.status_code());
|
|
let current_user = ctx.current_user();
|
|
ctx.set_current_user(Arc::new(AdminUserInfo));
|
|
let error = instance
|
|
.do_exec_plan_inner(
|
|
plan,
|
|
Some(parse_one_sql("SELECT * FROM public.source")),
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::AccessDenied, error.status_code());
|
|
ctx.set_current_user(current_user);
|
|
instance
|
|
.do_query_inner("USE public", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
assert_eq!("public", ctx.current_schema());
|
|
instance
|
|
.do_query_inner("SELECT * FROM source", ctx)
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_empty_search_path_statements() -> TestResult<()> {
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
Plugins::new(),
|
|
)
|
|
.await?;
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
instance
|
|
.do_query_inner("SET search_path TO ''", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
let tables = instance
|
|
.do_query_inner("SHOW TABLES", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap()
|
|
.data
|
|
.pretty_print()
|
|
.await;
|
|
assert!(
|
|
!tables.contains("source") && !tables.contains("target"),
|
|
"{tables}"
|
|
);
|
|
let error = instance
|
|
.do_query_inner("INSERT INTO source VALUES (1, 0)", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(error, Error::TableOperation { source: operator::error::Error::TableNotFound { ref table_name, .. }, .. } if table_name == "greptime..source"),
|
|
"{error:?}"
|
|
);
|
|
for sql in [
|
|
"CREATE TABLE no_schema (ts TIMESTAMP TIME INDEX)",
|
|
"ALTER TABLE source ADD COLUMN no_schema_column INT",
|
|
"CREATE VIEW no_schema_view AS SELECT 1 AS n",
|
|
"CREATE FLOW no_schema_flow SINK TO sink AS SELECT * FROM public.source",
|
|
"CREATE FLOW no_schema_flow SINK TO public.sink AS SELECT * FROM source",
|
|
] {
|
|
let error = instance
|
|
.do_query_inner(sql, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert!(
|
|
matches!(error, Error::TableOperation { source: operator::error::Error::SchemaNotFound { ref schema_info, .. }, .. } if schema_info.is_empty()),
|
|
"{sql}: {error:?}"
|
|
);
|
|
}
|
|
|
|
for sql in ["SELECT * FROM source", "DELETE FROM source"] {
|
|
assert!(
|
|
instance
|
|
.do_query_inner(sql, ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.is_err(),
|
|
"{sql}"
|
|
);
|
|
}
|
|
let output = instance
|
|
.do_query_inner(
|
|
"SELECT current_schema() IS NULL AS empty, current_schemas(false) AS schemas",
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
let printed = output.data.pretty_print().await;
|
|
assert!(
|
|
printed.contains("true") && printed.contains("[]"),
|
|
"{printed}"
|
|
);
|
|
let output = instance
|
|
.do_query_inner("DROP TABLE IF EXISTS source", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
assert!(matches!(output.data, OutputData::AffectedRows(0)));
|
|
instance
|
|
.do_query_inner("USE public", ctx.clone())
|
|
.await
|
|
.remove(0)
|
|
.unwrap();
|
|
assert!(
|
|
instance
|
|
.do_query_inner("SELECT * FROM source", ctx)
|
|
.await
|
|
.remove(0)
|
|
.is_ok()
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_operator_rejects_search_path_without_frontend() -> TestResult<()> {
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
Plugins::new(),
|
|
)
|
|
.await?;
|
|
let ctx = Arc::new(QueryContext::with_channel(
|
|
"greptime",
|
|
"public",
|
|
Channel::Postgres,
|
|
));
|
|
let error = instance
|
|
.statement_executor
|
|
.execute_sql(parse_one_sql("SET search_path TO denied"), ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert!(matches!(error, operator::error::Error::NotSupported { .. }));
|
|
assert_eq!("public", ctx.current_schema());
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_write_only_grpc_sql_is_checked_after_parsing() -> TestResult<()> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(WriteOnlyPermissionChecker));
|
|
let instance = test_instance_with_plugins(
|
|
test_table(1024, "source")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
|
|
let insert = Request::Query(api::v1::QueryRequest {
|
|
query: Some(Query::Sql(
|
|
"INSERT INTO target SELECT * FROM source".to_string(),
|
|
)),
|
|
});
|
|
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
insert,
|
|
QueryContext::arc(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
|
|
let select = Request::Query(api::v1::QueryRequest {
|
|
query: Some(Query::Sql("SELECT * FROM source".to_string())),
|
|
});
|
|
assert_permission_denied(
|
|
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
select,
|
|
QueryContext::arc(),
|
|
)
|
|
.await,
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_target_independent_checker_skips_target_resolution() -> TestResult<()> {
|
|
let physical_table = "physical_metric";
|
|
let checker = Arc::new(TargetIndependentPermissionChecker::default());
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let catalog = catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(
|
|
1024,
|
|
physical_table,
|
|
)?);
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: "target".to_string(),
|
|
table_id: 1025,
|
|
table: test_table(1025, "target")?,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: "target".to_string(),
|
|
})?;
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
let ctx = test_query_ctx(1);
|
|
let physical_target = PermissionTableTarget::new("greptime", "public", physical_table);
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&ctx,
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![physical_target]),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
assert_eq!(1, checker.checks.load(atomic::Ordering::Relaxed));
|
|
assert_eq!(
|
|
vec![physical_table.to_string(), "target".to_string()],
|
|
PrometheusHandler::filter_metadata_metric_names(
|
|
&instance,
|
|
vec![physical_table.to_string(), "target".to_string()],
|
|
"public",
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap()
|
|
);
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
assert_eq!(2, checker.checks.load(atomic::Ordering::Relaxed));
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_query_permission_targets_are_deduplicated() -> TestResult<()> {
|
|
struct RecordingTargetChecker(std::sync::Mutex<Vec<PermissionTableTargets>>);
|
|
impl PermissionChecker for RecordingTargetChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.0.lock().unwrap().push(targets);
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(RecordingTargetChecker(Default::default()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: "target".to_string(),
|
|
table_id: 1025,
|
|
table: test_table(1025, "target")?,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: "target".to_string(),
|
|
})?;
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
let ctx = test_query_ctx(1);
|
|
let target = PermissionTableTarget::new("greptime", "public", "target");
|
|
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&ctx,
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![target.clone(), target.clone()]),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(1, counting_catalog.table_calls());
|
|
assert_eq!(0, counting_catalog.table_id_calls());
|
|
assert_eq!(0, counting_catalog.table_info_by_id_calls());
|
|
assert_eq!(
|
|
*checker.0.lock().unwrap(),
|
|
vec![PermissionTableTargets::Resolved(vec![target])]
|
|
);
|
|
|
|
counting_catalog.reset_counts();
|
|
instance
|
|
.check_sql_permission(&parse_one_sql("COPY target TO '/unused.parquet'"), &ctx)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(1, counting_catalog.total_table_lookups());
|
|
assert_eq!(3, checker.0.lock().unwrap().len());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_physical_target_permission_reaches_checker() -> TestResult<()> {
|
|
struct PhysicalChecker {
|
|
allow: bool,
|
|
}
|
|
impl PermissionChecker for PhysicalChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn grpc_table_targets(
|
|
&self,
|
|
request: &api::v1::greptime_request::Request,
|
|
catalog: &str,
|
|
schema: &str,
|
|
) -> PermissionTableTargets {
|
|
let api::v1::greptime_request::Request::Ddl(ddl) = request else {
|
|
panic!("expected DDL")
|
|
};
|
|
let Some(api::v1::ddl_request::Expr::CommentOn(comment)) = &ddl.expr else {
|
|
panic!("expected comment")
|
|
};
|
|
PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
|
|
catalog,
|
|
schema,
|
|
&comment.object_name,
|
|
)])
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let PermissionTableTargets::Resolved(targets) = targets else {
|
|
panic!("physical target must retain its identity")
|
|
};
|
|
assert_eq!(targets.len(), 1);
|
|
assert_eq!(targets[0].catalog, "greptime");
|
|
assert_eq!(targets[0].schema, "public");
|
|
assert_eq!(targets[0].table, "physical_metric");
|
|
assert!(targets[0].is_physical_metric_table);
|
|
Ok(if self.allow {
|
|
PermissionResp::Allow
|
|
} else {
|
|
PermissionResp::Reject
|
|
})
|
|
}
|
|
}
|
|
for allow in [true, false] {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(PhysicalChecker { allow }));
|
|
let instance = test_instance_with_plugins(
|
|
test_physical_table(1024, "physical_metric")?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
let ctx = test_query_ctx(1);
|
|
for sql in [
|
|
"SHOW CREATE TABLE physical_metric",
|
|
"SELECT * FROM physical_metric",
|
|
] {
|
|
let result = instance
|
|
.check_sql_permission(&parse_one_sql(sql), &ctx)
|
|
.await;
|
|
assert_eq!(allow, result.is_ok());
|
|
if let Err(error) = result {
|
|
assert_eq!(StatusCode::PermissionDenied, error.status_code());
|
|
}
|
|
}
|
|
if !allow {
|
|
let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CommentOn(
|
|
api::v1::CommentOnExpr {
|
|
object_name: "physical_metric".to_string(),
|
|
object_type: api::v1::CommentObjectType::Table as i32,
|
|
..Default::default()
|
|
},
|
|
)),
|
|
});
|
|
let err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance, request, ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_physical_query_targets_fail_closed() -> TestResult<()> {
|
|
let physical_table = "physical_metric";
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
|
|
let instance = test_instance_with_plugins(
|
|
test_physical_table(1024, physical_table)?,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
)
|
|
.await?;
|
|
|
|
let ctx = test_query_ctx(1);
|
|
let logical_target = PermissionTableTarget::new("greptime", "public", "target");
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&ctx,
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![logical_target.clone()]),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let physical_target = PermissionTableTarget::new("greptime", "public", physical_table)
|
|
.with_physical_metric_table(true);
|
|
let err = instance
|
|
.check_resolved_table_permission(
|
|
&ctx,
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![
|
|
logical_target,
|
|
PermissionTableTarget::new("greptime", "public", physical_table),
|
|
]),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
assert_eq!(
|
|
vec!["target".to_string()],
|
|
PrometheusHandler::filter_metadata_metric_names(
|
|
&instance,
|
|
vec!["target".to_string(), "denied".to_string()],
|
|
"public",
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap()
|
|
);
|
|
|
|
let query = PromQuery {
|
|
query: physical_table.to_string(),
|
|
..Default::default()
|
|
};
|
|
let err = PrometheusHandler::check_query_target_permission(
|
|
&instance,
|
|
PermissionTableTargets::resolved(vec![physical_target]),
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
let err = PrometheusHandler::check_query_permission(
|
|
&instance,
|
|
std::slice::from_ref(&query),
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
let err = PrometheusHandler::do_query(&instance, &query, ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
for sql in [
|
|
"SELECT * FROM physical_metric",
|
|
"TQL EVAL (0, 10, '5s') physical_metric",
|
|
"INSERT INTO target SELECT * FROM physical_metric",
|
|
] {
|
|
let mut results = instance.do_query_inner(sql, ctx.clone()).await;
|
|
assert_eq!(1, results.len(), "{sql}");
|
|
let err = results.remove(0).unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
|
|
}
|
|
let err = LogQueryHandler::query(
|
|
&instance,
|
|
LogQuery {
|
|
table: TableName::new("greptime", "public", physical_table),
|
|
..Default::default()
|
|
},
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
let err = instance
|
|
.do_describe_inner(parse_one_sql("SELECT * FROM physical_metric"), ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
let request = ReadRequest {
|
|
queries: vec![RemoteQuery {
|
|
matchers: vec![LabelMatcher {
|
|
r#type: PromMatcherType::Eq as i32,
|
|
name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
|
|
value: physical_table.to_string(),
|
|
}],
|
|
..Default::default()
|
|
}],
|
|
..Default::default()
|
|
};
|
|
let Err(err) = PromStoreProtocolHandler::read(&instance, request, ctx.clone()).await else {
|
|
panic!("physical remote-read target must be rejected");
|
|
};
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
let err = PrometheusHandler::query_label_values(
|
|
&instance,
|
|
physical_table.to_string(),
|
|
"host".to_string(),
|
|
vec![],
|
|
SystemTime::UNIX_EPOCH,
|
|
SystemTime::UNIX_EPOCH,
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_non_exact_query_discovery_keeps_denied_targets_for_batch_check() -> TestResult<()>
|
|
{
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
|
|
let instance = test_instance_with_plugins_and_metric_names(
|
|
test_logical_table(1024, "denied")?,
|
|
test_logical_table(1025, "target")?,
|
|
plugins,
|
|
Some(test_metric_names_table()),
|
|
)
|
|
.await?;
|
|
let ctx = test_query_ctx(1);
|
|
|
|
let mut metric_names = PrometheusHandler::query_metric_names(
|
|
&instance,
|
|
vec![Matcher::new(
|
|
promql_parser::label::MatchOp::NotEqual,
|
|
"__name__",
|
|
"",
|
|
)],
|
|
"public",
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
metric_names.sort_unstable();
|
|
assert_eq!(
|
|
vec!["denied".to_string(), "target".to_string()],
|
|
metric_names
|
|
);
|
|
|
|
let queries = metric_names
|
|
.into_iter()
|
|
.map(|query| PromQuery {
|
|
query,
|
|
..Default::default()
|
|
})
|
|
.collect::<Vec<_>>();
|
|
let err = PrometheusHandler::check_query_permission(&instance, &queries, &ctx)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// `info` reads `target_info` without naming it. With a label selector the query used to be
|
|
/// answered as a discovery over the tables the caller may read, which never named it either.
|
|
#[tokio::test]
|
|
async fn test_info_query_checks_the_info_table() -> TestResult<()> {
|
|
struct DenyInfoTable;
|
|
|
|
impl PermissionChecker for DenyInfoTable {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let reject = match targets {
|
|
PermissionTableTargets::Unresolved => true,
|
|
PermissionTableTargets::Resolved(targets) => {
|
|
targets.iter().any(|target| target.table == "target_info")
|
|
}
|
|
};
|
|
Ok(if reject {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
}
|
|
}
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(DenyInfoTable));
|
|
let instance = test_instance_with_plugins_and_metric_names(
|
|
test_logical_table(1024, "target_info")?,
|
|
test_logical_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
)
|
|
.await?;
|
|
let ctx = Arc::new(
|
|
QueryContextBuilder::default()
|
|
.channel(Channel::Mysql)
|
|
.conn_info(ConnInfo::new(None, Channel::Mysql))
|
|
.extensions(HashMap::from([(
|
|
query::promql::planner::NATIVE_PROMQL_EXTENSION_KEY.to_string(),
|
|
"true".to_string(),
|
|
)]))
|
|
.build(),
|
|
);
|
|
|
|
for promql in [
|
|
"info(target)",
|
|
r#"info(target, {version="v1"})"#,
|
|
// Not a shape that reads `target_info`, and not a discovery either: unresolved.
|
|
r#"info(target, {__schema__="public", version="v1"})"#,
|
|
] {
|
|
let query = PromQuery {
|
|
query: promql.to_string(),
|
|
..Default::default()
|
|
};
|
|
let err = PrometheusHandler::do_query(&instance, &query, ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{promql}");
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[test]
|
|
fn test_should_track_statement_process() {
|
|
assert!(should_track_statement_process(&parse_one_sql(
|
|
"SELECT * FROM demo"
|
|
)));
|
|
assert!(should_track_statement_process(&parse_one_sql(
|
|
"INSERT INTO demo SELECT * FROM source"
|
|
)));
|
|
assert!(!should_track_statement_process(&parse_one_sql(
|
|
"INSERT INTO demo VALUES (1)"
|
|
)));
|
|
assert!(!should_track_statement_process(&parse_one_sql(
|
|
"INSERT INTO demo VALUES (now())"
|
|
)));
|
|
}
|
|
|
|
#[test]
|
|
fn test_should_track_plan_process() {
|
|
let select_stmt = parse_one_sql("SELECT * FROM demo");
|
|
let insert_select_stmt = parse_one_sql("INSERT INTO demo SELECT * FROM source");
|
|
let insert_values_stmt = parse_one_sql("INSERT INTO demo VALUES (now())");
|
|
|
|
let empty_plan = LogicalPlanBuilder::empty(false).build().unwrap();
|
|
assert!(should_track_plan_process(Some(&select_stmt), &empty_plan));
|
|
assert!(should_track_plan_process(
|
|
Some(&insert_select_stmt),
|
|
&insert_dml_plan()
|
|
));
|
|
assert!(!should_track_plan_process(
|
|
Some(&insert_values_stmt),
|
|
&insert_dml_plan()
|
|
));
|
|
assert!(!should_track_plan_process(None, &insert_dml_plan()));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_exemplar_slow_query() -> TestResult<()> {
|
|
use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
|
|
use servers::exemplar::query::Query as ExemplarQuery;
|
|
|
|
for invalid_destination in [false, true] {
|
|
let table_name = if invalid_destination {
|
|
METRICS_EXEMPLARS_TABLE
|
|
} else {
|
|
"source"
|
|
};
|
|
let mut instance = test_instance_with_tables(
|
|
test_table(1024, table_name)?,
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?;
|
|
let recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
|
|
instance.slow_query_recorder = recorder.clone();
|
|
instance.slow_query_options.sample_ratio = 1.0;
|
|
instance.slow_query_options.record_type = SlowQueriesRecordType::SystemTable;
|
|
|
|
for (enabled, threshold, should_record) in [
|
|
(true, Duration::ZERO, true),
|
|
(false, Duration::ZERO, false),
|
|
(true, Duration::from_secs(3600), false),
|
|
] {
|
|
instance.slow_query_options.enable = enabled;
|
|
instance.slow_query_options.threshold = threshold;
|
|
let query =
|
|
ExemplarQuery::parse("source".into(), "-0.001", "0.001", "public").unwrap();
|
|
let result = instance.query_exemplars(query, QueryContext::arc()).await;
|
|
if invalid_destination {
|
|
assert!(result.is_err());
|
|
} else {
|
|
assert!(result.unwrap().is_empty());
|
|
}
|
|
|
|
let queries = std::mem::take(&mut *recorder.queries.lock().unwrap());
|
|
let expected = if should_record {
|
|
vec!["query_exemplars(source, start_ns=-1000000, end_ns=1999999)"]
|
|
} else {
|
|
vec![]
|
|
};
|
|
assert_eq!(
|
|
queries, expected,
|
|
"invalid_destination={invalid_destination}, enabled={enabled}, threshold={threshold:?}"
|
|
);
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_insert_select_slow_query() -> TestResult<()> {
|
|
let mut instance =
|
|
test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
|
|
.await?;
|
|
let recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
|
|
instance.slow_query_recorder = recorder.clone();
|
|
let sql = "INSERT INTO target SELECT * FROM source";
|
|
|
|
for prepared in [false, true] {
|
|
for (enabled, threshold, should_record) in [
|
|
(true, Duration::ZERO, true),
|
|
(false, Duration::ZERO, false),
|
|
(true, Duration::from_secs(3600), false),
|
|
] {
|
|
instance.slow_query_options.enable = enabled;
|
|
instance.slow_query_options.threshold = threshold;
|
|
let output =
|
|
execute_sql_maybe_prepared(&instance, sql, test_query_ctx(42), prepared)
|
|
.await?;
|
|
assert!(matches!(output.data, OutputData::AffectedRows(0)));
|
|
|
|
let queries = std::mem::take(&mut *recorder.queries.lock().unwrap());
|
|
let expected = if should_record { vec![sql] } else { vec![] };
|
|
assert_eq!(
|
|
queries, expected,
|
|
"prepared={prepared}, enabled={enabled}, threshold={threshold:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn test_insert_select_is_visible_in_show_processlist() -> TestResult<()> {
|
|
let insert_sql = "INSERT INTO target SELECT * FROM source";
|
|
let (started_tx, mut started_rx) = mpsc::unbounded_channel();
|
|
let (finish_tx, finish_rx) = oneshot::channel();
|
|
let interceptor = Arc::new(BlockingInsertSelectInterceptor::new(started_tx, finish_rx));
|
|
let instance = Arc::new(test_instance_with_insert_select_interceptor(interceptor).await?);
|
|
|
|
let insert_task = tokio::spawn({
|
|
let instance = instance.clone();
|
|
async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
|
|
});
|
|
|
|
tokio::time::timeout(Duration::from_secs(5), started_rx.recv())
|
|
.await
|
|
.context(InsertStartTimeoutSnafu)?
|
|
.context(InsertStartChannelClosedSnafu)?;
|
|
|
|
let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
|
|
let process_list = output.data.pretty_print().await;
|
|
assert!(
|
|
process_list.contains(insert_sql),
|
|
"process list did not contain running insert:\n{process_list}"
|
|
);
|
|
|
|
finish_tx
|
|
.send(())
|
|
.map_err(|_| ReleaseBlockedInsertSnafu.build())?;
|
|
insert_task.await.context(InsertTaskPanicSnafu)??;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_show_processlist_catalog_scope() -> TestResult<()> {
|
|
let instance =
|
|
test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
|
|
.await?;
|
|
let _current_catalog = instance.process_manager().register_query(
|
|
"greptime".to_string(),
|
|
vec!["public".to_string()],
|
|
"current_catalog_query".to_string(),
|
|
String::new(),
|
|
None,
|
|
None,
|
|
);
|
|
let _other_catalog = instance.process_manager().register_query(
|
|
"other".to_string(),
|
|
vec!["public".to_string()],
|
|
"other_catalog_query".to_string(),
|
|
String::new(),
|
|
None,
|
|
None,
|
|
);
|
|
|
|
for sql in ["SHOW PROCESSLIST", "SHOW FULL PROCESSLIST"] {
|
|
let output = execute_one_sql(&instance, sql, test_query_ctx(43)).await?;
|
|
let process_list = output.data.pretty_print().await;
|
|
assert!(
|
|
process_list.contains("current_catalog_query"),
|
|
"{process_list}"
|
|
);
|
|
assert!(
|
|
!process_list.contains("other_catalog_query"),
|
|
"{process_list}"
|
|
);
|
|
|
|
let admin_ctx = test_query_ctx(44);
|
|
admin_ctx.set_current_user(Arc::new(AdminUserInfo));
|
|
let output = execute_one_sql(&instance, sql, admin_ctx).await?;
|
|
let process_list = output.data.pretty_print().await;
|
|
assert!(
|
|
process_list.contains("current_catalog_query"),
|
|
"{process_list}"
|
|
);
|
|
assert!(
|
|
process_list.contains("other_catalog_query"),
|
|
"{process_list}"
|
|
);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn test_kill_query_cancels_insert_select() -> TestResult<()> {
|
|
assert_kill_cancels_insert_select("KILL QUERY 4242").await
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn test_kill_process_id_cancels_insert_select() -> TestResult<()> {
|
|
assert_kill_cancels_insert_select("KILL 'test-frontend/4242'").await
|
|
}
|
|
|
|
async fn assert_kill_cancels_insert_select(kill_sql: &str) -> TestResult<()> {
|
|
let insert_sql = "INSERT INTO target SELECT * FROM source";
|
|
let (source_polled_tx, source_polled_rx) = oneshot::channel();
|
|
let instance = Arc::new(
|
|
test_instance_with_tables(
|
|
pending_table(1024, "source", source_polled_tx)?,
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?,
|
|
);
|
|
|
|
let insert_task = tokio::spawn({
|
|
let instance = instance.clone();
|
|
async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
|
|
});
|
|
|
|
tokio::time::timeout(Duration::from_secs(5), source_polled_rx)
|
|
.await
|
|
.context(SourcePollTimeoutSnafu)?
|
|
.context(SourcePollChannelClosedSnafu)?;
|
|
|
|
let output = execute_one_sql(&instance, kill_sql, test_query_ctx(43)).await?;
|
|
assert!(matches!(output.data, OutputData::AffectedRows(1)));
|
|
|
|
let insert_result = tokio::time::timeout(Duration::from_secs(5), insert_task)
|
|
.await
|
|
.context(InsertTaskTimeoutSnafu)?
|
|
.context(InsertTaskPanicSnafu)?;
|
|
let err = match insert_result {
|
|
Ok(_) => return InsertSelectNotCancelledSnafu.fail(),
|
|
Err(TestError::ExecuteSql { source, .. }) => source,
|
|
Err(err) => return Err(err),
|
|
};
|
|
assert_eq!(StatusCode::Cancelled, err.status_code());
|
|
|
|
let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
|
|
let process_list = output.data.pretty_print().await;
|
|
assert!(
|
|
!process_list.contains(insert_sql),
|
|
"process list still contains killed insert:\n{process_list}"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn test_insert_select_timeout_depends_on_channel() -> TestResult<()> {
|
|
let insert_sql = "INSERT INTO target SELECT * FROM source";
|
|
for prepared in [false, true] {
|
|
for channel in [Channel::Postgres, Channel::Mysql] {
|
|
let (source_polled_tx, source_polled_rx) = oneshot::channel();
|
|
let instance = Arc::new(
|
|
test_instance_with_tables(
|
|
pending_table(1024, "source", source_polled_tx)?,
|
|
test_table(1025, "target")?,
|
|
)
|
|
.await?,
|
|
);
|
|
let query_ctx = Arc::new(
|
|
QueryContextBuilder::default()
|
|
.channel(channel)
|
|
.conn_info(ConnInfo::new(None, channel))
|
|
.process_id(4242)
|
|
.build(),
|
|
);
|
|
query_ctx.set_query_timeout(Duration::from_millis(100));
|
|
|
|
let insert_task = tokio::spawn({
|
|
let instance = instance.clone();
|
|
async move {
|
|
execute_sql_maybe_prepared(&instance, insert_sql, query_ctx, prepared).await
|
|
}
|
|
});
|
|
// MySQL enforces the session timeout on read-only statements only. Postgres may time
|
|
// out before the source is polled, so only MySQL waits for the scan to start.
|
|
if channel == Channel::Mysql {
|
|
tokio::time::timeout(Duration::from_secs(5), source_polled_rx)
|
|
.await
|
|
.context(SourcePollTimeoutSnafu)?
|
|
.context(SourcePollChannelClosedSnafu)?;
|
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
|
assert!(!insert_task.is_finished(), "prepared={prepared}");
|
|
let output =
|
|
execute_one_sql(&instance, "KILL QUERY 4242", test_query_ctx(43)).await?;
|
|
assert!(matches!(output.data, OutputData::AffectedRows(1)));
|
|
}
|
|
|
|
let insert_result = tokio::time::timeout(Duration::from_secs(5), insert_task)
|
|
.await
|
|
.context(InsertTaskTimeoutSnafu)?
|
|
.context(InsertTaskPanicSnafu)?;
|
|
let Err(TestError::ExecuteSql { source: err, .. }) = insert_result else {
|
|
return InsertSelectNotCancelledSnafu.fail();
|
|
};
|
|
assert!(
|
|
matches!(
|
|
(channel, &err),
|
|
(Channel::Postgres, Error::StatementTimeout { .. })
|
|
| (Channel::Mysql, Error::Cancelled { .. })
|
|
),
|
|
"prepared={prepared}: {err:?}"
|
|
);
|
|
|
|
let output =
|
|
execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
|
|
let process_list = output.data.pretty_print().await;
|
|
assert!(!process_list.contains(insert_sql), "{process_list}");
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn insert_dml_plan() -> LogicalPlan {
|
|
let schema = SchemaRef::new(Schema::new(vec![Field::new(
|
|
"value",
|
|
DataType::Int64,
|
|
true,
|
|
)]));
|
|
let target = Arc::new(LogicalTableSource::new(schema));
|
|
let input = LogicalPlanBuilder::empty(false).build().unwrap();
|
|
|
|
LogicalPlanBuilder::insert_into(input, "demo", target, InsertOp::Append)
|
|
.unwrap()
|
|
.build()
|
|
.unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn test_exec_validation() {
|
|
let query_ctx = QueryContext::arc();
|
|
let plugins: Plugins = Plugins::new();
|
|
plugins.insert(QueryOptions {
|
|
disallow_cross_catalog_query: true,
|
|
});
|
|
|
|
let sql = r#"
|
|
SELECT * FROM demo;
|
|
EXPLAIN SELECT * FROM demo;
|
|
CREATE DATABASE test_database;
|
|
SHOW DATABASES;
|
|
"#;
|
|
let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
|
|
assert_eq!(stmts.len(), 4);
|
|
for stmt in stmts {
|
|
let re = check_permission(plugins.clone(), &stmt, &query_ctx);
|
|
re.unwrap();
|
|
}
|
|
|
|
let sql = r#"
|
|
SHOW CREATE TABLE demo;
|
|
ALTER TABLE demo ADD COLUMN new_col INT;
|
|
"#;
|
|
let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
|
|
assert_eq!(stmts.len(), 2);
|
|
for stmt in stmts {
|
|
let re = check_permission(plugins.clone(), &stmt, &query_ctx);
|
|
re.unwrap();
|
|
}
|
|
|
|
fn replace_test(template_sql: &str, plugins: Plugins, query_ctx: &QueryContextRef) {
|
|
// test right
|
|
let right = vec![("", ""), ("", "public."), ("greptime.", "public.")];
|
|
for (catalog, schema) in right {
|
|
let sql = do_fmt(template_sql, catalog, schema);
|
|
do_test(&sql, plugins.clone(), query_ctx, true);
|
|
}
|
|
|
|
let wrong = vec![
|
|
("wrongcatalog.", "public."),
|
|
("wrongcatalog.", "wrongschema."),
|
|
];
|
|
for (catalog, schema) in wrong {
|
|
let sql = do_fmt(template_sql, catalog, schema);
|
|
do_test(&sql, plugins.clone(), query_ctx, false);
|
|
}
|
|
}
|
|
|
|
fn do_fmt(template: &str, catalog: &str, schema: &str) -> String {
|
|
let vars = HashMap::from([
|
|
("catalog".to_string(), catalog),
|
|
("schema".to_string(), schema),
|
|
]);
|
|
template.format(&vars).unwrap()
|
|
}
|
|
|
|
fn do_test(sql: &str, plugins: Plugins, query_ctx: &QueryContextRef, is_ok: bool) {
|
|
let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
|
|
let re = check_permission(plugins, stmt, query_ctx);
|
|
if is_ok {
|
|
re.unwrap();
|
|
} else {
|
|
assert!(re.is_err());
|
|
}
|
|
}
|
|
|
|
// test insert
|
|
let sql = "INSERT INTO {catalog}{schema}monitor(host) VALUES ('host1');";
|
|
replace_test(sql, plugins.clone(), &query_ctx);
|
|
|
|
// test create table
|
|
let sql = r#"CREATE TABLE {catalog}{schema}demo(
|
|
host STRING,
|
|
ts TIMESTAMP,
|
|
TIME INDEX (ts),
|
|
PRIMARY KEY(host)
|
|
) engine=mito;"#;
|
|
replace_test(sql, plugins.clone(), &query_ctx);
|
|
|
|
// test drop table
|
|
let sql = "DROP TABLE {catalog}{schema}demo;";
|
|
replace_test(sql, plugins.clone(), &query_ctx);
|
|
|
|
// test undrop table
|
|
#[cfg(feature = "enterprise")]
|
|
{
|
|
let sql = "UNDROP TABLE {catalog}{schema}demo;";
|
|
replace_test(sql, plugins.clone(), &query_ctx);
|
|
}
|
|
|
|
// test show tables
|
|
let sql = "SHOW TABLES FROM public";
|
|
let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
|
|
check_permission(plugins.clone(), &stmt[0], &query_ctx).unwrap();
|
|
|
|
let sql = "SHOW TABLES FROM private";
|
|
let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
|
|
let re = check_permission(plugins.clone(), &stmt[0], &query_ctx);
|
|
assert!(re.is_ok());
|
|
|
|
// test describe table
|
|
let sql = "DESC TABLE {catalog}{schema}demo;";
|
|
replace_test(sql, plugins.clone(), &query_ctx);
|
|
|
|
let comment_flow_cases = [
|
|
("COMMENT ON FLOW my_flow IS 'comment';", true),
|
|
("COMMENT ON FLOW greptime.my_flow IS 'comment';", true),
|
|
("COMMENT ON FLOW wrongcatalog.my_flow IS 'comment';", false),
|
|
];
|
|
for (sql, is_ok) in comment_flow_cases {
|
|
let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
|
|
let result = check_permission(plugins.clone(), stmt, &query_ctx);
|
|
assert_eq!(result.is_ok(), is_ok);
|
|
}
|
|
|
|
let show_flow_cases = [
|
|
("SHOW CREATE FLOW my_flow;", true),
|
|
("SHOW CREATE FLOW greptime.my_flow;", true),
|
|
("SHOW CREATE FLOW wrongcatalog.my_flow;", false),
|
|
];
|
|
for (sql, is_ok) in show_flow_cases {
|
|
let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
|
|
let result = check_permission(plugins.clone(), stmt, &query_ctx);
|
|
assert_eq!(result.is_ok(), is_ok);
|
|
}
|
|
}
|
|
|
|
/// A `DropView` DDL sent through the direct gRPC ingress must return an error
|
|
/// (e.g. table not found) instead of panicking on `todo!()`.
|
|
#[tokio::test]
|
|
async fn qx_152_drop_view_via_grpc_ddl_returns_error_not_panic() -> TestResult<()> {
|
|
let instance =
|
|
test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
|
|
.await?;
|
|
|
|
let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::DropView(
|
|
api::v1::DropViewExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
view_name: "non_existent_view".to_string(),
|
|
view_id: None,
|
|
drop_if_exists: false,
|
|
},
|
|
)),
|
|
});
|
|
|
|
let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await;
|
|
|
|
let err = match result {
|
|
Ok(_) => panic!("DropView DDL request must return an error instead of panicking"),
|
|
Err(err) => err,
|
|
};
|
|
assert_eq!(
|
|
err.status_code(),
|
|
StatusCode::TableNotFound,
|
|
"dropping a non-existent view without IF EXISTS must report TableNotFound, got {err}"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn logical_ddl_validates_and_authorizes_rewritten_batch_before_submission()
|
|
-> TestResult<()> {
|
|
struct Rewrite(&'static str);
|
|
impl SqlQueryInterceptor for Rewrite {
|
|
type Error = Error;
|
|
fn pre_parsing<'a>(
|
|
&self,
|
|
query: &'a str,
|
|
_: QueryContextRef,
|
|
) -> Result<std::borrow::Cow<'a, str>> {
|
|
Ok(if self.0 == "sql_bytes" {
|
|
std::borrow::Cow::Owned(format!("{query}{}", " ".repeat(1024 * 1024 + 1)))
|
|
} else {
|
|
std::borrow::Cow::Borrowed(query)
|
|
})
|
|
}
|
|
fn pre_execute(
|
|
&self,
|
|
statement: Option<&Statement>,
|
|
_: Option<&LogicalPlan>,
|
|
_: QueryContextRef,
|
|
) -> Result<()> {
|
|
ensure!(
|
|
!(self.0 == "pre_execute"
|
|
&& matches!(statement,
|
|
Some(Statement::CreateTable(create)) if create.name.to_string() == "allowed2")),
|
|
InvalidSqlSnafu {
|
|
err_msg: "second member rejected by interceptor"
|
|
}
|
|
);
|
|
Ok(())
|
|
}
|
|
fn post_parsing(
|
|
&self,
|
|
mut statements: Vec<Statement>,
|
|
_: QueryContextRef,
|
|
) -> Result<Vec<Statement>> {
|
|
match self.0 {
|
|
"target" => {
|
|
statements[1] = parse_one_sql(
|
|
"CREATE TABLE denied (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy')",
|
|
)
|
|
}
|
|
"count" => statements = (0..129).map(|i| parse_one_sql(&format!(
|
|
"CREATE TABLE allowed_{i} (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy')"
|
|
))).collect(),
|
|
"type" => statements[1] = parse_one_sql("SELECT 1"),
|
|
"secret_bytes" | "array_bytes" | "small_option" => {
|
|
if let Statement::CreateTable(create) = &mut statements[1] {
|
|
let value = "x".repeat(if self.0 == "small_option" { 10 } else { 2 * 1024 * 1024 });
|
|
if self.0 == "array_bytes" {
|
|
create.options.insert_options("non_scalar", vec![value.as_str()].into());
|
|
} else {
|
|
create.options.insert("secret_access_key".to_string(), value);
|
|
}
|
|
}
|
|
}
|
|
"partition_shape" => {
|
|
if let Statement::CreateTable(create) = &mut statements[1] {
|
|
create.partitions = Some(sql::statements::create::Partitions {
|
|
column_list: vec![],
|
|
exprs: vec![sqlparser::ast::Expr::Identifier(sqlparser::ast::Ident::new("hidden"))],
|
|
});
|
|
}
|
|
}
|
|
"vector_hidden" => {
|
|
statements[1] = parse_one_sql("CREATE TABLE allowed2 (ts TIMESTAMP TIME INDEX, v VECTOR(3)) ENGINE=metric WITH (on_physical_table='phy')");
|
|
if let Statement::CreateTable(create) = &mut statements[1] {
|
|
create.columns[1].column_def.options.push(sqlparser::ast::ColumnOptionDef {
|
|
name: None,
|
|
option: sqlparser::ast::ColumnOption::Comment("private-value".repeat(200_000)),
|
|
});
|
|
}
|
|
}
|
|
mode if mode.starts_with("fulltext_") || mode.starts_with("skipping_")
|
|
|| mode.starts_with("inverted_") || mode.starts_with("vector_") => {
|
|
if let Statement::CreateTable(create) = &mut statements[1] {
|
|
let (kind, value_type) = mode.split_once('_').unwrap();
|
|
let value = "x".repeat(if value_type == "small" { 10 } else { 2 * 1024 * 1024 });
|
|
let extensions = &mut create.columns[1].extensions;
|
|
let options = match kind {
|
|
"fulltext" => &mut extensions.fulltext_index_options,
|
|
"skipping" => &mut extensions.skipping_index_options,
|
|
"inverted" => &mut extensions.inverted_index_options,
|
|
_ => &mut extensions.vector_options,
|
|
}.get_or_insert_default();
|
|
if kind == "vector" {
|
|
options.insert("dim".to_string(), "3".to_string());
|
|
}
|
|
if value_type == "array" {
|
|
options.insert_options("non_scalar", vec![value.as_str()].into());
|
|
} else {
|
|
options.insert("secret_access_key".to_string(), value);
|
|
}
|
|
}
|
|
}
|
|
"physical_null" | "physical_array" => {
|
|
let value = if self.0 == "physical_null" { "NULL" } else { "['x']" };
|
|
statements[1] = parse_one_sql(&format!(
|
|
"CREATE TABLE allowed2 (ts TIMESTAMP TIME INDEX) ENGINE=metric WITH (on_physical_table='phy', physical_metric_table={value})"
|
|
));
|
|
}
|
|
"ast_bytes" => {
|
|
if let Statement::CreateTable(create) = &mut statements[1] {
|
|
create.name =
|
|
ObjectName(vec![sqlparser::ast::ObjectNamePart::Identifier(
|
|
sqlparser::ast::Ident::new("t".repeat(1024 * 1024)),
|
|
)]);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
Ok(statements)
|
|
}
|
|
}
|
|
for mode in [
|
|
"none",
|
|
"target",
|
|
"count",
|
|
"type",
|
|
"sql_bytes",
|
|
"ast_bytes",
|
|
"secret_bytes",
|
|
"array_bytes",
|
|
"small_option",
|
|
"physical_null",
|
|
"physical_array",
|
|
"fulltext_secret",
|
|
"fulltext_array",
|
|
"fulltext_small",
|
|
"skipping_secret",
|
|
"skipping_array",
|
|
"skipping_small",
|
|
"inverted_secret",
|
|
"inverted_array",
|
|
"inverted_small",
|
|
"vector_secret",
|
|
"vector_array",
|
|
"vector_small",
|
|
"vector_hidden",
|
|
"partition_shape",
|
|
"pre_execute",
|
|
"cross_catalog",
|
|
"valid",
|
|
] {
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
|
|
plugins.insert::<SqlQueryInterceptorRef<Error>>(Arc::new(Rewrite(mode)));
|
|
plugins.insert(QueryOptions {
|
|
disallow_cross_catalog_query: mode == "cross_catalog",
|
|
});
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
executor.clone(),
|
|
)
|
|
.await?;
|
|
let create = |name| {
|
|
format!(
|
|
"CREATE TABLE {name} (ts TIMESTAMP TIME INDEX, host STRING) ENGINE=metric WITH (on_physical_table='phy')"
|
|
)
|
|
};
|
|
let sql = format!(
|
|
"{};{}",
|
|
create("allowed"),
|
|
create(match mode {
|
|
"none" => "denied",
|
|
"cross_catalog" => "other.public.allowed2",
|
|
_ => "allowed2",
|
|
})
|
|
);
|
|
let result =
|
|
SqlQueryHandler::create_logical_tables(&instance, &sql, QueryContext::arc()).await;
|
|
let submits = matches!(mode, "valid" | "small_option")
|
|
|| (mode.ends_with("_small") && !mode.starts_with("vector_"));
|
|
if matches!(mode, "none" | "target") {
|
|
let err = result.unwrap_err();
|
|
assert_eq!(
|
|
err.status_code(),
|
|
StatusCode::PermissionDenied,
|
|
"{mode}: {err}"
|
|
);
|
|
} else {
|
|
assert_eq!(
|
|
result.unwrap_err().status_code(),
|
|
match mode {
|
|
_ if submits => StatusCode::Unsupported,
|
|
"cross_catalog" => StatusCode::AccessDenied,
|
|
_ => StatusCode::InvalidArguments,
|
|
},
|
|
"{mode}"
|
|
);
|
|
}
|
|
assert_eq!(
|
|
executor.submitted.lock().unwrap().len(),
|
|
usize::from(submits),
|
|
"{mode}"
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// `DROP VIEW IF EXISTS` on a missing view through the direct gRPC ingress must
|
|
/// succeed with 0 affected rows (no error, no DDL task submitted), instead of
|
|
/// returning `TableNotFound`.
|
|
#[tokio::test]
|
|
async fn qx_152_drop_view_if_exists_missing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
|
|
let catalog_manager =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog_manager,
|
|
test_table(1025, "target")?,
|
|
Plugins::new(),
|
|
None,
|
|
procedure_executor.clone() as ProcedureExecutorRef,
|
|
)
|
|
.await?;
|
|
|
|
let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::DropView(
|
|
api::v1::DropViewExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
view_name: "non_existent_view".to_string(),
|
|
view_id: None,
|
|
drop_if_exists: true,
|
|
},
|
|
)),
|
|
});
|
|
|
|
let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await;
|
|
|
|
let output = match result {
|
|
Ok(output) => output,
|
|
Err(err) => {
|
|
panic!("DROP VIEW IF EXISTS on a missing view must succeed, got error: {err}")
|
|
}
|
|
};
|
|
assert!(
|
|
matches!(output.data, OutputData::AffectedRows(0)),
|
|
"DROP VIEW IF EXISTS on a missing view must report 0 affected rows"
|
|
);
|
|
assert!(
|
|
procedure_executor.submitted.lock().unwrap().is_empty(),
|
|
"DROP VIEW IF EXISTS on a missing view must not submit a DDL task"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
/// A `CREATE VIEW` followed by `DROP VIEW` through the direct gRPC ingress must
|
|
/// succeed end to end: the view is registered in the catalog and then removed.
|
|
#[tokio::test]
|
|
async fn qx_152_drop_existing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
|
|
let catalog_manager =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog_manager,
|
|
test_table(1025, "target")?,
|
|
Plugins::new(),
|
|
None,
|
|
procedure_executor.clone() as ProcedureExecutorRef,
|
|
)
|
|
.await?;
|
|
|
|
// The default "greptime.public" schema must be visible to the kv-backed table
|
|
// metadata manager for `CREATE VIEW`/`CREATE TABLE` to pass validation.
|
|
instance
|
|
.table_metadata_manager()
|
|
.schema_manager()
|
|
.create(
|
|
common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
|
|
None,
|
|
true,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
|
|
let create_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateView(
|
|
api::v1::CreateViewExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
view_name: "my_view".to_string(),
|
|
logical_plan: vec![1, 2, 3],
|
|
create_if_not_exists: false,
|
|
or_replace: false,
|
|
table_names: vec![],
|
|
columns: vec![],
|
|
plan_columns: vec![],
|
|
definition: "CREATE VIEW my_view AS SELECT * FROM source".to_string(),
|
|
},
|
|
)),
|
|
});
|
|
|
|
let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
create_view_request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await
|
|
{
|
|
Ok(output) => output,
|
|
Err(err) => panic!("CREATE VIEW via gRPC DDL must succeed, got error: {err}"),
|
|
};
|
|
assert!(
|
|
matches!(output.data, OutputData::AffectedRows(0)),
|
|
"CREATE VIEW via gRPC DDL must report 0 affected rows"
|
|
);
|
|
|
|
// The view is registered in the catalog as a view.
|
|
let view = instance
|
|
.catalog_manager()
|
|
.table("greptime", "public", "my_view", None)
|
|
.await
|
|
.unwrap()
|
|
.expect("view should exist after CREATE VIEW");
|
|
assert_eq!(view.table_info().table_type, TableType::View);
|
|
|
|
let drop_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::DropView(
|
|
api::v1::DropViewExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
view_name: "my_view".to_string(),
|
|
view_id: None,
|
|
drop_if_exists: false,
|
|
},
|
|
)),
|
|
});
|
|
|
|
let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
drop_view_request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await
|
|
{
|
|
Ok(output) => output,
|
|
Err(err) => panic!("DROP VIEW via gRPC DDL must succeed, got error: {err}"),
|
|
};
|
|
assert!(
|
|
matches!(output.data, OutputData::AffectedRows(0)),
|
|
"DROP VIEW via gRPC DDL must report 0 affected rows"
|
|
);
|
|
|
|
// The view is gone after the drop.
|
|
assert!(
|
|
instance
|
|
.catalog_manager()
|
|
.table("greptime", "public", "my_view", None)
|
|
.await
|
|
.unwrap()
|
|
.is_none(),
|
|
"view should be removed after DROP VIEW"
|
|
);
|
|
|
|
let submitted = procedure_executor.submitted.lock().unwrap();
|
|
assert_eq!(
|
|
submitted.len(),
|
|
2,
|
|
"expected create and drop view tasks, got {submitted:?}"
|
|
);
|
|
assert!(matches!(&submitted[0], DdlTask::CreateView(_)));
|
|
assert!(matches!(&submitted[1], DdlTask::DropView(_)));
|
|
Ok(())
|
|
}
|
|
|
|
/// A direct gRPC `CreateTable` whose time index column is not a timestamp must
|
|
/// be rejected with `InvalidArguments` instead of panicking while building the schema.
|
|
#[tokio::test]
|
|
async fn qx_153_create_table_with_non_timestamp_time_index_via_grpc_returns_error()
|
|
-> TestResult<()> {
|
|
let instance =
|
|
test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
|
|
.await?;
|
|
|
|
let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateTable(
|
|
api::v1::CreateTableExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
table_name: "demo".to_string(),
|
|
desc: String::new(),
|
|
column_defs: vec![api::v1::ColumnDef {
|
|
name: "host".to_string(),
|
|
data_type: api::v1::ColumnDataType::String as i32,
|
|
is_nullable: true,
|
|
default_constraint: vec![],
|
|
semantic_type: 0,
|
|
comment: String::new(),
|
|
datatype_extension: None,
|
|
options: None,
|
|
}],
|
|
time_index: "host".to_string(),
|
|
primary_keys: vec![],
|
|
create_if_not_exists: false,
|
|
table_options: HashMap::new(),
|
|
table_id: None,
|
|
engine: "mito".to_string(),
|
|
},
|
|
)),
|
|
});
|
|
|
|
let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await;
|
|
|
|
let err = match result {
|
|
Ok(_) => panic!("CreateTable with a non-timestamp time index must be rejected"),
|
|
Err(err) => err,
|
|
};
|
|
assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}");
|
|
Ok(())
|
|
}
|
|
|
|
/// A valid `CREATE TABLE` (timestamp time index) through the direct gRPC ingress
|
|
/// must succeed, guarding that the `validate_create_expr` ingress check doesn't
|
|
/// accidentally reject good requests.
|
|
#[tokio::test]
|
|
async fn qx_153_create_table_with_timestamp_time_index_via_grpc_succeeds() -> TestResult<()> {
|
|
let catalog_manager =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog_manager,
|
|
test_table(1025, "target")?,
|
|
Plugins::new(),
|
|
None,
|
|
procedure_executor.clone() as ProcedureExecutorRef,
|
|
)
|
|
.await?;
|
|
|
|
// The default "greptime.public" schema must be visible to the kv-backed table
|
|
// metadata manager for `CREATE TABLE` to pass validation.
|
|
instance
|
|
.table_metadata_manager()
|
|
.schema_manager()
|
|
.create(
|
|
common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
|
|
None,
|
|
true,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
|
|
let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateTable(
|
|
api::v1::CreateTableExpr {
|
|
catalog_name: String::new(),
|
|
schema_name: String::new(),
|
|
table_name: "demo".to_string(),
|
|
desc: String::new(),
|
|
column_defs: vec![
|
|
api::v1::ColumnDef {
|
|
name: "host".to_string(),
|
|
data_type: api::v1::ColumnDataType::String as i32,
|
|
is_nullable: true,
|
|
default_constraint: vec![],
|
|
semantic_type: 0,
|
|
comment: String::new(),
|
|
datatype_extension: None,
|
|
options: None,
|
|
},
|
|
api::v1::ColumnDef {
|
|
name: "ts".to_string(),
|
|
data_type: api::v1::ColumnDataType::TimestampMillisecond as i32,
|
|
is_nullable: true,
|
|
default_constraint: vec![],
|
|
semantic_type: 0,
|
|
comment: String::new(),
|
|
datatype_extension: None,
|
|
options: None,
|
|
},
|
|
],
|
|
time_index: "ts".to_string(),
|
|
primary_keys: vec![],
|
|
create_if_not_exists: false,
|
|
table_options: HashMap::new(),
|
|
table_id: None,
|
|
engine: "mito".to_string(),
|
|
},
|
|
)),
|
|
});
|
|
|
|
let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
request,
|
|
QueryContext::arc(),
|
|
)
|
|
.await
|
|
{
|
|
Ok(output) => output,
|
|
Err(err) => panic!("CREATE TABLE via gRPC DDL must succeed, got error: {err}"),
|
|
};
|
|
assert!(
|
|
matches!(output.data, OutputData::AffectedRows(0)),
|
|
"CREATE TABLE via gRPC DDL must report 0 affected rows"
|
|
);
|
|
|
|
// The table is registered in the catalog.
|
|
let table = instance
|
|
.catalog_manager()
|
|
.table("greptime", "public", "demo", None)
|
|
.await
|
|
.unwrap()
|
|
.expect("table should exist after CREATE TABLE");
|
|
assert_eq!(table.table_info().table_type, TableType::Base);
|
|
|
|
let submitted = procedure_executor.submitted.lock().unwrap();
|
|
assert_eq!(
|
|
submitted.len(),
|
|
1,
|
|
"expected one create table task, got {submitted:?}"
|
|
);
|
|
assert!(matches!(&submitted[0], DdlTask::CreateTable(_)));
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_copy_in_checks_table_permissions() -> TestResult<()> {
|
|
use servers::query_handler::CopyInHandler;
|
|
|
|
for source in [
|
|
test_table(1024, "denied")?,
|
|
test_physical_table(1024, "physical")?,
|
|
] {
|
|
let name = source.table_info().name.clone();
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
|
|
let instance =
|
|
test_instance_with_plugins(source, test_table(1025, "target")?, plugins).await?;
|
|
let ctx = QueryContext::arc();
|
|
assert_permission_denied(
|
|
instance
|
|
.copy_in_table("greptime", "public", &name, ctx.clone())
|
|
.await,
|
|
);
|
|
assert!(
|
|
instance
|
|
.copy_in_table("greptime", "public", "target", ctx.clone())
|
|
.await
|
|
.unwrap()
|
|
.is_some()
|
|
);
|
|
assert!(
|
|
instance
|
|
.copy_in_table("greptime", "public", "missing", ctx)
|
|
.await
|
|
.unwrap()
|
|
.is_none()
|
|
);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// COPY FROM STDIN must enforce the same cross-catalog restriction as
|
|
/// SQL INSERT when `disallow_cross_catalog_query` is configured.
|
|
#[tokio::test]
|
|
async fn test_copy_in_cross_catalog_restriction() -> TestResult<()> {
|
|
use catalog::memory::MemoryCatalogManager;
|
|
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
|
use servers::query_handler::CopyInHandler;
|
|
|
|
let catalog = MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
// A table in another catalog.
|
|
catalog.register_catalog_sync("other").unwrap();
|
|
catalog
|
|
.register_schema_sync(catalog::RegisterSchemaRequest {
|
|
catalog: "other".to_string(),
|
|
schema: DEFAULT_SCHEMA_NAME.to_string(),
|
|
})
|
|
.unwrap();
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "other".to_string(),
|
|
schema: DEFAULT_SCHEMA_NAME.to_string(),
|
|
table_name: "copy_guard".to_string(),
|
|
table_id: 2048,
|
|
table: test_table(2048, "copy_guard")?,
|
|
})
|
|
.unwrap();
|
|
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert(QueryOptions {
|
|
disallow_cross_catalog_query: true,
|
|
});
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
executor,
|
|
)
|
|
.await?;
|
|
|
|
let ctx = Arc::new(QueryContext::with(
|
|
DEFAULT_CATALOG_NAME,
|
|
DEFAULT_SCHEMA_NAME,
|
|
));
|
|
|
|
// Cross-catalog COPY is rejected before any data is streamed.
|
|
let err = instance
|
|
.copy_in_table("other", DEFAULT_SCHEMA_NAME, "copy_guard", ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert!(
|
|
format!("{err:?}").contains("Illegal access to catalog"),
|
|
"{err}"
|
|
);
|
|
|
|
// Same-catalog COPY resolves normally.
|
|
let found = instance
|
|
.copy_in_table(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "target", ctx)
|
|
.await
|
|
.unwrap();
|
|
assert!(found.is_some());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Scope-targeted COPY formats (OTLP logs/traces) run the same
|
|
/// cross-catalog restriction through `copy_in_validate_scope` before
|
|
/// any data is streamed.
|
|
#[tokio::test]
|
|
async fn test_copy_in_validate_scope_cross_catalog_restriction() -> TestResult<()> {
|
|
use catalog::memory::MemoryCatalogManager;
|
|
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
|
use servers::query_handler::CopyInHandler;
|
|
|
|
let catalog = MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert(QueryOptions {
|
|
disallow_cross_catalog_query: true,
|
|
});
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
executor,
|
|
)
|
|
.await?;
|
|
|
|
let ctx = Arc::new(QueryContext::with(
|
|
DEFAULT_CATALOG_NAME,
|
|
DEFAULT_SCHEMA_NAME,
|
|
));
|
|
|
|
// A target outside the session's catalog is rejected before any
|
|
// data is streamed; a same-catalog schema is not.
|
|
let err = instance
|
|
.copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx.clone())
|
|
.await
|
|
.unwrap_err();
|
|
assert!(
|
|
format!("{err:?}").contains("Illegal access to catalog"),
|
|
"{err}"
|
|
);
|
|
instance
|
|
.copy_in_validate_scope(DEFAULT_CATALOG_NAME, "other_schema", ctx.clone())
|
|
.await
|
|
.unwrap();
|
|
|
|
// Without the restriction every scope validates.
|
|
let plugins = Plugins::new();
|
|
plugins.insert(QueryOptions {
|
|
disallow_cross_catalog_query: false,
|
|
});
|
|
let catalog = MemoryCatalogManager::new_with_table(test_table(1026, "source")?);
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog.clone(),
|
|
test_table(1027, "target")?,
|
|
plugins,
|
|
None,
|
|
Arc::new(MockProcedureExecutor::new(catalog)),
|
|
)
|
|
.await?;
|
|
instance
|
|
.copy_in_validate_scope("other", DEFAULT_SCHEMA_NAME, ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
Ok(())
|
|
}
|
|
|
|
const NATIVE_PROMQL_OPTION: &str = "query.experimental_native_promql";
|
|
|
|
/// A frontend whose `public` schema holds two metric-engine logical tables, `cpu_usage` and
|
|
/// `target`, with `checker` as its permission checker.
|
|
async fn test_metric_discovery_instance(checker: PermissionCheckerRef) -> TestResult<Instance> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker);
|
|
test_instance_with_plugins_and_metric_names(
|
|
test_logical_table(1024, "cpu_usage")?,
|
|
test_logical_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
)
|
|
.await
|
|
}
|
|
|
|
/// An expression that has to be answered by discovering the schema's metric tables: it names
|
|
/// no exact metric, only a name matcher.
|
|
fn discovery_metric_expr() -> promql_parser::parser::Expr {
|
|
promql_parser::parser::parse(r#"{__name__=~"cpu.*"}"#).unwrap()
|
|
}
|
|
|
|
/// The tables a bounded scope allows, sorted so a test can state them.
|
|
fn allowed_tables(scope: &MetricDiscoveryScope) -> Vec<String> {
|
|
let MetricDiscoveryScope::Allowed(allowed) = scope else {
|
|
panic!("expected a table-bounded discovery scope, got {scope:?}");
|
|
};
|
|
let mut tables = allowed
|
|
.iter()
|
|
.map(|target| target.table.clone())
|
|
.collect::<Vec<_>>();
|
|
tables.sort_unstable();
|
|
tables
|
|
}
|
|
|
|
/// A session `SET` turns the native route on without any request hint, so the scope has to be
|
|
/// bounded by the caller's grants in exactly that case too.
|
|
#[tokio::test]
|
|
async fn test_discovery_scope_bounds_a_session_enabled_native_route() -> TestResult<()> {
|
|
let instance =
|
|
test_metric_discovery_instance(Arc::new(RejectUnresolvedPermissionChecker)).await?;
|
|
let mut ctx = test_query_ctx(1);
|
|
ctx.configuration_parameter()
|
|
.set_query_option(NATIVE_PROMQL_OPTION, "true")
|
|
.unwrap();
|
|
assert!(
|
|
ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
|
|
"a session SET is not a request hint"
|
|
);
|
|
|
|
instance
|
|
.prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert_eq!(
|
|
vec!["cpu_usage".to_string(), "target".to_string()],
|
|
allowed_tables(ctx.metric_discovery_scope())
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// With the switch off and nothing stated, the route never reads discovery, so the scope stays
|
|
/// unrestricted and no per-table grant is asked for: a query that does not use the route pays
|
|
/// nothing here.
|
|
#[tokio::test]
|
|
async fn test_discovery_scope_is_not_computed_when_the_route_is_off() -> TestResult<()> {
|
|
let counter = Arc::new(CountingPermissionChecker::default());
|
|
let instance = test_metric_discovery_instance(counter.clone()).await?;
|
|
let mut ctx = test_query_ctx(1);
|
|
assert!(ctx.extension(NATIVE_PROMQL_OPTION).is_none());
|
|
assert_eq!(
|
|
None,
|
|
ctx.effective_query_options()
|
|
.unwrap()
|
|
.get(NATIVE_PROMQL_OPTION),
|
|
"nothing states the option here"
|
|
);
|
|
|
|
instance
|
|
.prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert!(
|
|
matches!(
|
|
ctx.metric_discovery_scope(),
|
|
MetricDiscoveryScope::Unrestricted
|
|
),
|
|
"a route that is off reads no scope: {:?}",
|
|
ctx.metric_discovery_scope()
|
|
);
|
|
assert_eq!(
|
|
0,
|
|
counter.table_target_checks(),
|
|
"an off route asked for per-table grants"
|
|
);
|
|
assert!(
|
|
ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
|
|
"resolving the switch must not state the option"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// A checker that decides without table targets needs no bound: there is nothing to narrow.
|
|
#[tokio::test]
|
|
async fn test_discovery_scope_stays_unrestricted_without_table_targets() -> TestResult<()> {
|
|
let instance =
|
|
test_metric_discovery_instance(Arc::new(TargetIndependentPermissionChecker::default()))
|
|
.await?;
|
|
let mut ctx = test_query_ctx(1);
|
|
|
|
instance
|
|
.prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert!(
|
|
matches!(
|
|
ctx.metric_discovery_scope(),
|
|
MetricDiscoveryScope::Unrestricted
|
|
),
|
|
"got {:?}",
|
|
ctx.metric_discovery_scope()
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// Resolving the switch must not state it: the option a query inherits stays inherited, so
|
|
/// nothing this function does can change what planning later resolves. With nothing stated and
|
|
/// the engine default off the route is off, which leaves discovery unrestricted - the scope is
|
|
/// the only thing this function changes, and the route reads the option, not the scope.
|
|
///
|
|
/// The routing itself is asserted where the plan is built
|
|
/// (`query::planner`'s `test_engine_option_is_the_default_a_request_or_session_overrides`
|
|
/// covers the "nothing stated, engine default" case): a catalog of plain in-memory tables
|
|
/// cannot plan a discovery expression natively, so a frontend-level plan assertion would only
|
|
/// restate the legacy planner's own rejections.
|
|
#[tokio::test]
|
|
async fn test_discovery_scope_does_not_state_the_native_option() -> TestResult<()> {
|
|
let instance =
|
|
test_metric_discovery_instance(Arc::new(RejectUnresolvedPermissionChecker)).await?;
|
|
let mut ctx = test_query_ctx(1);
|
|
assert!(ctx.extension(NATIVE_PROMQL_OPTION).is_none());
|
|
|
|
instance
|
|
.prepare_metric_discovery_scope(&discovery_metric_expr(), &mut ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert!(
|
|
matches!(
|
|
ctx.metric_discovery_scope(),
|
|
MetricDiscoveryScope::Unrestricted
|
|
),
|
|
"an off route reads no scope: {:?}",
|
|
ctx.metric_discovery_scope()
|
|
);
|
|
assert!(
|
|
ctx.extension(NATIVE_PROMQL_OPTION).is_none(),
|
|
"computing the scope must not state the option"
|
|
);
|
|
assert_eq!(
|
|
None,
|
|
ctx.effective_query_options()
|
|
.unwrap()
|
|
.get(NATIVE_PROMQL_OPTION),
|
|
"the route stays on the engine default"
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// TQL discovers metrics as the Prometheus handler does: bounded by the tables the statement's
|
|
/// own request may read, and that scope reaches planning. A table the statement names is still
|
|
/// checked by name.
|
|
#[tokio::test]
|
|
async fn test_tql_discovery_is_bounded_by_the_statement_grants() -> TestResult<()> {
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
|
|
let instance = test_instance_with_plugins_and_metric_names(
|
|
test_logical_table(1024, "denied")?,
|
|
test_logical_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
)
|
|
.await?;
|
|
let ctx = test_query_ctx(1);
|
|
ctx.configuration_parameter()
|
|
.set_query_option(NATIVE_PROMQL_OPTION, "true")
|
|
.unwrap();
|
|
|
|
for sql in [
|
|
r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#,
|
|
r#"TQL EXPLAIN (0, 10, '5s') sum({__name__=~".+"})"#,
|
|
r#"WITH t AS (TQL EVAL (0, 10, '5s') {__name__=~".+"}) SELECT * FROM t"#,
|
|
] {
|
|
let planning_ctx = instance
|
|
.check_sql_permission(&parse_one_sql(sql), &ctx)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
vec!["target".to_string()],
|
|
allowed_tables(planning_ctx.metric_discovery_scope()),
|
|
"{sql}"
|
|
);
|
|
}
|
|
|
|
let err = instance
|
|
.check_sql_permission(
|
|
&parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"} + denied"#),
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
/// A TQL statement discovers only the tables its own SQL request may read, even where a
|
|
/// PromQL grant would also allow one: the HTTP action must not widen what TQL reads.
|
|
#[tokio::test]
|
|
async fn test_tql_discovery_checks_the_statement_request() -> TestResult<()> {
|
|
struct PromqlOnlyDenied;
|
|
|
|
impl PermissionChecker for PromqlOnlyDenied {
|
|
fn check_permission(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
_req: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_user_info: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_current_schema: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let reject = match targets {
|
|
PermissionTableTargets::Unresolved => true,
|
|
PermissionTableTargets::Resolved(targets) => {
|
|
matches!(req, PermissionReq::SqlStatement(_))
|
|
&& targets.iter().any(|target| target.table == "denied")
|
|
}
|
|
};
|
|
Ok(if reject {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
}
|
|
}
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(PromqlOnlyDenied));
|
|
let instance = test_instance_with_plugins_and_metric_names(
|
|
test_logical_table(1024, "denied")?,
|
|
test_logical_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
)
|
|
.await?;
|
|
let ctx = test_query_ctx(1);
|
|
ctx.configuration_parameter()
|
|
.set_query_option(NATIVE_PROMQL_OPTION, "true")
|
|
.unwrap();
|
|
|
|
let planning_ctx = instance
|
|
.check_sql_permission(
|
|
&parse_one_sql(r#"TQL EVAL (0, 10, '5s') {__name__=~".+"}"#),
|
|
&ctx,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
vec!["target".to_string()],
|
|
allowed_tables(planning_ctx.metric_discovery_scope())
|
|
);
|
|
|
|
Ok(())
|
|
}
|
|
|
|
struct CountingCatalogManager {
|
|
inner: Arc<catalog::memory::MemoryCatalogManager>,
|
|
table_calls: atomic::AtomicUsize,
|
|
table_id_calls: atomic::AtomicUsize,
|
|
table_info_by_id_calls: atomic::AtomicUsize,
|
|
}
|
|
|
|
impl CountingCatalogManager {
|
|
fn new(inner: Arc<catalog::memory::MemoryCatalogManager>) -> Self {
|
|
Self {
|
|
inner,
|
|
table_calls: atomic::AtomicUsize::new(0),
|
|
table_id_calls: atomic::AtomicUsize::new(0),
|
|
table_info_by_id_calls: atomic::AtomicUsize::new(0),
|
|
}
|
|
}
|
|
|
|
fn reset_counts(&self) {
|
|
self.table_calls.store(0, atomic::Ordering::Relaxed);
|
|
self.table_id_calls.store(0, atomic::Ordering::Relaxed);
|
|
self.table_info_by_id_calls
|
|
.store(0, atomic::Ordering::Relaxed);
|
|
}
|
|
|
|
fn table_calls(&self) -> usize {
|
|
self.table_calls.load(atomic::Ordering::Relaxed)
|
|
}
|
|
|
|
fn table_id_calls(&self) -> usize {
|
|
self.table_id_calls.load(atomic::Ordering::Relaxed)
|
|
}
|
|
|
|
fn table_info_by_id_calls(&self) -> usize {
|
|
self.table_info_by_id_calls.load(atomic::Ordering::Relaxed)
|
|
}
|
|
|
|
fn total_table_lookups(&self) -> usize {
|
|
self.table_calls() + self.table_id_calls() + self.table_info_by_id_calls()
|
|
}
|
|
}
|
|
|
|
#[async_trait::async_trait]
|
|
impl catalog::CatalogManager for CountingCatalogManager {
|
|
fn as_any(&self) -> &dyn std::any::Any {
|
|
self
|
|
}
|
|
|
|
async fn catalog_names(&self) -> catalog::error::Result<Vec<String>> {
|
|
self.inner.catalog_names().await
|
|
}
|
|
|
|
async fn schema_names(
|
|
&self,
|
|
catalog: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<Vec<String>> {
|
|
self.inner.schema_names(catalog, query_ctx).await
|
|
}
|
|
|
|
async fn table_names(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<Vec<String>> {
|
|
self.inner.table_names(catalog, schema, query_ctx).await
|
|
}
|
|
|
|
async fn catalog_exists(&self, catalog: &str) -> catalog::error::Result<bool> {
|
|
self.inner.catalog_exists(catalog).await
|
|
}
|
|
|
|
async fn schema_exists(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<bool> {
|
|
self.inner.schema_exists(catalog, schema, query_ctx).await
|
|
}
|
|
|
|
async fn table_exists(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
table: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<bool> {
|
|
self.inner
|
|
.table_exists(catalog, schema, table, query_ctx)
|
|
.await
|
|
}
|
|
|
|
async fn table(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
table_name: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<Option<TableRef>> {
|
|
self.table_calls.fetch_add(1, atomic::Ordering::Relaxed);
|
|
self.inner
|
|
.table(catalog, schema, table_name, query_ctx)
|
|
.await
|
|
}
|
|
|
|
async fn table_id(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
table_name: &str,
|
|
query_ctx: Option<&QueryContext>,
|
|
) -> catalog::error::Result<Option<table::metadata::TableId>> {
|
|
self.table_id_calls.fetch_add(1, atomic::Ordering::Relaxed);
|
|
self.inner
|
|
.table_id(catalog, schema, table_name, query_ctx)
|
|
.await
|
|
}
|
|
|
|
async fn table_info_by_id(
|
|
&self,
|
|
table_id: table::metadata::TableId,
|
|
) -> catalog::error::Result<Option<table::metadata::TableInfoRef>> {
|
|
self.table_info_by_id_calls
|
|
.fetch_add(1, atomic::Ordering::Relaxed);
|
|
self.inner.table_info_by_id(table_id).await
|
|
}
|
|
|
|
async fn tables_by_ids(
|
|
&self,
|
|
catalog: &str,
|
|
schema: &str,
|
|
table_ids: &[table::metadata::TableId],
|
|
) -> catalog::error::Result<Vec<TableRef>> {
|
|
self.inner.tables_by_ids(catalog, schema, table_ids).await
|
|
}
|
|
|
|
fn tables<'a>(
|
|
&'a self,
|
|
catalog: &'a str,
|
|
schema: &'a str,
|
|
query_ctx: Option<&'a QueryContext>,
|
|
) -> futures::stream::BoxStream<'a, catalog::error::Result<TableRef>> {
|
|
self.inner.tables(catalog, schema, query_ctx)
|
|
}
|
|
}
|
|
|
|
async fn test_instance_with_counting_catalog(
|
|
catalog_manager: Arc<CountingCatalogManager>,
|
|
plugins: Plugins,
|
|
) -> TestResult<Instance> {
|
|
let kv_backend = Arc::new(MemoryKvBackend::new());
|
|
let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None));
|
|
catalog_manager
|
|
.inner
|
|
.register_process_list_table(process_manager.clone());
|
|
let cache_registry = test_cache_registry(kv_backend.clone())?;
|
|
|
|
FrontendBuilder::new(
|
|
FrontendOptions::default(),
|
|
kv_backend,
|
|
cache_registry,
|
|
catalog_manager,
|
|
Arc::new(client::client_manager::NodeClients::default()),
|
|
Arc::new(NoopProcedureExecutor),
|
|
process_manager,
|
|
)
|
|
.with_plugin(plugins)
|
|
.try_build()
|
|
.await
|
|
.context(BuildFrontendSnafu)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_precheck_allow_skips_catalog_lookups() -> TestResult<()> {
|
|
struct PrecheckAllowChecker;
|
|
impl PermissionChecker for PrecheckAllowChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
Ok(TableTargetPrecheck::Allow)
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
panic!("check_permission_with_table_targets should be skipped on precheck Allow")
|
|
}
|
|
}
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(PrecheckAllowChecker));
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "target",
|
|
)]),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_precheck_reject_skips_catalog_lookups() -> TestResult<()> {
|
|
struct PrecheckRejectChecker;
|
|
impl PermissionChecker for PrecheckRejectChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
Ok(match (req, targets) {
|
|
(PermissionReq::Action(COPY_TO), PermissionTableTargets::Resolved(_)) => {
|
|
TableTargetPrecheck::Allow
|
|
}
|
|
_ => TableTargetPrecheck::Reject,
|
|
})
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
panic!("check_permission_with_table_targets should be skipped on precheck Reject")
|
|
}
|
|
}
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(PrecheckRejectChecker));
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
let err = instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "target",
|
|
)]),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert!(matches!(err, Error::Permission { .. }));
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
// A plugin can construct the public variant with an incomplete target.
|
|
let err = instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(COPY_TO),
|
|
PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "",
|
|
)]),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
let err = instance
|
|
.check_sql_permission(
|
|
&parse_one_sql("COPY target TO '/unused.parquet'"),
|
|
&test_query_ctx(1),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_precheck_partial_indices_only_resolves_listed_targets() -> TestResult<()> {
|
|
struct PartialPrecheckChecker(std::sync::Mutex<Vec<PermissionTableTargets>>);
|
|
impl PermissionChecker for PartialPrecheckChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
let PermissionTableTargets::Resolved(targets) = targets else {
|
|
return Ok(TableTargetPrecheck::Reject);
|
|
};
|
|
if targets.len() == 2 {
|
|
Ok(TableTargetPrecheck::NeedsPhysicalResolution(vec![1]))
|
|
} else {
|
|
Ok(TableTargetPrecheck::Allow)
|
|
}
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.0.lock().unwrap().push(targets);
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(PartialPrecheckChecker(Default::default()));
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "wide")?);
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: "narrow".to_string(),
|
|
table_id: 1025,
|
|
table: test_physical_table(1025, "narrow")?,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: "narrow".to_string(),
|
|
})?;
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "wide"),
|
|
PermissionTableTarget::new("greptime", "public", "narrow"),
|
|
]),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(1, counting_catalog.table_calls());
|
|
assert_eq!(0, counting_catalog.table_id_calls());
|
|
assert_eq!(0, counting_catalog.table_info_by_id_calls());
|
|
assert_eq!(
|
|
*checker.0.lock().unwrap(),
|
|
vec![PermissionTableTargets::Resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "wide"),
|
|
PermissionTableTarget::new("greptime", "public", "narrow")
|
|
.with_physical_metric_table(true),
|
|
])]
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_precheck_runs_once_for_multi_chunk_resolution() -> TestResult<()> {
|
|
struct MultiChunkPrecheckChecker {
|
|
precheck_calls: std::sync::Mutex<Vec<PermissionTableTargets>>,
|
|
final_calls: std::sync::Mutex<Vec<PermissionTableTargets>>,
|
|
}
|
|
impl PermissionChecker for MultiChunkPrecheckChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
self.precheck_calls.lock().unwrap().push(targets.clone());
|
|
let PermissionTableTargets::Resolved(targets) = targets else {
|
|
return Ok(TableTargetPrecheck::Reject);
|
|
};
|
|
Ok(TableTargetPrecheck::NeedsPhysicalResolution(
|
|
(0..targets.len()).collect(),
|
|
))
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.final_calls.lock().unwrap().push(targets);
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(MultiChunkPrecheckChecker {
|
|
precheck_calls: Default::default(),
|
|
final_calls: Default::default(),
|
|
});
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(1024, "t0")?);
|
|
let mut targets = vec![PermissionTableTarget::new("greptime", "public", "t0")];
|
|
for i in 1..10u32 {
|
|
let name = format!("t{i}");
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: name.clone(),
|
|
table_id: 1024 + i,
|
|
table: test_table(1024 + i, &name)?,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu { table_name: name })?;
|
|
targets.push(PermissionTableTarget::new(
|
|
"greptime",
|
|
"public",
|
|
format!("t{i}"),
|
|
));
|
|
}
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
let mut request_targets = targets.clone();
|
|
request_targets.push(targets[0].clone());
|
|
instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(request_targets),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(10, counting_catalog.table_calls());
|
|
assert_eq!(0, counting_catalog.table_id_calls());
|
|
assert_eq!(0, counting_catalog.table_info_by_id_calls());
|
|
|
|
let precheck_calls = checker.precheck_calls.lock().unwrap();
|
|
assert_eq!(1, precheck_calls.len());
|
|
assert_eq!(
|
|
PermissionTableTargets::Resolved(targets.clone()),
|
|
precheck_calls[0]
|
|
);
|
|
|
|
let mut expected_final = targets;
|
|
expected_final[0].is_physical_metric_table = true;
|
|
let final_calls = checker.final_calls.lock().unwrap();
|
|
assert_eq!(1, final_calls.len());
|
|
assert_eq!(
|
|
PermissionTableTargets::Resolved(expected_final),
|
|
final_calls[0]
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_target_independent_checker_preserves_target_hook_without_lookups()
|
|
-> TestResult<()> {
|
|
struct EndpointHookChecker {
|
|
target_hook_calls: atomic::AtomicUsize,
|
|
}
|
|
impl PermissionChecker for EndpointHookChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn uses_table_targets(&self) -> bool {
|
|
false
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
self.target_hook_calls
|
|
.fetch_add(1, atomic::Ordering::Relaxed);
|
|
Ok(PermissionResp::Reject)
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(EndpointHookChecker {
|
|
target_hook_calls: atomic::AtomicUsize::new(0),
|
|
});
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
|
|
let err = instance
|
|
.check_resolved_table_permission(
|
|
&test_query_ctx(1),
|
|
PermissionReq::Action(PROMQL_QUERY),
|
|
PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "target",
|
|
)]),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code());
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
assert_eq!(1, checker.target_hook_calls.load(atomic::Ordering::Relaxed));
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_precheck_out_of_bounds_index_returns_internal_error() -> TestResult<()> {
|
|
struct BadIndexChecker;
|
|
impl PermissionChecker for BadIndexChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
Ok(TableTargetPrecheck::NeedsPhysicalResolution(vec![99]))
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
_: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
unreachable!("must fail before check_permission_with_table_targets")
|
|
}
|
|
}
|
|
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(Arc::new(BadIndexChecker));
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "target")?);
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance =
|
|
test_instance_with_counting_catalog(counting_catalog.clone(), plugins).await?;
|
|
counting_catalog.reset_counts();
|
|
let ctx = test_query_ctx(1);
|
|
|
|
for targets in [
|
|
PermissionTableTargets::resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "target",
|
|
)]),
|
|
PermissionTableTargets::Unresolved,
|
|
] {
|
|
let err = instance
|
|
.check_resolved_table_permission(&ctx, PermissionReq::Action(PROMQL_QUERY), targets)
|
|
.await
|
|
.unwrap_err();
|
|
assert!(matches!(err, Error::Permission { .. }));
|
|
assert_eq!(StatusCode::Unexpected, err.status_code());
|
|
assert_eq!(0, counting_catalog.total_table_lookups());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_check_sql_permission_normalizes_unquoted_and_preserves_quoted() -> TestResult<()>
|
|
{
|
|
struct RecordingPhysicalChecker {
|
|
resolved_targets: std::sync::Mutex<Vec<PermissionTableTargets>>,
|
|
}
|
|
|
|
impl PermissionChecker for RecordingPhysicalChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn precheck_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: &PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<TableTargetPrecheck> {
|
|
let PermissionTableTargets::Resolved(targets) = targets else {
|
|
return Ok(TableTargetPrecheck::Reject);
|
|
};
|
|
Ok(TableTargetPrecheck::NeedsPhysicalResolution(
|
|
(0..targets.len()).collect(),
|
|
))
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let denied = matches!(
|
|
&targets,
|
|
PermissionTableTargets::Resolved(list)
|
|
if list.iter().any(|t| t.schema == "public" && t.table == "readings")
|
|
);
|
|
self.resolved_targets.lock().unwrap().push(targets);
|
|
Ok(if denied {
|
|
PermissionResp::Reject
|
|
} else {
|
|
PermissionResp::Allow
|
|
})
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(RecordingPhysicalChecker {
|
|
resolved_targets: Default::default(),
|
|
});
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
|
|
let catalog = catalog::memory::MemoryCatalogManager::new_with_table(test_physical_table(
|
|
1024, "readings",
|
|
)?);
|
|
catalog
|
|
.register_table_sync(catalog::RegisterTableRequest {
|
|
catalog: "greptime".to_string(),
|
|
schema: "public".to_string(),
|
|
table_name: "Readings".to_string(),
|
|
table_id: 1025,
|
|
table: test_table(1025, "Readings")?,
|
|
})
|
|
.with_context(|_| RegisterTableSnafu {
|
|
table_name: "Readings".to_string(),
|
|
})?;
|
|
let counting_catalog = Arc::new(CountingCatalogManager::new(catalog));
|
|
let instance = test_instance_with_counting_catalog(counting_catalog, plugins).await?;
|
|
let ctx = test_query_ctx(1);
|
|
|
|
// Both unquoted spellings resolve to `readings`, look up the physical table `readings`,
|
|
// and receive the same PermissionDenied decision.
|
|
for sql in [
|
|
"SELECT * FROM readings",
|
|
"SELECT * FROM Readings",
|
|
"SELECT * FROM Public.Readings",
|
|
] {
|
|
let err = instance
|
|
.check_sql_permission(&parse_one_sql(sql), &ctx)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
|
|
}
|
|
|
|
// Quoted `"Readings"` preserves case, looks up non-physical `"Readings"`, and is allowed.
|
|
instance
|
|
.check_sql_permission(&parse_one_sql(r#"SELECT * FROM "Readings""#), &ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
// TQL metric names stay case-sensitive.
|
|
instance
|
|
.check_sql_permission(&parse_one_sql("TQL EVAL (0, 10, '5s') Readings"), &ctx)
|
|
.await
|
|
.unwrap();
|
|
|
|
let recorded = checker.resolved_targets.lock().unwrap();
|
|
assert_eq!(
|
|
*recorded,
|
|
vec![
|
|
PermissionTableTargets::Resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "readings")
|
|
.with_physical_metric_table(true),
|
|
]),
|
|
PermissionTableTargets::Resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "readings")
|
|
.with_physical_metric_table(true),
|
|
]),
|
|
PermissionTableTargets::Resolved(vec![
|
|
PermissionTableTarget::new("greptime", "public", "readings")
|
|
.with_physical_metric_table(true),
|
|
]),
|
|
PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "Readings"
|
|
)]),
|
|
PermissionTableTargets::Resolved(vec![PermissionTableTarget::new(
|
|
"greptime", "public", "Readings"
|
|
)]),
|
|
]
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_create_flow_sink_permission_preserves_checker_errors() -> TestResult<()> {
|
|
#[derive(Clone)]
|
|
enum SinkCreateMode {
|
|
Deny,
|
|
InternalError,
|
|
BackendError,
|
|
DenyOnResultView,
|
|
ErrorOnResultView,
|
|
}
|
|
|
|
struct FlowSinkChecker {
|
|
mode: std::sync::Mutex<SinkCreateMode>,
|
|
}
|
|
|
|
impl PermissionChecker for FlowSinkChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn grpc_table_targets(
|
|
&self,
|
|
request: &Request,
|
|
_catalog: &str,
|
|
_schema: &str,
|
|
) -> PermissionTableTargets {
|
|
match request {
|
|
Request::Ddl(ddl)
|
|
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
|
{
|
|
PermissionTableTargets::resolved(vec![])
|
|
}
|
|
_ => PermissionTableTargets::Unresolved,
|
|
}
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req else {
|
|
return Ok(PermissionResp::Allow);
|
|
};
|
|
let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr else {
|
|
return Ok(PermissionResp::Allow);
|
|
};
|
|
let _ = targets;
|
|
match self.mode.lock().unwrap().clone() {
|
|
SinkCreateMode::Deny => Ok(PermissionResp::Reject),
|
|
SinkCreateMode::InternalError => auth::error::InternalStateSnafu {
|
|
msg: "checker internal failure",
|
|
}
|
|
.fail(),
|
|
SinkCreateMode::BackendError => {
|
|
Err::<PermissionResp, _>(BoxedError::new(PlainError::new(
|
|
"auth backend unavailable".to_string(),
|
|
StatusCode::StorageUnavailable,
|
|
)))
|
|
.context(auth::error::AuthBackendSnafu)
|
|
}
|
|
SinkCreateMode::DenyOnResultView => {
|
|
if create_table.table_name.ends_with("_result") {
|
|
Ok(PermissionResp::Reject)
|
|
} else {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
SinkCreateMode::ErrorOnResultView => {
|
|
if create_table.table_name.ends_with("_result") {
|
|
auth::error::InternalStateSnafu {
|
|
msg: "result view check failed",
|
|
}
|
|
.fail()
|
|
} else {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(FlowSinkChecker {
|
|
mode: std::sync::Mutex::new(SinkCreateMode::Deny),
|
|
});
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
executor.clone(),
|
|
)
|
|
.await?;
|
|
let ctx = test_query_ctx(1);
|
|
|
|
let grpc_create_flow = |name: &str, incremental: bool| {
|
|
let mut flow_options = std::collections::HashMap::new();
|
|
if incremental {
|
|
flow_options.insert("incremental".to_string(), "true".to_string());
|
|
}
|
|
Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
|
api::v1::CreateFlowExpr {
|
|
flow_name: name.to_string(),
|
|
source_table_names: vec![api::v1::TableName {
|
|
catalog_name: "greptime".to_string(),
|
|
schema_name: "public".to_string(),
|
|
table_name: "source".to_string(),
|
|
}],
|
|
sink_table_name: Some(api::v1::TableName {
|
|
catalog_name: "greptime".to_string(),
|
|
schema_name: "public".to_string(),
|
|
table_name: "target".to_string(),
|
|
}),
|
|
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
|
sql: "SELECT id, ts FROM source".to_string(),
|
|
flow_options,
|
|
..Default::default()
|
|
},
|
|
)),
|
|
})
|
|
};
|
|
|
|
// Denied `table.create` via SQL still submits the flow with `allow_sink_create = false`.
|
|
execute_one_sql(
|
|
&instance,
|
|
"CREATE FLOW sql_denied_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
|
|
ctx.clone(),
|
|
)
|
|
.await?;
|
|
// Denied `table.create` via gRPC still submits the flow with `allow_sink_create = false`.
|
|
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
grpc_create_flow("grpc_denied_sink", false),
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
|
|
// Incremental result view denial returns `Ok(false)` instead of `Ok(true)`.
|
|
*checker.mode.lock().unwrap() = SinkCreateMode::DenyOnResultView;
|
|
assert!(
|
|
!instance
|
|
.can_create_flow_sinks(
|
|
&ctx,
|
|
"greptime".to_string(),
|
|
"public".to_string(),
|
|
"target".to_string(),
|
|
Some("true"),
|
|
None,
|
|
)
|
|
.await
|
|
.unwrap()
|
|
);
|
|
|
|
{
|
|
let mut submitted = executor.submitted.lock().unwrap();
|
|
assert_eq!(2, submitted.len());
|
|
for task in submitted.drain(..) {
|
|
let DdlTask::CreateFlow(flow_task) = task else {
|
|
panic!("expected CreateFlow task");
|
|
};
|
|
assert!(!flow_task.allow_sink_create);
|
|
}
|
|
}
|
|
|
|
// Non-PermissionDenied checker errors must propagate unchanged and submit no DDL task.
|
|
for (mode, expected_status) in [
|
|
(SinkCreateMode::InternalError, StatusCode::Unexpected),
|
|
(SinkCreateMode::BackendError, StatusCode::StorageUnavailable),
|
|
] {
|
|
*checker.mode.lock().unwrap() = mode;
|
|
let sql_err = instance
|
|
.do_query_inner(
|
|
"CREATE FLOW sql_err_sink SINK TO target EVAL INTERVAL '10s' AS SELECT id, ts FROM source",
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.remove(0)
|
|
.unwrap_err();
|
|
assert_eq!(expected_status, sql_err.status_code());
|
|
|
|
let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
grpc_create_flow("grpc_err_sink", false),
|
|
ctx.clone(),
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(expected_status, grpc_err.status_code());
|
|
assert!(executor.submitted.lock().unwrap().is_empty());
|
|
}
|
|
|
|
// Incremental flow where the second sink probe (`_result` view) fails with a checker error
|
|
// also propagates the original error and submits no DDL task.
|
|
*checker.mode.lock().unwrap() = SinkCreateMode::ErrorOnResultView;
|
|
let probe_err = instance
|
|
.can_create_flow_sinks(
|
|
&ctx,
|
|
"greptime".to_string(),
|
|
"public".to_string(),
|
|
"target".to_string(),
|
|
Some("true"),
|
|
None,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::Unexpected, probe_err.status_code());
|
|
|
|
let grpc_err = servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
grpc_create_flow("grpc_err_result", true),
|
|
ctx,
|
|
)
|
|
.await
|
|
.unwrap_err();
|
|
assert_eq!(StatusCode::Unexpected, grpc_err.status_code());
|
|
assert!(executor.submitted.lock().unwrap().is_empty());
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_grpc_create_flow_qualifies_sink_once() -> TestResult<()> {
|
|
struct RecordingSinkChecker {
|
|
checked_sinks: std::sync::Mutex<Vec<(String, String, String)>>,
|
|
}
|
|
|
|
impl PermissionChecker for RecordingSinkChecker {
|
|
fn check_permission(
|
|
&self,
|
|
_: UserInfoRef,
|
|
_: PermissionReq,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
|
|
fn grpc_table_targets(
|
|
&self,
|
|
request: &Request,
|
|
_catalog: &str,
|
|
_schema: &str,
|
|
) -> PermissionTableTargets {
|
|
match request {
|
|
Request::Ddl(ddl)
|
|
if matches!(ddl.expr, Some(api::v1::ddl_request::Expr::CreateFlow(_))) =>
|
|
{
|
|
PermissionTableTargets::resolved(vec![])
|
|
}
|
|
_ => PermissionTableTargets::Unresolved,
|
|
}
|
|
}
|
|
|
|
fn check_permission_with_table_targets(
|
|
&self,
|
|
_: UserInfoRef,
|
|
req: PermissionReq,
|
|
targets: PermissionTableTargets,
|
|
_: Option<&str>,
|
|
) -> auth::error::Result<PermissionResp> {
|
|
if let PermissionReq::GrpcRequest(Request::Ddl(ddl)) = req
|
|
&& let Some(api::v1::ddl_request::Expr::CreateTable(create_table)) = &ddl.expr
|
|
{
|
|
let PermissionTableTargets::Resolved(resolved) = &targets else {
|
|
panic!("expected resolved sink target");
|
|
};
|
|
assert_eq!(1, resolved.len());
|
|
assert_eq!(resolved[0].catalog, create_table.catalog_name);
|
|
assert_eq!(resolved[0].schema, create_table.schema_name);
|
|
assert_eq!(resolved[0].table, create_table.table_name);
|
|
self.checked_sinks.lock().unwrap().push((
|
|
create_table.catalog_name.clone(),
|
|
create_table.schema_name.clone(),
|
|
create_table.table_name.clone(),
|
|
));
|
|
}
|
|
Ok(PermissionResp::Allow)
|
|
}
|
|
}
|
|
|
|
let checker = Arc::new(RecordingSinkChecker {
|
|
checked_sinks: Default::default(),
|
|
});
|
|
let plugins = Plugins::new();
|
|
plugins.insert::<PermissionCheckerRef>(checker.clone());
|
|
|
|
let catalog =
|
|
catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
|
|
let executor = Arc::new(MockProcedureExecutor::new(catalog.clone()));
|
|
let instance = test_instance_with_catalog_manager(
|
|
catalog,
|
|
test_table(1025, "target")?,
|
|
plugins,
|
|
None,
|
|
executor.clone(),
|
|
)
|
|
.await?;
|
|
|
|
let ctx = QueryContextBuilder::default()
|
|
.current_catalog("greptime".to_string())
|
|
.current_schema("analytics".to_string())
|
|
.build()
|
|
.into();
|
|
|
|
for (flow_name, sink_catalog, sink_schema, sink_table) in [
|
|
("flow_unqual", "", "", "unqual_sink"),
|
|
("flow_schema_qual", "", "explicit_db", "schema_qual_sink"),
|
|
("flow_full_qual", "other_cat", "other_db", "full_qual_sink"),
|
|
] {
|
|
let request = Request::Ddl(api::v1::DdlRequest {
|
|
expr: Some(api::v1::ddl_request::Expr::CreateFlow(
|
|
api::v1::CreateFlowExpr {
|
|
flow_name: flow_name.to_string(),
|
|
source_table_names: vec![api::v1::TableName {
|
|
catalog_name: "greptime".to_string(),
|
|
schema_name: "public".to_string(),
|
|
table_name: "source".to_string(),
|
|
}],
|
|
sink_table_name: Some(api::v1::TableName {
|
|
catalog_name: sink_catalog.to_string(),
|
|
schema_name: sink_schema.to_string(),
|
|
table_name: sink_table.to_string(),
|
|
}),
|
|
eval_interval: Some(api::v1::EvalInterval { seconds: 10 }),
|
|
sql: "SELECT id, ts FROM greptime.public.source".to_string(),
|
|
..Default::default()
|
|
},
|
|
)),
|
|
});
|
|
servers::query_handler::grpc::GrpcQueryHandler::do_query(
|
|
&instance,
|
|
request,
|
|
Arc::clone(&ctx),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
let checked = checker.checked_sinks.lock().unwrap().clone();
|
|
assert_eq!(
|
|
checked,
|
|
vec![
|
|
(
|
|
"greptime".to_string(),
|
|
"analytics".to_string(),
|
|
"unqual_sink".to_string(),
|
|
),
|
|
(
|
|
"greptime".to_string(),
|
|
"explicit_db".to_string(),
|
|
"schema_qual_sink".to_string(),
|
|
),
|
|
(
|
|
"other_cat".to_string(),
|
|
"other_db".to_string(),
|
|
"full_qual_sink".to_string(),
|
|
),
|
|
]
|
|
);
|
|
|
|
let submitted = executor.submitted.lock().unwrap();
|
|
assert_eq!(3, submitted.len());
|
|
let expected_sinks = [
|
|
TableName::new("greptime", "analytics", "unqual_sink"),
|
|
TableName::new("greptime", "explicit_db", "schema_qual_sink"),
|
|
TableName::new("other_cat", "other_db", "full_qual_sink"),
|
|
];
|
|
for (task, expected_sink) in submitted.iter().zip(expected_sinks) {
|
|
let DdlTask::CreateFlow(flow_task) = task else {
|
|
panic!("expected CreateFlow task");
|
|
};
|
|
assert_eq!("greptime", flow_task.catalog_name);
|
|
assert_eq!(expected_sink, flow_task.sink_table_name);
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
}
|