Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions nvx-rs/src/host/cli/store/files.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//! Private, regular, non-link files, atomically replaced and synced under the state lock.

use std::fs;
use std::io;

use super::StateFile;
use super::locked::LockedState;
use crate::host::platform;
use crate::host::store::{files, regular};
use crate::{Error, Result};

/// Bounds a fixed record's paths and identities without reading an unbounded corrupt file.
const MAX_RECORD_BYTES: u64 = 1024 * 1024;

pub(super) fn read(state: &LockedState, name: StateFile) -> Result<Option<Vec<u8>>> {
let path = state.path(name);
let failed = |error| Error::io(format!("cannot read {}", path.display())).with_source(error);
let file = match regular::open_regular(&path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(failed(error)),
};
if let Some(problem) = platform::private_file_problem(&file).map_err(failed)? {
return Err(Error::io(format!(
"the sandbox file {} {problem}",
path.display()
)));
}
regular::read_at_most(file, MAX_RECORD_BYTES, "a sandbox record")
.map(Some)
.map_err(failed)
}

pub(super) fn replace(state: &LockedState, name: StateFile, bytes: &[u8]) -> Result<()> {
if bytes.len() as u64 > MAX_RECORD_BYTES {
return Err(Error::io("the sandbox record exceeds its size bound"));
}
// Refuse an existing unsafe entry rather than replacing it or following its target.
read(state, name)?;
files::write_private(&state.path(name), bytes)?;
files::sync_dir(state.dir())
}

pub(super) fn remove(state: &LockedState, name: StateFile) -> Result<()> {
read(state, name)?;
let path = state.path(name);
fs::remove_file(&path).map_err(|error| {
Error::io(format!("cannot remove {}", path.display())).with_source(error)
})?;
files::sync_dir(state.dir())
}
80 changes: 80 additions & 0 deletions nvx-rs/src/host/cli/store/launch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
//! Locked launch transitions, without spawning, recovery, or process termination.

use super::StateFile;
use super::files;
use super::locked::LockedState;
use super::record::{LaunchJournal, RuntimeRecord};
use crate::host::process::ProcessRef;
use crate::host::runtime::RuntimeIdentity;
use crate::host::vm::{Prepared, SavedVm};
use crate::{Error, Result};

/// A launch whose lock stays borrowed until commit or until its journal is left behind.
#[derive(Debug)]
pub(crate) struct Launch<'a> {
locked: &'a mut LockedState,
journal: LaunchJournal,
}

impl LockedState {
/// Durably publishes the capability and complete prepared journal before the caller spawns.
pub(crate) fn begin_launch(
&mut self,
prepared: &Prepared,
runtime: &RuntimeIdentity,
) -> Result<Launch<'_>> {
if self.journal()?.is_some() || self.runtime()?.is_some() {
return Err(Error::other(
"the sandbox already has a runtime record or an interrupted launch",
));
}
let journal = LaunchJournal::prepared(self, prepared, runtime)?;
files::replace(self, StateFile::Capability, &journal.capability)?;
self.write_record(StateFile::Journal, &journal)?;
Ok(Launch {
locked: self,
journal,
})
}
}

impl Launch<'_> {
/// Records only the caller's spawned process, durably, before changing the in-memory state.
pub(crate) fn record_process(&mut self, process: &ProcessRef) -> Result<()> {
if self.journal.process.is_some() {
return Err(Error::other("the launch has recorded its process already"));
}
let journal = LaunchJournal {
process: Some(process.clone()),
..self.journal.clone()
};
self.locked.write_record(StateFile::Journal, &journal)?;
self.journal = journal;
Ok(())
}

/// Publishes the exact saved VM, only after its matching process was journaled.
///
/// The runtime record is the commit. A failed journal removal keeps that committed record
/// and reports the failure; it never rolls back the commit or signals the VM.
pub(crate) fn commit(self, saved: &SavedVm) -> Result<()> {
if self.journal.process.as_ref() != Some(&saved.process)
|| self.journal.vm_dir != saved.vm_dir.path()
|| self.journal.endpoint != saved.endpoint
|| self.journal.capability != saved.capability
|| self.journal.runtime != saved.runtime
{
return Err(Error::other(
"the saved VM does not match the launch and its journaled process",
));
}
self.locked
.write_record(StateFile::Runtime, &RuntimeRecord::from(saved))?;
files::remove(self.locked, StateFile::Journal).map_err(|error| {
Error::io(format!(
"the VM runtime was committed but its launch journal could not be removed: {error}"
))
.with_source(error)
})
}
}
7 changes: 7 additions & 0 deletions nvx-rs/src/host/cli/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
//! and the Administrators group, as one under the user's profile does. An existing directory that
//! others may access is refused rather than restricted, since they could have placed files in it,
//! or still hold them open. The store creates its files readable only by the current user.
//!
//! A locked launch writes its prepared capability and outputs before spawn, records the spawned
//! process durably, and publishes the caller's exact saved VM only at commit. Dropping an
//! uncommitted launch keeps its journal; these transitions do not recover or signal a process.
#![cfg_attr(
not(test),
expect(
Expand All @@ -34,8 +38,11 @@
)
)]

mod files;
mod launch;
mod locked;
mod names;
mod record;

use std::io;
use std::path::{Path, PathBuf};
Expand Down
159 changes: 159 additions & 0 deletions nvx-rs/src/host/cli/store/record.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//! The fixed launch journal and the caller-saved VM's runtime record.

use std::fmt;
use std::path::PathBuf;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use super::StateFile;
use super::files;
use super::locked::LockedState;
use crate::host::process::ProcessRef;
use crate::host::runtime::RuntimeIdentity;
use crate::host::vm::{Prepared, SavedVm, VmDir, VmOutputs};
use crate::protocol::CAPABILITY_LEN;
use crate::{Error, Result};

#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct LaunchJournal {
pub(super) vm_dir: PathBuf,
pub(super) capability: [u8; CAPABILITY_LEN],
pub(super) log: PathBuf,
pub(super) outcome: PathBuf,
pub(super) endpoint: String,
pub(super) console: Option<String>,
pub(super) runtime: RuntimeIdentity,
pub(super) process: Option<ProcessRef>,
}

impl fmt::Debug for LaunchJournal {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("LaunchJournal")
.field("vm_dir", &self.vm_dir)
.field("log", &self.log)
.field("outcome", &self.outcome)
.field("endpoint", &self.endpoint)
.field("console", &self.console)
.field("runtime", &self.runtime)
.field("process", &self.process)
.finish_non_exhaustive()
}
}

impl LaunchJournal {
pub(super) fn prepared(
state: &LockedState,
prepared: &Prepared,
runtime: &RuntimeIdentity,
) -> Result<Self> {
runtime.check()?;
let vm_dir = VmDir::open(state.dir())?;
let VmOutputs {
log,
outcome,
endpoint,
console,
} = prepared.outputs();
if *log != vm_dir.path().join(StateFile::Log.name())
|| *outcome != vm_dir.path().join(StateFile::Outcome.name())
{
return Err(Error::other(
"the prepared launch belongs to another sandbox directory",
));
}
Ok(Self {
vm_dir: vm_dir.path().to_path_buf(),
capability: *prepared.capability().as_bytes(),
log: log.clone(),
outcome: outcome.clone(),
endpoint: endpoint.clone(),
console: console.clone(),
runtime: runtime.clone(),
process: None,
})
}

pub(crate) fn process(&self) -> Option<&ProcessRef> {
self.process.as_ref()
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(super) struct RuntimeRecord {
vm_dir: PathBuf,
endpoint: String,
capability: [u8; CAPABILITY_LEN],
process: ProcessRef,
runtime: RuntimeIdentity,
}

impl From<&SavedVm> for RuntimeRecord {
fn from(saved: &SavedVm) -> Self {
Self {
vm_dir: saved.vm_dir.path().to_path_buf(),
endpoint: saved.endpoint.clone(),
capability: saved.capability,
process: saved.process.clone(),
runtime: saved.runtime.clone(),
}
}
}

impl LockedState {
pub(crate) fn journal(&self) -> Result<Option<LaunchJournal>> {
self.read_record(StateFile::Journal)
}

pub(crate) fn runtime(&self) -> Result<Option<SavedVm>> {
let Some(record) = self.read_record::<RuntimeRecord>(StateFile::Runtime)? else {
return Ok(None);
};
let vm_dir = VmDir::open(self.dir())?;
if record.vm_dir != vm_dir.path() {
return Err(Error::io(
"the runtime record belongs to another sandbox directory",
));
}
Ok(Some(SavedVm {
vm_dir,
endpoint: record.endpoint,
capability: record.capability,
process: record.process,
runtime: record.runtime,
}))
}

pub(crate) fn capability(&self) -> Result<Option<[u8; CAPABILITY_LEN]>> {
files::read(self, StateFile::Capability)?
.map(|bytes| {
bytes.try_into().map_err(|_| {
Error::io(format!(
"the sandbox capability must hold {CAPABILITY_LEN} bytes"
))
})
})
.transpose()
}

fn read_record<T: DeserializeOwned>(&self, name: StateFile) -> Result<Option<T>> {
files::read(self, name)?
.map(|bytes| {
serde_json::from_slice(&bytes).map_err(|error| {
Error::io(format!("cannot parse {}", self.path(name).display()))
.with_source(error)
})
})
.transpose()
}

pub(super) fn write_record(&self, name: StateFile, record: &impl Serialize) -> Result<()> {
let bytes = serde_json::to_vec(record).map_err(|error| {
Error::io(format!("cannot serialize {}", self.path(name).display())).with_source(error)
})?;
files::replace(self, name, &bytes)
}
}
2 changes: 2 additions & 0 deletions nvx-rs/src/host/cli/store/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use super::*;
use crate::host::cli::deadline::Deadline;
use crate::host::store::{JOURNAL_NAME, RUNTIME_NAME, SandboxStore};

mod launch;

/// How long a test waits for a lock that it released to be free.
///
/// A process that a concurrent test spawns holds a copy of each descriptor of the test process
Expand Down
Loading
Loading