ic_backup/ops/persistence/layout_lifetime/
mod.rs1use crate::{
4 model::restore_references::{RestoreReferenceRecord, RestoreReferencesRecord},
5 ops::persistence::{
6 JournalLock, JournalLockError, PersistenceError, read_json, write_json_durable,
7 },
8};
9use ic_host_artifacts::artifact::Sha256Digest;
10use std::{
11 fs::{self, File},
12 io,
13 path::{Path, PathBuf},
14};
15
16const REFERENCES_FILE: &str = "restore-references.json";
17pub const MAX_RESTORE_REFERENCE_BYTES: u64 = 1024 * 1024;
19
20#[derive(Debug)]
25pub struct BackupLayoutGuard {
26 root: PathBuf,
27 directory: File,
28 _lock: JournalLock,
29}
30
31impl BackupLayoutGuard {
32 pub fn acquire(root: &Path) -> Result<Self, JournalLockError> {
40 let root = root.canonicalize()?;
41 let parent = root
42 .parent()
43 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
44 let name = root
45 .file_name()
46 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
47 let key = Sha256Digest::compute(name.as_encoded_bytes()).to_string();
48 let lock = JournalLock::acquire(&parent.join(format!(".ic-backup-layout-{key}")))?;
49 let directory = open_directory(&root)?;
50 Ok(Self {
51 root,
52 directory,
53 _lock: lock,
54 })
55 }
56
57 #[must_use]
59 pub fn root(&self) -> &Path {
60 &self.root
61 }
62
63 pub fn restore_references(&self) -> Result<RestoreReferencesRecord, PersistenceError> {
68 self.check_root()?;
69 let path = self.root.join(REFERENCES_FILE);
70 match fs::symlink_metadata(&path) {
71 Err(error) if error.kind() == io::ErrorKind::NotFound => {
72 return Ok(RestoreReferencesRecord::empty());
73 }
74 Err(error) => return Err(error.into()),
75 Ok(metadata) if !metadata.is_file() => {
76 return Err(PersistenceError::InvalidRestoreReferences { path });
77 }
78 Ok(_) => {}
79 }
80 read_json(&path, MAX_RESTORE_REFERENCE_BYTES)
81 }
82
83 pub fn has_restore_references(&self) -> Result<bool, PersistenceError> {
88 Ok(!self.restore_references()?.is_empty())
89 }
90
91 pub fn retain_restore(
100 &self,
101 journal: &Path,
102 authority: &str,
103 ) -> Result<RestoreReferenceRecord, PersistenceError> {
104 self.retain_with(journal, authority, write_json_durable)
105 }
106
107 fn retain_with(
108 &self,
109 journal: &Path,
110 authority: &str,
111 write: impl FnOnce(&Path, &RestoreReferencesRecord) -> Result<(), PersistenceError>,
112 ) -> Result<RestoreReferenceRecord, PersistenceError> {
113 let mut references = self.restore_references()?;
114 let reference = RestoreReferenceRecord::new(journal_identity(journal)?, authority)?;
115 let path = self.root.join(REFERENCES_FILE);
116 if references.retain(reference.clone())? {
117 super::json::check_json_size(&references, MAX_RESTORE_REFERENCE_BYTES)?;
118 write(&path, &references)?;
119 } else {
120 sync_reference(&path)?;
122 self.directory.sync_all()?;
123 }
124 Ok(reference)
125 }
126
127 pub(super) fn sync_references(&self) -> Result<(), PersistenceError> {
128 self.check_root()?;
129 let path = self.root.join(REFERENCES_FILE);
130 match fs::symlink_metadata(&path) {
131 Ok(_) => sync_reference(&path)?,
132 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
133 Err(error) => return Err(error.into()),
134 }
135 self.directory.sync_all()?;
136 Ok(())
137 }
138
139 pub(super) fn check_root(&self) -> Result<(), PersistenceError> {
140 #[cfg(unix)]
141 {
142 use std::os::unix::fs::MetadataExt;
143 let current = fs::symlink_metadata(&self.root)?;
144 let held = self.directory.metadata()?;
145 if current.is_dir() && current.dev() == held.dev() && current.ino() == held.ino() {
146 return Ok(());
147 }
148 }
149 Err(PersistenceError::LayoutChanged {
150 path: self.root.clone(),
151 })
152 }
153}
154
155pub(super) fn journal_identity(path: &Path) -> Result<PathBuf, PersistenceError> {
156 let name = path
157 .file_name()
158 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
159 let parent = path
160 .parent()
161 .filter(|parent| !parent.as_os_str().is_empty())
162 .unwrap_or_else(|| Path::new("."));
163 let parent = parent.canonicalize()?;
164 if !parent.is_dir() {
165 return Err(io::Error::from(io::ErrorKind::NotADirectory).into());
166 }
167 let journal = parent.join(name);
168 match fs::symlink_metadata(&journal) {
169 Ok(metadata) if !metadata.is_file() => {
170 return Err(PersistenceError::InvalidRestoreReferences { path: journal });
171 }
172 Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error.into()),
173 _ => {}
174 }
175 Ok(journal)
176}
177
178fn open_directory(path: &Path) -> io::Result<File> {
179 #[cfg(unix)]
180 {
181 use rustix::fs::{Mode, OFlags, open};
182 let fd = open(
183 path,
184 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
185 Mode::empty(),
186 )
187 .map_err(io::Error::from)?;
188 Ok(File::from(fd))
189 }
190 #[cfg(not(unix))]
191 {
192 let _ = path;
193 Err(io::Error::from(io::ErrorKind::Unsupported))
194 }
195}
196
197fn sync_reference(path: &Path) -> io::Result<()> {
198 #[cfg(unix)]
199 {
200 use rustix::fs::{FileType, Mode, OFlags, fstat, open};
201 let fd = open(
202 path,
203 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
204 Mode::empty(),
205 )
206 .map_err(io::Error::from)?;
207 let metadata = fstat(&fd).map_err(io::Error::from)?;
208 if !FileType::from_raw_mode(metadata.st_mode).is_file() {
209 return Err(io::Error::from(io::ErrorKind::InvalidInput));
210 }
211 File::from(fd).sync_all()
212 }
213 #[cfg(not(unix))]
214 {
215 let _ = path;
216 Err(io::Error::from(io::ErrorKind::Unsupported))
217 }
218}
219
220#[cfg(all(test, unix))]
221mod tests;