Skip to main content

openvmm_helpers/
disk.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Guest disk helpers.
5
6use anyhow::Context;
7use std::path::Path;
8use vm_resource::Resource;
9use vm_resource::kind::DiskHandleKind;
10
11fn disk_open_error(path: &Path, verb: &str) -> String {
12    let mut msg = format!("{verb} '{}'", path.display());
13
14    // On windows, attempt to detect we ran under wsl by reading the WSLENV and
15    // bail out with a helpful hint that it needs to be a windows path.
16    if cfg!(windows) && std::env::var_os("WSLENV").is_some() {
17        msg += ". Linux paths are not supported when running Windows executables \
18                under WSL, make sure the path is a valid Windows path \
19                (use `wslpath -w` to convert)";
20    }
21
22    msg
23}
24
25/// Options for opening a disk file.
26#[derive(Clone, Copy)]
27pub struct OpenDiskOptions {
28    /// Open the disk as read-only.
29    pub read_only: bool,
30    /// Bypass the OS page cache for direct disk I/O.
31    pub direct: bool,
32}
33
34/// Opens the resources needed for using a disk from a file at `path`.
35///
36/// If the file ends with .vhd and is a fixed VHD1, it will be opened using
37/// the user-mode VHD parser. Otherwise, if the file ends with .vhd, the
38/// file will be opened using the kernel-mode VHD parser (Windows only).
39///
40/// If the file ends with .vhdx, the kernel-mode VHD parser is used on
41/// Windows. On Linux, the pure-Rust VHDX parser is used, with automatic
42/// parent-locator walking for differencing chains.
43///
44/// If the file ends with .vmdk, the VMDK backend is used for all platforms.
45pub async fn open_disk_type(
46    path: &Path,
47    options: OpenDiskOptions,
48) -> anyhow::Result<Resource<DiskHandleKind>> {
49    let read_only = options.read_only;
50    let ensure_no_direct = |ext| {
51        if options.direct {
52            anyhow::bail!("direct I/O is not supported for {ext} files");
53        };
54        Ok(())
55    };
56    Ok(match path.extension().and_then(|s| s.to_str()) {
57        Some("vmdk") => {
58            ensure_no_direct(".vmdk")?;
59            disk_vmdk::open_vmdk(path, read_only)
60                .with_context(|| disk_open_error(path, "failed to open"))?
61        }
62        Some("vhd") => {
63            let file = std::fs::OpenOptions::new()
64                .read(true)
65                .write(!read_only)
66                .open(path)
67                .with_context(|| disk_open_error(path, "failed to open"))?;
68
69            match disk_vhd1::Vhd1Disk::open_fixed(file, read_only) {
70                Ok(vhd) => {
71                    ensure_no_direct("fixed .vhd")?;
72                    Resource::new(disk_backend_resources::FixedVhd1DiskHandle(
73                        vhd.into_inner(),
74                    ))
75                }
76                Err(disk_vhd1::OpenError::NotFixed) => {
77                    #[cfg(windows)]
78                    {
79                        Resource::new(disk_vhdmp::OpenVhdmpDiskConfig(
80                            disk_vhdmp::VhdmpDisk::options()
81                                .read_only(read_only)
82                                .cached_io(!options.direct)
83                                .open(path)
84                                .with_context(|| disk_open_error(path, "failed to open"))?,
85                        ))
86                    }
87                    #[cfg(not(windows))]
88                    anyhow::bail!("non-fixed VHD not supported on Linux");
89                }
90                Err(err) => return Err(err.into()),
91            }
92        }
93        Some("vhdx") => cfg_select! {
94            windows => Resource::new(disk_vhdmp::OpenVhdmpDiskConfig(
95                disk_vhdmp::VhdmpDisk::options()
96                    .read_only(read_only)
97                    .cached_io(!options.direct)
98                    .open(path)
99                    .with_context(|| disk_open_error(path, "failed to open"))?,
100            )),
101            _ => {{
102                ensure_no_direct(".vhdx")?;
103                disklayer_vhdx::chain::open_vhdx_chain(path, read_only).await?
104            }}
105        },
106        Some("iso") if !read_only => {
107            anyhow::bail!("iso file cannot be opened as read/write")
108        }
109        Some("vmgs") => {
110            ensure_no_direct(".vmgs")?;
111            // VMGS files are fixed VHD1s. Don't bother to validate the footer
112            // here; let the resource resolver do that later.
113            let file = std::fs::OpenOptions::new()
114                .read(true)
115                .write(!read_only)
116                .open(path)
117                .with_context(|| disk_open_error(path, "failed to open"))?;
118
119            Resource::new(disk_backend_resources::FixedVhd1DiskHandle(file))
120        }
121        _ => open_raw_disk(path, options, None)?,
122    })
123}
124
125/// Create and open the resources needed for using a disk from a file at `path`.
126pub fn create_disk_type(
127    path: &Path,
128    size: u64,
129    options: OpenDiskOptions,
130) -> anyhow::Result<Resource<DiskHandleKind>> {
131    Ok(match path.extension().and_then(|s| s.to_str()) {
132        Some("vhd") | Some("vmgs") => {
133            if options.direct {
134                anyhow::bail!("direct I/O is not supported for VHD files");
135            }
136            let file = std::fs::OpenOptions::new()
137                .create(true)
138                .truncate(true)
139                .read(true)
140                .write(true)
141                .open(path)
142                .with_context(|| disk_open_error(path, "failed to create"))?;
143
144            file.set_len(size)?;
145            disk_vhd1::Vhd1Disk::make_fixed(&file)?;
146            Resource::new(disk_backend_resources::FixedVhd1DiskHandle(file))
147        }
148        Some("vhdx") => {
149            anyhow::bail!("creating vhdx not supported")
150        }
151        Some("vmdk") => {
152            anyhow::bail!("creating vmdk not supported")
153        }
154        Some("iso") => {
155            anyhow::bail!("creating iso not supported")
156        }
157        _ => open_raw_disk(path, options, Some(size))?,
158    })
159}
160
161/// Open or create a raw file or block device, returning the appropriate
162/// disk resource for the current platform.
163fn open_raw_disk(
164    path: &Path,
165    options: OpenDiskOptions,
166    size: Option<u64>,
167) -> anyhow::Result<Resource<DiskHandleKind>> {
168    if options.direct && !cfg!(target_os = "linux") {
169        anyhow::bail!("direct I/O is only supported on Linux");
170    }
171
172    let create = size.is_some();
173    let mut opts = std::fs::OpenOptions::new();
174    opts.read(true).write(!options.read_only);
175    if create {
176        opts.create(true).truncate(true);
177    }
178
179    #[cfg(target_os = "linux")]
180    if options.direct {
181        use std::os::unix::fs::OpenOptionsExt;
182        opts.custom_flags(libc::O_DIRECT);
183    }
184
185    let verb = if create {
186        "failed to create"
187    } else {
188        "failed to open"
189    };
190    let file = opts
191        .open(path)
192        .with_context(|| disk_open_error(path, verb))?;
193
194    if let Some(size) = size {
195        file.set_len(size)?;
196    }
197
198    Ok(cfg_select! {
199        target_os = "linux" => {
200            Resource::new(disk_backend_resources::BlockDeviceDiskHandle { file })
201        }
202        _ => Resource::new(disk_backend_resources::FileDiskHandle(file)),
203    })
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use pal_async::async_test;
210
211    // Creates a minimal flat VMDK descriptor and source file for routing tests.
212    fn create_test_vmdk() -> (tempfile::TempDir, std::path::PathBuf) {
213        let directory = tempfile::tempdir().unwrap();
214        std::fs::write(directory.path().join("source.bin"), [0; 512]).unwrap();
215        let descriptor = directory.path().join("disk.vmdk");
216        std::fs::write(
217            &descriptor,
218            "# Disk DescriptorFile\n\
219             version=1\n\
220             parentCID=ffffffff\n\
221             createType=\"monolithicFlat\"\n\
222             # Extent description\n\
223             RW 1 FLAT \"source.bin\" 0\n",
224        )
225        .unwrap();
226        (directory, descriptor)
227    }
228
229    #[async_test]
230    async fn opens_flat_vmdk_read_only() {
231        let (_directory, descriptor) = create_test_vmdk();
232        open_disk_type(
233            &descriptor,
234            OpenDiskOptions {
235                read_only: true,
236                direct: false,
237            },
238        )
239        .await
240        .unwrap();
241    }
242
243    #[async_test]
244    async fn rejects_vmdk_write_direct_io_and_creation() {
245        let (_directory, descriptor) = create_test_vmdk();
246        // Writable VMDK opens are not supported.
247        assert!(
248            open_disk_type(
249                &descriptor,
250                OpenDiskOptions {
251                    read_only: false,
252                    direct: false,
253                },
254            )
255            .await
256            .is_err()
257        );
258        // VMDK sources cannot use direct I/O.
259        assert!(
260            open_disk_type(
261                &descriptor,
262                OpenDiskOptions {
263                    read_only: true,
264                    direct: true,
265                },
266            )
267            .await
268            .is_err()
269        );
270        // The generic disk creator must not treat VMDK as a raw file.
271        assert!(
272            create_disk_type(
273                &descriptor,
274                512,
275                OpenDiskOptions {
276                    read_only: false,
277                    direct: false,
278                },
279            )
280            .is_err()
281        );
282    }
283}