Skip to content
Open
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
149 changes: 124 additions & 25 deletions vmm_core/state_unit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::hash_map;
use std::fmt::Debug;
use std::fmt::Display;
use std::future::Future;
Expand Down Expand Up @@ -241,10 +240,39 @@ struct Unit {
inspect_sensitivity: inspect::SensitivityLevel,
}

/// An error returned when a state unit name is already in use.
/// An error returned when a state unit cannot be added to a set.
///
/// A unit that cannot be added leaves the set unchanged.
#[derive(Debug, Error)]
#[error("state unit name {0} is in use")]
pub struct NameInUse(Arc<str>);
pub enum UnitBuildError {
/// Another unit in the set has the name.
#[error("state unit name {0} is in use")]
NameInUse(Arc<str>),
/// A unit that the new unit depends on, or is a dependency of, has been
/// removed from the set.
#[error("state unit {unit} refers to removed state unit {removed}")]
RemovedUnit {
/// The name of the new unit.
unit: Arc<str>,
/// The name of the removed unit.
removed: Arc<str>,
},
/// The new unit would depend, directly or through other units, on a unit
/// that it would also be a dependency of. No state change that orders the
/// units could complete with such a cycle.
#[error("state unit {unit} would form a dependency cycle with state unit {dependent}")]
DependencyCycle {
/// The name of the new unit.
unit: Arc<str>,
/// The name of the unit that the new unit would both depend on and be a
/// dependency of.
dependent: Arc<str>,
},
}

/// The error returned by [`UnitBuilder::build`] and [`UnitBuilder::spawn`],
/// under its name from when they only checked the unit name.
pub type NameInUse = UnitBuildError;
Comment on lines +273 to +275

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Get rid of this, just fix callers


#[derive(Debug, Error)]
#[error("critical unit communication failure: {name}")]
Expand Down Expand Up @@ -475,8 +503,8 @@ impl StateUnits {
UnitBuilder {
units: self,
name: name.into(),
dependencies: BTreeSet::new(),
dependents: BTreeSet::new(),
dependencies: BTreeMap::new(),
dependents: BTreeMap::new(),
inspect_sensitivity: inspect::SensitivityLevel::Unspecified,
}
}
Expand Down Expand Up @@ -788,6 +816,53 @@ impl StateUnits {
}

impl Inner {
/// Checks that a unit named `name`, with `dependencies` and `dependents`
/// by ID and name, can be added to the set.
fn check_new_unit(
&self,
name: &Arc<str>,
dependencies: &BTreeMap<u64, Arc<str>>,
dependents: &BTreeMap<u64, Arc<str>>,
) -> Result<(), UnitBuildError> {
if self.names.contains_key(name) {
return Err(UnitBuildError::NameInUse(name.clone()));
}
if let Some(removed) = dependencies
.iter()
.chain(dependents)
.find_map(|(id, other)| (!self.units.contains_key(id)).then_some(other))
{
return Err(UnitBuildError::RemovedUnit {
unit: name.clone(),
removed: removed.clone(),
});
}
// The units in the set form no cycle, so a new cycle would run from the
// new unit to one of its dependencies, along existing dependency edges
// to one of its dependents, and back to the new unit. Without
// dependents, nothing leads back to the new unit.
if dependents.is_empty() {
return Ok(());
}
let mut pending = dependencies.keys().copied().collect::<Vec<_>>();
let mut reached = BTreeSet::new();
while let Some(id) = pending.pop() {
if let Some(dependent) = dependents.get(&id) {
return Err(UnitBuildError::DependencyCycle {
unit: name.clone(),
dependent: dependent.clone(),
});
}
// A unit that is not in the set has no edges to follow.
if reached.insert(id)
&& let Some(unit) = self.units.get(&id)
{
pending.extend(&unit.dependencies);
}
}
Ok(())
}

fn ready_set(&self, unit_ids: Option<&[u64]>) -> ReadySet {
let map = |id, unit: &Unit| {
(
Expand Down Expand Up @@ -820,6 +895,11 @@ struct ReadyState {
}

impl ReadySet {
/// Waits, in turn, for each unit of `deps` in this set to finish its state
/// change, and returns false at the first one that failed.
///
/// [`UnitBuilder::build`] rejects dependency cycles, so an operation's
/// waits all end once every unit answers its own request.
async fn wait(&self, op: &str, id: u64, deps: &[u64]) -> bool {
for dep in deps {
if let Some(dep) = self.0.get(dep) {
Expand Down Expand Up @@ -879,8 +959,10 @@ fn state_change<I: 'static, R: 'static + Send, Req: FnOnce(Rpc<I, R>) -> StateRe
pub struct UnitBuilder<'a> {
units: &'a StateUnits,
name: Arc<str>,
dependencies: BTreeSet<u64>,
dependents: BTreeSet<u64>,
// The units to order this one with, by ID, and their names, which a build
// reports if the unit has been removed by then.
dependencies: BTreeMap<u64, Arc<str>>,
dependents: BTreeMap<u64, Arc<str>>,
Comment on lines +962 to +965

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to store names here? Can we not just look them up when we need them?

inspect_sensitivity: inspect::SensitivityLevel,
}

Expand All @@ -890,7 +972,8 @@ impl UnitBuilder<'_> {
/// Operations will be ordered to ensure that a dependency will stop after
/// its dependants, and that it will reset or restore before its dependants.
pub fn depends_on(mut self, handle: &UnitHandle) -> Self {
self.dependencies.insert(self.handle_id(handle));
let UnitId { name, id } = self.unit_id(handle);
self.dependencies.insert(id, name);
self
}

Expand All @@ -899,7 +982,8 @@ impl UnitBuilder<'_> {
/// Operations will be ordered to ensure that a dependency will stop after
/// its dependants, and that it will reset or restore before its dependants.
pub fn dependency_of(mut self, handle: &UnitHandle) -> Self {
self.dependents.insert(self.handle_id(handle));
let UnitId { name, id } = self.unit_id(handle);
self.dependents.insert(id, name);
self
}

Expand All @@ -909,40 +993,53 @@ impl UnitBuilder<'_> {
self
}

fn handle_id(&self, handle: &UnitHandle) -> u64 {
fn unit_id(&self, handle: &UnitHandle) -> UnitId {
// Ensure this handle is associated with this set of state units.
assert_eq!(
Weak::as_ptr(handle.inner.as_ref().unwrap()),
Arc::as_ptr(&self.units.inner)
);
handle.id.id
handle.id.clone()
}

/// Adds a new state unit sending requests to `send`.
pub fn build(self, send: Sender<StateRequest>) -> Result<UnitHandle, NameInUse> {
///
/// Fails, and leaves the set unchanged, if another unit has the name, if
/// a unit passed to [`Self::depends_on`] or [`Self::dependency_of`] has
/// been removed since, or if the new unit would form a dependency cycle.
pub fn build(self, send: Sender<StateRequest>) -> Result<UnitHandle, UnitBuildError> {
let id = {
let mut inner = self.units.inner.lock();
// Check everything before changing the set, so that a unit that
// cannot be added leaves no name, edge, or ID behind.
inner.check_new_unit(&self.name, &self.dependencies, &self.dependents)?;
let id = inner.next_id;
let entry = match inner.names.entry(self.name.clone()) {
hash_map::Entry::Occupied(_) => return Err(NameInUse(self.name)),
hash_map::Entry::Vacant(e) => e,
};
entry.insert(id);
inner.names.insert(self.name.clone(), id);

for &dep in &self.dependencies {
inner.units.get_mut(&dep).unwrap().dependents.insert(id);
for &dep in self.dependencies.keys() {
inner
.units
.get_mut(&dep)
.expect("dependency exists")
.dependents
.insert(id);
}

for &dep in &self.dependents {
inner.units.get_mut(&dep).unwrap().dependencies.insert(id);
for &dep in self.dependents.keys() {
inner
.units
.get_mut(&dep)
.expect("dependent exists")
.dependencies
.insert(id);
}
inner.units.insert(
id,
Unit {
name: self.name.clone(),
send,
dependencies: self.dependencies,
dependents: self.dependents,
dependencies: self.dependencies.into_keys().collect(),
dependents: self.dependents.into_keys().collect(),
state: State::Stopped,
inspect_sensitivity: self.inspect_sensitivity,
},
Expand Down Expand Up @@ -970,7 +1067,7 @@ impl UnitBuilder<'_> {
self,
spawner: impl Spawn,
f: F,
) -> Result<SpawnedUnit<Fut::Output>, NameInUse>
) -> Result<SpawnedUnit<Fut::Output>, UnitBuildError>
where
F: FnOnce(Receiver<StateRequest>) -> Fut,
Fut: 'static + Send + Future,
Expand Down Expand Up @@ -1047,6 +1144,8 @@ impl Ready {

#[cfg(test)]
mod tests {
mod build;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it need to be a separate file or can they just be inlined?


use super::StateTransitionErrorKind;
use super::StateUnit;
use super::StateUnits;
Expand Down
Loading
Loading