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(&req.location, &req.connection, &self.local_file_access)
168 .await
169 .context(error::BuildBackendSnafu)?;
170 Ok(PreparedDatabaseExport { request: req, jobs })
171 }
172}
173
174#[derive(Debug)]
176pub struct DatabaseExportSummary {
177 pub rows: usize,
178 pub output_files: Vec<String>,
179}
180
181impl StatementExecutor {
182 pub async fn export_database(
186 &self,
187 plan: PreparedDatabaseExport,
188 cancellation: &CancellationToken,
189 ctx: QueryContextRef,
190 ) -> Result<DatabaseExportSummary> {
191 let mut output_files = Vec::new();
192 for job in &plan.jobs {
193 match job {
194 DatabaseExportJob::Ordinary { output, .. } => {
195 output_files.push(output.location.clone())
196 }
197 DatabaseExportJob::Metric(unit) => {
198 output_files.extend(unit.output_files().map(|file| file.location.clone()))
199 }
200 }
201 }
202 output_files.sort();
203 let req = &plan.request;
204 let parallelism = parse_parallelism_from_option_map(&req.with);
205 let budget = ExportWriteBudget::new(parallelism);
206 let packed = if is_packed_export(&req.with) {
207 let store =
208 build_backend_for_write(&req.location, &req.connection, &self.local_file_access)
209 .await
210 .context(error::BuildBackendSnafu)?;
211 Some(
212 PackedWriter::new(store).context(error::WriteStreamToFileSnafu {
213 path: &req.location,
214 })?,
215 )
216 } else {
217 None
218 };
219 let rows = run_database_export_jobs(plan.jobs, parallelism, cancellation, |job, token| {
220 let ctx = ctx.clone();
221 let budget = budget.clone();
222 let packed = packed.clone();
223 async move {
224 match job {
225 DatabaseExportJob::Metric(unit) => self
226 .export_logical_tables_managed(
227 &unit,
228 &req.location,
229 &req.connection,
230 req.time_range.as_ref(),
231 LogicalTableExportLimits::default(),
232 &token,
233 ctx,
234 budget,
235 packed,
236 )
237 .await
238 .map(|summary| summary.rows),
239 DatabaseExportJob::Ordinary { table, output } => {
240 let info = table.table_info();
241 let copy = CopyTableRequest {
242 catalog_name: info.catalog_name.clone(),
243 schema_name: info.schema_name.clone(),
244 table_name: info.name.clone(),
245 location: if packed.is_some() {
246 req.location.clone()
247 } else {
248 output.location
249 },
250 with: req.with.clone(),
251 connection: req.connection.clone(),
252 pattern: None,
253 direction: CopyDirection::Export,
254 timestamp_range: req.time_range,
255 limit: None,
256 };
257 let _permit = budget.writer(&token).await?;
258 let destination = packed.map(|shared| {
259 PackedTableWriter::new(shared, info.name.clone(), info.table_id(), true)
260 });
261 self.copy_captured_table_to_managed(
262 table,
263 copy,
264 ctx,
265 Some((&budget, &token)),
266 destination,
267 )
268 .await
269 }
270 }
271 }
272 })
273 .await;
274 if let Some(packed) = packed {
275 let mut packed = packed.lock().await;
276 let result = match rows {
277 Ok(rows) => packed
278 .finish(cancellation)
279 .await
280 .context(error::WriteStreamToFileSnafu {
281 path: &req.location,
282 })
283 .and_then(|files| {
284 Ok(DatabaseExportSummary {
285 rows,
286 output_files: files
287 .into_iter()
288 .map(|file| {
289 DatabaseExportFile::new(&req.location, &file, "")
290 .map(|f| f.location)
291 })
292 .collect::<Result<_>>()?,
293 })
294 }),
295 Err(error) => Err(error),
296 };
297 if result.is_err()
298 && let Err(error) = packed.abort().await
299 {
300 common_telemetry::warn!(error; "Failed to abort Metric pack");
301 }
302 result
303 } else {
304 Ok(DatabaseExportSummary {
305 rows: rows?,
306 output_files,
307 })
308 }
309 }
310}
311
312async fn run_database_export_jobs<J, F: Future<Output = Result<usize>>>(
313 jobs: impl IntoIterator<Item = J>,
314 parallelism: usize,
315 cancellation: &CancellationToken,
316 mut run: impl FnMut(J, CancellationToken) -> F,
317) -> Result<usize> {
318 let token = CancellationToken::new();
319 let mut jobs = jobs.into_iter();
320 let mut active = FuturesUnordered::new();
321 let mut first_error = None;
322 let mut rows = 0;
323 loop {
324 while first_error.is_none()
325 && !cancellation.is_cancelled()
326 && !token.is_cancelled()
327 && active.len() < parallelism.max(1)
328 {
329 let Some(job) = jobs.next() else { break };
330 active.push(run(job, token.clone()));
331 }
332 if first_error.is_none() && cancellation.is_cancelled() {
333 first_error = Some(error::DatabaseExportCancelledSnafu.build());
334 token.cancel();
335 }
336 if active.is_empty() {
337 break;
338 }
339 let result = tokio::select! {
340 biased;
341 _ = cancellation.cancelled(), if first_error.is_none() => {
342 first_error = Some(error::DatabaseExportCancelledSnafu.build());
343 token.cancel();
344 continue;
345 }
346 result = active.next() => result,
347 };
348 match result {
349 Some(Ok(count)) => rows += count,
350 Some(Err(err)) => {
351 if !cancellation.is_cancelled() || first_error.is_none() {
352 retain_error(&mut first_error, err);
353 }
354 token.cancel();
355 }
356 None => break,
357 }
358 }
359 match first_error {
360 Some(err) => Err(err),
361 None => Ok(rows),
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use std::sync::Arc;
368 use std::sync::atomic::{AtomicUsize, Ordering};
369
370 use tokio::sync::{Semaphore, mpsc};
371
372 use super::*;
373
374 #[tokio::test]
375 async fn bounded_admission_and_drain() {
376 for cancel in [false, true] {
377 let cancellation = CancellationToken::new();
378 let start_error = Arc::new(Semaphore::new(0));
379 let finish_io = Arc::new(Semaphore::new(0));
380 let (started, mut receiver) = mpsc::unbounded_channel();
381 let finished = Arc::new(AtomicUsize::new(0));
382 let task = tokio::spawn({
383 let cancellation = cancellation.clone();
384 let start_error = start_error.clone();
385 let finish_io = finish_io.clone();
386 let finished = finished.clone();
387 async move {
388 run_database_export_jobs(0..4, 2, &cancellation, |job, token| {
389 let started = started.clone();
390 let start_error = start_error.clone();
391 let finish_io = finish_io.clone();
392 let finished = finished.clone();
393 async move {
394 started.send(job).unwrap();
395 if job == 0 {
396 if cancel {
397 token.cancelled().await;
398 } else {
399 start_error.acquire().await.unwrap().forget();
400 }
401 return InvalidDatabaseExportSnafu {
402 reason: "first error",
403 }
404 .fail();
405 }
406 token.cancelled().await;
408 started.send(10).unwrap();
409 finish_io.acquire().await.unwrap().forget();
410 finished.fetch_add(1, Ordering::SeqCst);
411 InvalidDatabaseExportSnafu {
412 reason: "drain error",
413 }
414 .fail()
415 }
416 })
417 .await
418 }
419 });
420 assert_eq!(receiver.recv().await, Some(0));
421 assert_eq!(receiver.recv().await, Some(1));
422 assert!(receiver.try_recv().is_err());
423 if cancel {
424 cancellation.cancel();
425 } else {
426 start_error.add_permits(1);
427 }
428 assert_eq!(receiver.recv().await, Some(10));
429 assert!(!task.is_finished());
430 finish_io.add_permits(1);
431 let err = task.await.unwrap().unwrap_err();
432 if cancel {
433 assert!(matches!(err, error::Error::DatabaseExportCancelled { .. }));
434 } else {
435 assert!(
436 matches!(err, error::Error::InvalidDatabaseExport { reason } if reason == "first error")
437 );
438 }
439 assert_eq!(finished.load(Ordering::SeqCst), 1);
440 assert_eq!(receiver.recv().await, None);
441 }
442 }
443
444 #[tokio::test]
445 async fn cancellation_before_admission_and_successful_refill() {
446 let token = CancellationToken::new();
447 token.cancel();
448 let result = run_database_export_jobs(0..4, 2, &token, |_, _| async {
449 panic!("cancelled job admitted")
450 })
451 .await;
452 assert!(matches!(
453 result,
454 Err(error::Error::DatabaseExportCancelled { .. })
455 ));
456 let started = AtomicUsize::new(0);
457 let result = run_database_export_jobs(0..7, 2, &CancellationToken::new(), |job, _| {
458 started.fetch_add(1, Ordering::SeqCst);
459 async move { Ok(job) }
460 })
461 .await
462 .unwrap();
463 assert_eq!(result, 21);
464 assert_eq!(started.load(Ordering::SeqCst), 7);
465 }
466}