|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! The spill directories of a native plan. |
| 19 | +//! |
| 20 | +//! A [`DiskManager`] in `Directories` mode creates a `datafusion-*` directory in every local |
| 21 | +//! directory as soon as it is built, and removes it recursively when it is dropped. Each native |
| 22 | +//! plan has its own `DiskManager`, so building one in that mode costs a `stat` and a `mkdir` per |
| 23 | +//! local directory when the plan is created, and a recursive delete when it is released, even if |
| 24 | +//! the plan never spills (#7060). The plan's disk manager built here creates that `Directories` |
| 25 | +//! mode `DiskManager` on the plan's first spill instead, so a plan that never spills touches no |
| 26 | +//! directories, and a plan that spills gets the same directories, size limit and cleanup as |
| 27 | +//! before. |
| 28 | +
|
| 29 | +use datafusion::common::Result; |
| 30 | +use datafusion::execution::disk_manager::{DiskManager, DiskManagerBuilder, DiskManagerMode}; |
| 31 | +use datafusion::execution::{SpillFile, TempFileFactory}; |
| 32 | +use parking_lot::Mutex; |
| 33 | +use std::path::PathBuf; |
| 34 | +use std::sync::Arc; |
| 35 | + |
| 36 | +/// Returns the builder of a native plan's [`DiskManager`], which spills into a directory in each |
| 37 | +/// of `local_dirs` and limits the plan's spill files to `max_temp_directory_size` bytes in total. |
| 38 | +pub(crate) fn plan_disk_manager( |
| 39 | + local_dirs: Vec<PathBuf>, |
| 40 | + max_temp_directory_size: u64, |
| 41 | +) -> DiskManagerBuilder { |
| 42 | + let builder = DiskManagerBuilder::default() |
| 43 | + .with_mode(DiskManagerMode::Directories(local_dirs)) |
| 44 | + .with_max_temp_directory_size(max_temp_directory_size); |
| 45 | + DiskManagerBuilder::default() |
| 46 | + .with_temp_file_factory(Arc::new(LazyDiskManager { |
| 47 | + builder, |
| 48 | + disk_manager: Mutex::new(None), |
| 49 | + })) |
| 50 | + .with_max_temp_directory_size(max_temp_directory_size) |
| 51 | +} |
| 52 | + |
| 53 | +/// Creates spill files through a [`DiskManager`] that it builds for the first one. Every file |
| 54 | +/// counts against that manager's size limit, and keeps the manager and its directories alive. |
| 55 | +struct LazyDiskManager { |
| 56 | + builder: DiskManagerBuilder, |
| 57 | + disk_manager: Mutex<Option<Arc<DiskManager>>>, |
| 58 | +} |
| 59 | + |
| 60 | +impl TempFileFactory for LazyDiskManager { |
| 61 | + fn create_temp_file(&self, description: &str) -> Result<Arc<dyn SpillFile>> { |
| 62 | + let disk_manager = { |
| 63 | + let mut disk_manager = self.disk_manager.lock(); |
| 64 | + match disk_manager.as_ref() { |
| 65 | + Some(disk_manager) => Arc::clone(disk_manager), |
| 66 | + None => Arc::clone(disk_manager.insert(Arc::new(self.builder.clone().build()?))), |
| 67 | + } |
| 68 | + }; |
| 69 | + disk_manager.create_tmp_file(description) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +#[cfg(test)] |
| 74 | +mod tests { |
| 75 | + use super::*; |
| 76 | + use std::io::Write; |
| 77 | + use std::path::Path; |
| 78 | + |
| 79 | + fn entries(dir: &Path) -> Vec<PathBuf> { |
| 80 | + std::fs::read_dir(dir) |
| 81 | + .unwrap() |
| 82 | + .map(|entry| entry.unwrap().path()) |
| 83 | + .collect() |
| 84 | + } |
| 85 | + |
| 86 | + #[test] |
| 87 | + fn spill_directories_are_created_on_the_first_spill() -> Result<()> { |
| 88 | + let local_dirs = [tempfile::tempdir()?, tempfile::tempdir()?]; |
| 89 | + let paths = local_dirs.iter().map(|dir| dir.path().to_path_buf()); |
| 90 | + let disk_manager = Arc::new(plan_disk_manager(paths.collect(), 1 << 20).build()?); |
| 91 | + let spill_dirs = || -> Vec<PathBuf> { |
| 92 | + local_dirs |
| 93 | + .iter() |
| 94 | + .flat_map(|dir| entries(dir.path())) |
| 95 | + .collect() |
| 96 | + }; |
| 97 | + assert!(disk_manager.tmp_files_enabled()); |
| 98 | + assert!(spill_dirs().is_empty()); |
| 99 | + |
| 100 | + // The first spill file creates a directory in each local directory, and later ones |
| 101 | + // reuse them. |
| 102 | + let first = disk_manager.create_tmp_file("first")?; |
| 103 | + let second = disk_manager.create_tmp_file("second")?; |
| 104 | + let dirs = spill_dirs(); |
| 105 | + assert_eq!(dirs.len(), 2); |
| 106 | + for file in [&first, &second] { |
| 107 | + let parent = file.path().unwrap().parent().unwrap(); |
| 108 | + assert!(dirs.iter().any(|dir| dir == parent)); |
| 109 | + } |
| 110 | + |
| 111 | + drop((disk_manager, first, second)); |
| 112 | + assert!(spill_dirs().is_empty()); |
| 113 | + Ok(()) |
| 114 | + } |
| 115 | + |
| 116 | + #[test] |
| 117 | + fn each_plan_has_its_own_spill_directories_and_size_limit() -> Result<()> { |
| 118 | + let local_dir = tempfile::tempdir()?; |
| 119 | + let plan = || plan_disk_manager(vec![local_dir.path().to_path_buf()], 10).build(); |
| 120 | + let (first, second) = (Arc::new(plan()?), Arc::new(plan()?)); |
| 121 | + |
| 122 | + let first_file = first.create_tmp_file("first")?; |
| 123 | + let mut first_writer = first_file.open_writer()?; |
| 124 | + first_writer.write_all(&[0; 8])?; |
| 125 | + // A plan's spill files count against its own limit ... |
| 126 | + assert!(first_writer.write_all(&[0; 8]).is_err()); |
| 127 | + // ... and not against another plan's. |
| 128 | + let second_file = second.create_tmp_file("second")?; |
| 129 | + second_file.open_writer()?.write_all(&[0; 8])?; |
| 130 | + assert_eq!(entries(local_dir.path()).len(), 2); |
| 131 | + Ok(()) |
| 132 | + } |
| 133 | +} |
0 commit comments