openvmm_helpers/snapshot/
publish.rs1use super::SnapshotManifest;
7use anyhow::Context;
8use std::io;
9use std::io::Write;
10use std::path::Path;
11use std::path::PathBuf;
12
13pub 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
24struct 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 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 let _ = std::fs::remove_dir(dir);
56 }
57 }
58}
59
60fn 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
73pub 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 fs_err::create_dir(dir)?;
98 let mut cleanup = SnapshotCleanup {
99 files: Vec::new(),
100 dir: Some(dir.to_owned()),
101 };
102
103 write_synced(&mut cleanup, &dir.join("state.bin"), saved_state_bytes)
105 .context("failed to write state.bin")?;
106
107 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 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}