mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
fix(auth): enforce COPY export read and database table permissions (#10375)
* fix(frontend): authorize expanded COPY DATABASE table targets Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): cover authorized database copy paths Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(frontend): require read permission for COPY TO Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(auth): register the COPY TO permission action Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): group database copy authorization coverage Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): assert COPY read action targets Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(frontend): unify expanded COPY export authorization Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(frontend): defer database COPY target checks Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * fix(frontend): avoid empty database COPY authorization Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): check export authorization error status Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): check database COPY prerequisite assertions Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): use the registered COPY fixture name Signed-off-by: Dennis Zhuang <killme2008@gmail.com> * test(frontend): align physical COPY fixture registration Signed-off-by: Dennis Zhuang <killme2008@gmail.com> --------- Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
This commit is contained in:
+1
-1
@@ -32,7 +32,7 @@ pub use common::{
|
||||
userinfo_by_name, validate_mysql_native_password_verifier,
|
||||
};
|
||||
pub use permission::{
|
||||
ALL_ACTIONS, AccessMode, DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE,
|
||||
ALL_ACTIONS, AccessMode, COPY_TO, DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE,
|
||||
DefaultPermissionChecker, INFLUXDB_WRITE, JAEGER_QUERY, LOG_QUERY, LOG_WRITE, OPENTSDB_WRITE,
|
||||
OTLP_WRITE, PIPELINE_DELETE, PIPELINE_INSERT, PIPELINE_QUERY, PROM_STORE_READ,
|
||||
PROM_STORE_WRITE, PROMQL_QUERY, PermissionAction, PermissionChecker, PermissionReq,
|
||||
|
||||
@@ -145,6 +145,7 @@ impl PermissionAction {
|
||||
}
|
||||
}
|
||||
|
||||
pub const COPY_TO: PermissionAction = PermissionAction::read("copy.to");
|
||||
pub const PROMQL_QUERY: PermissionAction = PermissionAction::read("promql.query");
|
||||
pub const LOG_QUERY: PermissionAction = PermissionAction::read("log.query");
|
||||
pub const OPENTSDB_WRITE: PermissionAction = PermissionAction::write("opentsdb.write");
|
||||
@@ -170,6 +171,7 @@ pub const SEMANTIC_GRAPH_QUERY: PermissionAction = PermissionAction::read("seman
|
||||
/// Downstream crates may define additional actions with [`PermissionAction::read`] and
|
||||
/// [`PermissionAction::write`].
|
||||
pub const ALL_ACTIONS: &[PermissionAction] = &[
|
||||
COPY_TO,
|
||||
PROMQL_QUERY,
|
||||
LOG_QUERY,
|
||||
OPENTSDB_WRITE,
|
||||
|
||||
@@ -47,6 +47,11 @@ including caches owned by pipeline and protocol handlers.
|
||||
MySQL sessions without a selected database validate explicit scopes before
|
||||
planning or executing SQL, including prepared statements; unqualified targets
|
||||
fail without falling back to `public`.
|
||||
- **COPY DATABASE** (`instance.rs`, `instance/export_database.rs`): capture export
|
||||
tables or prepare import requests, authorize the complete resolved target set,
|
||||
then execute that same set. Export checks both SQL write permission and
|
||||
`COPY_TO` read permission; import permission failures must not be swallowed by
|
||||
`continue_on_error`.
|
||||
- **Exemplar query** (`instance/exemplar.rs`): authorize all selector branches
|
||||
before resolving logical schemas or calling
|
||||
`PromQueryInterceptor::pre_execute_exemplars`. Exact metric selectors project
|
||||
|
||||
@@ -85,6 +85,7 @@ tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
arrow-flight.workspace = true
|
||||
auth = { workspace = true, features = ["testing"] }
|
||||
catalog = { workspace = true, features = ["testing"] }
|
||||
common-test-util.workspace = true
|
||||
datatypes.workspace = true
|
||||
|
||||
@@ -41,8 +41,8 @@ use std::time::{Duration, SystemTime};
|
||||
use async_stream::stream;
|
||||
use async_trait::async_trait;
|
||||
use auth::{
|
||||
PROMQL_QUERY, PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
|
||||
PermissionTableTargets,
|
||||
COPY_TO, PROMQL_QUERY, PermissionChecker, PermissionCheckerRef, PermissionReq,
|
||||
PermissionTableTarget, PermissionTableTargets,
|
||||
};
|
||||
use catalog::CatalogManagerRef;
|
||||
use catalog::process_manager::{
|
||||
@@ -100,7 +100,7 @@ use sql::ast::ObjectNamePartExt;
|
||||
use sql::dialect::Dialect;
|
||||
use sql::parser::{ParseOptions, ParserContext};
|
||||
use sql::statements::comment::CommentObject;
|
||||
use sql::statements::copy::{CopyDatabase, CopyTable};
|
||||
use sql::statements::copy::{Copy, CopyDatabase, CopyTable};
|
||||
use sql::statements::statement::Statement;
|
||||
use sql::statements::tql::Tql;
|
||||
use sql::util::{
|
||||
@@ -439,6 +439,9 @@ impl Instance {
|
||||
{
|
||||
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;
|
||||
}
|
||||
self.statement_executor
|
||||
.execute_sql(stmt, query_ctx)
|
||||
.await
|
||||
@@ -583,6 +586,78 @@ fn attach_timeout(
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
async fn copy_database(
|
||||
&self,
|
||||
copy: CopyDatabase,
|
||||
stmt: &Statement,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<Output> {
|
||||
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(),
|
||||
);
|
||||
let targets = self
|
||||
.resolve_query_permission_targets(targets, &ctx)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
self.check_table_permission(&ctx, PermissionReq::SqlStatement(stmt), targets)
|
||||
.context(PermissionSnafu)?;
|
||||
self.statement_executor
|
||||
.copy_database_from_requests(req, requests, ctx)
|
||||
.await
|
||||
.context(TableOperationSnafu)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_sql_permission(
|
||||
&self,
|
||||
stmt: &Statement,
|
||||
@@ -600,6 +675,11 @@ impl Instance {
|
||||
)
|
||||
.context(PermissionSnafu)?;
|
||||
|
||||
// Database COPY needs the full table set before table-target authorization.
|
||||
if matches!(stmt, Statement::Copy(Copy::CopyDatabase(_))) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let targets = match extract_tables_from_statement_checked(stmt) {
|
||||
Some(tables) => PermissionTableTargets::resolved(
|
||||
tables
|
||||
@@ -621,6 +701,14 @@ impl Instance {
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(ExternalSnafu)?;
|
||||
if matches!(
|
||||
stmt,
|
||||
Statement::Copy(Copy::CopyTable(CopyTable::To(_)) | Copy::CopyQueryTo(_))
|
||||
) {
|
||||
// COPY retains its write permission requirement and also reads source data.
|
||||
self.check_table_permission(query_ctx, PermissionReq::Action(COPY_TO), targets.clone())
|
||||
.context(PermissionSnafu)?;
|
||||
}
|
||||
self.check_table_permission(query_ctx, PermissionReq::SqlStatement(stmt), targets)
|
||||
.context(PermissionSnafu)?;
|
||||
Ok(())
|
||||
@@ -3134,6 +3222,115 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
) -> 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");
|
||||
@@ -3394,6 +3591,7 @@ mod tests {
|
||||
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
|
||||
@@ -3823,6 +4021,108 @@ mod tests {
|
||||
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;
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use auth::{
|
||||
PermissionAction, PermissionChecker, PermissionCheckerRef, PermissionReq,
|
||||
PermissionTableTarget, PermissionTableTargets,
|
||||
COPY_TO, PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
|
||||
PermissionTableTargets,
|
||||
};
|
||||
use common_query::Output;
|
||||
use common_telemetry::error;
|
||||
@@ -136,12 +136,8 @@ impl Instance {
|
||||
self.check_table_permission(ctx, PermissionReq::SqlStatement(&stmt), targets.clone())
|
||||
.context(PermissionSnafu)?;
|
||||
// COPY is classified as a write by existing permission checkers.
|
||||
self.check_table_permission(
|
||||
ctx,
|
||||
PermissionReq::Action(PermissionAction::read("database.export")),
|
||||
targets,
|
||||
)
|
||||
.context(PermissionSnafu)?;
|
||||
self.check_table_permission(ctx, PermissionReq::Action(COPY_TO), targets)
|
||||
.context(PermissionSnafu)?;
|
||||
Ok(self
|
||||
.statement_executor
|
||||
.prepare_database_export(req, tables)
|
||||
|
||||
@@ -26,6 +26,7 @@ use object_store::Entry;
|
||||
use regex::Regex;
|
||||
use session::context::QueryContextRef;
|
||||
use snafu::ResultExt;
|
||||
use table::TableRef;
|
||||
use table::requests::{CopyDatabaseRequest, CopyDirection, CopyTableRequest};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
@@ -46,6 +47,19 @@ impl StatementExecutor {
|
||||
&self,
|
||||
req: CopyDatabaseRequest,
|
||||
ctx: QueryContextRef,
|
||||
) -> error::Result<Output> {
|
||||
let tables = self
|
||||
.capture_database_export_tables(&req, None, &ctx)
|
||||
.await?;
|
||||
self.copy_database_to_tables(req, tables, ctx).await
|
||||
}
|
||||
|
||||
/// Exports the captured tables without enumerating the database again.
|
||||
pub async fn copy_database_to_tables(
|
||||
&self,
|
||||
req: CopyDatabaseRequest,
|
||||
tables: Vec<TableRef>,
|
||||
ctx: QueryContextRef,
|
||||
) -> error::Result<Output> {
|
||||
validate_database_export_layout(&req.with)?;
|
||||
validate_database_directory(&req.location)?;
|
||||
@@ -54,9 +68,6 @@ impl StatementExecutor {
|
||||
"Copy database {}.{} to dir: {}, time: {:?}, parallelism: {}",
|
||||
req.catalog_name, req.schema_name, req.location, req.time_range, parallelism
|
||||
);
|
||||
let tables = self
|
||||
.capture_database_export_tables(&req, None, &ctx)
|
||||
.await?;
|
||||
let num_tables = tables.len();
|
||||
|
||||
let suffix = Format::try_from(&req.with)
|
||||
@@ -120,6 +131,15 @@ impl StatementExecutor {
|
||||
req: CopyDatabaseRequest,
|
||||
ctx: QueryContextRef,
|
||||
) -> error::Result<Output> {
|
||||
let requests = self.prepare_database_import(&req).await?;
|
||||
self.copy_database_from_requests(req, requests, ctx).await
|
||||
}
|
||||
|
||||
/// Lists and resolves all destination tables before importing any rows.
|
||||
pub async fn prepare_database_import(
|
||||
&self,
|
||||
req: &CopyDatabaseRequest,
|
||||
) -> error::Result<Vec<CopyTableRequest>> {
|
||||
if let Some(layout) = req.with.get("metric_data_layout") {
|
||||
return error::InvalidCopyParameterSnafu {
|
||||
key: "metric_data_layout",
|
||||
@@ -129,16 +149,11 @@ impl StatementExecutor {
|
||||
}
|
||||
validate_database_directory(&req.location)?;
|
||||
|
||||
let parallelism = parse_parallelism_from_option_map(&req.with);
|
||||
info!(
|
||||
"Copy database {}.{} from dir: {}, time: {:?}, parallelism: {}",
|
||||
req.catalog_name, req.schema_name, req.location, req.time_range, parallelism
|
||||
);
|
||||
let suffix = Format::try_from(&req.with)
|
||||
.context(error::ParseFileFormatSnafu)?
|
||||
.suffix();
|
||||
|
||||
let entries = list_files_to_copy(&req, suffix, &self.local_file_access).await?;
|
||||
let entries = list_files_to_copy(req, suffix, &self.local_file_access).await?;
|
||||
|
||||
let continue_on_error = req
|
||||
.with
|
||||
@@ -146,8 +161,7 @@ impl StatementExecutor {
|
||||
.and_then(|v| bool::from_str(v).ok())
|
||||
.unwrap_or(false);
|
||||
|
||||
let mut tasks = Vec::with_capacity(entries.len());
|
||||
let semaphore = Arc::new(Semaphore::new(parallelism));
|
||||
let mut requests = Vec::with_capacity(entries.len());
|
||||
|
||||
for e in entries {
|
||||
let (table_name, location) = match database_import_source(&req.location, e.path()) {
|
||||
@@ -162,10 +176,10 @@ impl StatementExecutor {
|
||||
}
|
||||
};
|
||||
|
||||
let req = CopyTableRequest {
|
||||
requests.push(CopyTableRequest {
|
||||
catalog_name: req.catalog_name.clone(),
|
||||
schema_name: req.schema_name.clone(),
|
||||
table_name: table_name.clone(),
|
||||
table_name,
|
||||
location,
|
||||
with: req.with.clone(),
|
||||
connection: req.connection.clone(),
|
||||
@@ -173,9 +187,33 @@ impl StatementExecutor {
|
||||
direction: CopyDirection::Import,
|
||||
timestamp_range: None,
|
||||
limit: None,
|
||||
};
|
||||
});
|
||||
}
|
||||
Ok(requests)
|
||||
}
|
||||
|
||||
/// Imports the prepared file requests without listing the source again.
|
||||
pub async fn copy_database_from_requests(
|
||||
&self,
|
||||
req: CopyDatabaseRequest,
|
||||
requests: Vec<CopyTableRequest>,
|
||||
ctx: QueryContextRef,
|
||||
) -> error::Result<Output> {
|
||||
let parallelism = parse_parallelism_from_option_map(&req.with);
|
||||
info!(
|
||||
"Copy database {}.{} from dir: {}, time: {:?}, parallelism: {}",
|
||||
req.catalog_name, req.schema_name, req.location, req.time_range, parallelism
|
||||
);
|
||||
let continue_on_error = req
|
||||
.with
|
||||
.get(CONTINUE_ON_ERROR_KEY)
|
||||
.and_then(|v| bool::from_str(v).ok())
|
||||
.unwrap_or(false);
|
||||
let mut tasks = Vec::with_capacity(requests.len());
|
||||
let semaphore = Arc::new(Semaphore::new(parallelism));
|
||||
for req in requests {
|
||||
let moved_ctx = ctx.clone();
|
||||
let moved_table_name = table_name.clone();
|
||||
let moved_table_name = req.table_name.clone();
|
||||
let moved_semaphore = semaphore.clone();
|
||||
tasks.push(async move {
|
||||
let _permit = moved_semaphore.acquire().await.unwrap();
|
||||
|
||||
Reference in New Issue
Block a user