Skip to content

Commit 99d0045

Browse files
Enrique SaurezCopilot
andcommitted
host: journal CLI launches and persist saved VM records
Port the scoped SL3.2b donor cf485b7 onto verified feature c52c710 without its historical producer history. Persist prepared capability and outputs before spawn, the matching process before commit, and every SavedVm field in the private runtime record. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: eb3cc7e0-f51e-45ed-b911-c7b214740e05
1 parent c52c710 commit 99d0045

6 files changed

Lines changed: 681 additions & 0 deletions

File tree

‎nvx-rs/src/host/cli/store/files.rs‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
//! Private, regular, non-link files, atomically replaced and synced under the state lock.
2+
3+
use std::fs;
4+
use std::io;
5+
6+
use super::StateFile;
7+
use super::locked::LockedState;
8+
use crate::host::platform;
9+
use crate::host::store::{files, regular};
10+
use crate::{Error, Result};
11+
12+
/// Bounds a fixed record's paths and identities without reading an unbounded corrupt file.
13+
const MAX_RECORD_BYTES: u64 = 1024 * 1024;
14+
15+
pub(super) fn read(state: &LockedState, name: StateFile) -> Result<Option<Vec<u8>>> {
16+
let path = state.path(name);
17+
let failed = |error| Error::io(format!("cannot read {}", path.display())).with_source(error);
18+
let file = match regular::open_regular(&path) {
19+
Ok(file) => file,
20+
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
21+
Err(error) => return Err(failed(error)),
22+
};
23+
if let Some(problem) = platform::private_file_problem(&file).map_err(failed)? {
24+
return Err(Error::io(format!(
25+
"the sandbox file {} {problem}",
26+
path.display()
27+
)));
28+
}
29+
regular::read_at_most(file, MAX_RECORD_BYTES, "a sandbox record")
30+
.map(Some)
31+
.map_err(failed)
32+
}
33+
34+
pub(super) fn replace(state: &LockedState, name: StateFile, bytes: &[u8]) -> Result<()> {
35+
if bytes.len() as u64 > MAX_RECORD_BYTES {
36+
return Err(Error::io("the sandbox record exceeds its size bound"));
37+
}
38+
// Refuse an existing unsafe entry rather than replacing it or following its target.
39+
read(state, name)?;
40+
files::write_private(&state.path(name), bytes)?;
41+
files::sync_dir(state.dir())
42+
}
43+
44+
pub(super) fn remove(state: &LockedState, name: StateFile) -> Result<()> {
45+
read(state, name)?;
46+
let path = state.path(name);
47+
fs::remove_file(&path).map_err(|error| {
48+
Error::io(format!("cannot remove {}", path.display())).with_source(error)
49+
})?;
50+
files::sync_dir(state.dir())
51+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
//! Locked launch transitions, without spawning, recovery, or process termination.
2+
3+
use super::StateFile;
4+
use super::files;
5+
use super::locked::LockedState;
6+
use super::record::{LaunchJournal, RuntimeRecord};
7+
use crate::host::process::ProcessRef;
8+
use crate::host::runtime::RuntimeIdentity;
9+
use crate::host::vm::{Prepared, SavedVm};
10+
use crate::{Error, Result};
11+
12+
/// A launch whose lock stays borrowed until commit or until its journal is left behind.
13+
#[derive(Debug)]
14+
pub(crate) struct Launch<'a> {
15+
locked: &'a mut LockedState,
16+
journal: LaunchJournal,
17+
}
18+
19+
impl LockedState {
20+
/// Durably publishes the capability and complete prepared journal before the caller spawns.
21+
pub(crate) fn begin_launch(
22+
&mut self,
23+
prepared: &Prepared,
24+
runtime: &RuntimeIdentity,
25+
) -> Result<Launch<'_>> {
26+
if self.journal()?.is_some() || self.runtime()?.is_some() {
27+
return Err(Error::other(
28+
"the sandbox already has a runtime record or an interrupted launch",
29+
));
30+
}
31+
let journal = LaunchJournal::prepared(self, prepared, runtime)?;
32+
files::replace(self, StateFile::Capability, &journal.capability)?;
33+
self.write_record(StateFile::Journal, &journal)?;
34+
Ok(Launch {
35+
locked: self,
36+
journal,
37+
})
38+
}
39+
}
40+
41+
impl Launch<'_> {
42+
/// Records only the caller's spawned process, durably, before changing the in-memory state.
43+
pub(crate) fn record_process(&mut self, process: &ProcessRef) -> Result<()> {
44+
if self.journal.process.is_some() {
45+
return Err(Error::other("the launch has recorded its process already"));
46+
}
47+
let journal = LaunchJournal {
48+
process: Some(process.clone()),
49+
..self.journal.clone()
50+
};
51+
self.locked.write_record(StateFile::Journal, &journal)?;
52+
self.journal = journal;
53+
Ok(())
54+
}
55+
56+
/// Publishes the exact saved VM, only after its matching process was journaled.
57+
///
58+
/// The runtime record is the commit. A failed journal removal keeps that committed record
59+
/// and reports the failure; it never rolls back the commit or signals the VM.
60+
pub(crate) fn commit(self, saved: &SavedVm) -> Result<()> {
61+
if self.journal.process.as_ref() != Some(&saved.process)
62+
|| self.journal.vm_dir != saved.vm_dir.path()
63+
|| self.journal.endpoint != saved.endpoint
64+
|| self.journal.capability != saved.capability
65+
|| self.journal.runtime != saved.runtime
66+
{
67+
return Err(Error::other(
68+
"the saved VM does not match the launch and its journaled process",
69+
));
70+
}
71+
self.locked
72+
.write_record(StateFile::Runtime, &RuntimeRecord::from(saved))?;
73+
files::remove(self.locked, StateFile::Journal).map_err(|error| {
74+
Error::io(format!(
75+
"the VM runtime was committed but its launch journal could not be removed: {error}"
76+
))
77+
.with_source(error)
78+
})
79+
}
80+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
//! and the Administrators group, as one under the user's profile does. An existing directory that
2727
//! others may access is refused rather than restricted, since they could have placed files in it,
2828
//! or still hold them open. The store creates its files readable only by the current user.
29+
//!
30+
//! A locked launch writes its prepared capability and outputs before spawn, records the spawned
31+
//! process durably, and publishes the caller's exact saved VM only at commit. Dropping an
32+
//! uncommitted launch keeps its journal; these transitions do not recover or signal a process.
2933
#![cfg_attr(
3034
not(test),
3135
expect(
@@ -34,8 +38,11 @@
3438
)
3539
)]
3640

41+
mod files;
42+
mod launch;
3743
mod locked;
3844
mod names;
45+
mod record;
3946

4047
use std::io;
4148
use std::path::{Path, PathBuf};
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
//! The fixed launch journal and the caller-saved VM's runtime record.
2+
3+
use std::fmt;
4+
use std::path::PathBuf;
5+
6+
use serde::de::DeserializeOwned;
7+
use serde::{Deserialize, Serialize};
8+
9+
use super::StateFile;
10+
use super::files;
11+
use super::locked::LockedState;
12+
use crate::host::process::ProcessRef;
13+
use crate::host::runtime::RuntimeIdentity;
14+
use crate::host::vm::{Prepared, SavedVm, VmDir, VmOutputs};
15+
use crate::protocol::CAPABILITY_LEN;
16+
use crate::{Error, Result};
17+
18+
#[derive(Clone, Serialize, Deserialize)]
19+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
20+
pub(crate) struct LaunchJournal {
21+
pub(super) vm_dir: PathBuf,
22+
pub(super) capability: [u8; CAPABILITY_LEN],
23+
pub(super) log: PathBuf,
24+
pub(super) outcome: PathBuf,
25+
pub(super) endpoint: String,
26+
pub(super) console: Option<String>,
27+
pub(super) runtime: RuntimeIdentity,
28+
pub(super) process: Option<ProcessRef>,
29+
}
30+
31+
impl fmt::Debug for LaunchJournal {
32+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33+
formatter
34+
.debug_struct("LaunchJournal")
35+
.field("vm_dir", &self.vm_dir)
36+
.field("log", &self.log)
37+
.field("outcome", &self.outcome)
38+
.field("endpoint", &self.endpoint)
39+
.field("console", &self.console)
40+
.field("runtime", &self.runtime)
41+
.field("process", &self.process)
42+
.finish_non_exhaustive()
43+
}
44+
}
45+
46+
impl LaunchJournal {
47+
pub(super) fn prepared(
48+
state: &LockedState,
49+
prepared: &Prepared,
50+
runtime: &RuntimeIdentity,
51+
) -> Result<Self> {
52+
runtime.check()?;
53+
let vm_dir = VmDir::open(state.dir())?;
54+
let VmOutputs {
55+
log,
56+
outcome,
57+
endpoint,
58+
console,
59+
} = prepared.outputs();
60+
if *log != vm_dir.path().join(StateFile::Log.name())
61+
|| *outcome != vm_dir.path().join(StateFile::Outcome.name())
62+
{
63+
return Err(Error::other(
64+
"the prepared launch belongs to another sandbox directory",
65+
));
66+
}
67+
Ok(Self {
68+
vm_dir: vm_dir.path().to_path_buf(),
69+
capability: *prepared.capability().as_bytes(),
70+
log: log.clone(),
71+
outcome: outcome.clone(),
72+
endpoint: endpoint.clone(),
73+
console: console.clone(),
74+
runtime: runtime.clone(),
75+
process: None,
76+
})
77+
}
78+
79+
pub(crate) fn process(&self) -> Option<&ProcessRef> {
80+
self.process.as_ref()
81+
}
82+
}
83+
84+
#[derive(Serialize, Deserialize)]
85+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
86+
pub(super) struct RuntimeRecord {
87+
vm_dir: PathBuf,
88+
endpoint: String,
89+
capability: [u8; CAPABILITY_LEN],
90+
process: ProcessRef,
91+
runtime: RuntimeIdentity,
92+
}
93+
94+
impl From<&SavedVm> for RuntimeRecord {
95+
fn from(saved: &SavedVm) -> Self {
96+
Self {
97+
vm_dir: saved.vm_dir.path().to_path_buf(),
98+
endpoint: saved.endpoint.clone(),
99+
capability: saved.capability,
100+
process: saved.process.clone(),
101+
runtime: saved.runtime.clone(),
102+
}
103+
}
104+
}
105+
106+
impl LockedState {
107+
pub(crate) fn journal(&self) -> Result<Option<LaunchJournal>> {
108+
self.read_record(StateFile::Journal)
109+
}
110+
111+
pub(crate) fn runtime(&self) -> Result<Option<SavedVm>> {
112+
let Some(record) = self.read_record::<RuntimeRecord>(StateFile::Runtime)? else {
113+
return Ok(None);
114+
};
115+
let vm_dir = VmDir::open(self.dir())?;
116+
if record.vm_dir != vm_dir.path() {
117+
return Err(Error::io(
118+
"the runtime record belongs to another sandbox directory",
119+
));
120+
}
121+
Ok(Some(SavedVm {
122+
vm_dir,
123+
endpoint: record.endpoint,
124+
capability: record.capability,
125+
process: record.process,
126+
runtime: record.runtime,
127+
}))
128+
}
129+
130+
pub(crate) fn capability(&self) -> Result<Option<[u8; CAPABILITY_LEN]>> {
131+
files::read(self, StateFile::Capability)?
132+
.map(|bytes| {
133+
bytes.try_into().map_err(|_| {
134+
Error::io(format!(
135+
"the sandbox capability must hold {CAPABILITY_LEN} bytes"
136+
))
137+
})
138+
})
139+
.transpose()
140+
}
141+
142+
fn read_record<T: DeserializeOwned>(&self, name: StateFile) -> Result<Option<T>> {
143+
files::read(self, name)?
144+
.map(|bytes| {
145+
serde_json::from_slice(&bytes).map_err(|error| {
146+
Error::io(format!("cannot parse {}", self.path(name).display()))
147+
.with_source(error)
148+
})
149+
})
150+
.transpose()
151+
}
152+
153+
pub(super) fn write_record(&self, name: StateFile, record: &impl Serialize) -> Result<()> {
154+
let bytes = serde_json::to_vec(record).map_err(|error| {
155+
Error::io(format!("cannot serialize {}", self.path(name).display())).with_source(error)
156+
})?;
157+
files::replace(self, name, &bytes)
158+
}
159+
}

‎nvx-rs/src/host/cli/store/tests.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ use super::*;
88
use crate::host::cli::deadline::Deadline;
99
use crate::host::store::{JOURNAL_NAME, RUNTIME_NAME, SandboxStore};
1010

11+
mod launch;
12+
1113
/// How long a test waits for a lock that it released to be free.
1214
///
1315
/// A process that a concurrent test spawns holds a copy of each descriptor of the test process

0 commit comments

Comments
 (0)