Skip to content

Commit 2e41db7

Browse files
Enrique SaurezCopilot
authored andcommitted
host: keep immutable named CLI snapshots
Port only SL3.7a commits 5a5cebc and 593a17d onto the actual preserved-parent reader/CLI input join 4662351. Validate and publish whole private snapshots without replacement, keep the exclusive per-name lock outside each immutable entry, and record only the restored sandbox's own source name. Reuse existing CLI privacy/locking helpers. No capture, restore, index, shared-lock mode or blockless driver is added. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 0c8e42ad-4102-451f-96f0-0a4ae0483d1a
1 parent eba4c8b commit 2e41db7

7 files changed

Lines changed: 473 additions & 41 deletions

File tree

‎nvx-rs/src/host/cli/mod.rs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,55 @@ mod run;
4747
mod sandbox;
4848
mod session;
4949
mod shell;
50+
mod snapshots;
5051
mod store;
5152

5253
use std::borrow::Cow;
5354
use std::ffi::OsString;
54-
use std::path::Path;
55+
use std::path::{Path, PathBuf};
5556

5657
use self::args::{Parser, Receiver, Spec, Stop, Syntax};
5758
use crate::ErrorCode;
5859
use crate::host::platform;
5960

61+
/// Returns the name of a temporary file next to `path`: `.NAME.UUID.tmp`, with a fresh UUID4 in
62+
/// hexadecimal.
63+
pub(crate) fn temporary_path(path: &Path) -> Result<PathBuf> {
64+
let Some(name) = path.file_name() else {
65+
return Err(Exit::error(
66+
ErrorCode::Other,
67+
format!("{} has an empty name", path.display()),
68+
));
69+
};
70+
let mut temporary = OsString::from(".");
71+
temporary.push(name);
72+
temporary.push(format!(".{}.tmp", uuid4_hex()?));
73+
Ok(path.with_file_name(temporary))
74+
}
75+
76+
/// Returns 32 lowercase hexadecimal digits of 122 random bits, with the version and variant bits
77+
/// of a version-4 UUID.
78+
fn uuid4_hex() -> Result<String> {
79+
let mut bytes = random_bytes::<16>()?;
80+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
81+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
82+
Ok(hex(&bytes))
83+
}
84+
85+
/// Returns `N` random bytes from the operating system.
86+
pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N]> {
87+
let mut bytes = [0u8; N];
88+
getrandom::fill(&mut bytes).map_err(|error| {
89+
Exit::error(ErrorCode::Io, format!("cannot read random bytes: {error}"))
90+
})?;
91+
Ok(bytes)
92+
}
93+
94+
/// Returns `bytes` in lowercase hexadecimal.
95+
pub(crate) fn hex(bytes: &[u8]) -> String {
96+
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
97+
}
98+
6099
/// The commands, in the order in which usage messages list them.
61100
const COMMANDS: [&str; 5] = ["artifacts", "download", "egress", "run", "sandbox"];
62101
/// The options of the top-level parser.

‎nvx-rs/src/host/cli/sandbox/state.rs‎

Lines changed: 36 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,9 @@
3030
//! [`Config::network`] reads back for `start` to render. It replaces the network options that
3131
//! `nvx.py` recorded, which no reader reads: `start` refuses a configuration without it.
3232
33-
use std::ffi::OsString;
3433
use std::fs::OpenOptions;
3534
use std::io::Write;
36-
use std::path::{Path, PathBuf};
35+
use std::path::Path;
3736

3837
use serde::de::DeserializeOwned;
3938
use serde::{Deserialize, Deserializer, Serialize};
@@ -44,6 +43,7 @@ use super::{MAX_MEMORY_MIB, path_string};
4443
use crate::ErrorCode;
4544
use crate::host::cli::json::{Object, pretty_serde, read_object};
4645
use crate::host::cli::output::LINE_SEPARATOR;
46+
use crate::host::cli::snapshots::Name as SnapshotName;
4747
use crate::host::cli::{Exit, Result, io_error, io_message};
4848
use crate::host::filesystem::ExportPlan;
4949
use crate::host::paths;
@@ -53,6 +53,11 @@ use crate::host::sandbox::scratch::ScratchBinding;
5353
use crate::host::sandbox::{SandboxLaunch, SandboxNetwork, SandboxSettings, SandboxUpper};
5454
use crate::protocol::root::RootUpper;
5555

56+
pub(crate) use crate::host::cli::{hex, random_bytes, temporary_path};
57+
58+
#[cfg(test)]
59+
mod tests;
60+
5661
/// The configuration that earlier builds wrote for a sandbox without shares, whose `mount` is
5762
/// `null`, which `start` still reads.
5863
pub(crate) const CONFIG_FORMAT: u64 = 1;
@@ -69,44 +74,6 @@ pub(crate) const CONFIG_FORMATS: [u64; 3] =
6974
/// What messages call a configuration.
7075
const DESCRIPTION: &str = "sandbox configuration";
7176

72-
/// Returns the name of a temporary file next to `path`: `.NAME.UUID.tmp`, with a fresh UUID4 in
73-
/// hexadecimal.
74-
pub(crate) fn temporary_path(path: &Path) -> Result<PathBuf> {
75-
let Some(name) = path.file_name() else {
76-
return Err(Exit::error(
77-
ErrorCode::Other,
78-
format!("{} has an empty name", path.display()),
79-
));
80-
};
81-
let mut temporary = OsString::from(".");
82-
temporary.push(name);
83-
temporary.push(format!(".{}.tmp", uuid4_hex()?));
84-
Ok(path.with_file_name(temporary))
85-
}
86-
87-
/// Returns 32 lowercase hexadecimal digits of 122 random bits, with the version and variant bits
88-
/// of a version-4 UUID.
89-
pub(crate) fn uuid4_hex() -> Result<String> {
90-
let mut bytes = random_bytes::<16>()?;
91-
bytes[6] = (bytes[6] & 0x0f) | 0x40;
92-
bytes[8] = (bytes[8] & 0x3f) | 0x80;
93-
Ok(hex(&bytes))
94-
}
95-
96-
/// Returns `N` random bytes from the operating system.
97-
pub(crate) fn random_bytes<const N: usize>() -> Result<[u8; N]> {
98-
let mut bytes = [0u8; N];
99-
getrandom::fill(&mut bytes).map_err(|error| {
100-
Exit::error(ErrorCode::Io, format!("cannot read random bytes: {error}"))
101-
})?;
102-
Ok(bytes)
103-
}
104-
105-
/// Returns `bytes` in lowercase hexadecimal.
106-
pub(crate) fn hex(bytes: &[u8]) -> String {
107-
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
108-
}
109-
11077
/// Atomically replaces `path` with the JSON `text` and a line end, with the line separator of the
11178
/// host for each `\n`, in a temporary file of mode 0600 that then replaces `path`.
11279
pub(crate) fn write_json(path: &Path, text: &str) -> Result {
@@ -280,6 +247,9 @@ struct Record<'a> {
280247
scratch_binding: Option<&'a ScratchBinding>,
281248
/// The export plan of the shares, or `None` without shares.
282249
export: Option<&'a ExportPlan>,
250+
/// The immutable named snapshot that supplies this sandbox's restore view.
251+
#[serde(skip_serializing_if = "Option::is_none")]
252+
source_snapshot: Option<&'a SnapshotName>,
283253
}
284254

285255
/// Returns the JSON text of the configuration that `provision` records for `launch` and the other
@@ -291,6 +261,17 @@ pub(crate) fn serialize_launch(
291261
distro: &RecordedDistro,
292262
scratch: Option<&RecordedScratch>,
293263
config: &ProvisionConfig<'_>,
264+
) -> Result<String> {
265+
serialize_launch_with_snapshot(launch, distro, scratch, config, None)
266+
}
267+
268+
/// Records a restored sandbox's source alongside its own launch, without a snapshot index.
269+
pub(crate) fn serialize_launch_with_snapshot(
270+
launch: &SandboxLaunch,
271+
distro: &RecordedDistro,
272+
scratch: Option<&RecordedScratch>,
273+
config: &ProvisionConfig<'_>,
274+
source_snapshot: Option<&SnapshotName>,
294275
) -> Result<String> {
295276
let layer = &distro.layer;
296277
let settings = launch.settings();
@@ -314,6 +295,7 @@ pub(crate) fn serialize_launch(
314295
distro_binding: &distro.binding,
315296
scratch_binding: scratch.map(|scratch| &scratch.binding),
316297
export: launch.export(),
298+
source_snapshot,
317299
};
318300
pretty_serde(&record, DESCRIPTION)
319301
}
@@ -375,9 +357,22 @@ pub(crate) struct Config {
375357
/// The sandbox's network, `null` for none, if recorded.
376358
#[serde(default, deserialize_with = "present")]
377359
network: Option<Value>,
360+
/// The source of a restored sandbox, absent for a cold launch.
361+
source_snapshot: Option<SnapshotName>,
378362
}
379363

380364
impl Config {
365+
#[cfg_attr(
366+
not(test),
367+
expect(
368+
dead_code,
369+
reason = "SL3.8a locks a restored sandbox's source snapshot"
370+
)
371+
)]
372+
pub(crate) fn source_snapshot(&self) -> Option<&SnapshotName> {
373+
self.source_snapshot.as_ref()
374+
}
375+
381376
/// Returns the fields of `object`, a configuration that [`read_config`] read, which fails as
382377
/// `sandbox configuration is malformed` without a field that it requires, or with a value of
383378
/// another type.
@@ -403,6 +398,7 @@ impl Config {
403398
),
404399
));
405400
}
401+
406402
serde_json::from_value(Value::Object(object)).map_err(|_| malformed())
407403
}
408404

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use super::*;
2+
use crate::host::sandbox::layer::LayerRole;
3+
4+
#[test]
5+
fn restored_sandbox_records_round_trip_only_their_own_snapshot_name() {
6+
let directory = tempfile::tempdir().unwrap();
7+
let image = directory.path().join("distro.erofs");
8+
std::fs::write(&image, b"distro layer\n").unwrap();
9+
let layer = SandboxLayer::new(
10+
LayerRole::Distro,
11+
image.to_str().unwrap(),
12+
"11111111-1111-1111-1111-111111111111",
13+
);
14+
let binding = DistroBinding::verify(&layer).unwrap();
15+
let launch =
16+
SandboxLaunch::new(vec![layer], SandboxUpper::RAM, SandboxSettings::default()).unwrap();
17+
let distro = RecordedDistro::new(&launch, binding).unwrap();
18+
let options = ProvisionConfig {
19+
hypervisor: "whp",
20+
memory_mib: 128,
21+
cmdline: "",
22+
};
23+
for source in [None, Some("My.snapshot-1"), Some("other")] {
24+
let name = source.map(|name| SnapshotName::try_from(name.to_owned()).unwrap());
25+
let text = serialize_launch_with_snapshot(&launch, &distro, None, &options, name.as_ref())
26+
.unwrap();
27+
let object: Object = serde_json::from_str(&text).unwrap();
28+
assert_eq!(object.contains_key("source_snapshot"), source.is_some());
29+
let record = Config::new(object.clone()).unwrap();
30+
assert_eq!(record.source_snapshot(), name.as_ref());
31+
let mut malformed = object;
32+
malformed.insert("source_snapshot".to_owned(), Value::from("../other"));
33+
assert!(Config::new(malformed).is_err());
34+
}
35+
}

‎nvx-rs/src/host/cli/snapshots.rs‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
//! Immutable named snapshots and their external, exclusive locks.
2+
//!
3+
//! Names map to hexadecimal directory names under `snapshots/`. Each published directory
4+
//! contains only the strict snapshot's three entries; its lock stays under `locks/`.
5+
//! Completed private directories under `staging/` publish with one non-replacing rename.
6+
#![cfg_attr(
7+
not(test),
8+
expect(dead_code, reason = "SL3.7b and SL3.8a use the named snapshot store")
9+
)]
10+
11+
use std::path::{Path, PathBuf};
12+
13+
use serde::{Deserialize, Serialize};
14+
15+
use super::deadline::Deadline;
16+
use super::store::{LockedState, StateDir};
17+
use super::{Exit, Result, hex, io_error, temporary_path};
18+
use crate::host::snapshot::Snapshot;
19+
use crate::host::{platform, store};
20+
use crate::{Error, ErrorCode};
21+
22+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23+
#[serde(try_from = "String")]
24+
pub(crate) struct Name(String);
25+
26+
impl TryFrom<String> for Name {
27+
type Error = Error;
28+
29+
fn try_from(value: String) -> crate::Result<Self> {
30+
if !(1..=64).contains(&value.len())
31+
|| !value.as_bytes()[0].is_ascii_alphanumeric()
32+
|| !value
33+
.bytes()
34+
.all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
35+
{
36+
return Err(Error::unsupported(
37+
"a snapshot name must be 1 to 64 ASCII letters, digits, dots, underscores or \
38+
hyphens, starting with a letter or digit",
39+
));
40+
}
41+
Ok(Self(value))
42+
}
43+
}
44+
45+
#[derive(Debug)]
46+
pub(crate) struct Store {
47+
root: StateDir,
48+
entries: StateDir,
49+
locks: StateDir,
50+
staging: StateDir,
51+
}
52+
53+
impl Store {
54+
pub(crate) fn create(root: &Path) -> Result<Self> {
55+
let root = StateDir::create(&std::path::absolute(root).map_err(Exit::from_os_error)?)?;
56+
Ok(Self {
57+
entries: StateDir::create(&root.dir().join("snapshots"))?,
58+
locks: StateDir::create(&root.dir().join("locks"))?,
59+
staging: StateDir::create(&root.dir().join("staging"))?,
60+
root,
61+
})
62+
}
63+
64+
fn check(&self) -> Result {
65+
for directory in [&self.root, &self.entries, &self.locks, &self.staging] {
66+
StateDir::open(directory.dir())?;
67+
}
68+
Ok(())
69+
}
70+
71+
pub(crate) fn lock(&self, name: &Name, deadline: Deadline) -> Result<LockedSnapshot<'_>> {
72+
self.check()?;
73+
// Hex preserves case distinctions and avoids reserved host filenames.
74+
let directory = hex(name.0.as_bytes());
75+
let lock = StateDir::create(&self.locks.dir().join(&directory))?.lock(deadline)?;
76+
Ok(LockedSnapshot {
77+
store: self,
78+
dir: self.entries.dir().join(directory),
79+
_lock: lock,
80+
})
81+
}
82+
}
83+
84+
#[derive(Debug)]
85+
pub(crate) struct LockedSnapshot<'a> {
86+
store: &'a Store,
87+
dir: PathBuf,
88+
_lock: LockedState,
89+
}
90+
91+
impl LockedSnapshot<'_> {
92+
pub(crate) fn stage(&self) -> Result<StateDir> {
93+
self.store.check()?;
94+
StateDir::create(&temporary_path(&self.store.staging.dir().join("snapshot"))?)
95+
}
96+
97+
pub(crate) fn open(&self) -> Result<Snapshot> {
98+
self.store.check()?;
99+
Snapshot::open(&self.dir).map_err(Into::into)
100+
}
101+
102+
pub(crate) fn publish(&self, staged: StateDir) -> Result<Snapshot> {
103+
self.store.check()?;
104+
if staged.dir().parent() != Some(self.store.staging.dir()) {
105+
return Err(Exit::error(
106+
ErrorCode::Io,
107+
"only a private staging directory can publish a named snapshot",
108+
));
109+
}
110+
Snapshot::open(staged.dir())?;
111+
store::files::sync_dir(staged.dir())?;
112+
platform::rename_no_replace(staged.dir(), &self.dir)
113+
.map_err(|error| io_error(ErrorCode::Io, &error, &self.dir))?;
114+
store::files::sync_dir(self.store.entries.dir())?;
115+
store::files::sync_dir(self.store.staging.dir())?;
116+
self.open()
117+
}
118+
}
119+
120+
#[cfg(test)]
121+
mod tests;

0 commit comments

Comments
 (0)