mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
fix(flow): harden routed backfill admin
Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
@@ -37,6 +37,7 @@ includes = [
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/common/function/src/admin/purge_table.rs",
|
||||
"src/common/function/src/backfill.rs",
|
||||
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
|
||||
"src/common/meta/src/ddl/purge_dropped_table.rs",
|
||||
"src/common/meta/src/ddl/undrop_table.rs",
|
||||
|
||||
@@ -53,6 +53,7 @@ excludes = [
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/common/function/src/admin/purge_table.rs",
|
||||
"src/common/function/src/backfill.rs",
|
||||
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
|
||||
"src/common/meta/src/ddl/purge_dropped_table.rs",
|
||||
"src/common/meta/src/ddl/undrop_table.rs",
|
||||
|
||||
@@ -62,11 +62,6 @@ impl AdminFunction {
|
||||
registry.register(BuildIndexFunction::factory());
|
||||
registry.register(BuildSeriesIndexFunction::factory());
|
||||
registry.register(FlushFlowFunction::factory());
|
||||
#[cfg(feature = "enterprise")]
|
||||
{
|
||||
registry.register(FlowBackfillFunction::factory());
|
||||
registry.register(FlowBackfillStatusFunction::factory());
|
||||
}
|
||||
registry.register(ReconcileCatalogFunction::factory());
|
||||
registry.register(ReconcileDatabaseFunction::factory());
|
||||
registry.register(ReconcileTableFunction::factory());
|
||||
@@ -77,6 +72,10 @@ impl AdminFunction {
|
||||
registry.register(DiscardUnflushedDataFunction::factory());
|
||||
registry.register(DiscardPendingTailsFunction::factory());
|
||||
#[cfg(feature = "enterprise")]
|
||||
registry.register(PurgeTableFunction::factory());
|
||||
{
|
||||
registry.register(PurgeTableFunction::factory());
|
||||
registry.register(FlowBackfillFunction::factory());
|
||||
registry.register(FlowBackfillStatusFunction::factory());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
// Copyright 2023-2026 GrepTime Inc.
|
||||
//
|
||||
// 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
|
||||
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
|
||||
// the GreptimeDB Enterprise License. You may not use this file except in
|
||||
// compliance with that license. A copy of the license is available at the root
|
||||
// of this repository in the file LICENSE-ENTERPRISE.
|
||||
//
|
||||
// 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.
|
||||
// Unless required by applicable law or agreed to in writing, this software is
|
||||
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
||||
// either express or implied.
|
||||
|
||||
//! `ADMIN flow_backfill(...)` and `ADMIN flow_backfill_status(...)`.
|
||||
//!
|
||||
@@ -284,9 +281,14 @@ mod tests {
|
||||
#[test]
|
||||
fn test_flow_backfill_registration() {
|
||||
for name in ["flow_backfill", "flow_backfill_status"] {
|
||||
let factory = crate::function_registry::FUNCTION_REGISTRY
|
||||
.get_function(name)
|
||||
.unwrap_or_else(|| panic!("{name} is not registered as an admin function"));
|
||||
let factory = crate::function_registry::get_admin_function(name)
|
||||
.unwrap_or_else(|| panic!("{name} is not registered as an ADMIN function"));
|
||||
assert!(
|
||||
crate::function_registry::FUNCTION_REGISTRY
|
||||
.get_function(name)
|
||||
.is_none(),
|
||||
"{name} must not resolve through the ordinary scalar registry"
|
||||
);
|
||||
let function = factory.provide(FunctionContext::mock());
|
||||
assert_eq!(name, function.name());
|
||||
assert_eq!(ArrowDataType::Utf8, function.return_type(&[]).unwrap());
|
||||
|
||||
+74
-37
@@ -14,7 +14,8 @@
|
||||
|
||||
use api::v1::flow::FlowRequestHeader;
|
||||
use async_trait::async_trait;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_error::ext::{BoxedError, PlainError};
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_function::handlers::FlowServiceHandler;
|
||||
use common_meta::key::flow::FlowMetadataManagerRef;
|
||||
use common_meta::node_manager::{FlownodeRef, NodeManagerRef};
|
||||
@@ -80,7 +81,7 @@ impl FlowServiceHandler for FlowServiceOperator {
|
||||
}),
|
||||
});
|
||||
|
||||
self.handle_routed(id, ctx, body).await
|
||||
self.handle_single_owner(id, ctx, body).await
|
||||
}
|
||||
|
||||
async fn backfill_status(
|
||||
@@ -97,7 +98,7 @@ impl FlowServiceHandler for FlowServiceOperator {
|
||||
flow: flow.to_string(),
|
||||
});
|
||||
|
||||
self.handle_routed(id, ctx, body).await
|
||||
self.handle_single_owner(id, ctx, body).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,13 +140,13 @@ impl FlowServiceOperator {
|
||||
.await)
|
||||
}
|
||||
|
||||
/// Sends `body` to every flownode that owns the flow `id` and merges their
|
||||
/// responses, keeping the extensions they answered with.
|
||||
/// Sends `body` to the one flownode that owns the flow `id`.
|
||||
///
|
||||
/// These are process-local answers (an attempt lives only in the process
|
||||
/// that owns the flow), so the extensions of the answering node(s) are what
|
||||
/// the caller reads back; they are never dropped here.
|
||||
async fn handle_routed(
|
||||
/// A backfill attempt and its status are process-local to the execution that
|
||||
/// owns the flow. Broadcasting would create or read different attempts on
|
||||
/// different nodes and then merge them under the same extension keys, so a
|
||||
/// multi-owner flow is refused before any RPC is sent.
|
||||
async fn handle_single_owner(
|
||||
&self,
|
||||
id: u32,
|
||||
ctx: QueryContextRef,
|
||||
@@ -153,31 +154,32 @@ impl FlowServiceOperator {
|
||||
) -> Result<api::v1::flow::FlowResponse> {
|
||||
use api::v1::flow::FlowRequest;
|
||||
|
||||
let all_flow_nodes = self.owning_flownodes(id).await?;
|
||||
|
||||
let mut final_result: Option<api::v1::flow::FlowResponse> = None;
|
||||
for node in all_flow_nodes {
|
||||
let req = FlowRequest {
|
||||
header: Some(FlowRequestHeader {
|
||||
tracing_context: TracingContext::from_current_span().to_w3c(),
|
||||
query_context: Some(to_meta_query_context(ctx.clone()).into()),
|
||||
}),
|
||||
body: Some(body.clone()),
|
||||
};
|
||||
let res = node
|
||||
.handle(req)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(common_query::error::ExecuteSnafu)?;
|
||||
|
||||
if let Some(prev) = &mut final_result {
|
||||
prev.extensions.extend(res.extensions);
|
||||
} else {
|
||||
final_result = Some(res);
|
||||
}
|
||||
let nodes = self.owning_flownodes(id).await?;
|
||||
if nodes.len() != 1 {
|
||||
return Err(BoxedError::new(PlainError::new(
|
||||
format!(
|
||||
"flow {id} is owned by {} flownodes; backfill requires exactly one",
|
||||
nodes.len()
|
||||
),
|
||||
StatusCode::InvalidArguments,
|
||||
)))
|
||||
.context(common_query::error::ExecuteSnafu);
|
||||
}
|
||||
|
||||
final_result.context(common_query::error::FlownodeNotFoundSnafu)
|
||||
let node = nodes
|
||||
.into_iter()
|
||||
.next()
|
||||
.context(common_query::error::FlownodeNotFoundSnafu)?;
|
||||
let req = FlowRequest {
|
||||
header: Some(FlowRequestHeader {
|
||||
tracing_context: TracingContext::from_current_span().to_w3c(),
|
||||
query_context: Some(to_meta_query_context(ctx).into()),
|
||||
}),
|
||||
body: Some(body),
|
||||
};
|
||||
node.handle(req)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(common_query::error::ExecuteSnafu)
|
||||
}
|
||||
|
||||
/// Flush the flownodes according to the flow id.
|
||||
@@ -279,10 +281,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds an operator over the flow `greptime.demo` (id 42) routed to flownode 1.
|
||||
async fn new_operator(handler: RecordingFlownode) -> FlowServiceOperator {
|
||||
/// Builds an operator over the flow `greptime.demo` (id 42) with `routes`.
|
||||
async fn new_operator_with_routes(
|
||||
handler: RecordingFlownode,
|
||||
routes: Vec<(u32, Peer)>,
|
||||
) -> FlowServiceOperator {
|
||||
let kv_backend = Arc::new(MemoryKvBackend::new());
|
||||
let flow_metadata_manager = Arc::new(FlowMetadataManager::new(kv_backend));
|
||||
let flownode_ids = routes.iter().map(|(id, _)| (*id, 1u64)).collect();
|
||||
flow_metadata_manager
|
||||
.create_flow_metadata(
|
||||
FLOW_ID,
|
||||
@@ -291,7 +297,7 @@ mod tests {
|
||||
all_source_table_names: vec![],
|
||||
unresolved_source_table_names: vec![],
|
||||
sink_table_name: TableName::new("greptime", "public", "demo_sink"),
|
||||
flownode_ids: [(1, 1u64)].into(),
|
||||
flownode_ids,
|
||||
catalog_name: "greptime".to_string(),
|
||||
query_context: None,
|
||||
flow_name: "demo".to_string(),
|
||||
@@ -305,7 +311,10 @@ mod tests {
|
||||
updated_time: Default::default(),
|
||||
eval_schedule: None,
|
||||
},
|
||||
vec![(1, FlowRouteValue::from(Peer::empty(1)))],
|
||||
routes
|
||||
.into_iter()
|
||||
.map(|(id, peer)| (id, FlowRouteValue::from(peer)))
|
||||
.collect(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -316,6 +325,11 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds an operator over the flow `greptime.demo` routed to flownode 1.
|
||||
async fn new_operator(handler: RecordingFlownode) -> FlowServiceOperator {
|
||||
new_operator_with_routes(handler, vec![(1, Peer::empty(1))]).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backfill_routes_the_request_and_keeps_the_extensions() {
|
||||
let handler = RecordingFlownode::default();
|
||||
@@ -358,6 +372,29 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backfill_refuses_a_multi_owner_flow_before_sending() {
|
||||
let handler = RecordingFlownode::default();
|
||||
let operator = new_operator_with_routes(
|
||||
handler.clone(),
|
||||
vec![(1, Peer::empty(1)), (2, Peer::empty(2))],
|
||||
)
|
||||
.await;
|
||||
|
||||
let err = operator
|
||||
.backfill("greptime", "demo", 0, 1000, QueryContext::arc())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("requires exactly one"),
|
||||
"multi-owner backfill must be refused: {err}"
|
||||
);
|
||||
assert!(
|
||||
handler.take_requests().is_empty(),
|
||||
"the refusal must happen before any flownode RPC"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_backfill_status_routes_the_request_and_keeps_the_extensions() {
|
||||
let handler = RecordingFlownode::default();
|
||||
|
||||
@@ -40,6 +40,7 @@ use session::context::QueryContextRef;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use sql::ast::{Expr, FunctionArg, FunctionArgExpr, FunctionArguments, Value as SqlValue};
|
||||
use sql::statements::admin::Admin;
|
||||
use sqlparser::ast::UnaryOperator;
|
||||
|
||||
use crate::error::{self, CastSnafu, ExecuteAdminFunctionSnafu, Result};
|
||||
use crate::statement::StatementExecutor;
|
||||
@@ -79,6 +80,7 @@ struct CoreAdminFunctionService {
|
||||
}
|
||||
|
||||
/// Parts of an `ADMIN` call needed both for execution and schema derivation.
|
||||
#[derive(Debug)]
|
||||
struct ResolvedAdminFunction {
|
||||
admin_udf: datafusion_expr::ScalarUDF,
|
||||
fn_name: String,
|
||||
@@ -123,19 +125,48 @@ fn resolve_admin_function(
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
let arg_values = args
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| {
|
||||
let FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(value))) = arg else {
|
||||
// ADMIN arguments are literals. Accept one leading `+`/`-` on a numeric
|
||||
// literal as well: sqlparser represents `-1000` as a unary expression, and
|
||||
// epoch-millisecond arguments are documented as signed. Signed strings,
|
||||
// nested signs, arithmetic and casts remain rejected.
|
||||
let mut owned_args = Vec::with_capacity(args.args.len());
|
||||
for arg in &args.args {
|
||||
let value = match arg {
|
||||
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::Value(value))) => value.value.clone(),
|
||||
FunctionArg::Unnamed(FunctionArgExpr::Expr(Expr::UnaryOp { op, expr })) => {
|
||||
let Expr::Value(value) = expr.as_ref() else {
|
||||
return error::BuildAdminFunctionArgsSnafu {
|
||||
msg: format!("unsupported function arg {arg} for {}", fn_name),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
let SqlValue::Number(raw, _) = &value.value else {
|
||||
return error::BuildAdminFunctionArgsSnafu {
|
||||
msg: format!("unsupported function arg {arg} for {}", fn_name),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
match op {
|
||||
UnaryOperator::Plus => SqlValue::Number(raw.clone(), false),
|
||||
UnaryOperator::Minus => SqlValue::Number(format!("-{raw}"), false),
|
||||
_ => {
|
||||
return error::BuildAdminFunctionArgsSnafu {
|
||||
msg: format!("unsupported function arg {arg} for {}", fn_name),
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return error::BuildAdminFunctionArgsSnafu {
|
||||
msg: format!("unsupported function arg {arg} for {}", fn_name),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
Ok(&value.value)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
}
|
||||
};
|
||||
owned_args.push(value);
|
||||
}
|
||||
let arg_values = owned_args.iter().collect::<Vec<_>>();
|
||||
|
||||
let args = args_to_vector(&signature.type_signature, &arg_values, query_ctx)?;
|
||||
let arg_types = args
|
||||
@@ -468,6 +499,7 @@ fn try_get_data_type_for_sql_value(value: &SqlValue) -> Result<ArrowDataType> {
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_function::state::FunctionState;
|
||||
use datafusion_expr::TypeSignature;
|
||||
use datatypes::arrow::datatypes::DataType as ArrowDataType;
|
||||
use datatypes::value::Value;
|
||||
@@ -479,7 +511,35 @@ mod tests {
|
||||
use sql::statements::statement::Statement;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::statement::admin::{admin_output_schema, args_to_vector, immediate_result};
|
||||
use crate::statement::admin::{
|
||||
admin_output_schema, args_to_vector, immediate_result, resolve_admin_function,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_admin_signed_numeric_args_resolve() {
|
||||
for sql in [
|
||||
"ADMIN flow_backfill('bf', -1000, 1000)",
|
||||
"ADMIN flow_backfill('bf', +1000, 2000)",
|
||||
"ADMIN flow_backfill('bf', -9223372036854775808, 0)",
|
||||
] {
|
||||
let statement = ParserContext::create_with_dialect(
|
||||
sql,
|
||||
&GreptimeDbDialect {},
|
||||
ParseOptions::default(),
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{sql} must parse: {e}"))
|
||||
.remove(0);
|
||||
let Statement::Admin(statement) = statement else {
|
||||
panic!("{sql} must be an ADMIN statement");
|
||||
};
|
||||
let resolved = resolve_admin_function(
|
||||
&statement,
|
||||
&QueryContext::arc(),
|
||||
Arc::new(FunctionState::default()),
|
||||
);
|
||||
assert!(resolved.is_ok(), "{sql} must resolve: {resolved:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_args_to_vector_arity() {
|
||||
|
||||
Reference in New Issue
Block a user