Skip to content

Initial IPv6 Support - #533

Merged
taspelund merged 146 commits into
mainfrom
trey/ipv6
Dec 3, 2025
Merged

taspelund merged 146 commits into
mainfrom
trey/ipv6

Conversation

@taspelund

@taspelund taspelund commented Aug 8, 2025 •

Copy link
Copy Markdown
Contributor

This PR adds initial support for IPv6 static routing in maghemite, with the very beginnings of BGP support (really just originated IPv6 prefixes).
This addresses a few bugs found along the way (e.g. #529), adds unit tests for old/new functionality, and does a good bit of code cleanup, e.g.

  • mostly standardizing on oxnet::IpNet in generic spots and rdb::Prefix in db-specific spots, rather than several unique types
  • moving common functionality into mg-common where it can be used by all other crates w/o creating circular dependencies

Along the way I found that our handling of Connection Collisions was incorrect in a number of ways
e.g.

  • We were not properly babysitting the second connection up through a received Open
  • We were not always using the correct peer ASN (.unwrap_or(0) would return 0 all the time leading to incorrect behavior when the peer has a higher RID)
  • We were not sending Collision Resolution messages
  • Incomplete connection handling during collision window (e.g. HoldTime was set for the whole peer, not for a given connection)

This eventually became a pretty significant rewrite of much of the FSM for various reasons,
e.g.

  • To facilitate multiple connections, some state (like hold time / keepalive time) needed to be moved from the per-peer SessionRunner struct into the per-connection (TCP or Channel) BgpConnection trait.
  • The codepaths for inbound and outbound connections were not handled equally by the FSM
  • There were many unused FsmEvent enum invariants, leading to many catch-all match arms in the FSM state handlers
  • Our implementation deviated from the RFC in seemingly unnecessary ways (e.g. Active holding onto a connection, several FSM events returning us to Connect or Active when the RFC said to move into Idle, etc.),

Some highlights from the FSM work:

  • Connections now own a bit of state that was previously owned by the SessionRunner (particularly timers)
  • Introduced BgpConnector trait that mirrors the BgpListener trait but for outbound connections
  • Both inbound and outbound connections are now handled asynchronously and present themselves to the SessionRunner as FsmEvents (TcpConnectionAcked (previously named Connected) for inbound, TcpConnectionConfirmed for outbound)
  • Connection policy (ttl / md5) is now applied by BgpConnector or BgpListener before a connection is sent to the FSM/SessionRunner
  • The SessionRunner now owns a connection registry so we can keep track of more than one valid (registered) connection in parallel - with storage for a single "primary" connection for ease of querying connection state (users/operators shouldn't have to care about multiple connections in parallel)
  • a new ConnectionId type is introduced and added as a member of the FsmEvent variants that are meant only for a specific connection (this allows the FSM event queue to be multiplexed for multiple connections, since events can now be associated with a specific connection. e.g. a Notification for connection X doesn't affect connection Y)
  • FsmState::ConnectionCollision has been introduced to provide an entire pseudo-state (as in, not RFC defined) where we can emulate an FSM for two connections in parallel despite only implementing a single FSM
  • Unused FsmEvent variants have been moved to an UnusedEvent enum (decorated with dead_code) so we don't have to clutter the FSM methods with handlers for them (I deliberately wanted to make sure we don't use catch-all match arms)
  • enum FsmEvent now holds event type sub-enums that group the FsmEvents based on the category of event (admin, session-wide, and connection-specific)
  • The FsmState methods have been almost completely rewritten in order to align with the RFC (some events took incorrect actions, some logic lived in the wrong state, some states held onto connections when they shouldn't, etc.)
  • Lots of test restructuring (helper functions, use of generics to add TCP support, a LoopbackIpManager added to add/remove IPs as needed for TCP tests to work w/o changing the addr_to_session paradigm).
  • All logging in mgd (minus ddm) now uses slog, with only a couple exceptions where a custom macro including context-specific kv pairs for use with slog::o!

taspelund added 14 commits July 25, 2025 12:38
Removes one of the multiple duplicate types that implement an IP Prefix.

Signed-off-by: Trey Aspelund <[email protected]>
Moves to ddm/oxnet types to represent an IP Prefix instead of custom
types. Step 2 in standardizing around oxnet Prefix types.

Signed-off-by: Trey Aspelund <[email protected]>
Remove unused BgpAttributes4, BgpAttributes6, OriginChangeSet, and
Status types.  There were a couple other unused types that seemed more
forward-looking, so I left those in place (i.e. fn to_buf(), Policy4Key)

Signed-off-by: Trey Aspelund <[email protected]>
Updates Db to incorporate new methods that support IPv6.
The RIB is now split into three separate types:
- Rib: Holds Prefix (protocol-agnostic enum)
- Rib4: Holds Prefix4 (IPv4 specific struct)
- Rib6: Holds Prefix6 (IPv6 specific struct)
Updates bestpaths() to be completely prefix-agnostic (now accepts paths
as an argument in lieu of a prefix and Rib).
Callers of prefix add/remove methods are now responsible for managing
locks for the appropriate RIB structures, allowing each protocol's RIB
to be locked independently and giving the caller the option to reduce
how many times the lock needs to be acquired/released.

Signed-off-by: Trey Aspelund <[email protected]>
Initial implementation of IPv6 Static Routing:
- New mgd APIs
- New mgadm commands (mirroring v4 static routing commands)

Signed-off-by: Trey Aspelund <[email protected]>
During creation of Prefix4/Prefix6 structs, an Ipv{4,6}Addr was blindly
allowed w/o any validation or zeroing of the host bits.  This allowed
for the RIB to hold multiple entries for routes w/ the same underlying
subnet (e.g. 1.1.1.1/24 and 1.1.1.2/24 would be considered unique keys,
but the underlying subnet is still 1.1.1.0/24), possibly even with
differing next-hop values.
This commit addresses that issue by adding a step to zero the host bits
during the creation of new Prefix4/Prefix6 structs.  Figuring out a
migration strategy for the on-disk sled::Db remains a concern, but
this prevents new problematic entries from being created.

Fixes: #529

Signed-off-by: Trey Aspelund <[email protected]>
Second half of the fix for #529. First we moved to a constructor that
enforced all host bits be zeroed when creating a Prefix* type. Now, we
check whether the routes in the on-disk db are valid (host bits unset)
and remove them if they're invalid.
This also moves most of the logic into methods of the Prefix* types,
with the exception of the mg-admin-client mirrors of them, as progenitor
can't know about methods/traits from the openapi spec so that logic
has to live somewhere.

Fixes: #529

Signed-off-by: Trey Aspelund <[email protected]>
Some helpful parsing and retry macros were sitting in bgp and other
crates couldn't use them... so I moved them to mg-common.

Signed-off-by: Trey Aspelund <[email protected]>
Adds APIs, db methods, mgadm commands and unit tests for IPv6 BGP Origin

Signed-off-by: Trey Aspelund <[email protected]>
Signed-off-by: Trey Aspelund <[email protected]>
@taspelund
taspelund requested a review from rcgoodfellow August 8, 2025 22:45
@taspelund taspelund self-assigned this Aug 8, 2025
@taspelund taspelund added bgp Border Gateway Protocol mgd Maghemite daemon customer For any bug reports or feature requests tied to customer requests static Static Routing rust Pull requests that update rust code labels Aug 8, 2025
Signed-off-by: Trey Aspelund <[email protected]>
@taspelund taspelund linked an issue Aug 8, 2025 that may be closed by this pull request
Moves RIB queries from /bgp to /rib (this will likely require
a corresponding update in Nexus), as rib_in and rib_loc are not
specific to BGP.
Moves RIB logic into its own set of files (mgd/src/rib_admin.rs,
mgadm/src/rib.rs).
Refactors print_rib() and move it into rib.rs.
Adds support for server-side filtering of RIB queries by AddressFamily
and Protocol (BGP/Static).
Removes a bunch of duplicate types and impls by using progenitor's
"replace" directive in generate_api!() macro to automatically map
progenitor's auto-derived types back to their original rdb types (this
is something we should do further refactoring on, as there is quite a
lot of type/impl duplication going on).

Fixes: #525

Signed-off-by: Trey Aspelund <[email protected]>
Comment thread bgp/src/test.rs Resolved
Comment thread bgp/src/router.rs Resolved
In mgd startup, we look for an existing on-disk db and parse static
routes from it. Previously we were filtering all routes that had any of
the host bits set (rightmost bits not included by the net mask), but
that could result in broken connectivity. Instead, we now normalize
prefixes as we parse them (zeroing the host bits) and consolidate
matching entries (same prefix, next-hop, vlan-id, etc.) when we can. If
we end up with multiple entries for the same prefix whose paths are not
able to be consolidated, we treat these as separate entries just like we
would for static routes explicitly configured for ECMP.

This also adds prefix validation into the API handlers that accept
prefixes (static routes, bgp origin, and bgp_apply), which checks host
bits and whether the routes overlap with non-routable address ranges.

The validation logic lives in a few new functions that are now in a new
mgd validation mod alongside a bunch of proptests.

Signed-off-by: Trey Aspelund <[email protected]>
Introduce helper function to reduce code duplication of connection id
checks in FSM event handlers.

Signed-off-by: Trey Aspelund <[email protected]>
It is currently impossible for the receiver of the FSM event queue
(implemented via mpsc channel) to return RecvTimeoutError::Disconnected
because there is always a clone of its sender until both the sender and
receiver go out of scope (when a peer is removed and its SessionRunner
is dropped) at the same time. It would be mighty difficult to imagine a
valid scenario where all clones of the sender get dropped when one of
the clones has the same owner as the receiver.

Signed-off-by: Trey Aspelund <[email protected]>
React to unexpected timer events more defensively. While the RFC says in
the FSM description to respond to unexpected timers by transitioning to
Idle and sending an FSM Error Notification, many of these timer events
are both internal and harmless. Instead of closing the connection and
restarting the FSM from Idle, stop the offending timer, log it as a bug,
and continue where the FSM left off.

Signed-off-by: Trey Aspelund <[email protected]>
Signed-off-by: Trey Aspelund <[email protected]>
@rcgoodfellow

Copy link
Copy Markdown
Collaborator

Things we need to cover for interop testing with Cisco/Juniper/Arista

  • Getting both sides to established and then:
    • Knocking the upstream side over in a loop and making sure we get back to established
    • ^ but knocking over the Oxide side instead
    • Making updates on the upstream side that result in a session bounce in a loop and making sure we get back to established.
    • ^ but updating the Oxide side
  • Route refresh handling.
  • Graceful restart handling.
  • Transitioning between tcp/md5 and just regular tcp (transition to and from, and from both sides)

Signed-off-by: Trey Aspelund <[email protected]>
Adds a per-peer FSM event history. This history is split into two
separate ring buffers, one for major events and one for all events.
These are stored separately to ensure that significant events will not
be overrun by chatty minor events.

API endpoints are also added for the FSM event history along with CLI
support via mgadm. The existing BGP message history has been moved to a
new API endpoint alongside the FSM history:
- /bgp/history/fsm
- /bgp/history/message (previously /bgp/message-history)

Closes: #361

Signed-off-by: Trey Aspelund <[email protected]>
Fixes for 3 different thread leaks:
1: MD5 SA thread not closed when BgpConnection is dropped
2: ConnectionClock thread not closed when BgpConnection is dropped
3: SessionClock thread not closed when SessionRunner is dropped

All 3 of these leaks come down to the same fundamental issue:
The Drop impl of the type responsible for these threads was incorrectly
checking if Arc::strong_count == 1 before setting the shutdown/dropped
flag (Arc<AtomicBool>) to true. The correct behavior is for the Drop
impl of the owning types to unconditionally set the dropped flag true.

Context:
The initial implementation of the SessionRunner connection registry used
a BTreeMap that held clones of BgpConnections. These BgpConnections hold
an Arc<AtomicBool> that is used to signal shutdown to its child threads
(MD5 SA keepalive thread + ConnectionClock). Because there were multiple
BgpConnection clones that each had an Arc clone of the AtomicBool, we
needed to check whether the strong_count had reached 1 so we didn't set
the dropped flag too early.
After the recent rewrite of the ConnectionRegistry, BgpConnections are
no longer cloned. Instead, there is proper shared ownership via Arc
wrappers (Arc<BgpConnection>). Since there is now only a single instance
of the BgpConnection, it is safe (and necessary) for the dropped flag to
be set by the Drop impl without checking the strong count of the Arc
wrapping the dropped flag.

The ConnectionClock and SessionClock types also followed this pattern
(which was never needed for the SessionClock), causing both of these
threads to get leaked during shutdown as well. The SessionClock leak
only occurred when the entire SessionRunner was dropped, i.e. when a
neighbor is unconfigured.

Along with the corrected Drop impl, this moves the ThreadState enum
into mg-common and provides a ManagedThread wrapper which holds both a
dropped flag and a ThreadState enum.

This also adds a testing utility to check the number of threads in the
current process and a bgp test that ensures there are no threads leaked
by the lifecycle of the BgpConnection, SessionRunner or Router types.

Signed-off-by: Trey Aspelund <[email protected]>
The Router type has a shutdown() method and a shutdown flag but the
behavior didn't seem to be fully functional. The shutdown flag was only
ever written, but never read (or cloned).

This introduces explicit handling for the shutdown flag:
- shutdown() sets Router.shutdown flag and sets shutdown for sessions
- run() unsets Router.shutdown flag and starts sessions
- admin events now check Router.shutdown before attempting to propagate
  changes to neighbors (e.g. when updating originated routes)

Additionally, a Drop impl is added for Router which calls shutdown on
all sessions so their threads actually close when a Router is deleted.

Signed-off-by: Trey Aspelund <[email protected]>
Move to using std::thread::Builder for all BGP threads instead of
calling std::thread::spawn directly. This allows us to name our threads
and gives us the opportunity to handle a spawn failure rather than
panicking unconditionally if the spawn goes wrong.
Additionally, the logic of the test functions that counted the number of
active threads needed to be tweaked, as it checked the total number of
threads for this process rather than looking just for BGP threads. This
caused issues in the thread count because it didn't filter out unrelated
threads threads like slog-async, sled-io, or the rdb::Db reaper.

Signed-off-by: Trey Aspelund <[email protected]>
Pull in the serial_test dependency so we can make sure the new thread
count tests are not run in parallel with other tests that could spawn
bgp threads. In addition to this, have a wait condition for the baseline
number of bgp threads to be 0, just in case tests are not run using
nextest (`cargo test` executes all tests in the same process).

In the Router code, move SessionRunner thread spawning into its own
method so we avoid the possibility of having subtly different code to do
the same thing. Also make sure that we update fanout during shutdown()
and run() to support a Router being restarted.

Signed-off-by: Trey Aspelund <[email protected]>
Signed-off-by: Trey Aspelund <[email protected]>
Signed-off-by: Trey Aspelund <[email protected]>
Signed-off-by: Trey Aspelund <[email protected]>
Instead of sleeping for a solid 60 seconds (PFKEY_KEEPALIVE) and being
unable to check the shutdown flag for this whole time, modify the loop
to sleep for 1s at a time and check if the current time has exceeded
60s since the last SA update. This ensures there is not a 60s window
where MD5 SA keepalive threads can linger. In manual testing, it was
observed that while flapping a BGP session once per second would result
in ~60 MD5 threads hanging around at any given time (assuming MD5 is
enabled for the session). This change reduces that window to just 1s,
significantly reducing the upper bounds of how many extra threads can
hang around sleeping all day (the lazy freeloaders!).

Signed-off-by: Trey Aspelund <[email protected]>
The read timeout value used by the recv loops comes from recv_timeout
set on the BgpConnection itself, which is set by accept() or connect()
methods when a connection succesfully completes. However, accept() and
connect() were passing their own timeout values to recv_timeout rather
than giving the recv loop its own timeout value.
e.g.
When the Dispatcher calls accept() it statically passes IO_TIMEOUT
(100ms) but the Connector is passed connect_retry / 3 (generally on the
order of multiple seconds).

This resulted in the potentially (hopefully) long-running recv loop to
have different timeout values depending on the direction of its
connection (inbound or outbound).

Instead of playing these games, let's use a matching value for both
directions (IO_TIMEOUT).

Signed-off-by: Trey Aspelund <[email protected]>
Have the MD5 SA keepalive thread sleep for IO_TIMEOUT so that it matches
what the recv loop and event_recv do in terms of timeout values.

Signed-off-by: Trey Aspelund <[email protected]>
it would be so nice if cargo could detect errors in conditional code for
other platforms... but alas

Signed-off-by: Trey Aspelund <[email protected]>
@taspelund

Copy link
Copy Markdown
Contributor Author

Peers resetting the session in a loop: ✅
Local system resetting sessions in a loop: ✅
Route refresh (tested bidirectionally): ✅
GR: upon further inspection of our code, GR helper has not been implemented. Routes are only marked stale when we send a Route Refresh (with the assumption that either the peer re-advertises us routes and un-marks them stale, or they get removed by the db reaper)
MD5 mismatch: ✅
Changing MD5 password: ✅
Toggling MD5 password: ✅

The manual testing of resetting sessions in a loop did a few thread leaks (issues in the shutdown flag logic) which I've fixed. I've also updated the MD5 SA Keepalive thread logic to have shorter sleeps so we aren't stuck waiting 60 seconds for the shutdown flag to get noticed (manual testing showed that flapping the session ~1/s resulted in ~60 threads lingering per peer, which makes sense given the old sleep was 60s).

With that all done, I would say everything is looking good and is ready for final review.

@rcgoodfellow

Copy link
Copy Markdown
Collaborator

Ok great - let's get this through a lap in a4x2 to test things e2e.

mg-admin-client had mg-common as a dependency, but it was unneeded.
Worse than that, it was causing a circular dependency that prevented
omicron from building:
omicron-common -> mg-admin-client -> mg-common -> omicron-common

Signed-off-by: Trey Aspelund <[email protected]>
The retry logic in mg-common/src/nexus.rs was depending on
omicron-common for a couple pieces functions from backoff. This was
creating a dependency loop when trying to build omicron.

Signed-off-by: Trey Aspelund <[email protected]>
cargo-machete identified several unused dependencies in the admin client
crates. However, because both ddm-admin-client and mg-admin-client use
progenitor::generate_api! to generate code from OpenAPI specs at compile
time, static analysis tools cannot see into macro-generated code,
leading
to false positives.

To determine which dependencies were genuinely unused, each flagged
dependency was systematically tested by commenting it out and running
cargo check to verify if compilation failed.

Removed (genuinely unused):
- ddm-admin-client: percent-encoding, serde_json
- mg-admin-client: anyhow, percent-encoding

Kept (used by progenitor-generated code):
- serde, serde_json: Required for serialization/deserialization
- uuid: Required for OpenAPI fields with format: "uuid"
- chrono: Required for OpenAPI fields with format: "date-time"
- oxnet: Explicitly configured in progenitor crates config

Added cargo-machete ignore lists to both Cargo.toml files to suppress
false positives for dependencies used by macro-generated code.

Signed-off-by: Trey Aspelund <[email protected]>
When building omicron (which depends on maghemite), cargo reports a
cyclic package dependency:

  omicron-common -> mg-admin-client -> rdb -> mg-common -> oximeter
                                                              |
                                                              v
                                                         omicron-common

This cycle was introduced in commit ccaca84 ("bgp: consolidate to rdb
Prefix types"). The issue is that mg-admin-client only needs lightweight
type definitions (Prefix, AddressFamily, ProtocolFilter) but pulling in
rdb brings the entire database implementation plus mg-common's oximeter
integration.

Extract the shared types into a new rdb-types crate with minimal
dependencies (serde, schemars, oxnet). This breaks the cycle:

  omicron-common -> mg-admin-client -> rdb-types (no cycle)
  rdb -> mg-common -> oximeter -> omicron-common (separate chain)

The rdb crate re-exports types from rdb-types for backward
compatibility. Database-specific operations are implemented via a new
PrefixDbKey trait to avoid inherent impl on external types.

Signed-off-by: Trey Aspelund <[email protected]>
@taspelund

Copy link
Copy Markdown
Contributor Author

I've run this through a4x2 using a new omicron branch trey/ipv6 and networking seems to be working well.

I am noticing an issue where the api server seems to go near unresponsive while my browser is open and trying to load the initial login page (curling the ping endpoint from the hypervisor running a4x2 hangs until I stop the browser connection), but I don't believe this is related to these changes.

@rcgoodfellow rcgoodfellow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

e2e testing looks good to me. Thanks for all the work in putting this together and getting this across the line @taspelund!

@taspelund
taspelund merged commit 38ff221 into main Dec 3, 2025
@taspelund
taspelund deleted the trey/ipv6 branch December 3, 2025 05:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bgp Border Gateway Protocol customer For any bug reports or feature requests tied to customer requests mgd Maghemite daemon rust Pull requests that update rust code static Static Routing

Projects

None yet

2 participants