Skip to content

Serialize NIC add/remove on the target VM's work job queue - #14139

Merged
weizhouapache merged 2 commits into
apache:4.22from
bhouse-nexthop:fix-vpc-router-nic-queue-bypass
Nov 24, 2026
Merged

weizhouapache merged 2 commits into
apache:4.22from
bhouse-nexthop:fix-vpc-router-nic-queue-bypass

Conversation

@bhouse-nexthop

@bhouse-nexthop bhouse-nexthop commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Description

On a redundant VPC, bringing up several tiers with VMs in parallel corrupts both virtual routers' NIC layout. Their keepalived configs diverge and VRRP breaks — the routers end up FAULT or both PRIMARY, and the VPC is unusable until restarted. Root-cause analysis in #11710.

Cause — a lockless read-then-persist in device id allocation

NetworkOrchestrator.createNicForVm() picks the device id and persists the nic in two separate steps:

int deviceId = _nicDao.getFreeDeviceId(vm.getId());   // reads the vm's existing nics
...
allocateNic(..., deviceId, ...);                        // persists the row much later

getFreeDeviceId() takes no lock, and the row it is choosing an id for is not written until the end of allocateNic(). Two nics added to the same VM concurrently both read the same free id and land on the same ethN.

This is triggered when several VPC tiers are created in parallel: each tier attaches the shared redundant VR, so N concurrent createNicForVm() calls run against one router. Observed nics rows for one router during reproduction (all live at once):

nic id network device_id
3499 300 2
3502 301 2
3520 302 3
3523 303 3

Two guest nics share one ethN (one network blackholed), and because the two routers of a redundant VPC end up with different device_id → network maps, their keepalived virtual_ipaddress sets diverge → both go PRIMARY.

Fix

Compute the free device id and persist the nic under the vm_instance row lock, so device id assignment is atomic per VM:

Transaction.execute(... -> {
    _vmDao.lockRow(vm.getId(), true);
    int deviceId = _nicDao.getFreeDeviceId(vm.getId());
    return allocateNic(..., deviceId, ...);
});
  • Same shape as the existing persistNicAfterRaceCheck() IPv4 race guard.
  • No change to job dispatch and no new cross-thread waiting. getFreeDeviceId()'s only caller is createNicForVm(), so this covers the whole device-id race surface — the user-VM add-nic path and the VPC tier attach to the shared VR alike — not just the reported case. (The initial deploy path assigns device ids from a single precomputed set, so it was never exposed to this race.)
  • Serializing per router is exactly what the non-concurrent path already does implicitly (one tier at a time).

This revises the earlier version of this PR, which serialized the three addVmToNetwork/removeNicFromVm/removeVmFromNetwork dispatch sites through the work-job queue. Per review feedback that fixes the symptom downstream and risks a worker-pool stall under a large parallel apply; fixing the allocation at its source is simpler and safer.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)
  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (improves an existing feature and functionality)
  • Cleanup (Code refactoring and cleanup, that may add test cases)
  • Build/CI
  • Test (unit or integration test code)

Feature/Enhancement Scale or Bug Severity

Bug Severity

  • BLOCKER
  • Critical
  • Major
  • Minor
  • Trivial

How Has This Been Tested?

Unit test — NetworkOrchestratorTest.testAllocateNicWithFreeDeviceIdLocksVmRowBeforeReadingFreeDeviceId asserts (via InOrder) that the vm_instance row is locked before getFreeDeviceId() is read, and that allocateNic() runs with that id. Full suite (59 tests) green.

Live — 4.22.1.0, KVM, two management servers, VXLAN, patch deployed on both. Redundant VPC ("VPC HA"), then 8 tiers each with a VM created in parallel via the API (mimics terraform apply):

  • Before the fix: duplicate device_ids on a router (two guest NICs on one ethN, table above), routers FAULT/PRIMARY.
  • After the fix: zero duplicate device_ids on every run — the persistent corruption is gone. Restarting the VPC (the recovery the issue documents) now re-applies both routers to byte-identical keepalived configs and a clean BACKUP + PRIMARY election, because there is no longer any duplicated device id to re-render.

Full disclosure on the test environment: its secondary storage was flaky enough that a pristine 8/8 parallel bring-up could not be captured — a couple of VM deploys timed out, and the resulting partial application left one router's keepalived missing some gateways, which by itself can still cause a transient dual-PRIMARY on first bring-up. That is a distinct failure mode (a per-router network-apply failure being swallowed while the VPC still reports success — see #11710 discussion) from the device-id race this PR fixes, and is worth a follow-up. What this change is verified to remove is the duplicate-device_id corruption that put two networks on one ethN.

How did you try to break this feature and the system with this change?

  • Lock scope / deadlock: the lock is the vm_instance row of the VM getting the nic (the router). It is held across allocateNic(), which acquires only leaf locks (IP address rows) — consistent vm → ip ordering, no inversion. implementNetwork()'s network op-lock is taken after allocation, outside this transaction. The router being attached is already running, so it is never being started concurrently under its own row lock.
  • Contention: concurrent tier attaches to one router now serialize — which is required for correctness and matches the non-concurrent path. Different VMs/routers lock different rows and proceed in parallel.
  • Exception behaviour: unchanged — allocateNic's InsufficientCapacity/ConcurrentOperation exceptions propagate as before (the callback's throws widens to InsufficientCapacityException, already declared by createNicForVm).

@codecov

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.33333% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 18.01%. Comparing base (b9a5977) to head (a6762e9).
⚠️ Report is 58 commits behind head on 4.22.

Files with missing lines Patch % Lines
...tack/engine/orchestration/NetworkOrchestrator.java 73.33% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               4.22   #14139      +/-   ##
============================================
+ Coverage     17.94%   18.01%   +0.06%     
- Complexity    16145    16221      +76     
============================================
  Files          5928     5936       +8     
  Lines        535174   535718     +544     
  Branches      65494    65597     +103     
============================================
+ Hits          96017    96484     +467     
- Misses       428228   428236       +8     
- Partials      10929    10998      +69     
Flag Coverage Δ
uitests 4.02% <ø> (ø)
unittests 19.08% <73.33%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bhouse-nexthop
bhouse-nexthop force-pushed the fix-vpc-router-nic-queue-bypass branch from 8fae08a to f734aa0 Compare September 10, 2026 20:44
@bhouse-nexthop
bhouse-nexthop marked this pull request as draft September 10, 2026 20:48
@bhouse-nexthop
bhouse-nexthop force-pushed the fix-vpc-router-nic-queue-bypass branch 3 times, most recently from a4f03f6 to 74fc025 Compare September 10, 2026 22:34
@bhouse-nexthop
bhouse-nexthop marked this pull request as ready for review September 10, 2026 23:32
@bhouse-nexthop
bhouse-nexthop force-pushed the fix-vpc-router-nic-queue-bypass branch from 74fc025 to 7564538 Compare September 11, 2026 00:39
@bhouse-nexthop

Copy link
Copy Markdown
Collaborator Author

@vladimirpetrov @sureshanaparti could you take a look at this one? We'd like this fix to make it into the upcoming 4.22.2 release.

createNicForVm() reads the next free device id and persists the nic in two
separate steps:

    int deviceId = _nicDao.getFreeDeviceId(vm.getId());   // reads existing nics
    ...
    allocateNic(..., deviceId, ...);                       // persists much later

getFreeDeviceId() has no lock, and the nic row it is choosing an id for is not
written until the end of allocateNic(). Two nics added to the same VM at once
therefore both read the same free id and land on the same ethN.

This happens when several tiers of a VPC are brought up in parallel: each tier
attaches the *shared* redundant VR, so N concurrent createNicForVm() calls run
against one router. The result is two guest nics on one ethN (one network
blackholed) and, because the two routers of a redundant VPC end up with
different device -> network maps, divergent keepalived configs -> both routers
go PRIMARY and the VPC is dead. (issue apache#11710)

Fix: compute the free device id and persist the nic under the vm_instance row
lock, so device id assignment is atomic per VM. This is the same shape as the
existing persistNicAfterRaceCheck() IPv4 race guard and needs no change to job
dispatch. Serializing per router is what the non-concurrent path already does
implicitly (one tier at a time).

Fixes: apache#11710

Signed-off-by: Brad House <bhouse@nexthop.ai>
@bhouse-nexthop
bhouse-nexthop force-pushed the fix-vpc-router-nic-queue-bypass branch from 7564538 to c65369e Compare October 1, 2026 15:27
The previous commit held the vm_instance row lock in a transaction that
spanned the whole of allocateNic(). That made the device id atomic, but
it also pulled persistNicAfterRaceCheck() into the outer transaction, so
a new nic was no longer committed when it was written but only once the
rest of the allocation had finished. Until then its guest ip is invisible
to other vms in the network, both to the guru picking a free ip and to
the race check that is meant to catch two nics taking the same one. The
vm row lock does nothing for that, as it only serialises nics of one vm.

Choose the device id where the nic is written instead. persistNic() runs
the ip race check, takes the vm row lock, reads the free device id and
persists the nic in one short transaction, as persistNicAfterRaceCheck()
did before, so the nic is committed as soon as it exists.
allocateNicWithFreeDeviceId() asks for that with FREE_DEVICE_ID and no
longer opens a transaction of its own.

Signed-off-by: Brad House <bhouse@nexthop.ai>

@DaanHoogland DaanHoogland left a comment

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.

clgtm

@Damans227 Damans227 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.

thanks @bhouse-nexthop, fix looks right. LGTM

@bhouse-nexthop

bhouse-nexthop commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

@DaanHoogland this has your and @Damans227's approvals and CI is green, but it hasn't had a Trillian run yet. Could you kick one and add it to the 4.22.2 milestone? I understand 4.22.2 is due out late this week or early next, and we'd like this fix in it.

@DaanHoogland

Copy link
Copy Markdown
Contributor

@blueorangutan package

@blueorangutan

Copy link
Copy Markdown

@DaanHoogland a [SL] Jenkins job has been kicked to build packages. It will be bundled with KVM, XenServer and VMware SystemVM templates. I'll keep you posted as I make progress.

@blueorangutan

Copy link
Copy Markdown

Packaging result [SF]: ✔️ el8 ✔️ el9 ✔️ el10 ✔️ debian ✔️ suse15. SL-JID 19685

@DaanHoogland

Copy link
Copy Markdown
Contributor

@blueorangutan test

@blueorangutan

Copy link
Copy Markdown

@DaanHoogland a [SL] Trillian-Jenkins test job (ol8 mgmt + kvm-ol8) has been kicked to run smoke tests

@blueorangutan

blueorangutan commented Oct 24, 2026 •

Copy link
Copy Markdown

[SF] Trillian test result (tid-17223)
Environment: kvm-ol8 (x2), zone: Advanced Networking with Mgmt server ol8
Total time taken: 64392 seconds
Marvin logs: [archive removed]
Smoke tests completed. 147 look OK, 2 have errors, 0 did not run
Only failed and skipped tests results shown below:

Test Result Time (s) Test File
test_02_enableHumanReadableLogs Error 0.31 test_human_readable_logs.py
test_01_vpn_usage Error 1.10 test_usage.py

@bhouse-nexthop

Copy link
Copy Markdown
Collaborator Author

Test report: parallel tier bring-up on a redundant VPC

Environment

  • A CloudStack 24.0 (main) build with this PR applied, alongside some of my other open PRs. One management server.
  • Three KVM hosts on Ubuntu 24.04, nested virtualisation; Ceph RBD primary storage.
  • System VM template 4.22.0.
  • A VPC on the default Redundant VPC offering. Its two routers ran on different hosts.

Method. I ran three rounds. Each round:

  • created 8 tiers one after another (allocated, not yet implemented);
  • deployed one cirros VM into each tier, all 8 deploys at once;
  • waited 60 s, then checked the routers' NICs in the DB, ip -br a and keepalived.conf on both routers, and redundantstate;
  • destroyed the VMs and tiers.

After the three rounds I kept two tiers with a VM each and ran restartVPC cleanup=true.

1. Duplicate device ids: none

This query returned no rows after every round, before the restart, and after it:

SELECT n.instance_id, n.device_id, COUNT(*) FROM nics n JOIN vm_instance v ON v.id=n.instance_id
WHERE n.removed IS NULL AND v.type='DomainRouter' AND v.vpc_id=<rvpc> GROUP BY 1,2 HAVING COUNT(*)>1;

No two guest NICs shared an ethN on either router.

2. Recovery with restartVPC cleanup=true

  • The new routers came up one PRIMARY and one BACKUP.
  • Their virtual_ipaddress sets were identical.
  • The two keepalived.conf files differ only in router_id (each router's own name). That line is expected to differ, so "byte-identical" in the description is true apart from that line.

So the corruption this PR targets did not appear: two networks on one ethN, which persists until a restart.

3. A separate failure mode, not fixed by this PR

Not every parallel deploy succeeded:

Round Deploys Running redundantstate VIP sets
1 5 / 8 PRIMARY + PRIMARY differ by one tier gateway
2 4 / 8 PRIMARY + PRIMARY differ by one tier gateway
3 3 / 8 PRIMARY + BACKUP identical

All 12 failures have the same cause:

Failed to re-program the network as a part of network Network {"name": "r1t5", ...} implement due to aggregated commands execution failure!

The agent of the router's host logged the answer to the AggregationControlCommand Finish:

java.lang.NullPointerException: Cannot invoke "java.util.Queue.clear()" because "queue" is null

VirtualRoutingResource keeps one aggregation queue per router name, in a plain HashMap. So when several networks are implemented on the same router at once, their aggregations share and overwrite one queue:

  • A second Start replaces the first job's queue, so the commands the first job had already queued are dropped.
  • The first Finish applies whatever is in the queue and removes it.
  • The second Finish finds no queue and throws the NPE above. Its deploy fails.

So a deploy can report success while one router never got its tier's config. That explains the VIP sets in rounds 1 and 2. There, the missing gateway belonged to a tier whose deploy was Running. I think this is the "partial application" mentioned under How Has This Been Tested. It comes from the agent, not from storage. It needs its own fix: serialise aggregated applies per router, or key the aggregation by job rather than by router name.

Result: pass for this PR's change.

  • Zero duplicate device ids across 24 parallel attaches and the restart.
  • The restart gives one PRIMARY, one BACKUP and matching configs.
  • The deploy failures and the dual PRIMARY in rounds 1 and 2 come from the separate agent-side aggregation race above.

@bhouse-nexthop

Copy link
Copy Markdown
Collaborator Author

@weizhouapache @RosiKyu this fixes NICs added to the same VM at the same time getting the same device id. On a redundant VPC, bringing up tiers in parallel breaks both routers' NIC layout and VRRP. It has two code approvals (DaanHoogland, Damans227), but still needs an independent test review before it can be merged.

Could one of you test it, or kick a fresh Trillian run? It's on 4.22, so if it gets in before the 24.0 freeze this week it would also land in 24.0 through the merge forward.

@jmsperu jmsperu 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.

Tested the PR head (a6762e9) on 4.22.1.1 (KVM, Ubuntu 24.04, two hosts), with this PR applied on the management server and #14640 on the agents. The PR applies cleanly on the 4.22.1.1 tag and its unit tests pass (NetworkOrchestratorTest, 62 run, 0 failures).

Scenario: create a VPC, then create 6 tiers in parallel and deploy one instance in each, so that all tiers are plugged into the VPC router at the same time. After each run I compared the device IDs of the router NICs in the database and the gateways configured inside the router.

  • Without the PR (control, same day): 2 of 3 runs gave the router two NICs with the same device ID, and in both the router had 5 of 6 tier gateways with one unprocessed guest_network.json left in /var/cache/cloud, while every tier and instance was reported as Implemented and Running. Yesterday the same control gave 4 bad runs of 6.
  • With the PR: 8 of 8 runs clean. Device IDs 0 to 7 with no duplicates, 6 of 6 gateways, nothing left unprocessed, 6 of 6 instances Running, no NullPointerException in the agent log.

LGTM from a functional test. Not tested: VMware or XenServer, adding and removing NICs on user instances by hand, redundant VPC routers.

@weizhouapache weizhouapache left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

code lgtm

@weizhouapache

Copy link
Copy Markdown
Member

merging based on approvals, thanks @bhouse-nexthop @jmsperu

@weizhouapache
weizhouapache merged commit 878175f into apache:4.22 Nov 24, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants