1use std::collections::{BTreeMap, HashMap};
19use std::future::Future;
20
21use common_datasource::file_format::Format;
22use common_datasource::object_store::build_backend_for_write;
23use common_datasource::packed_writer::{PackedTableWriter, PackedWriter};
24use common_meta::key::table_route::TableRouteValue;
25use futures::StreamExt;
26use futures::stream::FuturesUnordered;
27use session::context::QueryContextRef;
28use snafu::{OptionExt, ResultExt, ensure};
29use store_api::metric_engine_consts::{LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME};
30use table::TableRef;
31use table::metadata::TableType;
32use table::requests::{CopyDatabaseRequest, CopyDirection, CopyTableRequest};
33use tokio_util::sync::CancellationToken;
34
35use crate::error::{self, InvalidDatabaseExportSnafu, Result};
36use crate::statement::StatementExecutor;
37use crate::statement::database_copy::{
38 DatabaseExportFile, parse_parallelism_from_option_map, prepare_database_export_files,
39 validate_database_directory, validate_database_export_layout,
40};
41use crate::statement::export_logical_tables::writers::{ExportWriteBudget, retain_error};
42use crate::statement::export_logical_tables::{LogicalTableExport, LogicalTableExportLimits};
43
44pub struct PreparedDatabaseExport {
46 request: CopyDatabaseRequest,
47 jobs: Vec<DatabaseExportJob>,
48}
49
50impl PreparedDatabaseExport {
51 #[cfg(feature = "testing")]
53 pub fn job_count_for_test(&self) -> usize {
54 self.jobs.len()
55 }
56}
57
58fn is_packed_export(with: &HashMap<String, String>) -> bool {
59 with.get("metric_data_layout")
60 .is_some_and(|v| v == "packed")
61}
62
63enum DatabaseExportJob {
64 Ordinary {
65 table: TableRef,
66 output: DatabaseExportFile,
67 },
68 Metric(LogicalTableExport),
69}
70
71impl StatementExecutor {
72 pub async fn prepare_database_export(
75 &self,
76 req: CopyDatabaseRequest,
77 tables: Vec<TableRef>,
78 ) -> Result<PreparedDatabaseExport> {
79 if !is_packed_export(&req.with) {
80 validate_database_export_layout(&req.with)?;
81 }
82 validate_database_directory(&req.location)?;
83 let format = Format::try_from(&req.with).context(error::ParseFileFormatSnafu)?;
84 ensure!(
85 matches!(format, Format::Parquet(_)),
86 error::UnsupportedFormatSnafu { format }
87 );
88 let outputs = prepare_database_export_files(
89 &req.location,
90 tables.iter().map(|table| table.table_info().name.clone()),
91 ".parquet",
92 is_packed_export(&req.with),
93 )?;
94 let mut logical = Vec::new();
95 let mut jobs = Vec::new();
96 for (table, output) in tables.into_iter().zip(outputs) {
97 let info = table.table_info();
98 ensure!(
99 info.catalog_name == req.catalog_name
100 && info.schema_name == req.schema_name
101 && table.table_type() == TableType::Base,
102 InvalidDatabaseExportSnafu {
103 reason: "expected base tables in the selected schema"
104 }
105 );
106 if info.meta.engine == METRIC_ENGINE_NAME {
107 ensure!(
108 info.meta
109 .options
110 .extra_options
111 .contains_key(LOGICAL_TABLE_METADATA_KEY),
112 InvalidDatabaseExportSnafu {
113 reason: "expected a Metric logical table"
114 }
115 );
116 logical.push(table);
117 } else {
118 jobs.push(DatabaseExportJob::Ordinary { table, output });
119 }
120 }
121 let ids = logical
122 .iter()
123 .map(|t| t.table_info().table_id())
124 .collect::<Vec<_>>();
125 let routes = self
126 .table_metadata_manager
127 .table_route_manager()
128 .table_route_storage()
129 .batch_get(&ids)
130 .await
131 .context(error::TableMetadataManagerSnafu)?;
132 let mut groups = BTreeMap::<_, Vec<TableRef>>::new();
133 for (table, route) in logical.into_iter().zip(routes) {
134 let Some(TableRouteValue::Logical(route)) = route else {
135 return InvalidDatabaseExportSnafu {
136 reason: format!(
137 "missing or non-logical route for {}",
138 table.table_info().table_id()
139 ),
140 }
141 .fail();
142 };
143 groups
144 .entry(route.physical_table_id())
145 .or_default()
146 .push(table);
147 }
148 let physical_ids = groups.keys().copied().collect::<Vec<_>>();
149 let mut physical = self
150 .catalog_manager
151 .tables_by_ids(&req.catalog_name, &req.schema_name, &physical_ids)
152 .await
153 .context(error::CatalogSnafu)?
154 .into_iter()
155 .map(|t| (t.table_info().table_id(), t))
156 .collect::<BTreeMap<_, _>>();
157 for (id, tables) in groups {
158 let table = physical
159 .remove(&id)
160 .with_context(|| InvalidDatabaseExportSnafu {
161 reason: format!("missing physical table {id} in the selected schema"),
162 })?;
163 jobs.push(DatabaseExportJob::Metric(
164 LogicalTableExport::try_new_in_directory(table, &tables, &req.location)?,
165 ));
166 }
167 build_backend_for_write(
168 &req.location,
169 &req.connection,
170 &self.local_file_access,
171 &self.remote_storage_access,
172 )
173 .await
174 .context(error::BuildBackendSnafu)?;
175 Ok(PreparedDatabaseExport { request: req, jobs })
176 }
177}
178
179#[derive(Debug)]
181pub struct DatabaseExportSummary {
182 pub rows: usize,
183 pub output_files: Vec<String>,
184}
185
186impl StatementExecutor {
187 pub async fn export_database(
191 &self,
192 plan: PreparedDatabaseExport,
193 cancellation: &CancellationToken,
194 ctx: QueryContextRef,
195 ) -> Result<DatabaseExportSummary> {
196 let mut output_files = Vec::new();
197 for job in &plan.jobs {
198 match job {
199 DatabaseExportJob::Ordinary { output, .. } => {
200 output_files.push(output.location.clone())
201 }
202 DatabaseExportJob::Metric(unit) => {
203 output_files.extend(unit.output_files().map(|file| file.location.clone()))
204 }
205 }
206 }
207 output_files.sort();
208 let req = &plan.request;
209 let parallelism = parse_parallelism_from_option_map(&req.with);
210 let budget = ExportWriteBudget::new(parallelism);
211 let packed = if is_packed_export(&req.with) {
212 let store = build_backend_for_write(
213 &req.location,
214 &req.connection,
215 &self.local_file_access,
216 &self.remote_storage_access,
217 )
218 .await
219 .context(error::BuildBackendSnafu)?;
220 Some(
221 PackedWriter::new(store).context(error::WriteStreamToFileSnafu {
222 path: &req.location,
223 })?,
224 )
225 } else {
226 None
227 };
228 let rows = run_database_export_jobs(plan.jobs, parallelism, cancellation, |job, token| {
229 let ctx = ctx.clone();
230 let budget = budget.clone();
231 let packed = packed.clone();
232 async move {
233 match job {
234 DatabaseExportJob::Metric(unit) => self
235 .export_logical_tables_managed(
236 &unit,
237 &req.location,
238 &req.connection,
239 req.time_range.as_ref(),
240 LogicalTableExportLimits::default(),
241 &token,
242 ctx,
243 budget,
244 packed,
245 )
246 .await
247 .map(|summary| summary.rows),
248 DatabaseExportJob::Ordinary { table, output } => {
249 let info = table.table_info();
250 let copy = CopyTableRequest {
251 catalog_name: info.catalog_name.clone(),
252 schema_name: info.schema_name.clone(),
253 table_name: info.name.clone(),
254 location: if packed.is_some() {
255 req.location.clone()
256 } else {
257 output.location
258 },
259 with: req.with.clone(),
260 connection: req.connection.clone(),
261 pattern: None,
262 direction: CopyDirection::Export,
263 timestamp_range: req.time_range,
264 limit: None,
265 };
266 let _permit = budget.writer(&token).await?;
267 let destination = packed.map(|shared| {
268 PackedTableWriter::new(shared, info.name.clone(), info.table_id(), true)
269 });
270 self.copy_captured_table_to_managed(
271 table,
272 copy,
273 ctx,
274 Some((&budget, &token)),
275 destination,
276 )
277 .await
278 }
279 }
280 }
281 })
282 .await;
283 if let Some(packed) = packed {
284 let mut packed = packed.lock().await;
285 let result = match rows {
286 Ok(rows) => packed
287 .finish(cancellation)
288 .await
289 .context(error::WriteStreamToFileSnafu {
290 path: &req.location,
291 })
292 .and_then(|files| {
293 Ok(DatabaseExportSummary {
294 rows,
295 output_files: files
296 .into_iter()
297 .map(|file| {
298 DatabaseExportFile::new(&req.location, &file, "")
299 .map(|f| f.location)
300 })
301 .collect::<Result<_>>()?,
302 })
303 }),
304 Err(error) => Err(error),
305 };
306 if result.is_err()
307 && let Err(error) = packed.abort().await
308 {
309 common_telemetry::warn!(error; "Failed to abort Metric pack");
310 }
311 result
312 } else {
313 Ok(DatabaseExportSummary {
314 rows: rows?,
315 output_files,
316 })
317 }
318 }
319}
320
321async fn run_database_export_jobs<J, F: Future<Output = Result<usize>>>(
322 jobs: impl IntoIterator<Item = J>,
323 parallelism: usize,
324 cancellation: &CancellationToken,
325 mut run: impl FnMut(J, CancellationToken) -> F,
326) -> Result<usize> {
327 let token = CancellationToken::new();
328 let mut jobs = jobs.into_iter();
329 let mut active = FuturesUnordered::new();
330 let mut first_error = None;
331 let mut rows = 0;
332 loop {
333 while first_error.is_none()
334 && !cancellation.is_cancelled()
335 && !token.is_cancelled()
336 && active.len() < parallelism.max(1)
337 {
338 let Some(job) = jobs.next() else { break };
339 active.push(run(job, token.clone()));
340 }
341 if first_error.is_none() && cancellation.is_cancelled() {
342 first_error = Some(error::DatabaseExportCancelledSnafu.build());
343 token.cancel();
344 }
345 if active.is_empty() {
346 break;
347 }
348 let result = tokio::select! {
349 biased;
350 _ = cancellation.cancelled(), if first_error.is_none() => {
351 first_error = Some(error::DatabaseExportCancelledSnafu.build());
352 token.cancel();
353 continue;
354 }
355 result = active.next() => result,
356 };
357 match result {
358 Some(Ok(count)) => rows += count,
359 Some(Err(err)) => {
360 if !cancellation.is_cancelled() || first_error.is_none() {
361 retain_error(&mut first_error, err);
362 }
363 token.cancel();
364 }
365 None => break,
366 }
367 }
368 match first_error {
369 Some(err) => Err(err),
370 None => Ok(rows),
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use std::sync::Arc;
377 use std::sync::atomic::{AtomicUsize, Ordering};
378
379 use tokio::sync::{Semaphore, mpsc};
380
381 use super::*;
382
383 #[tokio::test]
384 async fn bounded_admission_and_drain() {
385 for cancel in [false, true] {
386 let cancellation = CancellationToken::new();
387 let start_error = Arc::new(Semaphore::new(0));
388 let finish_io = Arc::new(Semaphore::new(0));
389 let (started, mut receiver) = mpsc::unbounded_channel();
390 let finished = Arc::new(AtomicUsize::new(0));
391 let task = tokio::spawn({
392 let cancellation = cancellation.clone();
393 let start_error = start_error.clone();
394 let finish_io = finish_io.clone();
395 let finished = finished.clone();
396 async move {
397 run_database_export_jobs(0..4, 2, &cancellation, |job, token| {
398 let started = started.clone();
399 let start_error = start_error.clone();
400 let finish_io = finish_io.clone();
401 let finished = finished.clone();
402 async move {
403 started.send(job).unwrap();
404 if job == 0 {
405 if cancel {
406 token.cancelled().await;
407 } else {
408 start_error.acquire().await.unwrap().forget();
409 }
410 return InvalidDatabaseExportSnafu {
411 reason: "first error",
412 }
413 .fail();
414 }
415 token.cancelled().await;
417 started.send(10).unwrap();
418 finish_io.acquire().await.unwrap().forget();
419 finished.fetch_add(1, Ordering::SeqCst);
420 InvalidDatabaseExportSnafu {
421 reason: "drain error",
422 }
423 .fail()
424 }
425 })
426 .await
427 }
428 });
429 assert_eq!(receiver.recv().await, Some(0));
430 assert_eq!(receiver.recv().await, Some(1));
431 assert!(receiver.try_recv().is_err());
432 if cancel {
433 cancellation.cancel();
434 } else {
435 start_error.add_permits(1);
436 }
437 assert_eq!(receiver.recv().await, Some(10));
438 assert!(!task.is_finished());
439 finish_io.add_permits(1);
440 let err = task.await.unwrap().unwrap_err();
441 if cancel {
442 assert!(matches!(err, error::Error::DatabaseExportCancelled { .. }));
443 } else {
444 assert!(
445 matches!(err, error::Error::InvalidDatabaseExport { reason } if reason == "first error")
446 );
447 }
448 assert_eq!(finished.load(Ordering::SeqCst), 1);
449 assert_eq!(receiver.recv().await, None);
450 }
451 }
452
453 #[tokio::test]
454 async fn cancellation_before_admission_and_successful_refill() {
455 let token = CancellationToken::new();
456 token.cancel();
457 let result = run_database_export_jobs(0..4, 2, &token, |_, _| async {
458 panic!("cancelled job admitted")
459 })
460 .await;
461 assert!(matches!(
462 result,
463 Err(error::Error::DatabaseExportCancelled { .. })
464 ));
465 let started = AtomicUsize::new(0);
466 let result = run_database_export_jobs(0..7, 2, &CancellationToken::new(), |job, _| {
467 started.fetch_add(1, Ordering::SeqCst);
468 async move { Ok(job) }
469 })
470 .await
471 .unwrap();
472 assert_eq!(result, 21);
473 assert_eq!(started.load(Ordering::SeqCst), 7);
474 }
475}