Skip to main content

openvmm_helpers/snapshot/
publish.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Writing VM snapshots to a directory.
5
6use super::SnapshotManifest;
7use anyhow::Context;
8use std::io;
9use std::io::Write;
10use std::path::Path;
11use std::path::PathBuf;
12
13/// Checks that `dir` can receive a new snapshot. The destination must not
14/// exist yet, so existing data is never overwritten or deleted.
15pub fn check_snapshot_destination(dir: &Path) -> anyhow::Result<()> {
16    match std::fs::symlink_metadata(dir) {
17        Ok(_) => anyhow::bail!("snapshot destination {} already exists", dir.display()),
18        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
19        Err(err) => Err(err)
20            .with_context(|| format!("failed to access snapshot destination {}", dir.display())),
21    }
22}
23
24/// Removes the files and directory created by a partially written snapshot
25/// unless disarmed.
26struct SnapshotCleanup {
27    files: Vec<PathBuf>,
28    dir: Option<PathBuf>,
29}
30
31impl SnapshotCleanup {
32    fn disarm(mut self) {
33        self.files.clear();
34        self.dir = None;
35    }
36}
37
38impl Drop for SnapshotCleanup {
39    fn drop(&mut self) {
40        // Remove in reverse creation order so the manifest, if present, goes
41        // first and a partially cleaned directory never looks complete.
42        for file in self.files.iter().rev() {
43            if let Err(err) = std::fs::remove_file(file) {
44                if err.kind() != io::ErrorKind::NotFound {
45                    tracing::warn!(
46                        path = %file.display(),
47                        error = &err as &dyn std::error::Error,
48                        "failed to clean up partial snapshot file"
49                    );
50                }
51            }
52        }
53        if let Some(dir) = &self.dir {
54            // Only removes the directory if it is empty.
55            let _ = std::fs::remove_dir(dir);
56        }
57    }
58}
59
60/// Creates `path`, which must not exist, writes `data` to it and flushes it to
61/// disk. Registers `path` for cleanup once the file has been created.
62fn write_synced(cleanup: &mut SnapshotCleanup, path: &Path, data: &[u8]) -> anyhow::Result<()> {
63    let mut file = fs_err::OpenOptions::new()
64        .write(true)
65        .create_new(true)
66        .open(path)?;
67    cleanup.files.push(path.to_owned());
68    file.write_all(data)?;
69    file.sync_all()?;
70    Ok(())
71}
72
73/// Write a snapshot to the given directory.
74///
75/// The directory must not exist; it is created by this call, along with any
76/// missing parent directories. The snapshot consists of:
77/// - `manifest.bin` — protobuf-encoded [`SnapshotManifest`]
78/// - `state.bin` — raw device saved-state bytes
79/// - `memory.bin` — hard link to the memory backing file
80///
81/// `state.bin` and `memory.bin` are written first and `manifest.bin` last,
82/// each flushed to disk, so the presence of `manifest.bin` indicates that the
83/// snapshot was written completely. On failure, the directory and the files
84/// created by this call are removed.
85pub fn write_snapshot(
86    dir: &Path,
87    manifest: &SnapshotManifest,
88    saved_state_bytes: &[u8],
89    memory_file_path: &Path,
90) -> anyhow::Result<()> {
91    check_snapshot_destination(dir)?;
92    if let Some(parent) = dir.parent() {
93        fs_err::create_dir_all(parent)?;
94    }
95    // Creating the directory claims the destination, so a concurrent save to
96    // the same destination fails here.
97    fs_err::create_dir(dir)?;
98    let mut cleanup = SnapshotCleanup {
99        files: Vec::new(),
100        dir: Some(dir.to_owned()),
101    };
102
103    // Write device state.
104    write_synced(&mut cleanup, &dir.join("state.bin"), saved_state_bytes)
105        .context("failed to write state.bin")?;
106
107    // Hard-link memory.bin to the backing file.
108    let memory_bin_path = dir.join("memory.bin");
109    let canonical_source = fs_err::canonicalize(memory_file_path)?;
110    if let Err(err) = std::fs::hard_link(&canonical_source, &memory_bin_path) {
111        if err.kind() == io::ErrorKind::CrossesDevices {
112            anyhow::bail!(
113                "memory backing file ({}) must be on the same filesystem as the snapshot \
114                 directory ({})",
115                memory_file_path.display(),
116                dir.display(),
117            );
118        }
119        return Err(err).with_context(|| {
120            format!(
121                "failed to hard-link {} -> {}",
122                canonical_source.display(),
123                memory_bin_path.display()
124            )
125        });
126    }
127    cleanup.files.push(memory_bin_path);
128
129    // Write the manifest last.
130    let manifest_bytes = mesh::payload::encode(manifest.clone());
131    write_synced(&mut cleanup, &dir.join("manifest.bin"), &manifest_bytes)
132        .context("failed to write manifest.bin")?;
133
134    cleanup.disarm();
135    Ok(())
136}