feat: add the Kube-OVN BGP speaker under Overlay Networks > Settings and a BGP option on subnets (#1262) (#1274)

* feat: add the Kube-OVN BGP page and a BGP option on subnets

Add an Overlay Networks > BGP page that edits spec.bgp of the
kube-system/kubeovn Configuration: speaker hosts, neighbor IPv4 and IPv6
addresses, neighbor and cluster AS, router ID and next hops. Add a BGP
option to the subnet form that sets or removes the ovn.kubernetes.io/bgp
annotation. Both need Harvester v1.10.0 or later.



* refactor: move the BGP settings into the kubeovn-operator add-on

Every entry under Overlay Networks is a list, and BGP is a single setting
for the whole Kube-OVN install, so show it as a BGP tab in the
kubeovn-operator add-on's config instead of its own page. The tab saves
spec.bgp of the kube-system/kubeovn Configuration before the add-on is
saved, only when it changed and the add-on stays enabled. The subnet BGP
tooltip now points to it.



* feat: make the BGP tab clearer and check each field as it is typed

- Add a BGP Speaker Enabled/Disabled switch. Disabled removes the speaker
  hosts and keeps the other values. An untouched install opens as
  disabled, with empty fields instead of the placeholder values.
- Neighbors are one list of IPv4 or IPv6 addresses, split by family on
  save with duplicates dropped. Next hops are two single fields, one per
  family, under Advanced.
- Show the errors under each field as it is typed, and keep the same
  checks on save. A router ID is rejected when more than one host runs
  the speaker, because every speaker needs its own.
- Only write the Configuration when the form changed.



* fix: save the BGP tab on top of the latest Kube-OVN Configuration

The operator rewrites the Configuration's status about every five minutes,
so the copy loaded with the form went stale and saving it failed with a
conflict when the form had been open for a while. Fetch the latest copy
at save time and apply only spec.bgp to it. After a successful save,
remember it, so pressing Save again after a failed add-on save doesn't
send the Configuration twice.



* feat: warn on the subnet form when no host runs the BGP speaker

Turning BGP on for a subnet has no effect until some host runs the BGP
speaker. When the subnet's BGP option is Enabled and the Kube-OVN
Configuration has no speaker hosts, show a warning that links to the BGP
tab of the kubeovn-operator add-on. If the Configuration can't be read,
show nothing.

The add-on form now shows its tabs once the BGP data is loaded, so a link
to its #bgp tab opens that tab: Tabbed only honours the URL hash when the
tabs first appear.



* refactor: move the BGP speaker to Overlay Networks > Settings

Keep the BGP configuration out of the kubeovn-operator add-on: add an
Overlay Networks > Settings page that lists cluster-wide overlay network
settings as cards, like Advanced > Settings. The BGP Speaker card shows
whether the speaker is off or where it runs and what it peers with, and
its Edit action opens the BGP form on its own page.

The page owns its Save button, so Save stays disabled while the form has
errors. The add-on goes back to its generic form, and the subnet BGP
warning links to the new page. The speaker state the card and the
warning need is read through a kubeovn.io.configuration model.



* fix: show why Save is disabled on the BGP Speaker page

Save stays disabled while the form is invalid, but an empty Speaker Hosts
or Neighbor Addresses showed no error anywhere, and the neighbor list had
no required mark. Mark Neighbor Addresses as required and flag both
fields when they are left empty, like the other required fields.



* fix: show load errors and fix the add-on link on the BGP pages

- The BGP Speaker page showed only its title when the Kube-OVN
  Configuration could not be read, because the error was only shown
  inside the form. Show it on the page. The Settings card now says
  Unknown instead of Disabled in that case.
- The add-on link on the BGP Speaker page was a relative path, which
  resolved under /overlay-network-settings/ and opened the fail-whale.
  Both pages now link to the add-on by route name.
- The subnet form shows its BGP warning under the BGP option, like the
  DHCP banner, instead of in a column of its own.
- The BGP page reads hosts, neighbors and next hops through the model's
  getters instead of parsing them again.
- The "requires v1.10.0" message uses the product name token, and the
  subnet BGP comment and tooltip no longer say that "local" advertises
  the subnet's CIDR block.



* refactor: keep the Kube-OVN model's parsing helpers private

Nothing outside the model uses splitList or the placeholder neighbor
addresses since the BGP page reads the model's getters, so stop
exporting them.



* feat: tell users to label the external gateway hosts on BGP subnets

When BGP is enabled on a subnet, show a note under it: the hosts that
carry external traffic need the label ovn.kubernetes.io/external-gw=true.
It shows next to the existing warning about the BGP speaker having no
hosts.



* feat: separate the IPv4 and IPv6 BGP neighbors

- The BGP Speaker page now has one neighbor list per family, like the
  next hops. Each list only takes addresses of its own family, and one
  neighbor in either list is enough.
- Reject the placeholder neighbors Harvester installs (192.0.2.1 and
  2001:db8::1). The page hides them on load, so a saved one disappeared
  on the next visit and was dropped on the next save.
- Only treat the Configuration as never set up when it holds nothing
  but the installed values. A speaker set up with the private AS numbers
  64512/64513 and then disabled used to reopen with both AS fields blank.



* feat: edit the BGP speaker on the Overlay Network Settings page

Overlay Network Settings showed one card per setting and opened the BGP
speaker on a page of its own. Show the BGP speaker form on the settings
page instead, in an RcSection titled BGP Speaker, with Save and no
Cancel. Another setting would be another section on the same page, under
the same Save. Saving stays on the page and shows what was saved.

Inside the section, follow how the shell's own RcSection forms are
built: the Enabled/Disabled choice has no label of its own (the section
title names it), and the neighbors and the advanced options are nested
secondary sections, with the two neighbor lists under column headers
instead of their own headings.



* fix: reject IPv4 addresses with leading zeros in the BGP speaker

The speaker parses its addresses with Go, which rejects an IPv4 part
written with a leading zero, like 192.0.2.010. The form accepted those
in the IPv4 neighbors, the router ID and the next hops, and nothing on
the backend checks them, so saving one left the speaker unable to start.
Reject them on every address field, including an IPv6 address that ends
in an IPv4 one, and say how to write the address instead.



* feat: show the BGP speaker as its own entry under Overlay Networks

The backend owner asked for BGP to show in the menu by name rather than
behind a Settings entry. Replace Overlay Networks > Settings with an
Overlay Networks > BGP Speaker entry that opens the form directly,
titled BGP Speaker, and point the subnet's BGP warning and tooltip to
it. If more parts of the Kube-OVN Configuration get a form later, they
can move into a Configuration group under Overlay Networks.



---------


(cherry picked from commit 1b562cec41)

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
This commit is contained in:
mergify[bot]andMarcelo Fukumoto authored and GitHub committed 2026-11-23 11:44:26 +01:00
1 parent fca9eda4a0
commit 8b3585c501
11 files changed
+1386 -1

No files matched your search

+1
View File
@@ -89,6 +89,7 @@ const FEATURE_FLAGS = {
'repositoryStorageClass',
'shutdownVMOnMigrationFailure',
'vmListPagination',
'kubeovnBgp',
],
};
+17
View File
@@ -77,6 +77,8 @@ const EXTERNAL_IPS_GROUP = `${ NAT_INTERNET_GROUP }::External IPs`;
const RULES_GROUP = `${ NAT_INTERNET_GROUP }::Rules`;
const SOURCE_RULES_GROUP = `${ RULES_GROUP }::Source Rules`;
const DESTINATION_RULES_GROUP = `${ RULES_GROUP }::Destination Rules`;
// The BGP speaker part of the Kube-OVN Configuration. If more parts get a form, they can move into a Configuration group.
const BGP_SPEAKER = 'bgp-speaker';
export const PRODUCT_NAME = 'harvester';
@@ -664,6 +666,11 @@ export function init($plugin, store) {
OVERLAY_NETWORKS_GROUP
);
basicType(
[BGP_SPEAKER],
OVERLAY_NETWORKS_GROUP
);
basicType(
[HCI.VPC_NAT_GATEWAY, HCI.VPC_EGRESS_GATEWAY],
GATEWAYS_GROUP
@@ -962,6 +969,16 @@ export function init($plugin, store) {
ifHaveType: NETWORK_POLICY,
});
virtualType({
labelKey: 'harvester.bgp.label',
name: BGP_SPEAKER,
namespaced: false,
weight: 190,
route: { name: `${ PRODUCT_NAME }-c-cluster-bgp-speaker` },
exact: false,
ifHaveType: HCI.KUBEOVN_CONFIG,
});
configureType(HCI.PROVIDER_NETWORK, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({
@@ -92,6 +92,7 @@ export const HCI = {
NODE_UPGRADE_PAUSE_MAP: 'harvesterhci.io/node-upgrade-pause-map',
CDI_POPULATOR_KIND: 'cdi.kubevirt.io/storage.populator.kind',
CNI_NETWORKS: 'k8s.v1.cni.cncf.io/networks',
KUBEOVN_BGP: 'ovn.kubernetes.io/bgp',
WINDOWS_SYSPREP: 'harvesterhci.io/windows-sysprep',
SKIP_MIG_CONFIGURATION: 'harvesterhci.io/skip-mig-configuration',
};
@@ -0,0 +1,117 @@
import EditSubnet from '../index.vue';
const BGP_ANNOTATION = 'ovn.kubernetes.io/bgp';
const { bgpEnabled } = EditSubnet.computed;
function createContext(annotations) {
const value = {
metadata: annotations ? { annotations: { ...annotations } } : {},
setAnnotation(key, val) {
if (val) {
this.metadata.annotations = { ...this.metadata.annotations, [key]: val };
} else if (this.metadata.annotations) {
delete this.metadata.annotations[key];
}
},
};
return {
value,
get bgpEnabled() {
return bgpEnabled.get.call(this);
},
};
}
describe('edit: kubeovn.io.subnet BGP', () => {
it.each([
[undefined, false],
[{}, false],
[{ [BGP_ANNOTATION]: 'false' }, false],
[{ [BGP_ANNOTATION]: 'true' }, true],
[{ [BGP_ANNOTATION]: 'cluster' }, true],
[{ [BGP_ANNOTATION]: 'local' }, true],
])('should read the annotations %j as BGP enabled = %s', (annotations, expected) => {
expect(createContext(annotations).bgpEnabled).toBe(expected);
});
it('should add the BGP annotation when BGP is enabled', () => {
const context = createContext();
bgpEnabled.set.call(context, true);
expect(context.value.metadata.annotations).toStrictEqual({ [BGP_ANNOTATION]: 'true' });
});
it('should remove the BGP annotation when BGP is disabled', () => {
const context = createContext({ [BGP_ANNOTATION]: 'true', other: 'kept' });
bgpEnabled.set.call(context, false);
expect(context.value.metadata.annotations).toStrictEqual({ other: 'kept' });
});
it('should keep a "local" annotation set outside the form when BGP stays enabled', () => {
const context = createContext({ [BGP_ANNOTATION]: 'local' });
bgpEnabled.set.call(context, true);
expect(context.value.metadata.annotations).toStrictEqual({ [BGP_ANNOTATION]: 'local' });
});
});
describe('edit: kubeovn.io.subnet BGP speaker hint', () => {
function fetchContext({ featureEnabled = true, configuration } = {}) {
const dispatch = jest.fn((action) => {
if (action === 'harvester/find') {
return configuration instanceof Error ? Promise.reject(configuration) : Promise.resolve(configuration);
}
return Promise.resolve([]);
});
return {
bgpFeatureEnabled: featureEnabled,
bgpSpeakerOff: false,
$store: {
dispatch,
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/schemaFor': () => ({}),
},
},
};
}
it.each([
['no speaker hosts', { bgpSpeakerHosts: [] }, true],
['speaker hosts', { bgpSpeakerHosts: ['node-1'] }, false],
])('should know whether a host runs the BGP speaker: %s', async(_, configuration, speakerOff) => {
const context = fetchContext({ configuration });
await EditSubnet.fetch.call(context);
expect(context.$store.dispatch).toHaveBeenCalledWith('harvester/find', { type: 'kubeovn.io.configuration', id: 'kube-system/kubeovn' });
expect(context.bgpSpeakerOff).toBe(speakerOff);
});
it('should not warn when the Kube-OVN configuration cannot be read', async() => {
const context = fetchContext({ configuration: new Error('forbidden') });
await EditSubnet.fetch.call(context);
expect(context.bgpSpeakerOff).toBe(false);
});
it('should not read the Kube-OVN configuration on Harvester versions without BGP support', async() => {
const context = fetchContext({ featureEnabled: false });
await EditSubnet.fetch.call(context);
expect(context.$store.dispatch).not.toHaveBeenCalledWith('harvester/find', expect.anything());
});
it('should link to the BGP Speaker page', () => {
expect(EditSubnet.computed.bgpSettingsLocation.call({})).toStrictEqual({ name: 'harvester-c-cluster-bgp-speaker' });
});
});
+76 -1
View File
@@ -13,8 +13,12 @@ import { set, remove } from '@shell/utils/object';
import ArrayList from '@shell/components/form/ArrayList';
import { allHash } from '@shell/utils/promise';
import { HCI } from '../../types';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import ResourceTabs from '@shell/components/form/ResourceTabs/index';
import { Banner } from '@components/Banner';
import MessageLink from '@shell/components/MessageLink';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../config/harvester';
import { KUBEOVN_CONFIGURATION_ID } from '../../models/kubeovn.io.configuration';
import AccessControlList from './AccessControlList';
export default {
@@ -33,6 +37,7 @@ export default {
ArrayList,
ResourceTabs,
Loading,
MessageLink,
AccessControlList
},
@@ -40,6 +45,10 @@ export default {
inheritAttrs: false,
data() {
return { bgpSpeakerOff: false };
},
created() {
const vpc = this.$route.query.vpc || '';
const enableDHCP = this.value?.spec?.enableDHCP || false;
@@ -69,7 +78,16 @@ export default {
vlans: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN }),
};
await allHash(hash);
// BGP on a subnet only has an effect when some host runs the BGP speaker (Overlay Networks > Settings)
if (this.bgpFeatureEnabled && this.$store.getters[`${ inStore }/schemaFor`](HCI.KUBEOVN_CONFIG)) {
hash.kubeovnConfig = this.$store.dispatch(`${ inStore }/find`, { type: HCI.KUBEOVN_CONFIG, id: KUBEOVN_CONFIGURATION_ID }).catch(() => null);
}
const res = await allHash(hash);
if (res.kubeovnConfig) {
this.bgpSpeakerOff = !res.kubeovnConfig.bgpSpeakerHosts?.length;
}
},
computed: {
@@ -133,6 +151,29 @@ export default {
value: n.id,
}));
},
bgpFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('kubeovnBgp');
},
bgpSettingsLocation() {
return { name: `${ HARVESTER_PRODUCT }-c-cluster-bgp-speaker` };
},
bgpEnabled: {
get() {
const bgp = this.value?.metadata?.annotations?.[HCI_ANNOTATIONS.KUBEOVN_BGP];
// Kube-OVN also accepts "cluster" (same as "true") and "local" (only the pod IPs, from the hosts running them)
return !!bgp && bgp !== 'false';
},
set(enabled) {
if (enabled !== this.bgpEnabled) {
this.value.setAnnotation(HCI_ANNOTATIONS.KUBEOVN_BGP, enabled ? 'true' : null);
}
}
},
natOutgoingDisabled() {
// Disable the NAT Outgoing option when the subnet belongs to the ovn-cluster VPC and its name is join or ovn-default.
return this.value?.spec?.vpc === 'ovn-cluster' && ['join', 'ovn-default'].includes(this.value?.metadata?.name);
@@ -369,6 +410,40 @@ export default {
/>
</div>
</div>
<div
v-if="bgpFeatureEnabled"
class="row mt-20"
>
<div class="col span-6">
<RadioGroup
v-model:value="bgpEnabled"
name="bgp"
:options="[true, false]"
:label="t('harvester.subnet.bgp.label')"
:labels="[t('generic.enabled'), t('generic.disabled')]"
:mode="mode"
tooltip-key="harvester.subnet.bgp.tooltip"
/>
<Banner
v-if="bgpEnabled && bgpSpeakerOff"
color="warning"
data-testid="subnet-bgp-speaker-off"
>
<MessageLink
:to="bgpSettingsLocation"
prefix-label="harvester.subnet.bgp.speakerOff.prefix"
middle-label="harvester.subnet.bgp.speakerOff.middle"
suffix-label="harvester.subnet.bgp.speakerOff.suffix"
/>
</Banner>
<Banner
v-if="bgpEnabled"
color="info"
data-testid="subnet-bgp-external-gateway"
:label="t('harvester.subnet.bgp.externalGateway', null, true)"
/>
</div>
</div>
<ArrayList
v-if="showAllowSubnets"
v-model:value="value.spec.allowSubnets"
+65
View File
@@ -1432,6 +1432,14 @@ harvester:
private:
label: Private Subnet
tooltip: Enable network isolation for this Subnet. When enabled, VMs can only communicate within this subnet, even if other subnets exist under the same VPC.
bgp:
label: BGP
tooltip: Advertise this subnet to the BGP neighbors set in Overlay Networks > BGP Speaker.
externalGateway: Label the hosts that act as gateways for external traffic with the key "ovn.kubernetes.io/external-gw" and the value "true".
speakerOff:
prefix: No host runs the BGP speaker yet, so this subnet isn't advertised. Set it up on the
middle: BGP Speaker
suffix: page under Overlay Networks.
allowSubnet:
label: Allow Subnets
tooltip: You can specify certain subnets which can communicate with this subnet.
@@ -1515,6 +1523,63 @@ harvester:
validation:
ip: '"IP Address" must be an IPv4 address, an IPv6 address, or one of each separated by a comma.'
subnet: '"IP Address" must not be in subnet {subnet} ({cidr}) of this VPC.'
bgp:
label: BGP Speaker
noAddonEnabled:
prefix: The kubeovn-operator add-on is not enabled, click
middle: here
suffix: to enable the add-on before setting up the BGP speaker.
unsupported: The BGP speaker requires [[Harvester]] v1.10.0 or later.
description: The BGP speaker runs on the selected hosts and advertises every subnet that has BGP enabled to the BGP neighbors. Enable BGP on each subnet that should be reachable from the external network. When the speaker is disabled, no host runs it, and its settings are kept for when you enable it again.
sections:
advanced: Advanced
nodeNames:
label: Speaker Hosts
placeholder: Select hosts
tooltip: The hosts that run the BGP speaker. Each host connects to every neighbor.
clusterAS:
label: Cluster AS
placeholder: e.g. 65000
tooltip: The autonomous system (AS) number of this cluster.
routerID:
label: Router ID
placeholder: Each host's own IPv4 address
tooltip: Optional. Leave it empty so each host uses its own IPv4 address. Set it only when a single host runs the speaker.
neighborAS:
label: Neighbor AS
placeholder: e.g. 65030
tooltip: The autonomous system (AS) number of the neighbors. All neighbors must be in the same AS.
neighbors:
label: Neighbors
description: The addresses of the external BGP routers the speaker connects to. Add at least one, IPv4 or IPv6.
neighborsV4:
label: IPv4 Address
placeholder: e.g. 10.115.53.2
add: Add IPv4 Neighbor
neighborsV6:
label: IPv6 Address
placeholder: e.g. 2001:db8::2
add: Add IPv6 Neighbor
nextHopV4:
label: Next Hop (IPv4)
placeholder: Each host's own address
tooltip: Optional. The IPv4 next hop of the advertised routes. Leave it empty to use each host's own address.
nextHopV6:
label: Next Hop (IPv6)
placeholder: Each host's own address
tooltip: Optional. The IPv6 next hop of the advertised routes. Leave it empty to use each host's own address.
validation:
hostsRequired: Select at least one speaker host, or set the BGP speaker to Disabled.
neighborRequired: Add at least one neighbor address, IPv4 or IPv6.
neighborV4: '"{ip}" is not an IPv4 address.'
neighborV6: '"{ip}" is not an IPv6 address.'
placeholderNeighbor: '{ip} is the placeholder address Harvester installs, not a BGP router.'
leadingZero: '"{ip}" has a leading zero; write it as {fixed}.'
asNumber: '"{key}" must be a whole number from 1 to {max}.'
routerID: '"Router ID" must be an IPv4 address.'
routerIDMultipleHosts: Leave "Router ID" empty when more than one host runs the speaker, so each host uses its own address.
ipv4: '"{key}" must be an IPv4 address.'
ipv6: '"{key}" must be an IPv6 address.'
natGateway:
label: NAT Gateways
internalTenantNetwork:
@@ -0,0 +1,74 @@
import { isIpv4 } from '@shell/utils/string';
import { isValidIP } from '@shell/utils/validators/cidr';
import HarvesterResource from './harvester';
// The kubeovn-operator keeps a single Configuration; the BGP speaker reads its spec.bgp
export const KUBEOVN_CONFIGURATION_ID = 'kube-system/kubeovn';
// Values Harvester installs before anyone sets up BGP. The addresses are documentation addresses, never a real neighbor.
const PLACEHOLDER_AS = { neighborAS: 64512, clusterAS: 64513 };
const PLACEHOLDER_NEIGHBORS = ['192.0.2.1', '2001:db8::1'];
// spec.bgp keeps its lists as comma-separated strings
const splitList = (value) => `${ value || '' }`.split(',').map((item) => item.trim()).filter(Boolean);
export const isIpv6 = (ip) => isValidIP(ip) && !isIpv4(ip);
export const isPlaceholderNeighbor = (ip) => PLACEHOLDER_NEIGHBORS.includes(`${ ip || '' }`.trim());
// The speaker parses its addresses with Go, which rejects an IPv4 part written with a leading zero (192.0.2.010), so
// the speaker would not start. Returns the address without those zeros, or null when it has none. An IPv6 address
// can end in an IPv4 one (::ffff:10.0.0.1), so only its dotted tail is checked.
export const withoutLeadingZeros = (ip) => {
const value = `${ ip || '' }`.trim();
const tailStart = value.lastIndexOf(':') + 1;
const parts = value.slice(tailStart).split('.');
if (parts.length !== 4 || !parts.some((part) => /^0\d/.test(part))) {
return null;
}
return value.slice(0, tailStart) + parts.map((part) => part.replace(/^0+(?=\d)/, '')).join('.');
};
export default class KubeOvnConfiguration extends HarvesterResource {
get bgp() {
return this.spec?.bgp || {};
}
// The speaker only runs on these hosts: none means BGP is off
get bgpSpeakerHosts() {
return splitList(this.bgp.nodeNames);
}
// The placeholder neighbors are left out: they are never a real BGP router
get bgpNeighborsV4() {
return splitList(this.bgp.neighborV4Address).filter((ip) => !isPlaceholderNeighbor(ip));
}
get bgpNeighborsV6() {
return splitList(this.bgp.neighborV6Address).filter((ip) => !isPlaceholderNeighbor(ip));
}
get bgpNeighbors() {
return [...this.bgpNeighborsV4, ...this.bgpNeighborsV6];
}
get bgpNextHops() {
return splitList(this.bgp.nextHops);
}
// Nobody has set up BGP yet: only the values Harvester installs. A speaker that was set up and then disabled keeps
// its neighbors, so it never matches, even when its AS numbers happen to be the placeholder ones (they are private
// AS numbers anyone can pick).
get bgpUntouched() {
const bgp = this.bgp;
return !this.bgpSpeakerHosts.length &&
!this.bgpNeighbors.length &&
!bgp.routerID &&
!this.bgpNextHops.length &&
bgp.neighborAS === PLACEHOLDER_AS.neighborAS &&
bgp.clusterAS === PLACEHOLDER_AS.clusterAS;
}
}
@@ -0,0 +1,441 @@
import { shallowMount } from '@vue/test-utils';
import { Banner } from '@components/Banner';
import ArrayList from '@shell/components/form/ArrayList';
import CruResource from '@shell/components/CruResource';
import { RcSection } from '@components/RcSection';
import OverlayNetworkSettings from '../index.vue';
import KubeOvnConfiguration, { withoutLeadingZeros } from '../../../../../models/kubeovn.io.configuration';
// What Harvester installs before anyone sets up BGP
const PLACEHOLDER_BGP = {
neighborV4Address: '192.0.2.1',
neighborV6Address: '2001:db8::1',
neighborAS: 64512,
clusterAS: 64513,
};
const CONFIGURED_BGP = {
nodeNames: 'node-1',
neighborV4Address: '10.115.53.2',
neighborV6Address: '2001:db8::1',
neighborAS: 65030,
clusterAS: 65000,
};
// A real model, so the page reads the same getters as in the app
function createConfiguration(bgp = PLACEHOLDER_BGP) {
const configuration = Object.create(KubeOvnConfiguration.prototype);
Object.defineProperty(configuration, 'spec', {
value: { enableBGP: true, bgp: { ...bgp } }, writable: true, configurable: true
});
Object.defineProperty(configuration, 'canUpdate', { value: true, configurable: true });
Object.defineProperty(configuration, 'save', { value: jest.fn().mockResolvedValue({}), configurable: true });
return configuration;
}
// latest: what the API returns at save time, when it differs from the copy loaded with the page
// findError: the API refuses to return the Configuration
function mountPage({
featureEnabled = true, addonEnabled = true, configuration = createConfiguration(), latest = null, findError = null
} = {}) {
const dispatch = jest.fn((action, payload) => {
if (action === 'harvester/find') {
return findError ? Promise.reject(findError) : Promise.resolve(latest || configuration);
}
if (action === 'harvester/clone') {
return Promise.resolve(payload.resource);
}
if (action === 'harvester/findAll' && payload.type === 'harvesterhci.io.addon') {
return Promise.resolve([{ name: 'kubeovn-operator', spec: { enabled: addonEnabled } }]);
}
return Promise.resolve([]);
});
const router = { push: jest.fn() };
const wrapper = shallowMount(OverlayNetworkSettings, {
data: () => ({ addonEnabled, configuration }),
global: {
// the section and the form are stubbed, but what they hold is rendered
renderStubDefaultSlot: true,
mocks: {
$fetchState: { pending: false },
$router: router,
t: (key, args) => (args ? `${ key } ${ JSON.stringify(args) }` : key),
$store: {
dispatch,
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/all': () => [],
'harvester-common/getFeatureEnabled': () => featureEnabled,
},
},
},
},
});
if (configuration) {
wrapper.vm.loadBgp(configuration);
}
return {
wrapper, configuration, dispatch, router
};
}
// A valid, enabled form; each case overrides what it checks
function fill(wrapper, values) {
wrapper.setData({
bgpEnabled: true,
nodeNames: ['node-1'],
neighborsV4: ['10.115.53.2'],
neighborsV6: [],
neighborAS: '65030',
clusterAS: '65000',
routerID: '',
nextHopV4: '',
nextHopV6: '',
...values,
});
}
describe('page: Overlay Networks > BGP Speaker', () => {
it('should load an untouched install as disabled, without the placeholder values', async() => {
const { wrapper, dispatch } = mountPage();
await OverlayNetworkSettings.fetch.call(wrapper.vm);
expect(dispatch).toHaveBeenCalledWith('harvester/find', { type: 'kubeovn.io.configuration', id: 'kube-system/kubeovn' });
expect(wrapper.vm.formState()).toStrictEqual({
enabled: false,
nodeNames: [],
neighborsV4: [],
neighborsV6: [],
neighborAS: '',
clusterAS: '',
routerID: '',
nextHopV4: '',
nextHopV6: '',
});
});
it('should keep the AS numbers of a disabled speaker, even when they are the ones Harvester installs', () => {
// set up with the private AS numbers 64512/64513, then disabled: only the hosts are gone
const configuration = createConfiguration({ ...PLACEHOLDER_BGP, neighborV4Address: '10.115.53.2' });
const { wrapper } = mountPage({ configuration });
expect(wrapper.vm.formState()).toStrictEqual({
enabled: false,
nodeNames: [],
neighborsV4: ['10.115.53.2'],
neighborsV6: [],
neighborAS: '64512',
clusterAS: '64513',
routerID: '',
nextHopV4: '',
nextHopV6: '',
});
});
it('should load a configured speaker, with each neighbor family in its own list', () => {
const configuration = createConfiguration({
...CONFIGURED_BGP, nodeNames: 'node-1,node-2', neighborV6Address: '2001:db8::2', nextHops: '10.115.48.1,2001:db8::9'
});
const { wrapper } = mountPage({ configuration });
expect(wrapper.vm.formState()).toStrictEqual({
enabled: true,
nodeNames: ['node-1', 'node-2'],
neighborsV4: ['10.115.53.2'],
neighborsV6: ['2001:db8::2'],
neighborAS: '65030',
clusterAS: '65000',
routerID: '',
nextHopV4: '10.115.48.1',
nextHopV6: '2001:db8::9',
});
});
it('should edit the BGP speaker on this page, titled BGP Speaker, without a Cancel button', () => {
const { wrapper } = mountPage();
expect(wrapper.find('h1').text()).toBe('harvester.bgp.label');
// the page title names it, so the outer section has no header of its own
expect(wrapper.findComponent(RcSection).props()).toStrictEqual(expect.objectContaining({ type: 'primary', mode: 'no-header' }));
expect(wrapper.findComponent(CruResource).props('showCancel')).toBe(false);
});
it('should name the Enabled/Disabled choice and both neighbor lists for screen readers', async() => {
const { wrapper } = mountPage({ configuration: createConfiguration(CONFIGURED_BGP) });
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="bgp-enabled"]').attributes('aria-label')).toBe('harvester.bgp.label');
expect(wrapper.findAllComponents(ArrayList).map((list) => list.props('a11yLabel'))).toStrictEqual([
'harvester.bgp.neighborsV4.label',
'harvester.bgp.neighborsV6.label',
]);
});
it('should group the neighbors and the advanced options in their own sections when the speaker is enabled', async() => {
const { wrapper } = mountPage({ configuration: createConfiguration(CONFIGURED_BGP) });
await wrapper.vm.$nextTick();
expect(wrapper.findAllComponents(RcSection).map((section) => [section.props('title'), section.props('type')])).toStrictEqual([
['', 'primary'],
['harvester.bgp.neighbors.label', 'secondary'],
['harvester.bgp.sections.advanced', 'secondary'],
]);
});
it('should say the BGP speaker needs v1.10.0 on older Harvester versions', () => {
const { wrapper } = mountPage({ featureEnabled: false, configuration: null });
expect(wrapper.findComponent(RcSection).exists()).toBe(true);
expect(wrapper.findAllComponents(Banner).map((b) => b.props('label'))).toStrictEqual(['harvester.bgp.unsupported']);
expect(wrapper.findComponent(CruResource).exists()).toBe(false);
});
it('should only point to the add-on when it is disabled', () => {
const { wrapper } = mountPage({ addonEnabled: false, configuration: null });
const banners = wrapper.findAllComponents(Banner);
expect(banners).toHaveLength(1);
expect(banners[0].props('color')).toBe('warning');
expect(wrapper.findComponent(CruResource).exists()).toBe(false);
});
it('should show why there is no form when the configuration cannot be read', async() => {
const findError = Object.assign(new Error('configurations.kubeovn.io "kubeovn" is forbidden'), { status: 403 });
const { wrapper } = mountPage({ configuration: null, findError });
await OverlayNetworkSettings.fetch.call(wrapper.vm);
await wrapper.vm.$nextTick();
expect(wrapper.vm.configuration).toBeNull();
expect(wrapper.findAllComponents(Banner).map((b) => b.props('label'))).toStrictEqual(['configurations.kubeovn.io "kubeovn" is forbidden']);
});
it('should link to the kubeovn-operator add-on by route name', () => {
const { wrapper } = mountPage();
expect(wrapper.vm.addonLocation).toStrictEqual({
name: 'harvester-c-cluster-resource-namespace-id',
params: {
resource: 'harvesterhci.io.addon', namespace: 'kube-system', id: 'kubeovn-operator'
},
query: { mode: 'edit' },
});
});
it('should not load the configuration when the add-on is disabled', async() => {
const { wrapper, dispatch } = mountPage({ addonEnabled: false, configuration: null });
await OverlayNetworkSettings.fetch.call(wrapper.vm);
expect(wrapper.vm.addonEnabled).toBe(false);
expect(dispatch).not.toHaveBeenCalledWith('harvester/find', expect.anything());
});
it('should save both neighbor lists without duplicates or empty rows, keep the rest of the configuration and stay on the page', async() => {
const { wrapper, configuration, router } = mountPage();
const buttonCb = jest.fn();
fill(wrapper, {
nodeNames: ['node-1', 'node-2'],
neighborsV4: [' 10.115.53.2 ', '10.115.53.3', '10.115.53.2', ''],
neighborsV6: ['2001:db8::2', ''],
nextHopV4: '10.115.48.1',
nextHopV6: '2001:db8::9',
});
await wrapper.vm.save(buttonCb);
expect(buttonCb).toHaveBeenCalledWith(true);
expect(configuration.save).toHaveBeenCalledTimes(1);
expect(configuration.spec).toStrictEqual({
enableBGP: true,
bgp: {
nodeNames: 'node-1,node-2',
neighborV4Address: '10.115.53.2,10.115.53.3',
neighborV6Address: '2001:db8::2',
neighborAS: 65030,
clusterAS: 65000,
nextHops: '10.115.48.1,2001:db8::9',
},
});
expect(router.push).not.toHaveBeenCalled();
// the form now shows what was saved, so saving again without a change writes nothing
expect(wrapper.vm.formState()).toStrictEqual(expect.objectContaining({ neighborsV4: ['10.115.53.2', '10.115.53.3'], neighborsV6: ['2001:db8::2'] }));
await wrapper.vm.save(buttonCb);
expect(configuration.save).toHaveBeenCalledTimes(1);
});
it('should save on top of the latest copy of the configuration', async() => {
// the operator updated the Configuration after the page loaded it
const latest = createConfiguration();
latest.spec = {
enableBGP: false, ovnCentral: { replicas: 3 }, bgp: { ...PLACEHOLDER_BGP }
};
const { wrapper, configuration, dispatch } = mountPage({ latest });
fill(wrapper);
await wrapper.vm.save(jest.fn());
expect(dispatch).toHaveBeenCalledWith('harvester/find', {
type: 'kubeovn.io.configuration', id: 'kube-system/kubeovn', opt: { force: true }
});
expect(configuration.save).not.toHaveBeenCalled();
expect(latest.save).toHaveBeenCalledTimes(1);
expect(latest.spec).toStrictEqual({
enableBGP: false,
ovnCentral: { replicas: 3 },
bgp: {
nodeNames: 'node-1', neighborV4Address: '10.115.53.2', neighborAS: 65030, clusterAS: 65000
},
});
});
it('should only remove the speaker hosts when BGP is disabled', async() => {
const { wrapper, configuration } = mountPage({ configuration: createConfiguration(CONFIGURED_BGP) });
// invalid values are ignored while disabled
fill(wrapper, { bgpEnabled: false, neighborAS: '' });
expect(wrapper.vm.validationPassed).toBe(true);
await wrapper.vm.save(jest.fn());
const { nodeNames, ...rest } = CONFIGURED_BGP;
expect(configuration.spec.bgp).toStrictEqual(rest);
});
it.each([
['an untouched install', PLACEHOLDER_BGP],
['a configured speaker', CONFIGURED_BGP],
])('should not save the configuration when nothing changed on %s', async(_, bgp) => {
const { wrapper, configuration, router } = mountPage({ configuration: createConfiguration(bgp) });
const buttonCb = jest.fn();
await wrapper.vm.save(buttonCb);
expect(configuration.save).not.toHaveBeenCalled();
expect(buttonCb).toHaveBeenCalledWith(true);
expect(router.push).not.toHaveBeenCalled();
});
it('should report a failed save as plain messages and stay on the page', async() => {
const { wrapper, configuration, router } = mountPage();
const buttonCb = jest.fn();
configuration.save.mockRejectedValue({ status: 409, message: 'the object has been modified' });
fill(wrapper);
await wrapper.vm.save(buttonCb);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(wrapper.vm.errors).toStrictEqual(['the object has been modified']);
expect(router.push).not.toHaveBeenCalled();
});
it.each([
['no speaker hosts', { nodeNames: [] }, 'harvester.bgp.validation.hostsRequired'],
['no neighbor', { neighborsV4: ['', ' '], neighborsV6: [''] }, 'harvester.bgp.validation.neighborRequired'],
['an invalid IPv4 neighbor', { neighborsV4: ['10.115.53.300'] }, 'harvester.bgp.validation.neighborV4'],
['an IPv6 address in the IPv4 neighbors', { neighborsV4: ['2001:db8::2'] }, 'harvester.bgp.validation.neighborV4'],
['an IPv4 address in the IPv6 neighbors', { neighborsV4: [], neighborsV6: ['10.115.53.2'] }, 'harvester.bgp.validation.neighborV6'],
['the IPv4 placeholder neighbor', { neighborsV4: ['192.0.2.1'] }, 'harvester.bgp.validation.placeholderNeighbor'],
['the IPv6 placeholder neighbor', { neighborsV6: ['2001:db8::1'] }, 'harvester.bgp.validation.placeholderNeighbor'],
['an IPv4 neighbor with a leading zero', { neighborsV4: ['192.0.2.010'] }, 'harvester.bgp.validation.leadingZero'],
['an IPv6 neighbor ending in an IPv4 address with a leading zero', { neighborsV6: ['::ffff:10.0.0.010'] }, 'harvester.bgp.validation.leadingZero'],
['a router ID with a leading zero', { routerID: '10.115.048.1' }, 'harvester.bgp.validation.leadingZero'],
['an IPv4 next hop with a leading zero', { nextHopV4: '010.115.48.1' }, 'harvester.bgp.validation.leadingZero'],
['an IPv6 next hop ending in an IPv4 address with a leading zero', { nextHopV6: '::ffff:10.115.48.01' }, 'harvester.bgp.validation.leadingZero'],
['an empty AS number', { neighborAS: '' }, 'harvester.bgp.validation.asNumber'],
['an AS number out of range', { clusterAS: '4294967295' }, 'harvester.bgp.validation.asNumber'],
['a router ID that is not IPv4', { routerID: '2001:db8::1' }, 'harvester.bgp.validation.routerID'],
['a router ID shared by two hosts', { nodeNames: ['node-1', 'node-2'], routerID: '10.115.48.1' }, 'harvester.bgp.validation.routerIDMultipleHosts'],
['an IPv6 address as the IPv4 next hop', { nextHopV4: '2001:db8::9' }, 'harvester.bgp.validation.ipv4'],
['an IPv4 address as the IPv6 next hop', { nextHopV6: '10.115.48.1' }, 'harvester.bgp.validation.ipv6'],
])('should disable Save and not save %s', async(_, values, errorKey) => {
const { wrapper, configuration } = mountPage();
const buttonCb = jest.fn();
fill(wrapper, values);
expect(wrapper.vm.validationPassed).toBe(false);
await wrapper.vm.save(buttonCb);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(wrapper.vm.errors).toStrictEqual([expect.stringContaining(errorKey)]);
expect(configuration.save).not.toHaveBeenCalled();
});
it('should flag missing speaker hosts and neighbors on the fields', async() => {
const { wrapper } = mountPage();
const [hostsRule] = wrapper.vm.nodeNamesRules;
const [v4Rule] = wrapper.vm.neighborV4Rules;
const [v6Rule] = wrapper.vm.neighborV6Rules;
fill(wrapper, {
nodeNames: [], neighborsV4: [''], neighborsV6: ['']
});
expect(hostsRule([])).toContain('harvester.bgp.validation.hostsRequired');
expect(hostsRule(['node-1'])).toBeUndefined();
// no neighbor yet: both lists say so
expect(v4Rule('')).toContain('harvester.bgp.validation.neighborRequired');
expect(v6Rule('')).toContain('harvester.bgp.validation.neighborRequired');
await wrapper.setData({ neighborsV6: ['2001:db8::2'] });
// one neighbor in either list is enough; an address of the wrong family is flagged
expect(v4Rule('')).toBeUndefined();
expect(v4Rule('2001:db8::2')).toContain('harvester.bgp.validation.neighborV4');
expect(v6Rule('10.115.53.2')).toContain('harvester.bgp.validation.neighborV6');
expect(v6Rule('2001:db8::1')).toContain('harvester.bgp.validation.placeholderNeighbor');
});
it.each([
['192.0.2.010', '192.0.2.10'],
['010.115.053.002', '10.115.53.2'],
['10.0.0.00', '10.0.0.0'],
['::ffff:10.0.0.010', '::ffff:10.0.0.10'],
['192.0.2.10', null],
['0.0.0.0', null],
['2001:db8::0002', null],
['', null],
])('should find the leading zeros the speaker cannot parse in %j', (ip, fixed) => {
expect(withoutLeadingZeros(ip)).toBe(fixed);
});
it('should say how to write an address with a leading zero', () => {
const { wrapper } = mountPage();
const [rule] = wrapper.vm.neighborV4Rules;
fill(wrapper);
expect(rule('192.0.2.010')).toBe('harvester.bgp.validation.leadingZero {"ip":"192.0.2.010","fixed":"192.0.2.10"}');
});
it('should flag a router ID inline as soon as a second host is picked', async() => {
const { wrapper } = mountPage();
const [rule] = wrapper.vm.routerIDRules;
fill(wrapper, { routerID: '10.115.48.1' });
expect(rule('10.115.48.1')).toBeUndefined();
await wrapper.setData({ nodeNames: ['node-1', 'node-2'] });
expect(rule('10.115.48.1')).toContain('harvester.bgp.validation.routerIDMultipleHosts');
});
});
@@ -0,0 +1,588 @@
<script>
import isEqual from 'lodash/isEqual';
import ArrayList from '@shell/components/form/ArrayList';
import CruResource from '@shell/components/CruResource';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import Loading from '@shell/components/Loading';
import MessageLink from '@shell/components/MessageLink';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import { RcSection } from '@components/RcSection';
import { RcContentGroup } from '@components/Layout';
import { NODE } from '@shell/config/types';
import { _EDIT, _VIEW } from '@shell/config/query-params';
import { isIpv4 } from '@shell/utils/string';
import { exceptionToErrorsArray } from '@shell/utils/error';
import { allHash } from '@shell/utils/promise';
import { HCI } from '../../../../types';
import { ADD_ONS } from '../../../../config/harvester-map';
import { PRODUCT_NAME } from '../../../../config/harvester';
import { KUBEOVN_CONFIGURATION_ID, isIpv6, isPlaceholderNeighbor, withoutLeadingZeros } from '../../../../models/kubeovn.io.configuration';
const AS_MAX = 4294967294;
const cleanList = (list) => [...new Set((list || []).map((item) => `${ item || '' }`.trim()).filter(Boolean))];
const isAsNumber = (value) => /^\d+$/.test(`${ value ?? '' }`.trim()) && Number(value) >= 1 && Number(value) <= AS_MAX;
const asText = (value) => `${ value ?? '' }`.trim();
// The BGP speaker part of the Kube-OVN Configuration (Overlay Networks > BGP Speaker)
export default {
name: 'HarvesterBgpSpeaker',
components: {
ArrayList,
Banner,
CruResource,
LabeledInput,
LabeledSelect,
Loading,
MessageLink,
RadioGroup,
RcContentGroup,
RcSection,
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const hash = await allHash({
addons: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.ADD_ONS }),
nodes: this.$store.dispatch(`${ inStore }/findAll`, { type: NODE }),
});
this.addonEnabled = hash.addons.find((addon) => addon.name === ADD_ONS.KUBEOVN_OPERATOR)?.spec?.enabled === true;
if (!this.addonEnabled || !this.featureEnabled) {
return;
}
try {
const configuration = await this.$store.dispatch(`${ inStore }/find`, { type: HCI.KUBEOVN_CONFIG, id: KUBEOVN_CONFIGURATION_ID });
this.configuration = await this.$store.dispatch(`${ inStore }/clone`, { resource: configuration });
this.loadBgp(this.configuration);
} catch (e) {
this.errors = exceptionToErrorsArray(e);
}
},
data() {
return {
addonEnabled: false,
configuration: null,
bgpEnabled: false,
nodeNames: [],
neighborsV4: [],
neighborsV6: [],
neighborAS: '',
clusterAS: '',
routerID: '',
nextHopV4: '',
nextHopV6: '',
loadedState: null,
// Bumped after a save so the form is drawn again from the saved values, as after a reload
formKey: 0,
errors: [],
};
},
computed: {
featureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('kubeovnBgp');
},
mode() {
return this.configuration?.canUpdate ? _EDIT : _VIEW;
},
isView() {
return this.mode === _VIEW;
},
addonLocation() {
return {
name: `${ PRODUCT_NAME }-c-cluster-resource-namespace-id`,
params: {
resource: HCI.ADD_ONS, namespace: 'kube-system', id: ADD_ONS.KUBEOVN_OPERATOR
},
query: { mode: _EDIT },
};
},
// Save stays disabled until the form is valid; each field shows its own error
validationPassed() {
return this.validateBgp().length === 0;
},
nodeOptions() {
const inStore = this.$store.getters['currentProduct'].inStore;
const nodes = this.$store.getters[`${ inStore }/all`](NODE) || [];
return nodes.map((node) => ({
label: node.nameDisplay,
value: node.id,
}));
},
// Each field shows its own error once touched, so a disabled Save always has a visible reason
nodeNamesRules() {
return [(value) => ((value || []).length ? undefined : this.t('harvester.bgp.validation.hostsRequired', null, true))];
},
neighborV4Rules() {
return [(value) => this.neighborError(value, isIpv4)];
},
neighborV6Rules() {
return [(value) => this.neighborError(value, isIpv6)];
},
// One neighbor in either list is enough
hasNeighbor() {
return cleanList(this.neighborsV4).length + cleanList(this.neighborsV6).length > 0;
},
neighborASRules() {
return [(value) => this.asError('neighborAS', value)];
},
clusterASRules() {
return [(value) => this.asError('clusterAS', value)];
},
routerIDRules() {
return [(value) => this.routerIDError(value)];
},
nextHopV4Rules() {
return [(value) => this.nextHopError('nextHopV4', value, isIpv4)];
},
nextHopV6Rules() {
return [(value) => this.nextHopError('nextHopV6', value, isIpv6)];
},
},
methods: {
loadBgp(configuration) {
const bgp = configuration.bgp;
const untouched = configuration.bgpUntouched;
this.nodeNames = configuration.bgpSpeakerHosts;
this.bgpEnabled = this.nodeNames.length > 0;
this.neighborsV4 = configuration.bgpNeighborsV4;
this.neighborsV6 = configuration.bgpNeighborsV6;
// An untouched install only has placeholder AS numbers: show empty fields instead of values nobody chose
this.neighborAS = untouched ? '' : bgp.neighborAS ?? '';
this.clusterAS = untouched ? '' : bgp.clusterAS ?? '';
this.routerID = bgp.routerID || '';
// The speaker uses the last next hop of each family
this.nextHopV4 = configuration.bgpNextHops.filter(isIpv4).pop() || '';
this.nextHopV6 = configuration.bgpNextHops.filter(isIpv6).pop() || '';
this.loadedState = this.formState();
},
formState() {
return {
enabled: this.bgpEnabled,
nodeNames: [...this.nodeNames],
neighborsV4: cleanList(this.neighborsV4),
neighborsV6: cleanList(this.neighborsV6),
neighborAS: asText(this.neighborAS),
clusterAS: asText(this.clusterAS),
routerID: this.routerID.trim(),
nextHopV4: this.nextHopV4.trim(),
nextHopV6: this.nextHopV6.trim(),
};
},
neighborError(value, isFamily) {
const ip = `${ value || '' }`.trim();
if (!ip) {
return this.hasNeighbor ? undefined : this.t('harvester.bgp.validation.neighborRequired', null, true);
}
if (withoutLeadingZeros(ip)) {
return this.leadingZeroError(ip);
}
// Harvester installs these before anyone sets up BGP, and this page hides them, so saving one would lose it
if (isPlaceholderNeighbor(ip)) {
return this.t('harvester.bgp.validation.placeholderNeighbor', { ip }, true);
}
const key = isFamily === isIpv4 ? 'neighborV4' : 'neighborV6';
return isFamily(ip) ? undefined : this.t(`harvester.bgp.validation.${ key }`, { ip }, true);
},
asError(field, value) {
return isAsNumber(value) ? undefined : this.t('harvester.bgp.validation.asNumber', { key: this.t(`harvester.bgp.${ field }.label`), max: AS_MAX }, true);
},
// The speaker can't parse these, so it would not start
leadingZeroError(ip) {
return this.t('harvester.bgp.validation.leadingZero', { ip, fixed: withoutLeadingZeros(ip) }, true);
},
routerIDError(value) {
const ip = `${ value || '' }`.trim();
if (!ip) {
return undefined;
}
if (withoutLeadingZeros(ip)) {
return this.leadingZeroError(ip);
}
if (!isIpv4(ip)) {
return this.t('harvester.bgp.validation.routerID', null, true);
}
// Every speaker needs its own router ID, and this one would go to every selected host
return this.nodeNames.length > 1 ? this.t('harvester.bgp.validation.routerIDMultipleHosts', null, true) : undefined;
},
nextHopError(field, value, isFamily) {
const ip = `${ value || '' }`.trim();
const key = isFamily === isIpv4 ? 'ipv4' : 'ipv6';
if (ip && withoutLeadingZeros(ip)) {
return this.leadingZeroError(ip);
}
return ip && !isFamily(ip) ? this.t(`harvester.bgp.validation.${ key }`, { key: this.t(`harvester.bgp.${ field }.label`) }, true) : undefined;
},
validateBgp() {
if (!this.bgpEnabled) {
return [];
}
const errors = [];
if (!this.nodeNames.length) {
errors.push(this.t('harvester.bgp.validation.hostsRequired', null, true));
}
if (!this.hasNeighbor) {
errors.push(this.t('harvester.bgp.validation.neighborRequired', null, true));
} else {
// The first bad address is enough here: the lists flag each one
errors.push([
...cleanList(this.neighborsV4).map((ip) => this.neighborError(ip, isIpv4)),
...cleanList(this.neighborsV6).map((ip) => this.neighborError(ip, isIpv6)),
].find(Boolean));
}
errors.push(
this.asError('neighborAS', this.neighborAS),
this.asError('clusterAS', this.clusterAS),
this.routerIDError(this.routerID),
this.nextHopError('nextHopV4', this.nextHopV4, isIpv4),
this.nextHopError('nextHopV6', this.nextHopV6, isIpv6),
);
return errors.filter(Boolean);
},
toBgpSpec(current = {}) {
const bgp = { ...current };
// Disabled: no host runs the speaker. Keep the other values for when it is turned back on.
if (!this.bgpEnabled) {
delete bgp.nodeNames;
return bgp;
}
const state = this.formState();
Object.assign(bgp, {
nodeNames: state.nodeNames.join(','),
neighborV4Address: state.neighborsV4.join(','),
neighborV6Address: state.neighborsV6.join(','),
neighborAS: Number(state.neighborAS),
clusterAS: Number(state.clusterAS),
routerID: state.routerID,
nextHops: [state.nextHopV4, state.nextHopV6].filter(Boolean).join(','),
});
// The CRD omits empty strings, so drop them instead of storing ''
Object.keys(bgp).forEach((key) => {
if (bgp[key] === '') {
delete bgp[key];
}
});
return bgp;
},
async save(buttonCb) {
// Save is disabled while the form is invalid; this is the backstop
const errors = this.validateBgp();
if (errors.length) {
this.errors = errors;
buttonCb(false);
return;
}
try {
if (!isEqual(this.formState(), this.loadedState)) {
// The operator keeps updating the Configuration's status, so the copy loaded with the page goes stale
// and saving it fails with a conflict. Save the BGP values on top of the latest copy instead.
const inStore = this.$store.getters['currentProduct'].inStore;
const latest = await this.$store.dispatch(`${ inStore }/find`, {
type: HCI.KUBEOVN_CONFIG, id: KUBEOVN_CONFIGURATION_ID, opt: { force: true }
});
const configuration = await this.$store.dispatch(`${ inStore }/clone`, { resource: latest });
const bgp = this.toBgpSpec(configuration.spec?.bgp);
if (!isEqual(bgp, configuration.spec?.bgp || {})) {
configuration.spec = { ...configuration.spec, bgp };
await configuration.save();
}
// Stay on the page, showing what was saved
this.configuration = configuration;
this.loadBgp(configuration);
this.formKey++;
}
this.errors = [];
buttonCb(true);
} catch (e) {
this.errors = exceptionToErrorsArray(e);
buttonCb(false);
}
},
},
};
</script>
<template>
<Loading v-if="$fetchState.pending" />
<div v-else>
<h1 class="mb-20">
{{ t('harvester.bgp.label') }}
</h1>
<CruResource
v-if="featureEnabled && addonEnabled && configuration"
:resource="configuration"
:mode="mode"
:can-yaml="false"
:show-cancel="false"
:validation-passed="validationPassed"
:errors="errors"
@finish="save"
@error="e => errors = e"
>
<RcSection
:key="formKey"
type="primary"
mode="no-header"
:expandable="false"
data-testid="bgp-section"
>
<RcContentGroup>
<Banner
color="info"
class="mt-0 mb-0"
:label="t('harvester.bgp.description')"
/>
<!-- The section title names this choice, as in the shell's own sections -->
<RadioGroup
v-model:value="bgpEnabled"
data-testid="bgp-enabled"
name="bgp-enabled"
:aria-label="t('harvester.bgp.label')"
:mode="mode"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
/>
</RcContentGroup>
<template v-if="bgpEnabled">
<RcContentGroup>
<div class="row">
<div class="col span-12">
<LabeledSelect
v-model:value="nodeNames"
data-testid="bgp-node-names"
:mode="mode"
:multiple="true"
:required="true"
:rules="nodeNamesRules"
:options="nodeOptions"
:label="t('harvester.bgp.nodeNames.label')"
:placeholder="t('harvester.bgp.nodeNames.placeholder')"
:tooltip="t('harvester.bgp.nodeNames.tooltip')"
/>
</div>
</div>
<div class="row">
<div class="col span-6">
<LabeledInput
v-model:value="clusterAS"
data-testid="bgp-cluster-as"
type="number"
min="1"
:required="true"
:mode="mode"
:rules="clusterASRules"
:label="t('harvester.bgp.clusterAS.label')"
:placeholder="t('harvester.bgp.clusterAS.placeholder')"
:tooltip="t('harvester.bgp.clusterAS.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="routerID"
data-testid="bgp-router-id"
:mode="mode"
:rules="routerIDRules"
:label="t('harvester.bgp.routerID.label')"
:placeholder="t('harvester.bgp.routerID.placeholder', null, true)"
:tooltip="t('harvester.bgp.routerID.tooltip')"
/>
</div>
</div>
</RcContentGroup>
<RcSection
:title="t('harvester.bgp.neighbors.label')"
type="secondary"
mode="with-header"
:expandable="false"
data-testid="bgp-neighbors-section"
>
<!-- One neighbor in either list is enough, so neither list is marked required -->
<p
v-if="!isView"
class="mb-0"
>
{{ t('harvester.bgp.neighbors.description') }}
</p>
<div class="row">
<div class="col span-6">
<ArrayList
v-model:value="neighborsV4"
data-testid="bgp-neighbors-v4"
:mode="mode"
:initial-empty-row="true"
:rules="neighborV4Rules"
:show-header="true"
:value-label="t('harvester.bgp.neighborsV4.label')"
:a11y-label="t('harvester.bgp.neighborsV4.label')"
:value-placeholder="t('harvester.bgp.neighborsV4.placeholder')"
:add-label="t('harvester.bgp.neighborsV4.add')"
/>
</div>
<div class="col span-6">
<ArrayList
v-model:value="neighborsV6"
data-testid="bgp-neighbors-v6"
:mode="mode"
:initial-empty-row="true"
:rules="neighborV6Rules"
:show-header="true"
:value-label="t('harvester.bgp.neighborsV6.label')"
:a11y-label="t('harvester.bgp.neighborsV6.label')"
:value-placeholder="t('harvester.bgp.neighborsV6.placeholder')"
:add-label="t('harvester.bgp.neighborsV6.add')"
/>
</div>
</div>
<div class="row">
<div class="col span-6">
<LabeledInput
v-model:value="neighborAS"
data-testid="bgp-neighbor-as"
type="number"
min="1"
:required="true"
:mode="mode"
:rules="neighborASRules"
:label="t('harvester.bgp.neighborAS.label')"
:placeholder="t('harvester.bgp.neighborAS.placeholder')"
:tooltip="t('harvester.bgp.neighborAS.tooltip')"
/>
</div>
</div>
</RcSection>
<RcSection
:title="t('harvester.bgp.sections.advanced')"
type="secondary"
mode="with-header"
:expandable="false"
data-testid="bgp-advanced-section"
>
<div class="row">
<div class="col span-6">
<LabeledInput
v-model:value="nextHopV4"
data-testid="bgp-next-hop-v4"
:mode="mode"
:rules="nextHopV4Rules"
:label="t('harvester.bgp.nextHopV4.label')"
:placeholder="t('harvester.bgp.nextHopV4.placeholder', null, true)"
:tooltip="t('harvester.bgp.nextHopV4.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="nextHopV6"
data-testid="bgp-next-hop-v6"
:mode="mode"
:rules="nextHopV6Rules"
:label="t('harvester.bgp.nextHopV6.label')"
:placeholder="t('harvester.bgp.nextHopV6.placeholder', null, true)"
:tooltip="t('harvester.bgp.nextHopV6.tooltip')"
/>
</div>
</div>
</RcSection>
</template>
</RcSection>
</CruResource>
<!-- No form: the section says why -->
<RcSection
v-else
type="primary"
mode="no-header"
:expandable="false"
data-testid="bgp-section"
>
<Banner
v-if="!featureEnabled"
color="warning"
class="mt-0 mb-0"
:label="t('harvester.bgp.unsupported')"
/>
<Banner
v-else-if="!addonEnabled"
color="warning"
class="mt-0 mb-0"
>
<MessageLink
:to="addonLocation"
prefix-label="harvester.bgp.noAddonEnabled.prefix"
middle-label="harvester.bgp.noAddonEnabled.middle"
suffix-label="harvester.bgp.noAddonEnabled.suffix"
/>
</Banner>
<!-- The Configuration could not be read -->
<template v-else>
<Banner
v-for="(err, i) in errors"
:key="i"
color="error"
class="mt-0 mb-0"
:label="err"
/>
</template>
</RcSection>
</div>
</template>
@@ -19,6 +19,7 @@ import HarvesterUnsupported from '../pages/c/_cluster/unsupported/index.vue';
import ForkliftDashboard from '../pages/c/_cluster/vm-migration/index.vue';
import ForkliftVmMigrationWizard from '../pages/c/_cluster/vm-migration/vm-migration-wizard.vue';
import ForkliftProviderWizard from '../pages/c/_cluster/vm-migration/provider-wizard.vue';
import BgpSpeaker from '../pages/c/_cluster/bgp-speaker/index.vue';
const routes = [
{
@@ -98,6 +99,10 @@ const routes = [
name: `${ PRODUCT_NAME }-c-cluster-vm-migration-provider-wizard`,
path: `/:product/c/:cluster/vm-migration/provider-wizard`,
component: ForkliftProviderWizard,
}, {
name: `${ PRODUCT_NAME }-c-cluster-bgp-speaker`,
path: `/:product/c/:cluster/bgp-speaker`,
component: BgpSpeaker,
}, {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
path: `/:product/c/:cluster/:resource`,
+1
View File
@@ -33,6 +33,7 @@ export const HCI = {
PROVIDER_NETWORK: 'kubeovn.io.providernetwork',
VPC_NAT_GATEWAY: 'kubeovn.io.vpcnatgateway',
VPC_EGRESS_GATEWAY: 'kubeovn.io.vpcegressgateway',
KUBEOVN_CONFIG: 'kubeovn.io.configuration',
VM_IMAGE_DOWNLOADER: 'harvesterhci.io.virtualmachineimagedownloader',
SUPPORT_BUNDLE: 'harvesterhci.io.supportbundle',
NETWORK_ATTACHMENT: 'harvesterhci.io.networkattachmentdefinition',