Skip to content

Commit

Permalink
New BlueprintDiff implementation
Browse files Browse the repository at this point in the history
This commit introduces an automated blueprint diff mechanism based on
[diffus](https://github.com/oxidecomputer/diffus) along with the visitor
pattern for traversing heterogeneous diff trees. It builds on several
prior commits that introduced diffus support and added visitors for
types:

#7261
#7336
#7362
#7366

The new `BlueprintDiffer` implements the relevant visitors and
accumulates change state from visitor method callbacks. The accumulated
state  is the `BlueprintDiff` which replaces the old `BlueprintDiff`.
The new structure intentionally groups resources by sleds, as the
4 primary maps in a `Blueprint` (`sled_state`, `blueprint_zones`,
`blueprint_disks`, `blueprint_datasets`) are going to be collapsed into
a single map. This allows us to modify the visitors to traverse the new
blueprint diffs in one place and not have to worry about modifying the
`BlueprintDiff` itself or any consumers. More details about why we are
collapsing these maps can be found in #7078.

We primarily use `BlueprintDiff`s for testing and omdb output, and
therefore the printed representation is absolutely critical for us.
This commit reuses the types and formatting contained in `nexus/
types/src/deployment/ blueprint_display.rs` and provides a new
type, `BpDiffPrintable` that can be created from a `BlueprintDiff`.
`BpDiffPrintable` contains our formatted tables ready to be used by
`BlueprintDiffDisplay` along with the orignal blueprints to render the
diff. It's possible that we can collapse `BlueprintDiffDisplay` and
`BpDiffPrintable` into one type and simplify a bit. I just haven't done
that yet.

The printable output of the diffs has maintained backwards compatibility
in all cases except for errors and warnings. Those have been
specifically adapted to work with our visitors and be accumulated while
walking the diffus diffs. This only resulted in the change to one test
output file, which should leave us confident in the correctness of this
new implementation. An optional `show_unchanged` flag was added
at key points in the code and in the future we plan to change
the default to only show actual changes. We didn't do that here so that
we could ensure the output of the new implementation matches the
existing code. We also plan to add more columns, such as `disposition`
for datasets.

Usage going forward
--------------------

This is a significant change to our blueprint diff code, and in some
cases it may take slightly more boilerplate in order to diff newly added
fields or structs, than in the older code. However, there are a few
things this new style has going for it. Figuring out the differences
between blueprints is now done automatically and completely. There
is no need to compute these differences, which is both error prone,
and complicated. See the old [BpDiffZones](https:// github.com/oxidecomputer/omicron/blob/888f90db8b36ccdf667d96423ae7805824c48aa9/nexus/types/src/deployment/blueprint_diff.rs#L195-L340)
code for what finding the differences for just zones in a blueprint looked like.

With automated diffs output from diffus, we now need to write code to
expose the necessary change information to consumers. We want to do
this in a unified and rigorous manner, and one that composes nicely. We
chose a `visitor` pattern for this. For each somewhat complex type (use
your judgement), we provide a visitor trait that walks the heterogeneous
diff tree and calls trait methods when a change is found. User code
implements only the visitor methods that it cares about and then
can accumulate its own internal state based on which callbacks fire.
We provide a top-level `VisitBlueprint` trait to detect all changes
in a blueprint and implement it in `BlueprintDiffer` to construct a
`BlueprintDiff` in a format we can use.

There are a few important things to note about our visitors. While
diffus provides a complete tree of all changes as well as fields and
variants that have not changed, the visitors as currently implemented
only expose changes. These changes are unified for simplicity into a
`Change` type. We also don't currently expose all changes. For most
fields that we don't expect to ever change, there is not a change
callback. Mostly this is because the visitors were written before
I had to use them :). It turns out it may actually be useful to expose
these fields so that we can report errors or warnings in our diffs
if they do change unexpectedly. You can see an example of error
tracking in the `BlueprintDiffer::visit_zone_type_change` method
and its test output in `nexus/reconfigurator/planning/tests/output/
planner_nonprovisionable_2_2a.txt`.

It is tedious to write visitor traits to walk a diffus diff and
then implement these traits to accumulate the state we want. It can
reasonably be asked why we wouldn't just walk the tree and generate
the state we want directly without the visitors. Indeed, this is quite
reasonable for small one off tasks. But we are building a foundation
that will grow over time in terms of type structure and number of
developers working on the system. For such a long term project, it's
usefulf to decouple the tree walking from the state accumulation. For
one thing, it makes each bit easier to read and write on its own. For
another, it allows us to build different implementations of the visitors
for different use cases, such as testing. Remember, users only have to
implement the methods they care about. Therefore if they only want to
see if a zone changed, they  don't have to worry about parsing diffus
types, but can just implement a callback. An example of this is the
`TestVisitor` in `live-tests/tests/test_nexus_add_remove.rs`.

I anticipate we will find ways to make implementing and using diff
visitors more ergonomic over time while maintaining the compositional
rigor that the separation of concerns provides in this model.

Testing
--------

I mainly have run planning tests locally to ensure diffs work as
expected. I still need to run the live tests and play with omdb.
  • Loading branch information
andrewjstone committed Jan 25, 2025
1 parent 9093ac6 commit d4abe9a
Show file tree
Hide file tree
Showing 15 changed files with 2,566 additions and 1,519 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions live-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ omicron-workspace-hack.workspace = true
[dev-dependencies]
anyhow.workspace = true
assert_matches.workspace = true
diffus.workspace = true
dropshot.workspace = true
futures.workspace = true
internal-dns-resolver.workspace = true
Expand Down
50 changes: 39 additions & 11 deletions live-tests/tests/test_nexus_add_remove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod common;
use anyhow::Context;
use common::reconfigurator::blueprint_edit_current_target;
use common::LiveTestContext;
use diffus::Diffable;
use futures::TryStreamExt;
use live_tests_macros::live_test;
use nexus_client::types::Saga;
Expand All @@ -15,14 +16,42 @@ use nexus_inventory::CollectionBuilder;
use nexus_reconfigurator_planning::blueprint_builder::BlueprintBuilder;
use nexus_reconfigurator_preparation::PlanningInputFromDb;
use nexus_sled_agent_shared::inventory::ZoneKind;
use nexus_types::deployment::SledFilter;
use nexus_types::deployment::diff_visitors::visit_blueprint::VisitBlueprint;
use nexus_types::deployment::diff_visitors::visit_blueprint_zones_config::VisitBlueprintZonesConfig;
use nexus_types::deployment::BpVisitorContext;
use nexus_types::deployment::{BlueprintZoneConfig, SledFilter};
use omicron_common::address::NEXUS_INTERNAL_PORT;
use omicron_test_utils::dev::poll::wait_for_condition;
use omicron_test_utils::dev::poll::CondCheckError;
use omicron_uuid_kinds::SledUuid;
use slog::{debug, info};
use std::net::SocketAddrV6;
use std::time::Duration;

// A visitor that is used to capture changes to a blueprint used by this test
#[derive(Default)]
pub struct TestVisitor {
pub added_zones: Vec<(SledUuid, BlueprintZoneConfig)>,
}

impl<'e> VisitBlueprint<'e> for TestVisitor {
fn zones_visitor(
&mut self,
) -> Option<&mut impl VisitBlueprintZonesConfig<'e>> {
Some(&mut *self)
}
}

impl<'e> VisitBlueprintZonesConfig<'e> for TestVisitor {
fn visit_zones_insert(
&mut self,
ctx: &mut nexus_types::deployment::BpVisitorContext,
node: &BlueprintZoneConfig,
) {
self.added_zones.push((ctx.sled_id.unwrap(), node.clone()));
}
}

// TODO-coverage This test could check other stuff:
//
// - that after adding:
Expand Down Expand Up @@ -71,16 +100,15 @@ async fn test_nexus_add_remove(lc: &LiveTestContext) {
.expect("editing blueprint to add zone");

// Figure out which zone is new and make a new client for it.
let diff = blueprint2.diff_since_blueprint(&blueprint1);
let new_zone = diff
.zones
.added
.values()
.next()
.expect("at least one sled with added zones")
.zones
.first()
.expect("at least one added zone on that sled");
// Utilize diffus directly rather than our wrapper to capture the changes
// in `TestVisitor`.
let diff = blueprint1.diff(&blueprint2);
let mut ctx = BpVisitorContext::default();
let mut visitor = TestVisitor::default();
visitor.visit_blueprint(&mut ctx, diff);
let (modified_sled_id, new_zone) =
visitor.added_zones.iter().next().expect("at least one added zone");
assert_eq!(*modified_sled_id, sled_id);
assert_eq!(new_zone.kind(), ZoneKind::Nexus);
let new_zone_addr = new_zone.underlay_ip();
let new_zone_sockaddr =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2010,11 +2010,12 @@ pub mod test {

// One sled was added.
assert_eq!(diff.sleds_added.len(), 1);
let sled_id = diff.sleds_added.first().unwrap();
let new_sled_zones = diff.zones.added.get(sled_id).unwrap();
let (sled_id, sled_insert) =
diff.sleds_added.first_key_value().unwrap();
let new_sled_zones = sled_insert.zones.unwrap();
assert_eq!(*sled_id, new_sled_id);
// The generation number should be newer than the initial default.
assert!(new_sled_zones.generation_after.unwrap() > Generation::new());
assert!(new_sled_zones.generation > Generation::new());

// All zones' underlay addresses ought to be on the sled's subnet.
for z in &new_sled_zones.zones {
Expand Down
Loading

0 comments on commit d4abe9a

Please sign in to comment.