Compare commits

..
2 Commits
115 changed files with 2195 additions and 15723 deletions

No files matched your search

+4 -15
View File
@@ -1,6 +1,6 @@
{ {
"name": "harvester-ui-extension", "name": "harvester-ui-extension",
"version": "1.10.0-dev", "version": "1.10.0-rc2",
"private": false, "private": false,
"engines": { "engines": {
"node": ">=24.0.0" "node": ">=24.0.0"
@@ -16,7 +16,6 @@
"cache-loader": "^4.1.0", "cache-loader": "^4.1.0",
"color": "4.2.3", "color": "4.2.3",
"ip": "2.0.1", "ip": "2.0.1",
"ipaddr.js": "2.4.0",
"@xterm/xterm": "6.0.0", "@xterm/xterm": "6.0.0",
"@xterm/addon-fit": "0.11.0", "@xterm/addon-fit": "0.11.0",
"@xterm/addon-search": "0.16.0", "@xterm/addon-search": "0.16.0",
@@ -30,31 +29,21 @@
}, },
"resolutions": { "resolutions": {
"@novnc/novnc": "1.7.0", "@novnc/novnc": "1.7.0",
"@tootallnate/once": "^2.0.1", "@types/node": "25.9.6",
"@types/lodash": "4.17.25",
"@types/node": "25.3.3",
"cookie": "0.7.2",
"cronstrue": "2.59.0", "cronstrue": "2.59.0",
"d3-color": "3.1.0", "d3-color": "3.1.0",
"**/diff2html/diff": "5.2.2",
"ejs": "3.1.10", "ejs": "3.1.10",
"follow-redirects": "1.16.0", "follow-redirects": "1.16.0",
"glob": "7.2.3", "glob": "7.2.3",
"glob-parent": "6.0.2", "glob-parent": "6.0.2",
"json5": "2.2.3", "json5": "2.2.3",
"markdown-it": "14.3.1", "@types/lodash": "4.17.25",
"merge": "2.1.1", "merge": "2.1.1",
"node-forge": "1.4.0", "node-forge": "1.4.0",
"nth-check": "2.1.1", "nth-check": "2.1.1",
"postcss": "8.5.26",
"postcss-selector-parser": "7.1.6",
"qs": "6.16.0", "qs": "6.16.0",
"roarr": "7.21.7", "roarr": "7.21.7",
"semver": "7.5.4", "semver": "7.8.5",
"serialize-javascript": "7.0.5",
"uuid": "11.1.1",
"webpack-dev-server": "5.2.6",
"ws": "8.21.0",
"@vue/cli-service/html-webpack-plugin": "^5.0.0" "@vue/cli-service/html-webpack-plugin": "^5.0.0"
}, },
"scripts": { "scripts": {
+5 -38
View File
@@ -6,30 +6,26 @@ import ModalWithCard from '@shell/components/ModalWithCard';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations'; import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import { STORAGE_CLASS } from '@shell/config/types';
import { HCI } from '../types'; import { HCI } from '../types';
import UpgradeInfo from './UpgradeInfo'; import UpgradeInfo from './UpgradeInfo';
import UpgradeRepositoryStorageClass, { getUpgradeRepositoryStorageClassDefault } from './UpgradeRepositoryStorageClass';
export default { export default {
name: 'HarvesterUpgrade', name: 'HarvesterUpgrade',
components: { components: {
Checkbox, ModalWithCard, LabeledSelect, Banner, UpgradeInfo, UpgradeRepositoryStorageClass Checkbox, ModalWithCard, LabeledSelect, Banner, UpgradeInfo
}, },
async fetch() { async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore; const inStore = this.$store.getters['currentProduct'].inStore;
const res = await allHash({ const res = await allHash({
upgradeVersion: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SETTING }), upgradeVersion: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SETTING }),
versions: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VERSION }), versions: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VERSION }),
upgrade: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.UPGRADE }), upgrade: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.UPGRADE }),
storageClasses: this.$store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS }),
}); });
this.upgrade = res.upgrade; this.upgrade = res.upgrade;
this.storageClassName = getUpgradeRepositoryStorageClassDefault(res.storageClasses);
}, },
data() { data() {
@@ -39,7 +35,6 @@ export default {
errors: '', errors: '',
selectMode: true, selectMode: true,
version: '', version: '',
storageClassName: '',
enableLogging: true, enableLogging: true,
skipSingleReplicaDetachedVol: false, skipSingleReplicaDetachedVol: false,
readyReleaseNote: false, readyReleaseNote: false,
@@ -64,10 +59,6 @@ export default {
return this.versionOptions.length > 0 && !this.isUpgradeInProgress; return this.versionOptions.length > 0 && !this.isUpgradeInProgress;
}, },
canSubmitUpgrade() {
return this.readyReleaseNote && (!this.repositoryStorageClassEnabled || !!this.storageClassName);
},
versionOptions() { versionOptions() {
const versions = this.$store.getters['harvester/all'](HCI.VERSION) || []; const versions = this.$store.getters['harvester/all'](HCI.VERSION) || [];
@@ -84,16 +75,6 @@ export default {
return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG); return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG);
}, },
storageClasses() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/all`](STORAGE_CLASS) || [];
},
repositoryStorageClassEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('repositoryStorageClass');
},
skipSingleReplicaDetachedVolFeatureEnabled() { skipSingleReplicaDetachedVolFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('skipSingleReplicaDetachedVol'); return this.$store.getters['harvester-common/getFeatureEnabled']('skipSingleReplicaDetachedVol');
}, },
@@ -143,13 +124,6 @@ export default {
upgradeValue.spec.logEnabled = this.enableLogging; upgradeValue.spec.logEnabled = this.enableLogging;
} }
if (this.repositoryStorageClassEnabled && this.storageClassName) {
upgradeValue.metadata.annotations = {
...upgradeValue.metadata.annotations,
[HCI_ANNOTATIONS.UPGRADE_STORAGE_CLASS]: this.storageClassName
};
}
const proxyResource = await this.$store.dispatch('harvester/create', upgradeValue); const proxyResource = await this.$store.dispatch('harvester/create', upgradeValue);
try { try {
@@ -230,13 +204,6 @@ export default {
:clearable="true" :clearable="true"
/> />
<UpgradeRepositoryStorageClass
v-if="repositoryStorageClassEnabled"
v-model:value="storageClassName"
class="mb-10"
:storage-classes="storageClasses"
/>
<div <div
v-if="canEnableLogging" v-if="canEnableLogging"
class="mb-5" class="mb-5"
@@ -296,7 +263,7 @@ export default {
<t k="generic.close" /> <t k="generic.close" />
</button> </button>
<button <button
:disabled="!canSubmitUpgrade" :disabled="!readyReleaseNote"
class="btn role-tertiary bg-primary" class="btn role-tertiary bg-primary"
@click.prevent="handleUpgrade" @click.prevent="handleUpgrade"
> >
+8
View File
@@ -141,6 +141,10 @@ export default {
filterCategorySettings() { filterCategorySettings() {
return this.settings.filter((s) => { return this.settings.filter((s) => {
if (!this.getFeatureEnabled(s.featureFlag)) {
return false;
}
if (this.category !== 'advanced') { if (this.category !== 'advanced') {
return (CATEGORY[this.category] || []).find((item) => item === s.id); return (CATEGORY[this.category] || []).find((item) => item === s.id);
} else if (this.category === 'advanced') { } else if (this.category === 'advanced') {
@@ -151,6 +155,10 @@ export default {
}) || []; }) || [];
}, },
getFeatureEnabled(id) {
return id ? this.$store.getters['harvester-common/getFeatureEnabled'](id) : true;
},
getSettingOption(id) { getSettingOption(id) {
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id); return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
}, },
@@ -1,83 +0,0 @@
<script>
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LVM_DRIVER } from '../models/harvester/storage.k8s.io.storageclass';
import { isInternalStorageClass } from '../utils/storage-class';
export function getUpgradeRepositoryStorageClassDefault(storageClasses) {
return storageClasses.find((storageClass) => storageClass.isDefault &&
!storageClass.parameters?.backingImage &&
storageClass.provisioner !== LVM_DRIVER &&
!isInternalStorageClass(storageClass.name))?.name || '';
}
export default {
name: 'UpgradeRepositoryStorageClass',
components: { LabeledSelect },
props: {
value: {
type: String,
default: '',
},
storageClasses: {
type: Array,
default: () => [],
},
disabled: {
type: Boolean,
default: false,
},
},
emits: ['update:value'],
computed: {
storageClassOptions() {
const t = this.$store.getters['i18n/t'];
return this.storageClasses
.filter((storageClass) => !storageClass.parameters?.backingImage && storageClass.provisioner !== LVM_DRIVER)
.map((storageClass) => {
let label = storageClass.isDefault ? `${ storageClass.name } (${ t('generic.default') })` : storageClass.name;
let disabled = false;
if (isInternalStorageClass(storageClass.name)) {
label += ` (${ t('harvester.storage.internal.label') })`;
disabled = true;
}
return {
label,
value: storageClass.name,
disabled
};
});
},
},
};
</script>
<template>
<LabeledSelect
:value="value"
:label="t('harvester.upgradePage.repositoryStorageClass')"
:tooltip="t('harvester.upgradePage.repositoryStorageClassTooltip')"
:placeholder="t('harvester.upgradePage.repositoryStorageClassPlaceholder')"
:options="storageClassOptions"
:disabled="disabled"
required
@update:value="$emit('update:value', $event)"
>
<template #no-options="{ searching }">
<span
v-if="!searching"
class="text-muted"
>
{{ t('harvester.upgradePage.repositoryStorageClassNoOptions', null, true) }}
</span>
</template>
</LabeledSelect>
</template>
@@ -1,86 +0,0 @@
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import HarvesterUpgrade from '../HarvesterUpgrade.vue';
const save = jest.fn().mockResolvedValue();
const upgrade = { notifyGeneratedName: jest.fn(), save };
function createForm(storageClassName = '', repositoryStorageClassEnabled = true) {
return {
version: 'v1.10.0',
storageClassName,
repositoryStorageClassEnabled,
canEnableLogging: false,
enableLogging: true,
skipSingleReplicaDetachedVolFeatureEnabled: false,
skipSingleReplicaDetachedVol: false,
cancel: jest.fn(),
errors: '',
$store: { dispatch: jest.fn().mockResolvedValue(upgrade) }
};
}
describe('component: HarvesterUpgrade', () => {
it('uses the shared Upgrade Repository StorageClass selector', () => {
expect(HarvesterUpgrade.components.UpgradeRepositoryStorageClass).toBeDefined();
});
it('leaves the default empty when it is unavailable for upgrade repositories', async() => {
const form = {
upgrade: [],
storageClassName: 'previous',
$store: {
getters: { currentProduct: { inStore: 'harvester' } },
dispatch: jest.fn()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{
name: 'lvm-local', isDefault: true, provisioner: 'lvm.driver.harvesterhci.io'
},
{ name: 'fast' }
])
}
};
await HarvesterUpgrade.fetch.call(form);
expect(form.storageClassName).toBe('');
});
it('blocks the upgrade when no StorageClass is selected', () => {
const canSubmitUpgrade = HarvesterUpgrade.computed.canSubmitUpgrade;
expect(canSubmitUpgrade.call({
readyReleaseNote: true,
repositoryStorageClassEnabled: true,
storageClassName: ''
})).toBe(false);
});
it('saves the selected StorageClass as an Upgrade annotation', async() => {
const form = createForm('fast');
await HarvesterUpgrade.methods.handleUpgrade.call(form);
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/create', expect.objectContaining({
metadata: expect.objectContaining({ annotations: { [HCI_ANNOTATIONS.UPGRADE_STORAGE_CLASS]: 'fast' } }),
spec: { version: 'v1.10.0' }
}));
});
it('omits the repository StorageClass when the feature is disabled', async() => {
const form = createForm('fast', false);
await HarvesterUpgrade.methods.handleUpgrade.call(form);
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/create', {
type: 'harvesterhci.io.upgrade',
metadata: {
generateName: 'hvst-upgrade-',
namespace: 'harvester-system'
},
spec: { version: 'v1.10.0' }
});
});
});
@@ -1,40 +0,0 @@
import UpgradeRepositoryStorageClass, { getUpgradeRepositoryStorageClassDefault } from '../UpgradeRepositoryStorageClass.vue';
const storageClasses = [
{ name: 'fast', isDefault: true },
{ name: 'image-cache', parameters: { backingImage: 'image' } },
{ name: 'lvm-local', provisioner: 'lvm.driver.harvesterhci.io' },
{ name: 'longhorn-static' },
{ name: 'slow' }
];
describe('component: UpgradeRepositoryStorageClass', () => {
it('omits backing-image and LVM StorageClasses while disabling internal classes', () => {
const form = {
storageClasses,
$store: { getters: { 'i18n/t': (key) => key } }
};
expect(UpgradeRepositoryStorageClass.computed.storageClassOptions.call(form)).toStrictEqual([
{
label: 'fast (generic.default)', value: 'fast', disabled: false
},
{
label: 'longhorn-static (harvester.storage.internal.label)', value: 'longhorn-static', disabled: true
},
{
label: 'slow', value: 'slow', disabled: false
},
]);
});
it('does not use an unavailable StorageClass as the default', () => {
expect(getUpgradeRepositoryStorageClassDefault([
{
name: 'lvm-local', isDefault: true, provisioner: 'lvm.driver.harvesterhci.io'
},
{ name: 'longhorn-static' },
{ name: 'fast' }
])).toBe('');
});
});
@@ -1,357 +0,0 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useStore } from 'vuex';
import SortableTable from '@shell/components/SortableTable';
import { BadgeState } from '@components/BadgeState';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcButton } from '@components/RcButton';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _EDIT, _VIEW } from '@shell/config/query-params';
import { HCI } from '../../types';
import {
AFFECTED_RESOURCES_TRUNCATE_COUNT, MESSAGE_TRUNCATE_LENGTH, activeAffectedResourceNames, affectedResourceLabel,
allAffectedResourceNames, hasIgnored, ignoreRuleName, ignoredResourceCount, resourceIgnoredBy, severityColor
} from '../../utils/component-health';
const props = defineProps({
rows: {
type: Array,
required: true,
},
ignoreRules: {
type: Array,
default: () => [],
},
// what is typed in the filter box of the table this one sits in
filterText: {
type: String,
default: '',
},
// the checks could not be loaded, so having none does not mean there are no issues
loadFailed: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['open-rule']);
const store = useStore();
const { t } = useI18n(store);
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.componentHealth.severity',
value: 'severityRank',
sort: 'severityRank',
search: false,
width: 110,
},
{
name: 'checkName',
labelKey: 'harvester.dashboard.sections.componentHealth.check',
value: 'checkName',
sort: 'checkName',
// all that a row shows, so the filter also finds a resource hidden behind "more"
search: 'filterText',
},
{
name: 'message',
labelKey: 'harvester.dashboard.sections.componentHealth.message',
value: 'message',
search: false,
canBeVariable: true,
},
{
name: 'affectedCount',
labelKey: 'harvester.dashboard.sections.componentHealth.affectedCount',
value: 'affectedCount',
sort: 'affectedCount',
search: false,
width: 340,
canBeVariable: true,
},
];
const table = ref(null);
// this table has no filter box of its own, but it filters its rows the same way
watch([table, () => props.filterText], ([checksTable, text]) => {
if (checksTable) {
checksTable.searchQuery = text;
}
});
const canCreateRule = computed(() => {
const schema = store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE);
return !!schema?.collectionMethods?.find((method) => method.toLowerCase() === 'post');
});
// only the rule the UI made for the check, others on it are left as they are
function actionsOf(row) {
const name = ignoreRuleName(row.componentHealthName, row.checkName);
const rule = props.ignoreRules.find(({ metadata }) => metadata?.name === name);
const action = (key, icon, invoke) => ({
action: key,
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
icon: `icon ${ icon }`,
enabled: true,
invoke,
});
const open = (mode) => () => emit('open-rule', {
row, rule, mode
});
if (!rule) {
return canCreateRule.value ? [action(_CREATE, 'icon-plus', open(_CREATE))] : [];
}
const actions = [action(_VIEW, 'icon-document', open(_VIEW))];
if (rule.canUpdate) {
actions.push(action(_EDIT, 'icon-edit', open(_EDIT)));
}
if (rule.canDelete) {
actions.push({ divider: true }, action('delete', 'icon-trash', () => rule.promptRemove()));
}
return actions;
}
// the table's action menu reads them from the row, as it does on a resource
const rowsWithActions = computed(() => props.rows.map((row) => ({ ...row, availableActions: actionsOf(row) })));
// a menu that could only say there is nothing to do is left out
const hasActions = computed(() => rowsWithActions.value.some((row) => row.availableActions.length));
const expandedMessageIds = ref([]);
const expandedResourceIds = ref([]);
const shownIgnoredIds = ref([]);
// a check ignored as a whole lists all its resources, the others only the ones still reported
function listedResourceNames(row) {
return row.ignored ? allAffectedResourceNames(row) : activeAffectedResourceNames(row);
}
function ignoredResourceNames(row) {
const active = activeAffectedResourceNames(row);
return allAffectedResourceNames(row).filter((name) => !active.includes(name));
}
// called from the template, where the refs are unwrapped, so the array is changed in place
function toggleId(list, id) {
const index = list.indexOf(id);
if (index === -1) {
list.push(id);
} else {
list.splice(index, 1);
}
}
function isMessageTruncated(message) {
return !!message && message.length > MESSAGE_TRUNCATE_LENGTH;
}
function displayedMessage(row, message) {
return expandedMessageIds.value.includes(row.id) || !isMessageTruncated(message) ? message : message.slice(0, MESSAGE_TRUNCATE_LENGTH);
}
// the ignored resources come after the others, once their link is used
function visibleAffectedResourceNames(row) {
const names = listedResourceNames(row);
const shown = expandedResourceIds.value.includes(row.id) ? names : names.slice(0, AFFECTED_RESOURCES_TRUNCATE_COUNT);
return shownIgnoredIds.value.includes(row.id) ? [...shown, ...ignoredResourceNames(row)] : shown;
}
function remainingAffectedResourcesCount(row) {
return Math.max(listedResourceNames(row).length - AFFECTED_RESOURCES_TRUNCATE_COUNT, 0);
}
function isResourceIgnored(row, name) {
return row.ignored || !!resourceIgnoredBy(row, name);
}
// the ignored resources of a check that is still reported, which have a link of their own
function ignoredLinkCount(row) {
return row.ignored ? 0 : ignoredResourceCount(row);
}
</script>
<template>
<div
v-if="!rows.length"
class="text-muted"
>
{{ t(`harvester.dashboard.sections.componentHealth.${ loadFailed ? 'checksNotLoaded' : 'noIssues' }`) }}
</div>
<SortableTable
v-else
ref="table"
:rows="rowsWithActions"
:headers="headers"
key-field="id"
:search="false"
:table-actions="false"
:row-actions="hasActions"
:paging="true"
:rows-per-page="10"
default-sort-by="severity"
>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<template #cell:checkName="{row, value}">
<span :class="{ 'text-muted': row.ignored, 'has-ignored': hasIgnored(row) }">
{{ value }}
<template v-if="row.ignored">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</template>
</span>
</template>
<template #cell:message="{row, value}">
<span :class="{ 'text-muted': row.ignored }">
{{ displayedMessage(row, value) }}
<RcButton
v-if="isMessageTruncated(value)"
variant="link"
size="small"
class="compact-link"
:aria-expanded="expandedMessageIds.includes(row.id)"
@click="toggleId(expandedMessageIds, row.id)"
>
{{ expandedMessageIds.includes(row.id) ? t('generic.showLess') : t('generic.showMore') }}
</RcButton>
</span>
</template>
<template #cell:affectedCount="{row, value}">
<div
v-if="allAffectedResourceNames(row).length"
class="affected-resources"
>
<div class="affected-title">
<span class="text-label">{{ affectedResourceLabel(row, store) }}</span>
<RcCounterBadge
:count="value || allAffectedResourceNames(row).length"
type="inactive"
/>
<span class="api-version text-muted">{{ row.affectedResources.apiVersion }}</span>
</div>
<div class="affected-names">
<RcTag
v-for="name in visibleAffectedResourceNames(row)"
:key="name"
class="affected-name"
:class="{ ignored: isResourceIgnored(row, name) }"
type="inactive"
:disabled="isResourceIgnored(row, name)"
>
<span class="name">{{ name }}</span>
<!-- when all of the check is ignored its name says so -->
<span v-if="!row.ignored && isResourceIgnored(row, name)">
({{ t('harvester.dashboard.sections.componentHealth.ignore.ignored') }})
</span>
</RcTag>
</div>
<div
v-if="remainingAffectedResourcesCount(row) || ignoredLinkCount(row)"
class="affected-links"
>
<RcButton
v-if="remainingAffectedResourcesCount(row)"
variant="link"
size="small"
class="compact-link more-link"
:aria-expanded="expandedResourceIds.includes(row.id)"
@click="toggleId(expandedResourceIds, row.id)"
>
{{ expandedResourceIds.includes(row.id) ? t('generic.showLess') : t('generic.plusMore', { n: remainingAffectedResourcesCount(row) }) }}
</RcButton>
<RcButton
v-if="ignoredLinkCount(row)"
variant="link"
size="small"
class="compact-link ignored-link"
:aria-expanded="shownIgnoredIds.includes(row.id)"
@click="toggleId(shownIgnoredIds, row.id)"
>
{{ shownIgnoredIds.includes(row.id) ? t('harvester.dashboard.sections.componentHealth.ignore.hideIgnored') : t('harvester.dashboard.sections.componentHealth.ignore.plusIgnored', { n: ignoredLinkCount(row) }) }}
</RcButton>
</div>
</div>
<span v-else>
{{ t('harvester.dashboard.sections.componentHealth.noAffectedResources') }}
</span>
</template>
</SortableTable>
</template>
<style lang="scss" scoped>
// a check with anything ignored stands out, in the colour of a warning banner
:deep(tbody tr.main-row:has(.has-ignored)) {
background-color: var(--warning-banner-bg);
}
// these sit next to text, so they line up with it
.compact-link {
--rc-button-padding: 0;
}
.affected-resources {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding: 4px 0;
}
.affected-title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 8px;
margin-bottom: 4px;
}
.api-version {
font-size: 12px;
}
.affected-links {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.affected-names {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.affected-name {
max-width: 100%;
font-size: 12px;
// a long name wraps, so none is ever cut off
.name {
min-width: 0;
overflow-wrap: anywhere;
}
// the ones that count are filled, the ignored ones are only outlined
&.rc-tag.ignored {
background: transparent;
border-style: dashed;
border-color: var(--rc-disabled-text-color);
}
}
</style>
@@ -1,350 +0,0 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { HCI } from '../../types';
import { useStore } from 'vuex';
import { useI18n } from '@shell/composables/useI18n';
import SortableTable from '@shell/components/SortableTable';
import { exceptionToErrorsArray } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { RcCounterBadge } from '@components/Pill';
import { RcButton } from '@components/RcButton';
import { useModal } from '@components/RcModal';
import ComponentChecksTable from './ComponentChecksTable.vue';
import IgnoreRuleModal from './IgnoreRuleModal.vue';
import {
COMPONENT_HEALTH_SEVERITIES, HEALTH_SUMMARY_SEVERITY_RANK, affectedResourceKind, affectedResourceLabel,
allAffectedResourceNames, componentOf, healthSummarySeverity, severityColor
} from '../../utils/component-health';
const store = useStore();
const { t } = useI18n(store);
const table = ref(null);
const loading = ref(true);
const lists = {
healthSummaries: ref([]),
componentHealths: ref([]),
ignoreRules: ref([]),
};
const { healthSummaries, componentHealths, ignoreRules } = lists;
// the lists that could not be loaded, with why
const loadErrors = ref({});
const headers = [
{
name: 'severity',
labelKey: 'harvester.dashboard.sections.healthSummary.severity',
value: 'severityRank',
sort: 'severityRank',
search: 'severity',
width: 110,
},
{
name: 'component',
labelKey: 'harvester.dashboard.sections.healthSummary.component',
value: 'component',
sort: 'component',
// the table's filter only looks at its own rows, the checks are in the sub-rows
search: ['component', 'checksFilterText'],
},
{
align: 'right',
name: 'errorCount',
labelKey: 'harvester.dashboard.sections.healthSummary.errorCount',
value: 'errorCount',
sort: 'errorCount',
search: false,
width: 120,
},
{
align: 'right',
name: 'warningCount',
labelKey: 'harvester.dashboard.sections.healthSummary.warningCount',
value: 'warningCount',
sort: 'warningCount',
search: false,
width: 120,
},
];
const {
open: openRuleModal, isOpen: ruleModalOpen, payload: ruleToOpen, modal: ruleModal
} = useModal();
const showIgnored = ref(false);
const filterText = computed(() => table.value?.searchQuery || '');
const checks = computed(() => {
const result = [];
(componentHealths.value || []).forEach((componentHealth) => {
const component = componentOf(componentHealth);
const statusChecks = componentHealth?.status?.checks || {};
Object.entries(statusChecks).forEach(([checkName, check]) => {
result.push({
id: `${ componentHealth.id }/${ checkName }`,
component,
componentHealthName: componentHealth.metadata?.name,
checkName,
ignored: !!check.ignored,
severity: check.severity,
// the table sorts on a row property, the severities are not in alphabetical order
severityRank: COMPONENT_HEALTH_SEVERITIES.indexOf(check.severity),
message: check.message,
affectedCount: check.affectedCount,
affectedResources: check.affectedResources,
});
});
});
return result;
});
const shownChecks = computed(() => checks.value.filter((check) => showIgnored.value || !check.ignored).map((check) => ({
...check,
filterText: [
check.component,
check.severity,
check.checkName,
check.message,
check.affectedResources?.apiVersion,
affectedResourceKind(check),
affectedResourceLabel(check, store),
// the ignored resources too, they are behind a link like the ones past the first few
...allAffectedResourceNames(check),
].join(' ').toLowerCase(),
})));
// the checks ignored as a whole, the ones the checkbox brings back
const ignoredCheckCount = computed(() => checks.value.filter((check) => check.ignored).length);
const rows = computed(() => {
const result = [];
(healthSummaries.value || []).forEach((healthSummary) => {
const components = healthSummary?.status?.components || {};
Object.entries(components).forEach(([component, counts]) => {
const componentChecks = shownChecks.value.filter((check) => check.component === component);
const row = {
id: `${ healthSummary.id }/${ component }`,
component,
errorCount: counts?.errorCount || 0,
warningCount: counts?.warningCount || 0,
checksFilterText: componentChecks.map((check) => check.filterText).join(' '),
checks: componentChecks,
};
row.severity = healthSummarySeverity(row);
// the table sorts on a row property, so the severity has to be on the row
row.severityRank = HEALTH_SUMMARY_SEVERITY_RANK[row.severity];
result.push(row);
});
});
return result;
});
onMounted(async() => {
const types = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
};
if (store.getters['harvester/schemaFor'](HCI.HEALTH_IGNORE_RULE)) {
types.ignoreRules = HCI.HEALTH_IGNORE_RULE;
}
// a list that fails does not stop the others from showing
await Promise.all(Object.entries(types).map(async([key, type]) => {
try {
lists[key].value = await store.dispatch('harvester/findAll', { type });
} catch (err) {
loadErrors.value[key] = exceptionToErrorsArray(err).join(', ');
}
}));
loading.value = false;
});
// the table has these from shell 3.0.15, in the props of its #header-right slot, so they can go with that bump
function expandAll() {
table.value.expanded = Object.fromEntries(rows.value.map((row) => [row.id, true]));
}
function collapseAll() {
table.value.expanded = {};
}
</script>
<template>
<Banner
v-for="(error, key) in loadErrors"
:key="key"
color="error"
:label="t(`harvester.dashboard.sections.componentHealth.loadFailed.${ key }`, { error })"
/>
<SortableTable
ref="table"
:rows="rows"
:headers="headers"
:loading="loading"
key-field="id"
:table-actions="false"
:row-actions="false"
:paging="true"
:rows-per-page="10"
:sub-rows="true"
:sub-expandable="true"
:sub-expand-column="true"
default-sort-by="severity"
>
<template #header-left>
<div
v-if="ignoredCheckCount"
class="show-ignored"
>
<!-- the label holds the badge, so the checkbox is named here -->
<Checkbox
v-model:value="showIgnored"
type="checkbox"
:alternate-label="`${ t('harvester.dashboard.sections.componentHealth.showIgnored') } ${ ignoredCheckCount }`"
>
<template #label>
<span class="show-ignored-label">
{{ t('harvester.dashboard.sections.componentHealth.showIgnored') }}
<RcCounterBadge
:count="ignoredCheckCount"
type="inactive"
/>
</span>
</template>
</Checkbox>
</div>
</template>
<template #header-right>
<div
v-if="rows.length"
class="expand-actions"
>
<RcButton
variant="link"
size="small"
@click="expandAll"
>
{{ t('harvester.dashboard.sections.healthSummary.expandAll') }}
</RcButton>
<RcButton
variant="link"
size="small"
@click="collapseAll"
>
{{ t('harvester.dashboard.sections.healthSummary.collapseAll') }}
</RcButton>
</div>
</template>
<template #cell:severity="{row}">
<BadgeState
:color="severityColor(row.severity)"
:label="row.severity"
/>
</template>
<!-- the table's chevron can't take the keyboard focus, this opens the row from the keyboard -->
<template #cell:component="{row}">
<RcButton
variant="link"
class="component-name"
:aria-expanded="!!table?.isExpanded(row)"
@click="table.toggleExpand(row)"
>
{{ row.component }}
</RcButton>
</template>
<template #sub-row="{row, fullColspan}">
<tr class="sub-row">
<td :colspan="fullColspan">
<ComponentChecksTable
class="sub-table"
:rows="row.checks"
:ignore-rules="ignoreRules"
:filter-text="filterText"
:load-failed="!!loadErrors.componentHealths"
@open-rule="openRuleModal"
/>
</td>
</tr>
</template>
</SortableTable>
<!-- mounted each time it opens, so the form always starts over -->
<IgnoreRuleModal
v-if="ruleModalOpen"
v-bind="ruleToOpen"
:modal="ruleModal"
/>
</template>
<style lang="scss" scoped>
// the filter box in the same row is taller, this lines up with it
.show-ignored {
display: flex;
align-items: center;
height: 100%;
}
.show-ignored-label {
display: inline-flex;
align-items: center;
gap: 6px;
}
.expand-actions {
display: flex;
align-items: center;
gap: 8px;
}
// a button is taller than the table's rows
.component-name {
--rc-button-padding: 0;
&.rc-button.btn-medium:not(.btn-sm) {
min-height: 0;
line-height: inherit;
}
}
// the shell has this look for a table in a sub-row from 3.0.15, this can go with that bump
.sub-row {
background-color: var(--body-bg) !important;
> td:first-child {
padding-left: 0;
padding-right: 0;
}
.sub-table {
padding: 16px 32px;
}
:deep(.sortable-table) {
border: 0;
border-radius: 0;
outline: 0;
}
:deep(thead tr:hover) {
background-color: var(--body-bg);
}
:deep(thead th) {
font-weight: 600;
}
:deep(tbody tr) {
border-bottom: 0;
}
}
</style>
@@ -1,327 +0,0 @@
<script setup>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
import isEqual from 'lodash/isEqual';
import Banner from '@components/Banner/Banner.vue';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcButton } from '@components/RcButton';
import { RcHeading } from '@components/RcHeading';
import { RcModal } from '@components/RcModal';
import LabelValue from '@shell/components/LabelValue';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { useI18n } from '@shell/composables/useI18n';
import { _CREATE, _VIEW } from '@shell/config/query-params';
import { exceptionToErrorsArray } from '@shell/utils/error';
import { dateTimeFormat } from '@shell/utils/time';
import { HCI } from '../../types';
import { IGNORE_DURATION_DAYS, IGNORE_RULE_SOURCE_LABEL, allAffectedResourceNames, ignoreRuleName } from '../../utils/component-health';
const props = defineProps({
row: {
type: Object,
required: true,
},
// empty when the rule is created
rule: {
type: Object,
default: null,
},
mode: {
type: String,
default: _CREATE,
},
// `show` and the `close` handler, from whoever owns this modal's visibility
modal: {
type: Object,
required: true,
},
});
const store = useStore();
const { t } = useI18n(store);
const isView = computed(() => props.mode === _VIEW);
const ruleResources = props.rule?.spec?.resources || [];
const expiresAt = props.rule?.spec?.expiresAt;
const hasExpired = !!expiresAt && !dayjs(expiresAt).isAfter(dayjs());
// a rule can still list resources that are no longer affected
const resourceOptions = computed(() => [...new Set([...allAffectedResourceNames(props.row), ...ruleResources])]);
// a rule that lists no resource ignores the entire check
const chosenScope = ref(props.rule && !ruleResources.length ? 'check' : null);
const scope = computed({
get: () => chosenScope.value || (resourceOptions.value.length ? 'resources' : 'check'),
// the shell's RadioGroup still takes the arrow keys once it is clicked, even when disabled
set: (value) => {
if (!locked.value && !isView.value) {
chosenScope.value = value;
}
},
});
// null selects every resource, the ones that are not selected are kept visible
const selected = ref(ruleResources.length ? ruleResources : null);
// a rule keeps the expiry it has until another duration is chosen
const duration = ref(props.rule ? null : 'days7');
const reason = ref(props.rule?.spec?.reason || '');
const errors = ref([]);
const saving = ref(false);
const selectedResources = computed(() => {
return selected.value === null ? resourceOptions.value : resourceOptions.value.filter((name) => selected.value.includes(name));
});
const scopeOptions = computed(() => [
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeCheck'), value: 'check' },
{ label: t('harvester.dashboard.sections.componentHealth.ignore.scopeResources'), value: 'resources' },
]);
const durationOptions = computed(() => Object.keys(IGNORE_DURATION_DAYS).map((key) => ({
label: t(`harvester.dashboard.sections.componentHealth.ignore.${ key }`),
value: key,
})));
// worked out once for each choice, so the date shown is the date saved
const newExpiresAt = computed(() => {
const days = IGNORE_DURATION_DAYS[duration.value];
return days ? dayjs().add(days, 'day').toISOString() : undefined;
});
const spec = computed(() => {
const out = {
componentHealth: props.row.componentHealthName,
checkKey: props.row.checkName,
};
// the rule only lists the selected resources, so it does not swallow the ones coming later
if (scope.value === 'resources') {
out.resources = selectedResources.value;
}
const expiry = duration.value ? newExpiresAt.value : expiresAt;
if (expiry) {
out.expiresAt = expiry;
}
if (reason.value) {
out.reason = reason.value;
}
return out;
});
// what the form changes, in an order that does not depend on the options
const editable = (ruleSpec) => ({
resources: [...(ruleSpec?.resources || [])].sort(),
expiresAt: ruleSpec?.expiresAt || '',
reason: ruleSpec?.reason || '',
});
const hasChanges = computed(() => !props.rule || !isEqual(editable(spec.value), editable(props.rule.spec)));
// an expired rule applies to nothing, so it only takes changes once it has a new expiration
const locked = computed(() => hasExpired && !isView.value && !duration.value);
// a rule that lists no resource would ignore the entire check
const canSave = computed(() => !locked.value && (scope.value === 'check' || selectedResources.value.length > 0) && hasChanges.value);
const currentExpiry = computed(() => {
if (!expiresAt) {
return t('harvester.dashboard.sections.componentHealth.ignore.neverExpires');
}
return t(`harvester.dashboard.sections.componentHealth.ignore.${ hasExpired ? 'expiredOn' : 'expiresOn' }`, { date: dateTimeFormat(expiresAt, store) });
});
const newExpiry = computed(() => {
if (!newExpiresAt.value) {
return t('harvester.dashboard.sections.componentHealth.ignore.willNeverExpire');
}
return t('harvester.dashboard.sections.componentHealth.ignore.willExpireOn', { date: dateTimeFormat(newExpiresAt.value, store) });
});
function close() {
// stays open while the rule is saved, so a failure can still be shown
if (!saving.value) {
props.modal.onClose();
}
}
async function save() {
errors.value = [];
saving.value = true;
try {
const rule = props.rule ? await store.dispatch('harvester/clone', { resource: props.rule }) : await store.dispatch('harvester/create', {
type: HCI.HEALTH_IGNORE_RULE,
metadata: {
name: ignoreRuleName(props.row.componentHealthName, props.row.checkName),
labels: { [IGNORE_RULE_SOURCE_LABEL]: 'user' },
},
});
rule.spec = spec.value;
await rule.save();
store.dispatch('growl/success', {
title: t('generic.notification.title.succeed'),
message: t(`harvester.dashboard.sections.componentHealth.ignore.${ props.rule ? 'updated' : 'created' }`, { name: props.row.checkName }),
}, { root: true });
saving.value = false;
close();
} catch (err) {
errors.value = exceptionToErrorsArray(err?.data || err);
saving.value = false;
}
}
</script>
<template>
<!-- Not v-bind="modal": closing goes through close(), which refuses while the rule is saved -->
<RcModal
:show="modal.show"
:title="t(`harvester.dashboard.sections.componentHealth.ignore.${ mode }`)"
data-testid="component-health-ignore-modal"
@close="close"
@primary-action="save"
>
<Banner
v-if="hasExpired && !isView"
class="m-0"
color="warning"
data-testid="component-health-ignore-expired"
:label="t('harvester.dashboard.sections.componentHealth.ignore.expiredBanner', { date: dateTimeFormat(expiresAt, store) })"
/>
<div class="row">
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.component')"
:value="row.component"
/>
</div>
<div class="col span-6">
<LabelValue
:name="t('harvester.dashboard.sections.componentHealth.check')"
:value="row.checkName"
/>
</div>
</div>
<!-- first, as an expired rule's other fields wait for it -->
<div>
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.duration') }}
</RcHeading>
<p
v-if="rule"
class="current-expiry mb-10"
data-testid="component-health-ignore-current-expiry"
>
{{ currentExpiry }}
</p>
<template v-if="!isView">
<RadioGroup
v-model:value="duration"
name="ignore-duration"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.duration')"
:mode="mode"
:options="durationOptions"
:row="true"
/>
<p
v-if="duration"
class="new-expiry text-muted"
data-testid="component-health-ignore-new-expiry"
>
{{ newExpiry }}
</p>
</template>
</div>
<div v-if="resourceOptions.length">
<RcHeading :size="4">
{{ t('harvester.dashboard.sections.componentHealth.ignore.scope') }}
</RcHeading>
<RadioGroup
v-model:value="scope"
name="ignore-scope"
:aria-label="t('harvester.dashboard.sections.componentHealth.ignore.scope')"
:mode="mode"
:disabled="locked"
:options="scopeOptions"
/>
<div
v-if="scope === 'resources'"
class="ignore-resources"
>
<LabeledSelect
:value="selectedResources"
:label="t('harvester.dashboard.sections.componentHealth.ignore.resources')"
:mode="mode"
:options="resourceOptions"
:multiple="true"
:close-on-select="false"
:clearable="false"
:required="!isView"
:disabled="locked"
@update:value="selected = $event"
/>
</div>
</div>
<LabeledInput
v-model:value="reason"
:label="t('harvester.dashboard.sections.componentHealth.ignore.reason')"
:placeholder="isView ? '' : t('harvester.dashboard.sections.componentHealth.ignore.reasonPlaceholder')"
:mode="mode"
:disabled="locked"
/>
<Banner
v-for="(err, i) in errors"
:key="i"
class="m-0"
color="error"
:label="err"
/>
<template
v-if="isView"
#actions="{ close: closeModal }"
>
<RcButton
variant="primary"
size="large"
data-testid="component-health-ignore-close"
@click="closeModal"
>
{{ t('generic.close') }}
</RcButton>
</template>
<template
v-else
#primary-action="{ primaryAction }"
>
<RcButton
variant="primary"
size="large"
:disabled="!canSave || saving"
:aria-busy="saving"
data-testid="component-health-ignore-confirm"
@click="primaryAction"
>
{{ t(rule ? 'generic.save' : 'generic.create') }}
</RcButton>
</template>
</RcModal>
</template>
<style lang="scss" scoped>
// lines the field up with the radio's label
.ignore-resources {
margin: 10px 0 0 19px;
}
</style>
@@ -1,992 +0,0 @@
import { mount as vtuMount, flushPromises } from '@vue/test-utils';
import { createStore } from 'vuex';
import Banner from '@components/Banner/Banner.vue';
import { BadgeState } from '@components/BadgeState';
import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { RcCounterBadge, RcTag } from '@components/Pill';
import { RcModal } from '@components/RcModal';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { HCI } from '../../../types';
import { affectedResourceLabel, hasIgnored, ignoreRuleName, totalErrorCount } from '../../../utils/component-health';
import HealthSummaryTable from '../HealthSummaryTable.vue';
import ComponentChecksTable from '../ComponentChecksTable.vue';
import IgnoreRuleModal from '../IgnoreRuleModal.vue';
jest.mock('focus-trap', () => ({
createFocusTrap: jest.fn(() => ({
activate: jest.fn(),
deactivate: jest.fn(),
})),
}));
const TYPES = {
healthSummaries: HCI.HEALTH_SUMMARY,
componentHealths: HCI.COMPONENT_HEALTH,
ignoreRules: HCI.HEALTH_IGNORE_RULE,
};
const saveRule = jest.fn();
const newRule = { save: saveRule };
const editedRule = { save: saveRule };
const createRule = jest.fn(() => newRule);
const cloneRule = jest.fn(() => editedRule);
let store;
// resources are fetched by the components themselves, so serve them from a mocked store
const opts = (props = {}) => {
store = createStore({
getters: {
'i18n/t': () => (k) => k,
'i18n/exists': () => () => true,
'prefs/get': () => () => false,
currentProduct: () => ({ inStore: 'harvester' }),
'harvester/schemaFor': () => (type) => (props.noSchemaFor === type ? null : { collectionMethods: props.collectionMethods || ['GET', 'POST'] }),
'type-map/labelFor': () => (schema, count) => `label of ${ count }`,
},
actions: {
'growl/success': jest.fn(),
'harvester/findAll': (_, { type }) => {
const key = Object.keys(TYPES).find((k) => TYPES[k] === type);
props.onFindAll?.(type);
return props.failing === key ? Promise.reject(new Error('failed')) : props[key] || [];
},
'harvester/create': createRule,
'harvester/clone': cloneRule,
}
});
return { global: { plugins: [store], stubs: { teleport: true } } };
};
const toggleExpand = jest.fn();
// renders the summary rows with every sub-row open, and the checks of each sub-row
const summaryTable = {
props: ['rows', 'headers'],
data() {
return { searchQuery: '', expanded: {} };
},
methods: { toggleExpand, isExpanded: () => false },
template: `<div>
<slot name="header-left" />
<slot name="header-right" />
<div class="summary">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>
<div v-for="row in rows" :key="row.id" class="name"><slot name="cell:component" :row="row" /></div>
<div v-for="row in rows" :key="row.id" :class="'sub-' + row.component"><slot name="sub-row" :row="row" :fullColspan="1" /></div>
</div>`,
};
const checksTable = {
props: ['rows', 'headers', 'rowActions'],
data() {
return { searchQuery: '' };
},
template: '<div class="checks">{{ rows.map(r => r.id + ":" + r.severityRank).join(",") }}</div>',
};
const mountSummary = async(props) => {
const base = opts(props);
const w = vtuMount(HealthSummaryTable, { ...base, global: { ...base.global, stubs: { ...base.global.stubs, SortableTable: summaryTable } } });
await flushPromises();
return w;
};
const mountChecks = (props, stubs = {}, storeProps = {}) => {
const base = opts(storeProps);
return vtuMount(ComponentChecksTable, {
...base,
props,
global: {
...base.global,
stubs: {
...base.global.stubs, SortableTable: checksTable, ...stubs
}
},
});
};
const summaryOf = (components) => ({ id: 's', status: { components } });
const healthOf = (id, component, checks) => ({
id, metadata: { name: id, labels: { 'health.harvesterhci.io/component': component } }, status: { checks }
});
const CHECK = {
id: 'h/a',
component: 'x',
componentHealthName: 'h',
checkName: 'a',
affectedResources: { kind: 'VirtualMachine', names: { one: {}, two: {} } },
};
const IN_A_WEEK = new Date(Date.now() + (7 * 24 * 3600 * 1000)).toISOString();
const LAST_WEEK = new Date(Date.now() - (7 * 24 * 3600 * 1000)).toISOString();
// named the way the UI names the rule of a check, unless `extra` says otherwise
const ruleOf = (spec = {}, extra = {}) => {
const fullSpec = {
componentHealth: 'h', checkKey: 'a', ...spec
};
return {
metadata: { name: ignoreRuleName(fullSpec.componentHealth, fullSpec.checkKey) },
spec: fullSpec,
canUpdate: true,
canDelete: true,
promptRemove: jest.fn(),
...extra,
};
};
const actionsOf = (props = {}, storeProps = {}) => {
const w = mountChecks({ rows: [CHECK], ...props }, {}, storeProps);
const actions = w.findComponent(checksTable).props('rows')[0].availableActions;
return {
w,
actions,
keys: actions.map((action) => (action.divider ? '-' : action.action)),
invoke: (key) => actions.find((action) => action.action === key).invoke(),
};
};
const mountRuleModal = ({
rule, mode, save = () => {}, row = CHECK
} = {}) => {
createRule.mockClear();
cloneRule.mockClear();
saveRule.mockReset().mockImplementation(save);
delete newRule.spec;
delete editedRule.spec;
const onClose = jest.fn();
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: {
row, rule, mode, modal: { show: true, onClose }
},
});
return {
w,
onClose,
confirm: () => w.find('[data-testid="component-health-ignore-confirm"]'),
duration: () => w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-duration'),
scopeGroup: () => w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-scope'),
currentExpiry: () => w.find('[data-testid="component-health-ignore-current-expiry"]'),
newExpiry: () => w.find('[data-testid="component-health-ignore-new-expiry"]'),
warning: () => w.findAllComponents(Banner).find((banner) => banner.props('color') === 'warning'),
};
};
describe('health components', () => {
it('ranks the health summary rows by severity', async() => {
const w = await mountSummary({
healthSummaries: [{
id: 'a',
status: {
components: {
x: { errorCount: 1 }, y: {}, z: { warningCount: 2 }
}
}
}]
});
expect(w.find('.summary').text()).toBe('a/x:0,a/y:2,a/z:1');
});
it('opens a row from the component name, which takes the keyboard focus', async() => {
toggleExpand.mockClear();
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const name = w.find('.name button');
expect(name.text()).toBe('x');
expect(name.attributes('aria-expanded')).toBe('false');
await name.trigger('click');
expect(toggleExpand.mock.calls.map(([row]) => row.component)).toStrictEqual(['x']);
});
it('shows the checks of a component in its sub-row', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [
healthOf('h1', 'x', { a: { severity: 'Error' } }),
healthOf('h2', 'y', { b: { severity: 'Warning' } }),
healthOf('h3', 'x', { c: { severity: 'Error' } }),
],
});
const rowsOf = (component) => w.findAllComponents(ComponentChecksTable).find((c) => c.element.closest(`.sub-${ component }`)).props('rows').map((r) => r.id);
expect(rowsOf('x')).toStrictEqual(['h1/a', 'h3/c']);
expect(rowsOf('y')).toStrictEqual(['h2/b']);
});
it('ranks the checks Error, Warning, Info', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: { severity: 'Info' }, b: { severity: 'Error' }, c: { severity: 'Warning' }
})],
});
expect(w.findComponent(ComponentChecksTable).props('rows').map((r) => `${ r.id }:${ r.severityRank }`)).toStrictEqual(['h/a:2', 'h/b:0', 'h/c:1']);
});
it('gives what was typed in the outer table to the table of checks', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
await w.findComponent(summaryTable).setData({ searchQuery: 'warn' });
expect(w.findComponent(ComponentChecksTable).props('filterText')).toBe('warn');
});
it('lets the table of checks filter its own rows', async() => {
const w = mountChecks({ rows: [CHECK], filterText: 'warn' });
const table = w.findComponent(checksTable);
await flushPromises();
expect(table.vm.searchQuery).toBe('warn');
await w.setProps({ filterText: 'error' });
expect(table.vm.searchQuery).toBe('error');
expect(table.props('headers').filter((header) => header.search !== false).map((header) => header.search)).toStrictEqual(['filterText']);
});
it('calls a row with errors Error, and only its errors match that word', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' }, b: { severity: 'Warning' } })],
});
const checks = w.findComponent(ComponentChecksTable).props('rows');
expect(w.findComponent(summaryTable).props('rows')[0].severity).toBe('Error');
expect(checks.map((r) => r.filterText.includes('error'))).toStrictEqual([true, false]);
});
it('does not search the count columns', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {} })] });
const { headers } = w.findComponent(summaryTable).props();
expect(headers.filter((header) => header.search !== false).map((header) => header.name)).toStrictEqual(['severity', 'component']);
});
it('gives the table filter what a sub-row shows', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', {
a: {
severity: 'Warning',
message: 'Some Message',
affectedResources: {
apiVersion: 'kubevirt.io/v1', kind: 'VirtualMachine', names: { 'vm-shown': {}, 'vm-hidden': { ignored: true } }
},
}
})],
});
const filterText = () => w.findComponent(summaryTable).props('rows')[0].checksFilterText;
['x', 'warning', 'a', 'some message', 'kubevirt.io/v1', 'virtualmachine', 'label of', 'vm-shown', 'vm-hidden'].forEach((text) => expect(filterText()).toContain(text));
});
it('leaves the rows as they are when filtering', async() => {
toggleExpand.mockClear();
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 }, y: { warningCount: 1 } })],
componentHealths: [healthOf('h1', 'x', { a: { severity: 'Error' } }), healthOf('h2', 'y', { b: { severity: 'Warning' } })],
});
const table = w.findComponent(summaryTable);
await table.setData({ searchQuery: 'warning' });
await table.setData({ searchQuery: '' });
expect(toggleExpand).not.toHaveBeenCalled();
expect(table.vm.expanded).toStrictEqual({});
});
it('expands and collapses all the rows', async() => {
const w = await mountSummary({ healthSummaries: [summaryOf({ x: {}, y: {} })] });
const table = w.findComponent(summaryTable);
const [expand, collapse] = w.findAll('.expand-actions button');
await expand.trigger('click');
expect(table.vm.expanded).toStrictEqual({ 's/x': true, 's/y': true });
await collapse.trigger('click');
expect(table.vm.expanded).toStrictEqual({});
});
it('only offers to expand and collapse when there are rows', async() => {
const w = await mountSummary({});
expect(w.find('.expand-actions').exists()).toBe(false);
});
it('only offers the ignored checks when there are some', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error', ignored: true }, b: { severity: 'Warning' } })],
});
const shownRows = () => w.findComponent(ComponentChecksTable).props('rows').map((r) => r.id);
expect(shownRows()).toStrictEqual(['h/b']);
expect(w.findComponent(Checkbox).text()).toContain('showIgnored');
expect(w.findComponent(Checkbox).findComponent(RcCounterBadge).props('count')).toBe(1);
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(shownRows()).toStrictEqual(['h/a', 'h/b']);
const clean = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { b: { severity: 'Warning' } })],
});
// its ignored resources have a link of their own in the row
const resourcesOnly = await mountSummary({
healthSummaries: [summaryOf({ x: { warningCount: 1 } })],
componentHealths: [healthOf('h', 'x', { b: { severity: 'Warning', affectedResources: { names: { one: { ignored: true }, two: {} } } } })],
});
expect(clean.findComponent(Checkbox).exists()).toBe(false);
expect(resourcesOnly.findComponent(Checkbox).exists()).toBe(false);
});
it('expands a long message', async() => {
const message = 'x'.repeat(150);
const table = { props: ['rows'], template: '<div><slot name="cell:message" :row="rows[0]" :value="rows[0].message" /></div>' };
const w = mountChecks({ rows: [{ ...CHECK, message }] }, { SortableTable: table });
expect(w.text()).not.toContain(message);
expect(w.text()).toContain('generic.showMore');
await w.find('button.variant-link').trigger('click');
expect(w.text()).toContain(message);
expect(w.text()).toContain('generic.showLess');
});
it('shows the resources as chips, under what the UI calls them and their full count', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK,
affectedCount: 7,
affectedResources: {
apiVersion: 'longhorn.io/v1beta2', kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} }
}
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.find('.affected-title .text-label').text()).toBe('label of 7');
expect(w.find('.affected-title .api-version').text()).toBe('longhorn.io/v1beta2');
expect(w.findComponent(RcCounterBadge).props('count')).toBe(7);
expect(w.findAllComponents(RcTag).map((tag) => tag.text())).toStrictEqual(['two']);
});
it('keeps the full count and shows the ignored resources from their own link', async() => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const row = {
...CHECK, affectedCount: 2, affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
const link = () => w.find('.ignored-link');
expect(w.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(w.findAllComponents(RcTag).map((tag) => tag.find('.name').text())).toStrictEqual(['two']);
expect(link().text()).toContain('ignore.plusIgnored');
expect(link().attributes('aria-expanded')).toBe('false');
await link().trigger('click');
expect(w.findAllComponents(RcTag).map((tag) => tag.find('.name').text())).toStrictEqual(['two', 'one']);
expect(link().text()).toContain('ignore.hideIgnored');
expect(link().attributes('aria-expanded')).toBe('true');
await link().trigger('click');
expect(w.findAllComponents(RcTag)).toHaveLength(1);
});
it('puts the ignored link after the more link, and leaves it out when the whole check is ignored', () => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const names = Object.fromEntries(['a', 'b', 'c', 'd'].map((name) => [name, {}]));
const row = {
...CHECK,
affectedCount: 6,
affectedResources: {
kind: 'Volume',
names: {
...names, e: { ignored: true }, f: { ignored: true }
}
}
};
const links = (r) => mountChecks({ rows: [r] }, { SortableTable: table }).findAll('.affected-links button').map((button) => (button.classes('ignored-link') ? 'ignored' : 'more'));
expect(links(row)).toStrictEqual(['more', 'ignored']);
expect(links({ ...row, ignored: true })).toStrictEqual(['more']);
});
it('tells which checks have anything ignored', () => {
expect(hasIgnored({ ignored: true })).toBe(true);
expect(hasIgnored({ affectedResources: { names: { a: { ignored: true }, b: {} } } })).toBe(true);
expect(hasIgnored({ affectedResources: { names: { a: {} } } })).toBe(false);
expect(hasIgnored(undefined)).toBe(false);
});
it('marks the checks that have anything ignored, for their background', () => {
const table = { props: ['rows'], template: '<div><slot v-for="row in rows" name="cell:checkName" :row="row" :value="row.checkName" /></div>' };
const rows = [
{
...CHECK, id: 'whole', ignored: true
},
{
...CHECK, id: 'partly', affectedResources: { kind: 'Volume', names: { one: { ignored: true }, two: {} } }
},
{ ...CHECK, id: 'clean' },
];
const w = mountChecks({ rows }, { SortableTable: table });
expect(w.findAll('span').filter((span) => span.text().startsWith('a')).map((span) => span.classes().includes('has-ignored'))).toStrictEqual([true, true, false]);
});
it('names the rule of a check after it', () => {
expect(ignoreRuleName('harvester-controller-vmimage', 'ImageRetryLimitExceeded')).toBe('harvester-controller-vmimage.imageretrylimitexceeded');
});
it('turns what a name can not have in a check into hyphens', () => {
expect(ignoreRuleName('harvester-controller-schedulevmbackup', 'Proactive Schedule Suspend')).toBe('harvester-controller-schedulevmbackup.proactive-schedule-suspend');
expect(ignoreRuleName('h', ' Reach_Max Failure! ')).toBe('h.reach-max-failure');
});
it('tells the ignored resources apart, and all of them when the check is ignored', async() => {
const table = { props: ['rows'], template: '<div><slot name="cell:severity" :row="rows[0]" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>' };
const row = {
...CHECK, severity: 'Error', affectedResources: { kind: 'Volume', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } }
};
const wholeRow = {
...row, ignored: true, affectedResources: { kind: 'Volume', names: { one: {}, two: {} } }
};
const tags = (w) => w.findAllComponents(RcTag).map((tag) => ({
ignored: tag.classes().includes('ignored'), disabled: tag.props('disabled'), says: tag.text().includes('ignore.ignored')
}));
const partly = mountChecks({ rows: [row] }, { SortableTable: table });
const whole = mountChecks({ rows: [wholeRow] }, { SortableTable: table });
await partly.find('.ignored-link').trigger('click');
expect(tags(partly)).toStrictEqual([
{
ignored: false, disabled: false, says: false
},
{
ignored: true, disabled: true, says: true
},
]);
expect(partly.findComponent(BadgeState).props('color')).toBe('bg-error');
expect(tags(whole)).toStrictEqual([
{
ignored: true, disabled: true, says: false
},
{
ignored: true, disabled: true, says: false
},
]);
expect(whole.findComponent(BadgeState).props('color')).toBe('bg-error');
});
it('keeps the resources past the first ones behind a link', async() => {
const table = { props: ['rows'], template: '<div><slot name="cell:affectedCount" :row="rows[0]" :value="rows[0].affectedCount" /></div>' };
const names = Object.fromEntries(['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((name) => [name, {}]));
const row = {
...CHECK, affectedCount: 7, affectedResources: { kind: 'VirtualMachine', names }
};
const w = mountChecks({ rows: [row] }, { SortableTable: table });
expect(w.findAllComponents(RcTag)).toHaveLength(3);
expect(w.find('button.variant-link').text()).toContain('generic.plusMore');
await w.find('button.variant-link').trigger('click');
expect(w.findAllComponents(RcTag)).toHaveLength(7);
expect(w.find('button.variant-link').text()).toContain('generic.showLess');
});
it('adds up the errors of all the components, for the alert on the tab', () => {
const components = {
x: { errorCount: 2, warningCount: 5 }, y: { errorCount: 1 }, z: {}
};
expect(totalErrorCount([summaryOf(components)])).toBe(3);
expect(totalErrorCount([summaryOf({ x: { warningCount: 5 } })])).toBe(0);
expect(totalErrorCount([{ id: 'empty' }])).toBe(0);
expect(totalErrorCount(undefined)).toBe(0);
});
it('names the resources by their schema, or by their kind without one', () => {
const store = {
getters: {
'harvester/schemaFor': (id) => (['longhorn.io.volume', 'node'].includes(id) ? { id } : null),
'type-map/labelFor': (schema, count) => `${ schema.id } ${ count }`,
}
};
const label = (apiVersion, kind) => affectedResourceLabel({ affectedCount: 6, affectedResources: { apiVersion, kind } }, store);
expect(label('longhorn.io/v1beta2', 'Volume')).toBe('longhorn.io.volume 6');
expect(label('v1', 'Node')).toBe('node 6');
expect(label('harvesterhci.io/v1beta1', 'Upgrade')).toBe('Upgrade');
});
it('tells when a component has no checks, unless they could not be loaded', () => {
expect(mountChecks({ rows: [] }).text()).toContain('noIssues');
expect(mountChecks({ rows: [], loadFailed: true }).text()).toContain('checksNotLoaded');
});
it('still shows the checks when the rules can not be loaded, and says so', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
failing: 'ignoreRules',
});
const checks = w.findComponent(ComponentChecksTable);
expect(checks.props('rows').map((r) => r.id)).toStrictEqual(['h/a']);
expect(checks.props('loadFailed')).toBe(false);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.ignoreRules%']);
});
it('does not call a component without issues when its checks can not be loaded', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
failing: 'componentHealths',
});
expect(w.findComponent(ComponentChecksTable).props('loadFailed')).toBe(true);
expect(w.findAllComponents(Banner).map((banner) => banner.props('label'))).toStrictEqual(['%harvester.dashboard.sections.componentHealth.loadFailed.componentHealths%']);
});
it('does not ask for the rules without their schema', async() => {
const onFindAll = jest.fn();
await mountSummary({ noSchemaFor: HCI.HEALTH_IGNORE_RULE, onFindAll });
expect(onFindAll.mock.calls.map(([type]) => type)).toStrictEqual([HCI.HEALTH_SUMMARY, HCI.COMPONENT_HEALTH]);
});
it('marks a check and the resources that are ignored', async() => {
const table = {
props: ['rows'],
template: '<div><slot name="cell:checkName" :row="rows[0]" :value="rows[0].checkName" /><slot name="cell:affectedCount" :row="rows[0]" :value="2" /></div>',
};
const row = { ...CHECK, affectedResources: { kind: 'VirtualMachine', names: { one: { ignored: true, ignoredBy: 'r' }, two: {} } } };
const textOf = async(props) => {
const w = mountChecks(props, { SortableTable: table });
await w.find('.ignored-link').trigger('click');
return w.text().replace(/\s+/g, ' ');
};
const partlyText = await textOf({ rows: [row] });
expect(partlyText).toMatch(/two ?one ?\(%harvester\.dashboard\.sections\.componentHealth\.ignore\.ignored%\)/);
expect(partlyText).not.toContain('a (%harvester');
expect(mountChecks({ rows: [{ ...row, ignored: true }] }, { SortableTable: table }).text().replace(/\s+/g, ' ')).toContain('a (%harvester.dashboard.sections.componentHealth.ignore.ignored%)');
});
describe('the actions of a check', () => {
it('offers to create a rule when the check has none from the UI', () => {
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [ruleOf({ checkKey: 'b' }), ruleOf({ componentHealth: 'other' }), elsewhere] });
expect(keys).toStrictEqual(['create']);
invoke('create');
expect(w.emitted('open-rule')).toStrictEqual([[{
row: CHECK, rule: undefined, mode: 'create'
}]]);
});
it('offers to view, edit and delete the rule of the check, and only that one', () => {
const rule = ruleOf();
const elsewhere = ruleOf({}, { metadata: { name: 'ignore-x7k2p' } });
const { w, keys, invoke } = actionsOf({ ignoreRules: [elsewhere, ruleOf({ checkKey: 'b' }), rule] });
expect(keys).toStrictEqual(['view', 'edit', '-', 'delete']);
invoke('view');
invoke('edit');
invoke('delete');
expect(w.emitted('open-rule')).toStrictEqual([
[{
row: CHECK, rule, mode: 'view'
}],
[{
row: CHECK, rule, mode: 'edit'
}],
]);
expect(rule.promptRemove).toHaveBeenCalledTimes(1);
expect(elsewhere.promptRemove).not.toHaveBeenCalled();
});
it('only offers what the user is allowed to do', () => {
const keysFor = (extra) => actionsOf({ ignoreRules: [ruleOf({}, extra)] }).keys;
expect(keysFor({ canDelete: false })).toStrictEqual(['view', 'edit']);
expect(keysFor({ canUpdate: false })).toStrictEqual(['view', '-', 'delete']);
expect(keysFor({ canUpdate: false, canDelete: false })).toStrictEqual(['view']);
expect(actionsOf({}, { collectionMethods: ['GET'] }).keys).toStrictEqual([]);
expect(actionsOf({}, { noSchemaFor: HCI.HEALTH_IGNORE_RULE }).keys).toStrictEqual([]);
});
it('leaves out the menu when no check has anything in it', () => {
const rowActions = (props, storeProps) => actionsOf(props, storeProps).w.findComponent(checksTable).props('rowActions');
expect(rowActions({}, { collectionMethods: ['GET'] })).toBe(false);
expect(rowActions({ ignoreRules: [ruleOf()] }, { collectionMethods: ['GET'] })).toBe(true);
expect(rowActions({})).toBe(true);
});
});
describe('creating a rule', () => {
it('starts the modal over each time it opens', async() => {
const w = await mountSummary({
healthSummaries: [summaryOf({ x: { errorCount: 1 } })],
componentHealths: [healthOf('h', 'x', { a: { severity: 'Error' } })],
});
const open = async() => {
await w.findComponent(ComponentChecksTable).vm.$emit('open-rule', { row: CHECK, mode: 'create' });
await flushPromises();
};
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
await w.findComponent(RcModal).vm.$emit('close');
await flushPromises();
expect(w.findComponent(RcModal).exists()).toBe(false);
await open();
expect(w.findComponent(LabeledInput).props('value')).toBe('');
});
it('ignores the selected resources for the chosen time', async() => {
const { w, onClose, confirm } = mountRuleModal();
await w.findComponent(LabeledSelect).vm.$emit('update:value', ['two']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(cloneRule).not.toHaveBeenCalled();
expect(newRule.spec).toStrictEqual({
componentHealth: 'h',
checkKey: 'a',
resources: ['two'],
expiresAt: expect.any(String),
reason: 'known issue',
});
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('names the rule after its check, so a second one for it is refused', async() => {
const { confirm } = mountRuleModal();
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata).toStrictEqual({ name: 'h.a', labels: { 'health.harvesterhci.io/source': 'user' } });
});
it('gives a check with spaces a valid name, and keeps the check as it is', async() => {
const { confirm } = mountRuleModal({ row: { ...CHECK, checkName: 'Proactive Schedule Suspend' } });
await confirm().trigger('click');
await flushPromises();
expect(createRule.mock.calls[0][1].metadata.name).toBe('h.proactive-schedule-suspend');
expect(newRule.spec.checkKey).toBe('Proactive Schedule Suspend');
});
it('says when the rule will expire, from 7 days on', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal();
expect(currentExpiry().exists()).toBe(false);
expect(duration().props('value')).toBe('days7');
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willNeverExpire');
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('ignores the entire check forever without listing its resources', async() => {
const { confirm, scopeGroup, duration: durationGroup } = mountRuleModal();
const scope = scopeGroup();
const duration = durationGroup();
await scope.vm.$emit('update:value', 'check');
await duration.vm.$emit('update:value', 'forever');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(newRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('only offers the entire check when the check lists no resources', () => {
const w = vtuMount(IgnoreRuleModal, {
...opts(),
props: { row: { ...CHECK, affectedResources: undefined }, modal: { show: true, onClose: jest.fn() } },
});
expect(w.findAllComponents(RadioGroup)).toHaveLength(1);
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
});
it('can not ignore without a resource selected', async() => {
const { w, confirm } = mountRuleModal();
expect(confirm().attributes('disabled')).toBeUndefined();
await w.findComponent(LabeledSelect).vm.$emit('update:value', []);
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
});
it('stays open and shows the error when saving fails', async() => {
const { w, onClose, confirm } = mountRuleModal({ save: () => Promise.reject(new Error('forbidden')) });
await confirm().trigger('click');
await flushPromises();
expect(w.text()).toContain('forbidden');
expect(onClose).not.toHaveBeenCalled();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('does not close while the rule is saved', async() => {
let finishSaving;
const { w, onClose, confirm } = mountRuleModal({
save: () => new Promise((resolve) => {
finishSaving = resolve;
})
});
await confirm().trigger('click');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await w.findComponent(RcModal).vm.$emit('close');
expect(onClose).not.toHaveBeenCalled();
finishSaving();
await flushPromises();
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe('editing a rule', () => {
it('starts from what the rule has, with no new duration chosen', () => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const {
w, duration, currentExpiry, newExpiry, scopeGroup
} = mountRuleModal({ rule, mode: 'edit' });
const scope = scopeGroup();
expect(scope.props('value')).toBe('resources');
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['two']);
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration().props('value')).toBeNull();
expect(duration().props('options').map((option) => option.value)).toStrictEqual(['days7', 'days30', 'forever']);
expect(newExpiry().exists()).toBe(false);
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
});
it('can not save until something changes', async() => {
const { w, confirm, duration } = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const reason = (value) => w.findComponent(LabeledInput).vm.$emit('update:value', value);
expect(confirm().attributes('disabled')).toBeDefined();
await reason('known issue');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
await reason('');
await duration().vm.$emit('update:value', 'forever');
await flushPromises();
expect(confirm().attributes('disabled')).toBeDefined();
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(confirm().attributes('disabled')).toBeUndefined();
});
it('saves on a copy of the rule, with the expiry it has', async() => {
const rule = ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
});
const { w, onClose, confirm } = mountRuleModal({ rule, mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'still known');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(createRule).not.toHaveBeenCalled();
expect(cloneRule.mock.calls[0][1]).toStrictEqual({ resource: rule });
expect(editedRule.spec).toStrictEqual({ ...rule.spec, reason: 'still known' });
expect(saveRule).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledTimes(1);
});
it('takes the resources, the expiry and the reason off the rule', async() => {
const { w, confirm, duration } = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'edit'
});
const scope = w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-scope');
await scope.vm.$emit('update:value', 'check');
await duration().vm.$emit('update:value', 'forever');
await w.findComponent(LabeledInput).vm.$emit('update:value', '');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec).toStrictEqual({ componentHealth: 'h', checkKey: 'a' });
});
it('renews an expired rule with the duration chosen', async() => {
const {
confirm, duration, currentExpiry, newExpiry
} = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(currentExpiry().text()).toContain('ignore.expiredOn');
await duration().vm.$emit('update:value', 'days30');
await flushPromises();
expect(newExpiry().text()).toContain('ignore.willExpireOn');
await confirm().trigger('click');
await flushPromises();
expect(new Date(editedRule.spec.expiresAt).getTime()).toBeGreaterThan(new Date(IN_A_WEEK).getTime());
});
it('opens an expired rule with a warning on top, and only its expiration can change until a new one is set', async() => {
const {
w, confirm, duration, warning, scopeGroup
} = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK, resources: ['one'] }), mode: 'edit' });
const locked = () => ({
scope: w.findAllComponents(RadioGroup).find((group) => group.props('name') === 'ignore-scope').props('disabled'),
resources: w.findComponent(LabeledSelect).props('disabled'),
reason: w.findComponent(LabeledInput).props('disabled'),
expiration: duration().props('disabled'),
save: confirm().attributes('disabled') !== undefined,
});
expect(warning().props('label')).toContain('ignore.expiredBanner');
expect(w.find('[data-testid="rc-modal-body"]').element.firstElementChild.getAttribute('data-testid')).toBe('component-health-ignore-expired');
expect(locked()).toStrictEqual({
scope: true, resources: true, reason: true, expiration: false, save: true
});
expect(w.findAllComponents(RadioGroup).map((group) => group.props('name'))).toStrictEqual(['ignore-duration', 'ignore-scope']);
// what the shell's RadioGroup sends for a click and the Up key, although it is disabled
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('resources');
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(locked()).toStrictEqual({
scope: false, resources: false, reason: false, expiration: false, save: false
});
expect(warning().props('label')).toContain('ignore.expiredBanner');
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('check');
});
it('neither warns nor locks a rule that has not expired, or an expired one that is only viewed', async() => {
const { w, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: IN_A_WEEK }), mode: 'edit' });
expect(warning()).toBeUndefined();
expect(w.findComponent(LabeledInput).props('disabled')).toBe(false);
const viewed = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'view' });
expect(viewed.warning()).toBeUndefined();
});
it('opens a rule without resources on the entire check, and selects them all when asked', async() => {
const {
w, confirm, duration, currentExpiry, scopeGroup
} = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const scope = scopeGroup();
expect(scope.props('value')).toBe('check');
expect(currentExpiry().text()).toContain('ignore.neverExpires');
expect(duration().props('value')).toBeNull();
expect(w.findComponent(LabeledSelect).exists()).toBe(false);
await scope.vm.$emit('update:value', 'resources');
await flushPromises();
expect(w.findComponent(LabeledSelect).props('value')).toStrictEqual(['one', 'two']);
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['one', 'two']);
});
it('keeps a resource of the rule that is no longer affected', async() => {
const { w, confirm } = mountRuleModal({ rule: ruleOf({ resources: ['gone', 'two'] }), mode: 'edit' });
const select = w.findComponent(LabeledSelect);
expect(select.props('options')).toStrictEqual(['one', 'two', 'gone']);
expect(select.props('value')).toStrictEqual(['two', 'gone']);
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
await confirm().trigger('click');
await flushPromises();
expect(editedRule.spec.resources).toStrictEqual(['two', 'gone']);
});
});
describe('viewing a rule', () => {
it('shows what the rule has without letting it change', async() => {
const {
w, onClose, confirm, duration, currentExpiry, scopeGroup
} = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'view'
});
await scopeGroup().vm.$emit('update:value', 'check');
await flushPromises();
expect(scopeGroup().props('value')).toBe('resources');
[...w.findAllComponents(RadioGroup), w.findComponent(LabeledSelect), w.findComponent(LabeledInput)].forEach((field) => {
expect(field.props('mode')).toBe('view');
});
expect(currentExpiry().text()).toContain('ignore.expiresOn');
expect(duration()).toBeUndefined();
expect(w.findComponent(LabeledInput).props('value')).toBe('known issue');
expect(confirm().exists()).toBe(false);
expect(w.find('[data-testid="rc-modal-cancel"]').exists()).toBe(false);
await w.find('[data-testid="component-health-ignore-close"]').trigger('click');
expect(onClose).toHaveBeenCalledTimes(1);
expect(cloneRule).not.toHaveBeenCalled();
expect(saveRule).not.toHaveBeenCalled();
});
});
});
@@ -1,224 +0,0 @@
<script>
import { RcButton } from '@components/RcButton';
import { RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger } from '@components/RcDropdown';
import { RcIcon } from '@components/RcIcon';
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
import { CONSOLE_STATUS } from './NovncConsole';
export const CONNECTION_STATE = {
CONNECTING: 'connecting',
CONNECTED: 'connected',
DISCONNECTED: 'disconnected',
NOT_RUNNING: 'notRunning',
};
export default {
name: 'NovncConnectionStatus',
components: {
RcButton, RcDropdown, RcDropdownItem, RcDropdownSeparator, RcDropdownTrigger, RcIcon, RcStatusIndicator
},
props: {
status: {
type: String,
default: CONSOLE_STATUS.CONNECTING,
},
label: {
type: String,
default: '',
},
vmName: {
type: String,
default: '',
},
},
emits: ['reconnect'],
computed: {
// The console reports five states; the toolbar only tells the user whether they can type.
state() {
if (this.status === CONNECTION_STATE.NOT_RUNNING) {
return CONNECTION_STATE.NOT_RUNNING;
}
if (this.status === CONSOLE_STATUS.CONNECTED) {
return CONNECTION_STATE.CONNECTED;
}
if (this.status === CONSOLE_STATUS.DISCONNECTED || this.status === CONSOLE_STATUS.FAILED) {
return CONNECTION_STATE.DISCONNECTED;
}
return CONNECTION_STATE.CONNECTING;
},
},
};
</script>
<template>
<div class="connection-status">
<!-- Only the label is announced, not the menu that opens next to it. -->
<span
class="sr-only"
role="status"
aria-live="polite"
>{{ label }}</span>
<rc-dropdown
v-if="state === 'connected'"
:aria-label="t('harvester.virtualMachine.detail.console.connection.menuLabel')"
placement="bottom-start"
>
<rc-dropdown-trigger
variant="ghost"
size="small"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<template #before>
<rc-status-indicator
shape="disc"
status="success"
/>
</template>
{{ label }}
<template #after>
<rc-icon
type="chevron-down"
size="inherit"
/>
</template>
</rc-dropdown-trigger>
<template #dropdownCollection>
<p class="connection-status__description">
{{ t('harvester.virtualMachine.detail.console.connection.description', { name: vmName }) }}
</p>
<rc-dropdown-separator />
<rc-dropdown-item
data-testid="vnc-connection-reconnect"
@click="$emit('reconnect')"
>
<template #before>
<rc-icon
type="refresh"
size="inherit"
/>
</template>
{{ t('harvester.action.reconnect') }}
</rc-dropdown-item>
</template>
</rc-dropdown>
<span
v-else-if="state === 'notRunning'"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<rc-status-indicator
shape="disc"
status="unknown"
/>
{{ label }}
</span>
<span
v-else-if="state === 'connecting'"
class="connection-status__pill"
data-testid="vnc-connection-status"
>
<rc-icon
type="spinner"
size="inherit"
class="icon-spin"
/>
{{ label }}
</span>
<span
v-else
class="connection-status__pill connection-status__pill--disconnected"
data-testid="vnc-connection-status"
>
<rc-status-indicator
shape="disc"
status="error"
/>
{{ label }}
<span
class="connection-status__divider"
aria-hidden="true"
/>
<rc-button
variant="ghost"
size="small"
class="connection-status__reconnect"
data-testid="vnc-connection-reconnect"
@click="$emit('reconnect')"
>
<template #before>
<rc-icon
type="refresh"
size="inherit"
/>
</template>
{{ t('harvester.action.reconnect') }}
</rc-button>
</span>
</div>
</template>
<style lang="scss" scoped>
.connection-status {
display: flex;
align-items: center;
// Shared by the dropdown trigger and the plain pills, so every state has the same shape.
&__pill {
display: inline-flex;
align-items: center;
gap: 8px;
height: 32px;
padding: 0 10px 0 12px;
// The connected pill is an RcButton, which takes its padding from this property.
--rc-button-padding: 0 10px 0 12px;
border: 1px solid var(--border);
border-radius: 16px;
color: var(--body-text);
font-size: 12px;
line-height: 18px;
white-space: nowrap;
&--disconnected {
border-color: var(--error);
}
}
&__divider {
width: 1px;
height: 16px;
background: var(--error);
}
// An RcButton keeps to its own small height, so its focus ring stays inside the pill.
&__reconnect {
--rc-button-padding: 0;
color: var(--error);
}
&__description {
max-width: 248px;
margin: 0;
padding: 4px 17px 8px;
color: var(--body-text);
font-size: 12px;
font-weight: 400;
line-height: 18px;
white-space: normal;
}
}
</style>
+81 -147
View File
@@ -1,8 +1,5 @@
<script> <script>
import { RcButton } from '@components/RcButton'; import ModalWithCard from '@shell/components/ModalWithCard';
import { RcIcon } from '@components/RcIcon';
import { RcModal } from '@components/RcModal';
import NovncStatusCard from './NovncStatusCard';
import ZoomableRFB from './ZoomableRFB'; import ZoomableRFB from './ZoomableRFB';
export const CONSOLE_STATUS = { export const CONSOLE_STATUS = {
@@ -23,8 +20,6 @@ export const CONSOLE_FAILURE = {
const MAXIMUM_RETRY_TIMES = 10; const MAXIMUM_RETRY_TIMES = 10;
const BASE_RECONNECT_DELAY = 1000; const BASE_RECONNECT_DELAY = 1000;
const MAXIMUM_RECONNECT_DELAY = 30000; const MAXIMUM_RECONNECT_DELAY = 30000;
// A VM that just started can refuse VNC for a moment; refusals this soon are retried, not reported.
const STARTUP_GRACE = 60000;
const clampLevel = (value, fallback) => { const clampLevel = (value, fallback) => {
const level = Number.parseInt(value, 10); const level = Number.parseInt(value, 10);
@@ -39,9 +34,7 @@ const clampLevel = (value, fallback) => {
export default { export default {
name: 'NovncConsole', name: 'NovncConsole',
components: { components: { ModalWithCard },
RcButton, RcIcon, RcModal, NovncStatusCard
},
props: { props: {
url: { url: {
@@ -65,17 +58,6 @@ export default {
type: Boolean, type: Boolean,
default: true default: true
}, },
vmName: {
type: String,
default: ''
},
// When the VM was seen starting to run on this page (ms), or 0.
startedAt: {
type: Number,
default: 0
},
}, },
emits: ['status-changed', 'capabilities'], emits: ['status-changed', 'capabilities'],
@@ -111,17 +93,16 @@ export default {
return this.status === CONSOLE_STATUS.FAILED || (this.status === CONSOLE_STATUS.DISCONNECTED && this.failure === CONSOLE_FAILURE.DROPPED); return this.status === CONSOLE_STATUS.FAILED || (this.status === CONSOLE_STATUS.DISCONNECTED && this.failure === CONSOLE_FAILURE.DROPPED);
}, },
// Only another session holding the console is something taking over can fix.
canTakeOver() { canTakeOver() {
return this.preserveSession && !this.isClosed && this.failure === CONSOLE_FAILURE.IN_USE; return this.preserveSession && !this.isClosed;
}, },
failureTitle() { failureTitle() {
return this.t(`harvester.virtualMachine.detail.console.failure.${ this.failure || CONSOLE_FAILURE.ERROR }`); return this.t(`harvester.virtualMachine.detail.console.failure.${ this.failure || CONSOLE_FAILURE.ERROR }`);
}, },
showConnecting() { showReconnecting() {
return this.status === CONSOLE_STATUS.CONNECTING || this.status === CONSOLE_STATUS.RECONNECTING; return this.status === CONSOLE_STATUS.RECONNECTING;
}, },
}, },
@@ -188,8 +169,6 @@ export default {
return; return;
} }
// noVNC paints its own grey behind the framebuffer; let the console area show through.
rfb.background = 'transparent';
rfb.addEventListener('connect', this.onConnect); rfb.addEventListener('connect', this.onConnect);
rfb.addEventListener('disconnect', this.onDisconnect); rfb.addEventListener('disconnect', this.onDisconnect);
rfb.addEventListener('securityfailure', this.onSecurityFailure); rfb.addEventListener('securityfailure', this.onSecurityFailure);
@@ -210,13 +189,6 @@ export default {
this.connect(); this.connect();
}, },
// Skip the wait before the next retry, still counting it as one, so a held console keeps
// being retried instead of turning into the in-use failure.
retryNow() {
this.clearReconnectTimer();
this.connect();
},
takeOver() { takeOver() {
this.showTakeOverModal = true; this.showTakeOverModal = true;
}, },
@@ -290,9 +262,7 @@ export default {
// Retries use preserveSession, so they fail while another session owns the // Retries use preserveSession, so they fail while another session owns the
// console. Keep retrying so the console is picked up once it is released, // console. Keep retrying so the console is picked up once it is released,
// instead of kicking the other session back out. // instead of kicking the other session back out.
this.statusDetail = this.isStartingUp() ? '' : this.t('harvester.virtualMachine.detail.console.status.inUse'); this.statusDetail = this.t('harvester.virtualMachine.detail.console.status.inUse');
this.scheduleReconnect();
} else if (this.isStartingUp()) {
this.scheduleReconnect(); this.scheduleReconnect();
} else { } else {
this.clearReconnectTimer(); this.clearReconnectTimer();
@@ -300,10 +270,6 @@ export default {
} }
}, },
isStartingUp() {
return !!this.startedAt && Date.now() - this.startedAt < STARTUP_GRACE;
},
// The browser cannot see why a WebSocket handshake failed. With preserveSession and a // The browser cannot see why a WebSocket handshake failed. With preserveSession and a
// running VM, a refused connection almost always means another session holds the console. // running VM, a refused connection almost always means another session holds the console.
fail(failure, detail) { fail(failure, detail) {
@@ -403,9 +369,7 @@ export default {
const settings = this.settings || {}; const settings = this.settings || {};
// View only shows the screen but sends no mouse or keyboard input.
rfb.viewOnly = !!settings.viewOnly; rfb.viewOnly = !!settings.viewOnly;
rfb.edgeToEdge = !!settings.edgeToEdge;
rfb.scaleViewport = !!settings.scaleViewport; rfb.scaleViewport = !!settings.scaleViewport;
rfb.resizeSession = !!settings.resizeSession; rfb.resizeSession = !!settings.resizeSession;
rfb.clipViewport = !!settings.clipViewport; rfb.clipViewport = !!settings.clipViewport;
@@ -429,120 +393,108 @@ export default {
</script> </script>
<template> <template>
<div <div class="novnc-console">
class="novnc-console"
:class="{ 'is-live': status === 'connected' }"
>
<div <div
ref="view" ref="view"
class="novnc-screen" class="novnc-screen"
:class="{ 'is-focused': focused, 'is-edge-to-edge': settings.edgeToEdge }" :class="{ 'is-focused': focused }"
/> />
<div <div
v-if="showError || showConnecting" v-if="showError || showReconnecting"
class="novnc-overlay" class="novnc-overlay"
data-testid="vnc-overlay"
> >
<NovncStatusCard <div
v-if="showError" v-if="showError"
:title="failureTitle" class="novnc-overlay__card text-center"
:detail="statusDetail"
> >
<RcButton <h3>
variant="primary" {{ failureTitle }}
data-testid="vnc-overlay-reconnect" </h3>
<p
v-if="statusDetail"
class="mt-10"
>
{{ statusDetail }}
</p>
<button
class="btn role-primary mt-20"
@click="reconnect" @click="reconnect"
> >
{{ t('harvester.action.reconnect') }} {{ t('harvester.action.reconnect') }}
</RcButton> </button>
<RcButton <button
v-if="canTakeOver" v-if="canTakeOver"
variant="secondary" class="btn role-secondary mt-20 ml-10"
data-testid="vnc-take-over"
@click="takeOver" @click="takeOver"
> >
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }} {{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</RcButton> </button>
</NovncStatusCard> </div>
<div <div
v-else v-else
class="novnc-overlay__connecting" class="text-center"
> >
<span class="novnc-overlay__spinner"> <h2>
<RcIcon {{ t('vncConsole.reconnecting.message') }}:{{ retryTimes }} of {{ maximumRetryTimes }}
type="spinner" </h2>
size="inherit"
class="icon-spin"
/>
</span>
<p class="novnc-overlay__connecting-label">
{{ t('harvester.virtualMachine.detail.console.overlay.connecting', { name: vmName }) }}
</p>
<p <p
v-if="retryTimes > 0" v-if="statusDetail"
class="novnc-overlay__detail" class="mt-10"
> >
{{ t('harvester.virtualMachine.detail.console.overlay.attempt', { retryTimes, maximumRetryTimes }) }} {{ statusDetail }}
<template v-if="statusDetail">
{{ statusDetail }}
</template>
</p> </p>
<RcButton
v-if="retryTimes > 0"
variant="secondary"
data-testid="vnc-reconnect-now"
@click="retryNow"
>
{{ t('harvester.virtualMachine.detail.console.overlay.reconnectNow') }}
</RcButton>
</div> </div>
</div> </div>
<RcModal <ModalWithCard
:show="showTakeOverModal" v-if="showTakeOverModal"
size="small" name="takeOverConsole"
:title="t('harvester.virtualMachine.detail.console.takeOver.title')" :width="480"
data-testid="vnc-take-over-modal" @finish="cancelTakeOver"
@close="cancelTakeOver"
> >
<p>{{ t('harvester.virtualMachine.detail.console.takeOver.confirm') }}</p> <template #title>
{{ t('harvester.virtualMachine.detail.console.takeOver.title') }}
<template #primary-action>
<RcButton
variant="primary"
size="large"
data-testid="vnc-take-over-confirm"
@click="confirmTakeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</RcButton>
</template> </template>
</RcModal>
<template #content>
<p>{{ t('harvester.virtualMachine.detail.console.takeOver.confirm') }}</p>
</template>
<template #footer>
<div class="take-over-actions">
<button
class="btn role-secondary mr-10"
@click="cancelTakeOver"
>
{{ t('generic.cancel') }}
</button>
<button
class="btn role-primary"
@click="confirmTakeOver"
>
{{ t('harvester.virtualMachine.detail.console.takeOver.label') }}
</button>
</div>
</template>
</ModalWithCard>
</div> </div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
// Without a live picture the screen is black like a monitor, so the overlays read the same in
// every theme; once connected the framebuffer is the screen and the page shows around it.
.novnc-console { .novnc-console {
position: relative; position: relative;
box-sizing: border-box; box-sizing: border-box;
height: 100%; height: 100%;
padding: 8px;
overflow: hidden; overflow: hidden;
background: #000;
&.is-live {
background: transparent;
}
} }
.novnc-screen { .novnc-screen {
height: 100%; height: 100%;
} }
// The overlay sits on the black screen, so its text is light whatever the theme.
.novnc-overlay { .novnc-overlay {
position: absolute; position: absolute;
top: 0; top: 0;
@@ -554,53 +506,35 @@ export default {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
overflow: auto; overflow: auto;
background: rgba(0, 0, 0, 0.6); background: rgba(0, 0, 0, 0.75);
// The overlay is always dark, so its text cannot follow the theme's text colours.
color: #fff; color: #fff;
text-align: center;
&__detail { h2,
margin: 0; h3 {
color: rgba(255, 255, 255, 0.8); color: #fff;
font-size: 13px;
line-height: 16px;
} }
&__connecting { p {
display: flex; color: rgba(255, 255, 255, 0.8);
flex-direction: column; }
align-items: center;
gap: 16px; &__card {
max-width: 480px; max-width: 480px;
padding: 0 20px; padding: 0 20px;
} }
}
// RcIcon has no 20px size, the one the design uses here, so it inherits it. .take-over-actions {
&__spinner { display: flex;
display: flex; justify-content: flex-end;
font-size: 20px; width: 100%;
}
&__connecting-label {
margin: 0;
font-size: 16px;
line-height: 21px;
}
} }
</style> </style>
<style lang="scss"> <style lang="scss">
// noVNC sets an inline `outline: none` on its canvas, so frame the screen with a ring instead: // noVNC sets an inline `outline: none` on its canvas, so mark keyboard focus with a ring instead.
// a thin border at rest and, while it holds the keyboard, a 2px ring set 2px off the screen so it
// never blends into a dark framebuffer edge (the SUSE light focus colour is a very dark green).
.novnc-screen canvas {
box-shadow: 0 0 0 1px var(--border);
}
.novnc-screen.is-focused canvas { .novnc-screen.is-focused canvas {
box-shadow: 0 0 0 2px var(--body-bg), 0 0 0 4px var(--primary-keyboard-focus); box-shadow: 0 0 0 2px var(--primary);
}
.novnc-screen.is-edge-to-edge canvas {
box-shadow: none;
} }
</style> </style>
@@ -1,355 +1,264 @@
<script> <script>
import { STEVE } from '@shell/config/types'; import { STEVE } from '@shell/config/types';
import { stringify } from '@shell/utils/error';
import Banner from '@components/Banner/Banner.vue'; import Banner from '@components/Banner/Banner.vue';
import { RcButton } from '@components/RcButton'; import AsyncButton from '@shell/components/AsyncButton';
import { RcIcon } from '@components/RcIcon'; import ModalWithCard from '@shell/components/ModalWithCard';
import { RcModal } from '@components/RcModal';
import RcTag from '@components/Pill/RcTag'; const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
import { LabeledInput } from '@components/Form/LabeledInput';
import NovncKeyRecorder from './NovncKeyRecorder';
import { readShortcuts, shortcutId, shortcutLabels, writeShortcuts } from './shortcuts';
export default { export default {
name: 'NovncConsoleCustomKeys', name: 'NovncConsoleCustomKeys',
components: {
Banner, RcButton, RcIcon, RcModal, RcTag, LabeledInput, NovncKeyRecorder
},
props: {
show: {
type: Boolean,
default: false,
},
},
emits: ['close'], emits: ['close'],
components: {
ModalWithCard, Banner, AsyncButton
},
data() { data() {
return { return {
keys: [], keysRecord: [],
name: '', addedShortcutKeys: [],
saving: false, preferredShortcutKeys: [],
error: '', isRecording: false,
}; };
}, },
computed: { computed: {
preference() { savedShortcutKeys() {
return this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0]; const preference = this.$store.getters['management/all'](STEVE.PREFERENCE);
const preferedShortcutKeys = preference?.[0]?.data?.[PREFERED_SHORTCUT_KEYS];
let out = [];
if (!preferedShortcutKeys) {
return out;
}
try {
out = JSON.parse(preferedShortcutKeys);
} catch (err) {
this.$store.dispatch('growl/fromError', {
title: this.t('generic.notification.title.error', { name: this.t('harvester.virtualMachine.detail.console.customShortcutKeys') }),
err,
}, { root: true });
}
return out;
}, },
shortcuts() { displayedKeys() {
return readShortcuts(this.preference).map((shortcut) => ({ ...shortcut, labels: shortcutLabels(shortcut) })); const out = this.addedShortcutKeys.concat(this.preferredShortcutKeys).map((item) => {
const out = item.map((K) => ` <code>${ K.key.charAt(0).toUpperCase() + K.key.slice(1) }</code>`);
return out.join(',');
});
return out;
}, },
isDuplicate() { recordButton() {
const id = shortcutId({ keys: this.keys }); if (this.isRecording) {
return 'harvester.virtualMachine.detail.console.record.stop';
}
return !!this.keys.length && this.shortcuts.some((shortcut) => shortcutId(shortcut) === id); return 'harvester.virtualMachine.detail.console.record.start';
},
keysRecordFormat() {
if (!this.isRecording && this.keysRecord.length === 0) {
return this.t('harvester.virtualMachine.detail.console.record.tips');
}
const out = this.keysRecord.map((item) => ` <code>${ item.key.charAt(0).toUpperCase() + item.key.slice(1) }</code>`);
return `Keys: ${ out.join(',') }`;
}, },
canAdd() { canAdd() {
return !!this.keys.length && !this.isDuplicate; const hasRecord = this.keysRecord.length > 0;
let validationList = [].concat(this.preferredShortcutKeys, this.addedShortcutKeys);
if (!hasRecord) {
return false;
}
validationList.push(this.keysRecord);
validationList = validationList.map((item) => {
const out = item.map((K) => K.key);
return out.join(',');
});
return validationList.length === new Set(validationList).size;
}, },
}, },
watch: { watch: {
show(show) { savedShortcutKeys: {
if (!show) { handler() {
this.error = ''; this.preferredShortcutKeys = [].concat(this.savedShortcutKeys) || [];
} },
immediate: true
}, },
}, },
methods: { methods: {
clear() { closeRecordingModal() {
this.keys = []; window.removeEventListener('keydown', this.handleShortcut);
this.name = ''; this.$emit('close');
}, },
// The buttons stay enabled while a change saves: disabling the one that was pressed would drop the toggleRecording() {
// keyboard's focus to the page. this.isRecording = !this.isRecording;
async add() {
if (!this.canAdd || this.saving) {
return;
}
const { name, keys } = this; if (this.isRecording) {
const shortcuts = [...this.shortcuts, { name: name.trim(), keys }]; this.keysRecord = [];
window.addEventListener('keydown', this.handleShortcut);
// The list shows the new shortcut while it saves, and a form still holding it would say it is already } else {
// saved, so the form empties now. Add shortcut turns disabled with it, so the recorder takes the focus. window.removeEventListener('keydown', this.handleShortcut);
this.clear();
this.$refs.recorder?.$el?.focus();
const added = await this.save(shortcuts);
// A failed save takes the shortcut out of the list again, so it goes back in the form, unless the next
// one was started meanwhile.
if (!added && !this.keys.length && !this.name) {
this.keys = keys;
this.name = name;
} }
}, },
async remove(index) { handleShortcut(event) {
if (this.saving) { event.preventDefault();
return;
}
const removed = await this.save(this.shortcuts.filter((_, i) => i !== index)); const {
key, keyCode, code, location, charCode
} = event;
// The row may be gone with the button that had the focus: the delete button now in its place, or this.keysRecord.push({
// the last one, takes it, and the recorder once the list is empty. key, keyCode, code, location, charCode
if (removed) { });
this.$nextTick(() => {
const buttons = this.$refs.list?.querySelectorAll('button') || [];
(buttons[index] || buttons[buttons.length - 1] || this.$refs.recorder?.$el)?.focus();
});
}
}, },
// Every change is saved straight away, so closing the modal can never lose one. addShortcutKey() {
async save(shortcuts) { this.addedShortcutKeys.push([].concat(this.keysRecord));
this.saving = true; },
this.error = '';
removeKey(keys) {
const key = keys.replace(/(\s*)<code>|<\/code>/g, '').replace(/\s*,\s*/g, ',');
this.addedShortcutKeys = this.addedShortcutKeys.filter((item) => {
const formatkey = item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join(',');
return formatkey !== key;
});
this.preferredShortcutKeys = this.preferredShortcutKeys.filter((item) => {
const formatkey = item.map((K) => K.key.charAt(0).toUpperCase() + K.key.slice(1)).join(',');
return formatkey !== key;
});
},
async saveKeys(buttonCb) {
const out = [].concat(this.preferredShortcutKeys, this.addedShortcutKeys);
const preference = this.$store.getters['management/all'](STEVE.PREFERENCE)?.[0];
try { try {
await writeShortcuts(this.preference, shortcuts.map(({ name, keys }) => ({ name, keys }))); preference.data[PREFERED_SHORTCUT_KEYS] = JSON.stringify(out);
await preference.save();
return true; this.closeRecordingModal();
buttonCb(true);
} catch (err) { } catch (err) {
// The console page has no growls, so the dialog says it itself. buttonCb(false);
const title = this.t('harvester.virtualMachine.detail.console.customKeys.saveError');
const reason = stringify(err);
this.error = reason ? `${ title }: ${ reason }` : title;
return false;
} finally {
this.saving = false;
} }
}, },
}, }
}; };
</script> </script>
<template> <template>
<RcModal <ModalWithCard
:show="show" name="recordShortcutKeys"
size="medium" :width="550"
:title="t('harvester.virtualMachine.detail.console.customKeys.title')"
data-testid="vnc-custom-keys-modal"
@close="$emit('close')"
> >
<Banner <template #title>
v-if="error" <t k="harvester.virtualMachine.detail.console.customShortcutKeys" />
color="error"
role="alert"
data-testid="vnc-custom-keys-error"
>
{{ error }}
</Banner>
<p class="custom-keys__intro">
{{ t('harvester.virtualMachine.detail.console.customKeys.description') }}
</p>
<section class="custom-keys__new">
<h3 class="custom-keys__heading">
{{ t('harvester.virtualMachine.detail.console.customKeys.new') }}
</h3>
<div class="custom-keys__field">
<span
id="vnc-key-combination-label"
class="custom-keys__label"
>{{ t('harvester.virtualMachine.detail.console.customKeys.combination') }}</span>
<NovncKeyRecorder
ref="recorder"
v-model:value="keys"
aria-labelledby="vnc-key-combination-label"
/>
<p
v-if="isDuplicate"
class="custom-keys__error"
role="alert"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.duplicate') }}
</p>
<p class="custom-keys__help">
{{ t('harvester.virtualMachine.detail.console.customKeys.reserved') }}
</p>
</div>
<LabeledInput
v-model:value="name"
:label="t('harvester.virtualMachine.detail.console.customKeys.name')"
data-testid="vnc-shortcut-name"
@keyup.enter="add"
/>
<div class="custom-keys__new-actions">
<RcButton
variant="secondary"
:disabled="!keys.length && !name"
@click="clear"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.clear') }}
</RcButton>
<RcButton
variant="primary"
data-testid="vnc-add-shortcut"
:disabled="!canAdd"
@click="add"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.add') }}
</RcButton>
</div>
</section>
<section v-if="shortcuts.length">
<h3 class="custom-keys__heading">
{{ t('harvester.virtualMachine.detail.console.customKeys.saved', { count: shortcuts.length }) }}
</h3>
<ul
ref="list"
class="custom-keys__list"
>
<li
v-for="(shortcut, index) in shortcuts"
:key="index"
class="custom-keys__item"
data-testid="vnc-custom-shortcut"
>
<span class="custom-keys__item-name">{{ shortcut.name || shortcut.labels.join('+') }}</span>
<span class="custom-keys__item-keys">
<RcTag
v-for="(label, i) in shortcut.labels"
:key="i"
type="active"
>
{{ label }}
</RcTag>
</span>
<RcButton
variant="tertiary"
:aria-label="t('harvester.virtualMachine.detail.console.customKeys.delete', { name: shortcut.name || shortcut.labels.join('+') }, true)"
@click="remove(index)"
>
<RcIcon
type="trash"
size="inherit"
/>
</RcButton>
</li>
</ul>
</section>
<template #actions="{ close }">
<RcButton
variant="primary"
size="large"
data-testid="vnc-custom-keys-done"
@click="close"
>
{{ t('harvester.virtualMachine.detail.console.customKeys.done') }}
</RcButton>
</template> </template>
</RcModal>
<template #content>
<div class="row">
<div class="col span-12">
<Banner color="info">
<span v-clean-html="keysRecordFormat"></span>
</Banner>
</div>
</div>
<div class="row">
<div class="col span-12">
<button
class="btn bg-primary"
@click="toggleRecording"
>
<t :k="recordButton" />
<i
class="icon icon-fw"
:class="isRecording ? 'icon-dot-open' : 'icon-dot'"
/>
</button>
<button
:disabled="!canAdd"
class="btn bg-primary"
@click="addShortcutKey"
>
<t k="generic.add" />
</button>
</div>
</div>
<hr>
<div class="displayed-keys mt-20">
<h4
v-clean-html="t('harvester.virtualMachine.detail.console.record.preferredKeys')"
class="text-default-text"
/>
<div class="displayed-banners">
<Banner
v-for="(keys,index) in displayedKeys"
:key="index"
>
<span v-clean-html="keys"></span>
</Banner>
</div>
</div>
</template>
<template #footer>
<div class="actions">
<button
class="btn role-secondary mr-20"
@click.prevent="closeRecordingModal"
>
<t k="generic.close" />
</button>
<AsyncButton
mode="done"
@click="saveKeys"
/>
</div>
</template>
</ModalWithCard>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.custom-keys { .displayed-keys {
&__intro { .banner {
margin: 0; margin: 0;
} }
}
&__new { .displayed-banners {
display: flex; max-height: 155px;
flex-direction: column; overflow: auto;
gap: 16px; }
padding: 16px 20px 20px;
border: 1px solid var(--border);
border-radius: 8px;
}
&__heading { .actions {
margin: 0 0 12px; width: 100%;
font-size: 14px; display: flex;
font-weight: 700; justify-content: flex-end;
line-height: 21px;
.custom-keys__new & {
margin: 0;
}
}
&__field {
display: flex;
flex-direction: column;
gap: 8px;
}
&__label {
color: var(--input-label);
font-size: 14px;
line-height: 21px;
}
&__help,
&__error {
margin: 0;
font-size: 12px;
line-height: 18px;
}
&__help {
color: var(--muted);
}
&__error {
color: var(--error);
}
&__new-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
}
&__list {
display: flex;
flex-direction: column;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
}
&__item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 8px 12px 20px;
border: 1px solid var(--border);
border-radius: 8px;
}
&__item-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&__item-keys {
display: flex;
gap: 6px;
}
} }
</style> </style>
@@ -0,0 +1,108 @@
<script>
export default {
name: 'NovncConsoleItem',
emits: ['send-keys', 'update'],
props: {
items: {
type: Object,
required: true,
default: () => {
return {};
}
},
path: {
type: Array,
required: true,
default: () => {
return [];
}
},
pos: {
type: Number,
required: true,
default: 0,
}
},
methods: {
keysDown(key, pos) {
this.addKeys({ key, pos });
this.$emit('send-keys');
},
addKeys({ key, pos }) {
this.$emit('update', { key, pos });
},
sendKeys() {
this.$emit('send-keys');
},
getOpenStatus(key, pos) {
return this.path[pos] === key;
}
}
};
</script>
<template>
<ul class="list-unstyled dropdown combination-keys__container">
<li
v-for="(item, key) in items"
:key="key"
>
<v-dropdown
v-if="!!item.keys"
placement="right-start"
trigger="click"
:container="false"
>
<span
:class="{ open: getOpenStatus(key, pos) }"
class="p-10 hand"
@click="addKeys({ key, pos })"
>{{ item.label }}</span>
<template #popper>
<novnc-console-item
:items="item.keys"
:path="path"
:pos="pos+1"
@update="addKeys"
@send-keys="sendKeys"
/>
</template>
</v-dropdown>
<span
v-else
class="p-10 hand"
@click="keysDown(key, pos)"
>{{ item.label }}</span>
</li>
</ul>
</template>
<style lang="scss" scoped>
.combination-keys__container {
max-width: 60px;
DIV, SPAN {
display: block;
text-align: center;
}
SPAN {
border-radius: 3px;
&:hover, &.open {
color: var(--primary-hover-text);
background: var(--primary-hover-bg);
}
}
}
</style>
File diff suppressed because it is too large. Load diff
@@ -1,73 +0,0 @@
<script>
// Icons the console needs that RcIcon does not have yet. Paths come from the VNC console design, on
// its 24px grid.
const ICONS = {
power: {
viewBox: '0 0 24 24',
paths: [
'M11.1253 12V2C11.1253 1.51675 11.517 1.125 12.0003 1.125C12.4835 1.125 12.8753 1.51675 12.8753 2V12C12.8753 12.4832 12.4835 12.875 12.0003 12.875C11.517 12.875 11.1253 12.4832 11.1253 12Z',
'M17.7812 5.98086C18.123 5.63921 18.6779 5.64006 19.0195 5.98184C20.398 7.361 21.337 9.11746 21.7187 11.0297C22.1004 12.9421 21.9076 14.9251 21.1641 16.7279C20.4204 18.5309 19.1592 20.0733 17.54 21.1605C15.921 22.2477 14.0166 22.8311 12.0664 22.8373C10.1161 22.8434 8.20695 22.2728 6.58105 21.1957C4.95519 20.1186 3.68464 18.5838 2.92968 16.7855C2.1748 14.9875 1.96928 13.006 2.33886 11.0912C2.70859 9.17628 3.63766 7.41274 5.00781 6.0248C5.3473 5.68128 5.90132 5.67771 6.24511 6.01699C6.58896 6.35643 6.59224 6.91038 6.25292 7.2543C5.12564 8.39621 4.36185 9.84678 4.05761 11.4223C3.75341 12.9978 3.92278 14.6283 4.54394 16.1078C5.16512 17.5874 6.21008 18.8505 7.54785 19.7367C8.88557 20.6229 10.4559 21.0923 12.0605 21.0873C13.6651 21.0823 15.2323 20.6028 16.5644 19.7084C17.8966 18.8138 18.934 17.5443 19.5459 16.0609C20.1578 14.5775 20.317 12.9461 20.0029 11.3725C19.6888 9.79885 18.9157 8.35303 17.7812 7.21816C17.4399 6.87639 17.4396 6.3224 17.7812 5.98086Z',
],
},
maximize: {
viewBox: '0 0 24 24',
paths: [
'M2.125 19V16C2.125 15.5168 2.51675 15.125 3 15.125C3.48325 15.125 3.875 15.5168 3.875 16V19C3.875 19.2984 3.99312 19.5849 4.2041 19.7959C4.41508 20.0069 4.70163 20.125 5 20.125H8C8.48325 20.125 8.875 20.5168 8.875 21C8.875 21.4832 8.48325 21.875 8 21.875H5C4.2375 21.875 3.50596 21.5724 2.9668 21.0332C2.42763 20.494 2.125 19.7625 2.125 19ZM20.125 19V16C20.125 15.5168 20.5168 15.125 21 15.125C21.4832 15.125 21.875 15.5168 21.875 16V19C21.875 19.7625 21.5724 20.494 21.0332 21.0332C20.494 21.5724 19.7625 21.875 19 21.875H16C15.5168 21.875 15.125 21.4832 15.125 21C15.125 20.5168 15.5168 20.125 16 20.125H19C19.2984 20.125 19.5849 20.0069 19.7959 19.7959C20.0069 19.5849 20.125 19.2984 20.125 19ZM2.125 8V5C2.125 4.2375 2.42763 3.50596 2.9668 2.9668C3.50596 2.42763 4.2375 2.125 5 2.125H8C8.48325 2.125 8.875 2.51675 8.875 3C8.875 3.48325 8.48325 3.875 8 3.875H5C4.70163 3.875 4.41508 3.99312 4.2041 4.2041C3.99312 4.41508 3.875 4.70163 3.875 5V8C3.875 8.48325 3.48325 8.875 3 8.875C2.51675 8.875 2.125 8.48325 2.125 8ZM20.125 8V5C20.125 4.70163 20.0069 4.41508 19.7959 4.2041C19.5849 3.99312 19.2984 3.875 19 3.875H16C15.5168 3.875 15.125 3.48325 15.125 3C15.125 2.51675 15.5168 2.125 16 2.125H19C19.7625 2.125 20.494 2.42763 21.0332 2.9668C21.5724 3.50596 21.875 4.2375 21.875 5V8C21.875 8.48325 21.4832 8.875 21 8.875C20.5168 8.875 20.125 8.48325 20.125 8Z',
],
},
minimize: {
viewBox: '0 0 24 24',
paths: [
'M7.125 21V18C7.125 17.7016 7.00688 17.4151 6.7959 17.2041C6.58492 16.9931 6.29837 16.875 6 16.875H3C2.51675 16.875 2.125 16.4832 2.125 16C2.125 15.5168 2.51675 15.125 3 15.125H6C6.7625 15.125 7.49404 15.4276 8.0332 15.9668C8.57237 16.506 8.875 17.2375 8.875 18V21C8.875 21.4832 8.48325 21.875 8 21.875C7.51675 21.875 7.125 21.4832 7.125 21ZM15.125 21V18C15.125 17.2375 15.4276 16.506 15.9668 15.9668C16.506 15.4276 17.2375 15.125 18 15.125H21C21.4832 15.125 21.875 15.5168 21.875 16C21.875 16.4832 21.4832 16.875 21 16.875H18C17.7016 16.875 17.4151 16.9931 17.2041 17.2041C16.9931 17.4151 16.875 17.7016 16.875 18V21C16.875 21.4832 16.4832 21.875 16 21.875C15.5168 21.875 15.125 21.4832 15.125 21ZM7.125 6V3C7.125 2.51675 7.51675 2.125 8 2.125C8.48325 2.125 8.875 2.51675 8.875 3V6C8.875 6.7625 8.57237 7.49404 8.0332 8.0332C7.49404 8.57237 6.7625 8.875 6 8.875H3C2.51675 8.875 2.125 8.48325 2.125 8C2.125 7.51675 2.51675 7.125 3 7.125H6C6.29837 7.125 6.58492 7.00688 6.7959 6.7959C7.00688 6.58492 7.125 6.29837 7.125 6ZM15.125 6V3C15.125 2.51675 15.5168 2.125 16 2.125C16.4832 2.125 16.875 2.51675 16.875 3V6C16.875 6.29837 16.9931 6.58492 17.2041 6.7959C17.4151 7.00688 17.7016 7.125 18 7.125H21C21.4832 7.125 21.875 7.51675 21.875 8C21.875 8.48325 21.4832 8.875 21 8.875H18C17.2375 8.875 16.506 8.57237 15.9668 8.0332C15.4276 7.49404 15.125 6.7625 15.125 6Z',
],
},
'wifi-off': {
viewBox: '0 0 24 24',
paths: [
'M1.38128 1.38128C1.72299 1.03957 2.27785 1.03957 2.61956 1.38128L22.6196 21.3813C22.9613 21.723 22.9613 22.2779 22.6196 22.6196C22.2779 22.9613 21.723 22.9613 21.3813 22.6196L15.9448 17.183C15.6121 17.3797 15.1772 17.3385 14.8881 17.0551C14.117 16.2993 13.0802 15.8764 12.0004 15.8764C10.9207 15.8764 9.88381 16.2993 9.11273 17.0551C8.76768 17.3933 8.21371 17.3883 7.87542 17.0434C7.53715 16.6983 7.54301 16.1434 7.88812 15.8051C8.98629 14.7288 10.4628 14.1264 12.0004 14.1264C12.3272 14.1264 12.651 14.1543 12.9692 14.2075L9.88714 11.1254C8.27735 11.5087 6.79851 12.3224 5.61273 13.4848C5.26764 13.8231 4.71371 13.8182 4.37542 13.4731C4.03714 13.128 4.04303 12.5741 4.38812 12.2358C5.55033 11.0965 6.94797 10.2366 8.47503 9.71331L5.98577 7.22405C4.74971 7.80461 3.60363 8.56219 2.58343 9.47308C2.22296 9.79494 1.66993 9.76324 1.34808 9.40277C1.02629 9.04229 1.05697 8.48925 1.41741 8.16741C2.40785 7.28308 3.5045 6.52832 4.68011 5.91839L1.38128 2.61956C1.03957 2.27785 1.03957 1.72299 1.38128 1.38128ZM12.0102 19.1254C12.4934 19.1254 12.8852 19.5172 12.8852 20.0004C12.8852 20.4837 12.4934 20.8754 12.0102 20.8754H12.0004C11.5172 20.8754 11.1254 20.4837 11.1254 20.0004C11.1254 19.5172 11.5172 19.1254 12.0004 19.1254H12.0102ZM16.2426 10.9028C16.4843 10.4845 17.0195 10.341 17.4379 10.5825C18.2294 11.0398 18.9602 11.5956 19.6127 12.2358C19.9576 12.5741 19.9636 13.1281 19.6254 13.4731C19.287 13.818 18.7331 13.8231 18.3881 13.4848C17.8406 12.9476 17.2271 12.4818 16.5629 12.0981C16.1445 11.8563 16.001 11.3212 16.2426 10.9028ZM10.6352 4.1889C12.7929 4.00208 14.9661 4.25848 17.0209 4.94281C19.0757 5.62716 20.9686 6.72516 22.5834 8.16839C22.9436 8.49044 22.9748 9.04348 22.6528 9.40374C22.3308 9.76385 21.7777 9.7949 21.4174 9.47308C19.9807 8.18898 18.2964 7.21188 16.4682 6.60296C14.6399 5.99405 12.7055 5.7658 10.7856 5.93206C10.3043 5.97356 9.88011 5.61739 9.83831 5.13616C9.79662 4.65472 10.1537 4.23059 10.6352 4.1889Z',
],
},
};
export default {
name: 'NovncIcon',
props: {
type: {
type: String,
required: true,
validator: (value) => Object.keys(ICONS).includes(value),
},
},
computed: {
icon() {
return ICONS[this.type];
},
},
};
</script>
<template>
<svg
class="novnc-icon"
:viewBox="icon.viewBox"
fill="currentColor"
aria-hidden="true"
focusable="false"
>
<path
v-for="(d, i) in icon.paths"
:key="i"
:d="d"
/>
</svg>
</template>
<style lang="scss" scoped>
.novnc-icon {
width: 16px;
height: 16px;
flex-shrink: 0;
}
</style>
@@ -1,232 +0,0 @@
<script>
import RcStatusIndicator from '@components/Pill/RcStatusIndicator';
import RcTag from '@components/Pill/RcTag';
import { MODIFIER_KEYS, baseKey, keyLabel, recordKey } from './shortcuts';
export default {
name: 'NovncKeyRecorder',
components: { RcStatusIndicator, RcTag },
props: {
// The recorded keys, as stored for a shortcut.
value: {
type: Array,
default: () => [],
},
ariaLabelledby: {
type: String,
default: undefined,
},
},
emits: ['update:value'],
data() {
return { recording: false, pending: [] };
},
computed: {
state() {
if (this.recording) {
return 'recording';
}
return this.value.length ? 'captured' : 'empty';
},
labels() {
return this.value.map((K) => keyLabel(baseKey(K, this.value).key));
},
valueId() {
return `vnc-key-recorder-value-${ this.$.uid }`;
},
// Read out with the field's label, so screen readers hear what is recorded.
announcement() {
if (this.state === 'recording') {
return this.t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus');
}
return this.labels.join('+');
},
},
methods: {
start() {
this.pending = [];
this.recording = true;
},
stop() {
this.recording = false;
this.pending = [];
},
// Modifiers wait for the key they go with; the first other key ends the combination.
onKeydown(event) {
if (!this.recording) {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
this.start();
}
return;
}
// Esc or Tab on their own leave the field, so it never traps the keyboard; with a modifier
// they are part of the combination (Ctrl+Shift+Esc).
if (!this.pending.length && (event.key === 'Escape' || event.key === 'Tab')) {
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
}
this.stop();
return;
}
event.preventDefault();
event.stopPropagation();
if (event.repeat) {
return;
}
if (MODIFIER_KEYS.includes(event.key)) {
if (!this.pending.some((K) => K.key === event.key)) {
this.pending.push(recordKey(event));
}
return;
}
this.$emit('update:value', [...this.pending, recordKey(event, this.pending)]);
this.stop();
},
// Modifiers released before any other key are the combination themselves, such as the Windows key on
// its own. It waits for the last one, so Ctrl+Shift can be let go one key at a time.
onKeyup(event) {
if (!this.recording || !this.pending.length || !MODIFIER_KEYS.includes(event.key)) {
return;
}
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
return;
}
event.preventDefault();
event.stopPropagation();
this.$emit('update:value', [...this.pending]);
this.stop();
},
},
};
</script>
<template>
<div
class="key-recorder"
:class="`key-recorder--${ state }`"
role="button"
tabindex="0"
:aria-labelledby="ariaLabelledby ? `${ ariaLabelledby } ${ valueId }` : valueId"
:aria-pressed="recording"
data-testid="vnc-key-recorder"
@click="start"
@keydown="onKeydown"
@keyup="onKeyup"
@blur="stop"
>
<span
:id="valueId"
class="sr-only"
aria-live="polite"
>{{ announcement }}</span>
<template v-if="state === 'recording'">
<span class="key-recorder__hint">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recording') }}</span>
<span class="key-recorder__status">
<RcStatusIndicator
shape="disc"
status="error"
/>
{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.recordingStatus') }}
</span>
</template>
<template v-else-if="state === 'captured'">
<span class="key-recorder__keys">
<RcTag
v-for="(label, i) in labels"
:key="i"
type="active"
>
{{ label }}
</RcTag>
</span>
<span class="key-recorder__again">{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.again') }}</span>
</template>
<span
v-else
class="key-recorder__hint"
>{{ t('harvester.virtualMachine.detail.console.customKeys.recorder.empty') }}</span>
</div>
</template>
<style lang="scss" scoped>
.key-recorder {
display: flex;
align-items: center;
gap: 8px;
min-height: 48px;
padding: 0 14px;
border: 1px solid var(--input-border);
border-radius: 4px;
background: var(--input-bg);
cursor: pointer;
&--empty {
border-style: dashed;
}
&--recording {
border: 2px solid var(--primary-keyboard-focus);
padding: 0 13px;
}
&:focus-visible {
@include focus-outline;
}
&__hint {
color: var(--muted);
font-size: 14px;
line-height: 21px;
}
&__keys {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
&__status,
&__again {
display: inline-flex;
align-items: center;
gap: 8px;
margin-left: auto;
font-size: 12px;
line-height: 18px;
}
&__again {
color: var(--muted);
}
}
</style>
@@ -1,404 +0,0 @@
<script>
import { h, inject } from 'vue';
import {
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger
} from '@components/RcDropdown';
import { RcIcon } from '@components/RcIcon';
import { shortcutLabels } from './shortcuts';
export const MODIFIERS = [
{ key: 'ControlLeft', label: 'Ctrl' },
{ key: 'AltLeft', label: 'Alt' },
];
export const FUNCTION_KEYS = ['F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'];
// Ctrl alone offers the browser shortcuts the guest cannot get from the keyboard (the browser keeps
// Ctrl+N/T/W for itself), as the old cascading menu did.
export const CTRL_KEYS = [
{ key: 'KeyN', label: 'N' },
{ key: 'KeyT', label: 'T' },
{ key: 'KeyW', label: 'W' },
{ key: 'KeyY', label: 'Y' },
];
// RcDropdown collects its items when the menu opens, and the arrow keys walk that list. Holding a modifier
// swaps the keys below it while the menu is open, so, as RcDropdown does for its submenus, the items are
// collected again on each key press and the arrows reach the keys shown now.
export const ShortcutMenuBody = {
name: 'ShortcutMenuBody',
setup(_props, { slots }) {
const dropdown = inject('dropdownContext', null);
const collectItems = (event) => {
const menu = event.currentTarget.closest('[dropdown-menu-collection]');
if (dropdown?.dropdownItems && menu) {
dropdown.dropdownItems.value = [...menu.querySelectorAll('[dropdown-menu-item]')];
}
};
return () => h('div', { class: 'shortcut-menu', onKeydownCapture: collectItems }, slots.default?.());
},
};
export default {
name: 'NovncShortcutKeysMenu',
components: {
RcDropdown, RcDropdownGroup, RcDropdownItem, RcDropdownItemCheckbox, RcDropdownSeparator, RcDropdownTrigger, RcIcon, ShortcutMenuBody
},
props: {
disabled: {
type: Boolean,
default: false,
},
// Saved custom shortcuts, as { name, keys }.
shortcuts: {
type: Array,
default: () => [],
},
// Keys only go out over a connected console; the menu still opens to manage shortcuts.
canSend: {
type: Boolean,
default: true,
},
// Why keys cannot be sent right now, shown at the top of the menu.
blockedReason: {
type: String,
default: '',
},
// Custom shortcuts are stored in the user preference, which standalone setups may not have.
canManage: {
type: Boolean,
default: true,
},
},
emits: ['send-keys', 'send-shortcut', 'manage', 'ctrl-alt-del'],
data() {
return { held: [] };
},
computed: {
modifiers() {
return MODIFIERS;
},
functionKeys() {
return FUNCTION_KEYS;
},
holdsCtrl() {
return this.held.includes('ControlLeft');
},
holdsAlt() {
return this.held.includes('AltLeft');
},
// What the keys below the toggles offer follows what is held, so the menu sends the same
// combinations as the old one: Ctrl+N/T/W/Y, Ctrl+Alt+Del, Alt+Print Screen and Alt+F1-F12, plus
// Ctrl+Alt+F1-F12 to switch Linux consoles.
keyOptions() {
if (this.holdsCtrl && this.holdsAlt) {
return [{ key: 'Delete', label: 'Del' }];
}
if (this.holdsCtrl) {
return CTRL_KEYS;
}
return [{ key: 'PrintScreen', label: this.t('harvester.virtualMachine.detail.console.shortcutMenu.printScreen') }];
},
showFunctionKeys() {
return !this.holdsCtrl || this.holdsAlt;
},
heldCombo() {
return MODIFIERS.filter((M) => this.held.includes(M.key)).map((M) => M.label).join('+');
},
items() {
return this.shortcuts.map((shortcut, index) => {
const label = shortcutLabels(shortcut).join('+');
return {
index, name: shortcut.name || label, label, keys: shortcut.keys
};
});
},
},
methods: {
// Held modifiers belong to this visit of the menu; closing it without a key lets them go.
onOpen(open) {
if (!open) {
this.held = [];
}
},
toggleModifier(key, on) {
this.held = on ? [...this.held, key] : this.held.filter((K) => K !== key);
},
// Held modifiers apply to the next key only, then the toggles reset.
sendKey(key) {
const modifiers = MODIFIERS.map((M) => M.key).filter((K) => this.held.includes(K));
// Ctrl+Alt+Del restarts most guests, so it goes through the same confirmation as its button.
if (key === 'Delete' && this.holdsCtrl && this.holdsAlt) {
this.$emit('ctrl-alt-del');
} else {
this.$emit('send-keys', [...modifiers, key]);
}
this.held = [];
},
},
};
</script>
<template>
<rc-dropdown
:aria-label="t('harvester.virtualMachine.detail.console.shortcutKeys')"
placement="bottom-start"
@update:open="onOpen"
>
<rc-dropdown-trigger
variant="tertiary"
data-testid="vnc-shortcut-keys"
:disabled="disabled"
>
<template #before>
<rc-icon
type="keyboard"
size="inherit"
/>
</template>
{{ t('harvester.virtualMachine.detail.console.shortcutKeys') }}
<template #after>
<rc-icon
type="chevron-down"
size="inherit"
/>
</template>
</rc-dropdown-trigger>
<template #dropdownCollection>
<shortcut-menu-body>
<p
v-if="!canSend && blockedReason"
class="shortcut-menu__blocked"
data-testid="vnc-shortcut-blocked"
>
{{ blockedReason }}
</p>
<template v-if="canManage && items.length">
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.yourShortcuts')">
<rc-dropdown-item
v-for="item in items"
:key="item.index"
:disabled="!canSend"
class="shortcut-menu__saved"
data-testid="vnc-saved-shortcut"
:title="item.name"
@click="$emit('send-shortcut', item.keys)"
>
<span class="shortcut-menu__saved-name">{{ item.name }}</span>
<template #after>
<span class="shortcut-menu__chip">{{ item.label }}</span>
</template>
</rc-dropdown-item>
</rc-dropdown-group>
<rc-dropdown-separator />
</template>
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.holdModifiers')">
<div class="shortcut-menu__row">
<rc-dropdown-item-checkbox
v-for="modifier in modifiers"
:key="modifier.key"
:disabled="!canSend"
indicator="checkmark"
class="shortcut-menu__chip shortcut-menu__toggle"
:class="{ 'is-on': held.includes(modifier.key) }"
:data-testid="`vnc-hold-${ modifier.label.toLowerCase() }`"
:model-value="held.includes(modifier.key)"
@update:model-value="toggleModifier(modifier.key, $event)"
>
{{ modifier.label }}
</rc-dropdown-item-checkbox>
</div>
<p
v-if="heldCombo"
class="shortcut-menu__help"
>
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.holdHint', { combo: heldCombo }) }}
</p>
</rc-dropdown-group>
<rc-dropdown-separator />
<rc-dropdown-group :label="t('harvester.virtualMachine.detail.console.shortcutMenu.keys')">
<div class="shortcut-menu__row">
<rc-dropdown-item
v-for="option in keyOptions"
:key="option.key"
:disabled="!canSend"
class="shortcut-menu__chip"
:data-testid="`vnc-key-${ option.key }`"
@click="sendKey(option.key)"
>
{{ option.label }}
</rc-dropdown-item>
</div>
</rc-dropdown-group>
<rc-dropdown-group
v-if="showFunctionKeys"
:label="t('harvester.virtualMachine.detail.console.shortcutMenu.functionKeys')"
>
<div class="shortcut-menu__grid">
<rc-dropdown-item
v-for="key in functionKeys"
:key="key"
:disabled="!canSend"
class="shortcut-menu__chip"
:data-testid="`vnc-key-${ key }`"
@click="sendKey(key)"
>
{{ key }}
</rc-dropdown-item>
</div>
</rc-dropdown-group>
<template v-if="canManage">
<rc-dropdown-separator />
<rc-dropdown-item
class="shortcut-menu__manage"
data-testid="vnc-manage-shortcuts"
@click="$emit('manage')"
>
<template #before>
<rc-icon
type="edit"
size="inherit"
/>
</template>
{{ t('harvester.virtualMachine.detail.console.shortcutMenu.manage') }}
</rc-dropdown-item>
</template>
</shortcut-menu-body>
</template>
</rc-dropdown>
</template>
<style lang="scss" scoped>
// The menu items are styled as the key chips of the design; `.shortcut-menu` raises the
// specificity above RcDropdownItem's own item styles.
.shortcut-menu {
width: 320px;
&__row,
&__grid {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 4px 16px 8px;
}
&__grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
}
// The chips are the design's small secondary buttons, so they take RcButton's secondary tokens
// (with its fallbacks) and follow the brand like every other button.
.shortcut-menu__chip {
justify-content: center;
min-height: 24px;
margin: 0;
padding: 0 8px;
border: 1px solid var(--secondary-border, var(--primary));
border-radius: 4px;
background: var(--secondary, transparent);
color: var(--on-secondary, var(--primary));
font-size: 12px;
line-height: 16px;
white-space: nowrap;
&:hover {
background: var(--secondary-hover, var(--accent-btn));
}
}
.shortcut-menu__chip[disabled],
.shortcut-menu__saved[disabled] .shortcut-menu__chip {
&,
&:hover {
border-color: var(--disabled-bg, var(--border));
background: transparent;
color: var(--disabled-text);
cursor: not-allowed;
}
}
&__blocked {
margin: 0;
padding: 4px 16px 8px;
color: var(--muted);
font-size: 12px;
line-height: 18px;
}
.shortcut-menu__toggle.is-on {
&,
&:hover {
border-color: var(--active, var(--primary));
background: var(--active, var(--primary));
color: var(--on-active, var(--primary-text));
}
}
.shortcut-menu__saved {
margin: 0 9px;
padding: 4px 8px;
font-size: 14px;
// Long names stay on two lines; the full one is in the tooltip.
.shortcut-menu__saved-name {
display: -webkit-box;
min-width: 0;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
line-clamp: 2;
}
.shortcut-menu__chip {
display: inline-flex;
align-items: center;
}
}
&__help {
margin: 0;
padding: 0 16px 8px;
color: var(--muted);
font-size: 12px;
line-height: 18px;
}
// The design's tertiary button.
.shortcut-menu__manage {
color: var(--on-tertiary, var(--primary));
}
}
</style>
@@ -1,104 +0,0 @@
<script>
import NovncIcon from './NovncIcon';
// The card the console shows on its black screen when there is nothing to type into: a failed
// connection, or a virtual machine that is not running.
export default {
name: 'NovncStatusCard',
components: { NovncIcon },
props: {
icon: {
type: String,
default: 'wifi-off',
},
title: {
type: String,
required: true,
},
detail: {
type: String,
default: '',
},
},
};
</script>
<template>
<div class="status-card">
<span
class="status-card__badge"
aria-hidden="true"
>
<NovncIcon :type="icon" />
</span>
<h3 class="status-card__title">
{{ title }}
</h3>
<p
v-if="detail"
class="status-card__detail"
>
{{ detail }}
</p>
<div
v-if="$slots.default"
class="status-card__actions"
>
<slot />
</div>
</div>
</template>
<style lang="scss" scoped>
// Always on the black screen, whatever the theme, so the text is light.
.status-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
max-width: 480px;
padding: 32px;
color: #fff;
text-align: center;
&__badge {
display: flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
border-radius: 50%;
background: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.8);
.novnc-icon {
width: 24px;
height: 24px;
}
}
&__title {
margin: 0;
color: #fff;
font-size: 16px;
font-weight: 700;
}
&__detail {
margin: 0;
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
line-height: 16px;
}
&__actions {
display: flex;
gap: 12px;
padding-top: 8px;
}
}
</style>
@@ -1,302 +0,0 @@
<script>
import ButtonGroup from '@shell/components/ButtonGroup';
import { RcButton } from '@components/RcButton';
import { RcIcon } from '@components/RcIcon';
import { MAXIMUM_ZOOM, MINIMUM_ZOOM, ZOOM_STEP } from './ZoomableRFB';
export const VIEW_MODE = {
SCALE: 'scale',
NONE: 'none',
};
const MAXIMUM_LEVEL = 9;
export default {
name: 'NovncViewOptions',
components: {
ButtonGroup, RcButton, RcIcon
},
props: {
settings: {
type: Object,
required: true,
},
},
emits: ['update', 'reset'],
computed: {
modeOptions() {
return [
{ value: VIEW_MODE.SCALE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.automatic') },
{ value: VIEW_MODE.NONE, label: this.t('harvester.virtualMachine.detail.console.viewOptions.manual') },
];
},
isManual() {
return this.settings.viewMode === VIEW_MODE.NONE;
},
zoom() {
return {
min: MINIMUM_ZOOM, max: MAXIMUM_ZOOM, step: ZOOM_STEP
};
},
maximumLevel() {
return MAXIMUM_LEVEL;
},
},
methods: {
update(key, value) {
this.$emit('update', { ...this.settings, [key]: value });
},
stepZoom(direction) {
const next = this.settings.zoomPercent + (direction * ZOOM_STEP);
this.update('zoomPercent', Math.min(Math.max(next, MINIMUM_ZOOM), MAXIMUM_ZOOM));
},
// Feeds the filled part of the track, which native range inputs do not draw on their own.
fill(value, min, max) {
return { '--fill': `${ ((value - min) / (max - min)) * 100 }%` };
},
},
};
</script>
<template>
<div
class="view-options"
data-testid="vnc-view-options"
>
<section class="view-options__section">
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.scaling') }}</span>
<ButtonGroup
class="view-options__mode"
size="medium"
:value="settings.viewMode"
:options="modeOptions"
@update:value="update('viewMode', $event)"
/>
<p class="view-options__help">
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ isManual ? 'manualHelp' : 'automaticHelp' }`) }}
</p>
</section>
<section class="view-options__section">
<label
for="vnc-zoom"
class="view-options__row"
>
<span class="view-options__label">{{ t('harvester.virtualMachine.detail.console.viewOptions.zoom') }}</span>
<span class="view-options__value">{{ settings.zoomPercent }}%</span>
</label>
<div class="view-options__zoom">
<RcButton
variant="secondary"
size="small"
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomOut')"
:disabled="!isManual || settings.zoomPercent <= zoom.min"
@click="stepZoom(-1)"
>
<RcIcon
type="minus"
size="inherit"
/>
</RcButton>
<input
id="vnc-zoom"
class="view-options__slider"
type="range"
:min="zoom.min"
:max="zoom.max"
:step="zoom.step"
:value="settings.zoomPercent"
:disabled="!isManual"
:aria-valuetext="`${ settings.zoomPercent }%`"
:style="fill(settings.zoomPercent, zoom.min, zoom.max)"
@input="update('zoomPercent', Number($event.target.value))"
>
<RcButton
variant="secondary"
size="small"
:aria-label="t('harvester.virtualMachine.detail.console.viewOptions.zoomIn')"
:disabled="!isManual || settings.zoomPercent >= zoom.max"
@click="stepZoom(1)"
>
<RcIcon
type="plus"
size="inherit"
/>
</RcButton>
</div>
</section>
<hr class="view-options__divider">
<section
v-for="level in ['qualityLevel', 'compressionLevel']"
:key="level"
class="view-options__section"
>
<label
:for="`vnc-${ level }`"
class="view-options__row"
>
<span class="view-options__label">{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.label`) }}</span>
<span class="view-options__value">{{ t('harvester.virtualMachine.detail.console.viewOptions.levelOf', { value: settings[level], max: maximumLevel }) }}</span>
</label>
<input
:id="`vnc-${ level }`"
class="view-options__slider"
type="range"
min="0"
:max="maximumLevel"
step="1"
:value="settings[level]"
:style="fill(settings[level], 0, maximumLevel)"
@input="update(level, Number($event.target.value))"
>
<p class="view-options__help">
{{ t(`harvester.virtualMachine.detail.console.viewOptions.${ level }.help`) }}
</p>
</section>
<RcButton
variant="link"
class="view-options__reset"
data-testid="vnc-view-reset"
@click="$emit('reset')"
>
{{ t('harvester.virtualMachine.detail.console.viewOptions.reset') }}
</RcButton>
</div>
</template>
<style lang="scss" scoped>
.view-options {
display: flex;
flex-direction: column;
gap: 18px;
width: 336px;
padding: 16px;
box-sizing: border-box;
&__section {
display: flex;
flex-direction: column;
gap: 8px;
}
&__row {
display: flex;
justify-content: space-between;
gap: 8px;
margin: 0;
}
&__label {
color: var(--body-text);
font-size: 12px;
font-weight: 700;
line-height: 18px;
}
&__value,
&__help {
color: var(--muted);
font-size: 12px;
line-height: 18px;
font-variant-numeric: tabular-nums;
}
&__help {
margin: 0;
}
&__mode {
display: flex;
button {
flex: 1;
}
}
&__zoom {
display: flex;
align-items: center;
gap: 8px;
// Between the zoom buttons the slider takes the room that is left. In the other sections, which
// are columns, the same rule would set its height and squash it to the track.
.view-options__slider {
flex: 1;
}
}
&__divider {
margin: 0;
border: 0;
border-top: 1px solid var(--border);
}
// Links sit flush with the panel text instead of carrying button padding.
&__reset {
align-self: flex-start;
--rc-button-padding: 0;
}
&__slider {
width: 100%;
height: 20px;
margin: 0;
background: transparent;
cursor: pointer;
appearance: none;
&::-webkit-slider-runnable-track {
height: 4px;
border-radius: 2px;
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
}
&::-moz-range-track {
height: 4px;
border-radius: 2px;
background: linear-gradient(to right, var(--primary) var(--fill), var(--muted) var(--fill));
}
&::-webkit-slider-thumb {
width: 16px;
height: 16px;
margin-top: -6px;
border: 2px solid var(--nav-bg);
border-radius: 50%;
background: var(--primary);
appearance: none;
}
&::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid var(--nav-bg);
border-radius: 50%;
background: var(--primary);
}
&:focus-visible {
@include focus-outline;
}
&:disabled {
cursor: not-allowed;
opacity: 0.5;
}
}
}
</style>
+2 -44
View File
@@ -1,12 +1,5 @@
import RFB from '@novnc/novnc/core/rfb'; import RFB from '@novnc/novnc/core/rfb';
export const MINIMUM_ZOOM = 50;
export const MAXIMUM_ZOOM = 200;
export const ZOOM_STEP = 10;
// The focus ring and the gap before it, drawn outside the canvas.
const FOCUS_RING_WIDTH = 4;
export function normalizeZoom(value) { export function normalizeZoom(value) {
const percent = Number(value); const percent = Number(value);
@@ -14,7 +7,7 @@ export function normalizeZoom(value) {
return 100; return 100;
} }
return Math.min(MAXIMUM_ZOOM, Math.max(MINIMUM_ZOOM, Math.round(percent / ZOOM_STEP) * ZOOM_STEP)); return Math.min(200, Math.max(50, Math.round(percent / 10) * 10));
} }
export default class ZoomableRFB extends RFB { export default class ZoomableRFB extends RFB {
@@ -27,47 +20,12 @@ export default class ZoomableRFB extends RFB {
this._updateScale(); this._updateScale();
} }
// The screen takes all the room it has, without a focus ring around it.
get edgeToEdge() {
return !!this._edgeToEdge;
}
set edgeToEdge(value) {
this._edgeToEdge = value;
this._updateScale();
}
_updateScale() { _updateScale() {
if (this.scaleViewport) { if (this.scaleViewport) {
// Fit inside the focus ring the console draws around the canvas, instead of under it. super._updateScale();
const size = this._screenSize();
const inset = this.edgeToEdge ? 0 : 2 * FOCUS_RING_WIDTH;
this._display.autoscale(size.w - inset, size.h - inset);
this._fixScrollbars();
} else { } else {
this._display.scale = this.zoomPercent / 100; this._display.scale = this.zoomPercent / 100;
this._fixScrollbars(); this._fixScrollbars();
} }
} }
// noVNC only stops a click on the screen, which Firefox delivers there (others to the page, past
// noVNC's mouse capture). An open menu would never see the click outside it and would stay open.
_handleMouse(ev) {
if (ev.type !== 'click') {
super._handleMouse(ev);
}
}
// noVNC hides the mouse over the screen until the guest sends a pointer image, and a text console
// or a guest that draws its own pointer never does. Show the system pointer unless one arrives.
_refreshCursor() {
super._refreshCursor();
const hasGuestPointer = this._cursorImage.rgbaPixels.some((value, index) => index % 4 === 3 && value > 0);
if (!hasGuestPointer) {
this._canvas.style.cursor = 'default';
}
}
} }
@@ -1,19 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import { RcButton } from '@components/RcButton';
import NovncConnectionStatus from '../NovncConnectionStatus.vue';
jest.mock('../ZoomableRFB', () => ({}));
describe('component: NovncConnectionStatus', () => {
// A plain button takes the global 40px button height, taller than the 32px pill around it.
it('should offer Reconnect as an RcButton when the console is disconnected', () => {
const wrapper = shallowMount(NovncConnectionStatus, { props: { status: 'disconnected', label: 'Disconnected' } });
const reconnect = wrapper.findComponent(RcButton);
expect(reconnect.attributes('data-testid')).toBe('vnc-connection-reconnect');
reconnect.vm.$emit('click');
expect(wrapper.emitted('reconnect')).toHaveLength(1);
});
});
@@ -97,36 +97,6 @@ describe('component: NovncConsole', () => {
lastRFB().emit('disconnect'); lastRFB().emit('disconnect');
expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE); expect(wrapper.vm.failure).toBe(CONSOLE_FAILURE.UNAVAILABLE);
expect(wrapper.vm.canTakeOver).toBe(false);
});
it('should retry, not report in use, when a VM that just started refuses the first connection', async() => {
const wrapper = mountConsole({ startedAt: Date.now() });
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
expect(wrapper.vm.failure).toBe('');
});
it('should keep counting retries when Reconnect now skips the wait', async() => {
const wrapper = mountConsole();
await jest.runOnlyPendingTimersAsync();
lastRFB().emit('connect');
lastRFB().emit('disconnect');
expect(wrapper.vm.retryTimes).toBe(1);
wrapper.vm.retryNow();
expect(wrapper.vm.retryTimes).toBe(1);
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
// Still held by the other session: back to waiting, not the in-use failure.
lastRFB().emit('disconnect');
expect(wrapper.vm.status).toBe(CONSOLE_STATUS.RECONNECTING);
expect(wrapper.vm.retryTimes).toBe(2);
}); });
it('should only take over after the modal is confirmed', async() => { it('should only take over after the modal is confirmed', async() => {
@@ -182,20 +152,6 @@ describe('component: NovncConsole', () => {
expect(view.classes()).not.toContain('is-focused'); expect(view.classes()).not.toContain('is-focused');
}); });
it('should drop the focus ring and its room when the screen goes edge to edge', async() => {
const wrapper = mountConsole();
const view = wrapper.find('.novnc-screen');
await jest.runOnlyPendingTimersAsync();
expect(view.classes()).not.toContain('is-edge-to-edge');
expect(lastRFB().edgeToEdge).toBe(false);
await wrapper.setProps({ settings: { edgeToEdge: true } });
expect(view.classes()).toContain('is-edge-to-edge');
expect(lastRFB().edgeToEdge).toBe(true);
});
describe('when the cluster does not support preserveSession', () => { describe('when the cluster does not support preserveSession', () => {
it('should connect without the parameter and offer no take over', async() => { it('should connect without the parameter and offer no take over', async() => {
const wrapper = mountConsole({ preserveSession: false }); const wrapper = mountConsole({ preserveSession: false });
@@ -1,161 +0,0 @@
import { reactive } from 'vue';
import { flushPromises, mount, shallowMount } from '@vue/test-utils';
import { RcButton } from '@components/RcButton';
import NovncConsoleCustomKeys from '../NovncConsoleCustomKeys.vue';
import { SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE } from '../shortcuts';
const key = (value, code) => ({ key: value, code });
const CTRL_F2 = [key('Control', 'ControlLeft'), key('F2', 'F2')];
const CTRL_SPACE = [key('Control', 'ControlLeft'), key(' ', 'Space')];
const ALT_T = [key('Alt', 'AltLeft'), key('t', 'KeyT')];
// `rendered` mounts the buttons and the recorder for real, in the document, so the focus can be checked.
const mountKeys = (saved = [], { rendered = false } = {}) => {
// Reactive like the store's, so the list follows what is saved.
const preference = reactive({
data: { [SHORTCUTS_PREFERENCE]: JSON.stringify(saved) },
save: jest.fn().mockResolvedValue(),
});
const wrapper = (rendered ? mount : shallowMount)(NovncConsoleCustomKeys, {
props: { show: true },
attachTo: rendered ? document.body : undefined,
global: {
mocks: { $store: { getters: { 'management/all': () => [preference] } } },
stubs: {
RcModal: { template: '<div><slot /></div>' }, Banner: { template: '<div><slot /></div>' }, LabeledInput: true
},
},
});
return { wrapper, preference };
};
const listed = (wrapper) => wrapper.findAll('[data-testid="vnc-custom-shortcut"]');
const removeShortcut = async(wrapper, index) => {
listed(wrapper)[index].findComponent(RcButton).vm.$emit('click');
await flushPromises();
};
const savedKeys = (preference) => JSON.parse(preference.data[SHORTCUTS_PREFERENCE]);
describe('component: NovncConsoleCustomKeys', () => {
it('should offer to remove every saved shortcut', () => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T]);
expect(listed(wrapper).map((item) => item.findComponent(RcButton).exists())).toStrictEqual([true, true]);
});
it('should save the list without the shortcut that was removed', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await removeShortcut(wrapper, 0);
expect(preference.save).toHaveBeenCalledTimes(1);
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
expect(listed(wrapper)).toHaveLength(1);
});
it('should remove a shortcut with the Space key in it', async() => {
const { wrapper, preference } = mountKeys([CTRL_SPACE, ALT_T]);
await removeShortcut(wrapper, 0);
expect(savedKeys(preference)).toStrictEqual([ALT_T]);
});
it('should keep the shortcut when removing it cannot be saved, and say so in the dialog', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
preference.save.mockRejectedValue(new Error('forbidden'));
await removeShortcut(wrapper, 0);
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
expect(listed(wrapper)).toHaveLength(2);
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').text()).toBe('%harvester.virtualMachine.detail.console.customKeys.saveError%: forbidden');
await wrapper.setProps({ show: false });
expect(wrapper.find('[data-testid="vnc-custom-keys-error"]').exists()).toBe(false);
});
it('should not start a second save while one is running', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
wrapper.vm.remove(0);
wrapper.vm.remove(1);
await flushPromises();
expect(preference.save).toHaveBeenCalledTimes(1);
});
it('should keep the focus on a delete button after a removal, and hand it to the recorder once the list is empty', async() => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T], { rendered: true });
const deleteButtons = () => wrapper.findAll('[data-testid="vnc-custom-shortcut"] button');
deleteButtons()[1].element.focus();
await deleteButtons()[1].trigger('click');
await flushPromises();
expect(document.activeElement).toBe(deleteButtons()[0].element);
await deleteButtons()[0].trigger('click');
await flushPromises();
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
wrapper.unmount();
});
it('should give the recorder the focus after a shortcut is added', async() => {
const { wrapper } = mountKeys([CTRL_F2], { rendered: true });
wrapper.vm.keys = ALT_T;
await wrapper.vm.$nextTick();
wrapper.find('[data-testid="vnc-add-shortcut"]').element.focus();
await wrapper.find('[data-testid="vnc-add-shortcut"]').trigger('click');
await flushPromises();
expect(document.activeElement).toBe(wrapper.find('[data-testid="vnc-key-recorder"]').element);
wrapper.unmount();
});
it('should empty the form as soon as a shortcut is added, so it does not say it is already saved while it saves', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
preference.save.mockReturnValue(new Promise(() => {}));
wrapper.vm.keys = ALT_T;
wrapper.vm.add();
await wrapper.vm.$nextTick();
expect(listed(wrapper)).toHaveLength(2);
expect(wrapper.vm.keys).toStrictEqual([]);
expect(wrapper.find('.custom-keys__error').exists()).toBe(false);
});
it('should put the shortcut back in the form when it cannot be saved', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
preference.save.mockRejectedValue(new Error('forbidden'));
wrapper.vm.keys = ALT_T;
wrapper.vm.name = 'Task manager';
await wrapper.vm.add();
expect(listed(wrapper)).toHaveLength(1);
expect(wrapper.vm.keys).toStrictEqual(ALT_T);
expect(wrapper.vm.name).toBe('Task manager');
});
it('should save a new shortcut straight away, with its name', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
wrapper.vm.keys = ALT_T;
wrapper.vm.name = ' Task manager ';
await wrapper.vm.add();
expect(savedKeys(preference)).toStrictEqual([CTRL_F2, ALT_T]);
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'AltLeft+KeyT': 'Task manager' });
expect(wrapper.vm.keys).toStrictEqual([]);
});
});
@@ -10,12 +10,7 @@ const consoleRef = {
focus: jest.fn(), focus: jest.fn(),
}; };
const CHECKBOX = { name: 'Checkbox' }; const mountWrapper = () => {
const mountWrapper = ({ preferences = [], storage = {} } = {}) => {
// The console settings are saved there, so one test's would load in the next.
window.localStorage.clear();
Object.entries(storage).forEach(([key, value]) => window.localStorage.setItem(key, JSON.stringify(value)));
consoleRef.ctrlAltDelete.mockClear(); consoleRef.ctrlAltDelete.mockClear();
consoleRef.focus.mockClear(); consoleRef.focus.mockClear();
@@ -29,7 +24,7 @@ const mountWrapper = ({ preferences = [], storage = {} } = {}) => {
mocks: { mocks: {
$store: { $store: {
getters: { getters: {
'management/all': () => preferences, 'management/all': () => [],
'harvester-common/getFeatureEnabled': () => true, 'harvester-common/getFeatureEnabled': () => true,
}, },
}, },
@@ -89,106 +84,6 @@ describe('component: NovncConsoleWrapper', () => {
expect(doSoftReboot).toHaveBeenCalledTimes(1); expect(doSoftReboot).toHaveBeenCalledTimes(1);
}); });
it('should keep the shortcut menu open to use while keys cannot be sent, and say why', () => {
const wrapper = mountWrapper();
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
expect(wrapper.vm.sendBlockedReason).toBe('%harvester.virtualMachine.detail.console.shortcutMenu.blockedDisconnected%');
// Without a user preference there is nothing to manage either, so only then is it disabled.
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
});
it('should keep the shortcut menu enabled while disconnected when there are shortcuts to manage', () => {
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
wrapper.vm.onStatusChanged({ status: 'reconnecting' });
expect(wrapper.vm.shortcutMenuProps.canSend).toBe(false);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
});
it('should disable the shortcut menu, managing shortcuts included, while view only is on', () => {
const wrapper = mountWrapper({ preferences: [{ data: {} }] });
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(false);
wrapper.vm.setViewOnly(true);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
});
it('should disable Ctrl+Alt+Del and Soft reboot while view only is on', async() => {
const wrapper = mountWrapper();
const doSoftReboot = jest.fn();
const button = (id) => wrapper.find(`[data-testid="${ id }"]`);
wrapper.vm.vmResource = { doSoftReboot, actions: { softreboot: 'url' } };
await wrapper.vm.$nextTick();
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('false');
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('false');
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(button('vnc-soft-reboot').attributes('disabled')).toBe('true');
expect(button('vnc-ctrl-alt-del').attributes('disabled')).toBe('true');
wrapper.vm.softReboot();
wrapper.vm.ctrlAltDelete();
expect(wrapper.vm.confirmAction).toBeNull();
expect(doSoftReboot).not.toHaveBeenCalled();
});
it('should say so under the console while view only is on', async() => {
const wrapper = mountWrapper();
const hint = () => wrapper.find('.console-area__hint').text();
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hint%');
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(hint()).toBe('%harvester.virtualMachine.detail.console.hintViewOnly%');
});
it('should not send keys while view only is on', () => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
expect(wrapper.vm.canSendKeys).toBe(false);
});
it('should switch view only with the checkbox, and not repeat it in the connection status', async() => {
const wrapper = mountWrapper();
const checkbox = () => wrapper.findComponent(CHECKBOX);
expect(checkbox().props('value')).toBe(false);
checkbox().vm.$emit('update:value', true);
await wrapper.vm.$nextTick();
expect(wrapper.vm.settings.viewOnly).toBe(true);
expect(checkbox().props('value')).toBe(true);
expect(wrapper.vm.statusLabel).toBe('%harvester.virtualMachine.detail.console.status.connected%');
});
it('should give the console the keyboard when view only is turned off, not when it is turned on', async() => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
await wrapper.vm.$nextTick();
expect(consoleRef.focus).not.toHaveBeenCalled();
wrapper.vm.setViewOnly(false);
await wrapper.vm.$nextTick();
expect(consoleRef.focus).toHaveBeenCalledTimes(1);
});
it('should not ask to send Ctrl+Alt+Del while keys cannot be sent', () => { it('should not ask to send Ctrl+Alt+Del while keys cannot be sent', () => {
const wrapper = mountWrapper(); const wrapper = mountWrapper();
@@ -197,125 +92,4 @@ describe('component: NovncConsoleWrapper', () => {
expect(wrapper.vm.confirmAction).toBeNull(); expect(wrapper.vm.confirmAction).toBeNull();
}); });
describe('view settings', () => {
it('should not take what the previous console saved on its first open as a choice', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': {
viewMode: 'none', zoomPercent: 100, viewOnly: false, qualityLevel: 6, compressionLevel: 2
}
}
});
expect(wrapper.vm.settings.viewMode).toBe('scale');
});
it('should carry view only over from the previous console, which saved it on only when the user turned it on', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': {
viewMode: 'none', zoomPercent: 150, viewOnly: true, qualityLevel: 9, compressionLevel: 0
}
}
});
expect(wrapper.vm.settings).toMatchObject({
viewOnly: true, viewMode: 'scale', zoomPercent: 100
});
});
it('should take view only from its own settings once it has saved them', () => {
const wrapper = mountWrapper({
storage: {
'harvester-vnc-console-settings': { viewOnly: true },
'harvester-vnc-console-view': { viewOnly: false },
}
});
expect(wrapper.vm.settings.viewOnly).toBe(false);
});
it('should save the settings only once the user changes one, and load them next time', async() => {
const wrapper = mountWrapper();
await wrapper.vm.$nextTick();
expect(window.localStorage).toHaveLength(0);
wrapper.vm.updateSettings({
...wrapper.vm.settings, viewMode: 'none', zoomPercent: 150
});
const reopened = mountWrapper({ storage: { 'harvester-vnc-console-view': JSON.parse(window.localStorage.getItem('harvester-vnc-console-view')) } });
expect(reopened.vm.settings).toMatchObject({ viewMode: 'none', zoomPercent: 150 });
});
it('should keep view only on when the View panel resets its settings', () => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
wrapper.vm.updateSettings({ ...wrapper.vm.settings, zoomPercent: 150 });
wrapper.vm.resetSettings();
expect(wrapper.vm.settings).toMatchObject({ viewOnly: true, zoomPercent: 100 });
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
});
});
describe('in full screen', () => {
it('should fill the window whatever the saved view mode, and go back to it afterwards', () => {
const wrapper = mountWrapper();
wrapper.vm.updateSettings({ ...wrapper.vm.settings, viewMode: 'none' });
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
wrapper.vm.isFullscreen = true;
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: true, edgeToEdge: true });
wrapper.vm.isFullscreen = false;
expect(wrapper.vm.rfbSettings).toMatchObject({ scaleViewport: false, edgeToEdge: false });
});
it('should leave the view only checkbox out of the bar, and keep view only as it was', async() => {
const wrapper = mountWrapper();
wrapper.vm.setViewOnly(true);
wrapper.vm.isFullscreen = true;
await wrapper.vm.$nextTick();
expect(wrapper.findComponent(CHECKBOX).exists()).toBe(false);
expect(wrapper.vm.rfbSettings.viewOnly).toBe(true);
expect(wrapper.vm.shortcutMenuProps.disabled).toBe(true);
wrapper.vm.isFullscreen = false;
await wrapper.vm.$nextTick();
expect(wrapper.findComponent(CHECKBOX).props('value')).toBe(true);
});
it('should leave Ctrl+Alt+Del out of the bar', async() => {
const wrapper = mountWrapper();
wrapper.vm.isFullscreen = true;
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="vnc-fullscreen-bar"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="vnc-ctrl-alt-del"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="vnc-fullscreen-ctrl-alt-del"]').exists()).toBe(false);
});
it('should put the whole page in full screen, so that dialogs rendered outside the console show', async() => {
const wrapper = mountWrapper();
const requestFullscreen = jest.fn().mockResolvedValue();
document.documentElement.requestFullscreen = requestFullscreen;
await wrapper.vm.toggleFullscreen();
expect(requestFullscreen).toHaveBeenCalledTimes(1);
delete document.documentElement.requestFullscreen;
});
});
}); });
@@ -1,91 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import NovncKeyRecorder from '../NovncKeyRecorder.vue';
const key = (k, code, extra = {}) => ({
key: k, code, keyCode: 0, location: 0, charCode: 0, repeat: false, preventDefault: jest.fn(), stopPropagation: jest.fn(), ...extra
});
describe('component: NovncKeyRecorder', () => {
it('should hold modifiers until another key ends the combination', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
wrapper.vm.onKeydown(key('Control', 'ControlLeft', { repeat: true }));
wrapper.vm.onKeydown(key('Escape', 'Escape'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft', 'Escape']);
expect(wrapper.vm.recording).toBe(false);
});
it('should keep the browser from acting on keys while recording', () => {
const wrapper = shallowMount(NovncKeyRecorder);
const event = key('w', 'KeyW');
wrapper.vm.start();
wrapper.vm.onKeydown(event);
expect(event.preventDefault).toHaveBeenCalledWith();
});
it('should record a modifier pressed and released on its own, such as the Windows key', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Meta', 'MetaLeft'));
wrapper.vm.onKeyup(key('Meta', 'MetaLeft'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['MetaLeft']);
expect(wrapper.vm.recording).toBe(false);
});
it('should wait for the last modifier to be released before recording them', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Control', 'ControlLeft'));
wrapper.vm.onKeydown(key('Shift', 'ShiftLeft'));
wrapper.vm.onKeyup(key('Shift', 'ShiftLeft', { ctrlKey: true }));
expect(wrapper.emitted('update:value')).toBeUndefined();
wrapper.vm.onKeyup(key('Control', 'ControlLeft'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.code)).toStrictEqual(['ControlLeft', 'ShiftLeft']);
});
it('should drop a combination of modifiers only when it loses focus', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
wrapper.vm.stop();
expect(wrapper.emitted('update:value')).toBeUndefined();
expect(wrapper.vm.state).toBe('empty');
});
it('should stop recording on Esc or Tab alone, without recording them', () => {
const wrapper = shallowMount(NovncKeyRecorder);
const tab = key('Tab', 'Tab');
wrapper.vm.start();
wrapper.vm.onKeydown(key('Escape', 'Escape'));
expect(wrapper.vm.recording).toBe(false);
wrapper.vm.start();
wrapper.vm.onKeydown(tab);
expect(wrapper.vm.recording).toBe(false);
expect(tab.preventDefault).not.toHaveBeenCalled();
expect(wrapper.emitted('update:value')).toBeUndefined();
});
it('should record a letter by its key, not the symbol a layout made of it', () => {
const wrapper = shallowMount(NovncKeyRecorder);
wrapper.vm.start();
wrapper.vm.onKeydown(key('Alt', 'AltLeft'));
wrapper.vm.onKeydown(key('©', 'KeyG'));
expect(wrapper.emitted('update:value')[0][0].map((K) => K.key)).toStrictEqual(['Alt', 'g']);
});
});
@@ -1,158 +0,0 @@
import { ref } from 'vue';
import { mount, shallowMount } from '@vue/test-utils';
import NovncShortcutKeysMenu, { ShortcutMenuBody } from '../NovncShortcutKeysMenu.vue';
import {
keyLabel, normalizeShortcut, readShortcuts, shortcutLabels, writeShortcuts, SHORTCUTS_PREFERENCE, SHORTCUT_NAMES_PREFERENCE
} from '../shortcuts';
const mountMenu = (props = {}) => shallowMount(NovncShortcutKeysMenu, { props });
describe('component: NovncShortcutKeysMenu', () => {
it('should send a key on its own when no modifier is held', () => {
const wrapper = mountMenu();
wrapper.vm.sendKey('F5');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['F5']]]);
});
it('should send held modifiers with the next key and then release them', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('AltLeft', true);
wrapper.vm.toggleModifier('ControlLeft', true);
expect(wrapper.vm.heldCombo).toBe('Ctrl+Alt');
wrapper.vm.sendKey('F2');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'AltLeft', 'F2']]]);
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should offer the keys that go with what is held, like the old menu', async() => {
const wrapper = mountMenu();
const keys = () => wrapper.vm.keyOptions.map((K) => K.key);
expect(keys()).toStrictEqual(['PrintScreen']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
wrapper.vm.toggleModifier('ControlLeft', true);
expect(keys()).toStrictEqual(['KeyN', 'KeyT', 'KeyW', 'KeyY']);
expect(wrapper.vm.showFunctionKeys).toBe(false);
wrapper.vm.toggleModifier('AltLeft', true);
expect(keys()).toStrictEqual(['Delete']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
wrapper.vm.toggleModifier('ControlLeft', false);
expect(keys()).toStrictEqual(['PrintScreen']);
expect(wrapper.vm.showFunctionKeys).toBe(true);
});
it('should send Ctrl+W from the menu', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.sendKey('KeyW');
expect(wrapper.emitted('send-keys')).toStrictEqual([[['ControlLeft', 'KeyW']]]);
});
it('should hand Ctrl+Alt+Del to the confirmation instead of sending it', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.toggleModifier('AltLeft', true);
wrapper.vm.sendKey('Delete');
expect(wrapper.emitted('ctrl-alt-del')).toHaveLength(1);
expect(wrapper.emitted('send-keys')).toBeUndefined();
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should let held modifiers go when the menu closes without a key', () => {
const wrapper = mountMenu();
wrapper.vm.toggleModifier('ControlLeft', true);
wrapper.vm.onOpen(false);
expect(wrapper.vm.held).toStrictEqual([]);
});
it('should name saved shortcuts by their keys when they have no name', () => {
const wrapper = mountMenu({
shortcuts: [
{ name: 'Open terminal', keys: [{ key: 'Control' }, { key: 'Alt' }, { key: 't' }] },
{ name: '', keys: [{ key: 'Escape' }] },
]
});
expect(wrapper.vm.items.map(({ name, label }) => [name, label])).toStrictEqual([
['Open terminal', 'Ctrl+Alt+T'],
['Esc', 'Esc'],
]);
});
it('should give the arrow keys the items shown after a modifier swapped them', async() => {
const dropdownItems = ref([]);
const keys = ref(['PrintScreen']);
const wrapper = mount({
components: { ShortcutMenuBody },
setup: () => ({ keys }),
template: '<div dropdown-menu-collection><shortcut-menu-body><div v-for="key in keys" :key="key" dropdown-menu-item>{{ key }}</div></shortcut-menu-body></div>',
}, { global: { provide: { dropdownContext: { dropdownItems } } } });
keys.value = ['KeyN', 'KeyT'];
await wrapper.vm.$nextTick();
await wrapper.find('[dropdown-menu-item]').trigger('keydown', { key: 'ArrowDown' });
expect(dropdownItems.value.map((item) => item.textContent)).toStrictEqual(['KeyN', 'KeyT']);
});
});
describe('shortcuts', () => {
it('should read both the old list format and the named format', () => {
const keys = [{ key: 'Control', code: 'ControlLeft' }];
expect(normalizeShortcut(keys)).toStrictEqual({ name: '', keys });
expect(normalizeShortcut({ name: 'Task manager', keys })).toStrictEqual({ name: 'Task manager', keys });
expect(normalizeShortcut({ name: 'Broken' })).toStrictEqual({ name: 'Broken', keys: [] });
});
it('should label keys the way the console menus show them', () => {
expect(keyLabel('Control')).toBe('Ctrl');
expect(keyLabel('a')).toBe('A');
expect(keyLabel('F2')).toBe('F2');
expect(shortcutLabels({ keys: [{ key: 'Shift' }, { key: ' ' }] })).toStrictEqual(['Shift', 'Space']);
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: '©', code: 'KeyG' }] })).toStrictEqual(['Alt', 'G']);
// Real keys of other layouts stay as typed: AZERTY comma on KeyM, Windows AltGr (Ctrl+Alt) letters.
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: ',', code: 'KeyM' }] })).toStrictEqual(['Ctrl', ',']);
expect(shortcutLabels({ keys: [{ key: 'Control', code: 'ControlLeft' }, { key: 'Alt', code: 'AltRight' }, { key: 'ą', code: 'KeyA' }] })).toStrictEqual(['Ctrl', 'Alt', 'Ą']);
expect(shortcutLabels({ keys: [{ key: 'Alt', code: 'AltLeft' }, { key: 'Dead', code: 'KeyE' }] })).toStrictEqual(['Alt', 'E']);
});
it('should keep the key list in the format older versions read and store names apart', async() => {
const keys = [{ key: 'Control', code: 'ControlLeft' }, { key: 't', code: 'KeyT' }];
const preference = { data: {}, save: jest.fn().mockResolvedValue() };
await writeShortcuts(preference, [{ name: 'Open terminal', keys }, { name: '', keys: [{ key: 'F2', code: 'F2' }] }]);
expect(JSON.parse(preference.data[SHORTCUTS_PREFERENCE])).toStrictEqual([keys, [{ key: 'F2', code: 'F2' }]]);
expect(JSON.parse(preference.data[SHORTCUT_NAMES_PREFERENCE])).toStrictEqual({ 'ControlLeft+KeyT': 'Open terminal' });
expect(readShortcuts(preference).map((shortcut) => shortcut.name)).toStrictEqual(['Open terminal', '']);
});
it('should put the preference back when the save fails', async() => {
const saved = JSON.stringify([[{ key: 'F2', code: 'F2' }]]);
const preference = { data: { [SHORTCUTS_PREFERENCE]: saved }, save: jest.fn().mockRejectedValue(new Error('403')) };
await expect(writeShortcuts(preference, [])).rejects.toThrow('403');
expect(preference.data).toStrictEqual({ [SHORTCUTS_PREFERENCE]: saved });
});
it('should read nothing from a preference it cannot parse', () => {
expect(readShortcuts({ data: { [SHORTCUTS_PREFERENCE]: '{not json' } })).toStrictEqual([]);
expect(readShortcuts(undefined)).toStrictEqual([]);
});
});
@@ -1,36 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import NovncViewOptions, { VIEW_MODE } from '../NovncViewOptions.vue';
jest.mock('../ZoomableRFB', () => ({
MINIMUM_ZOOM: 50, MAXIMUM_ZOOM: 200, ZOOM_STEP: 10
}));
const settings = {
viewMode: VIEW_MODE.NONE, zoomPercent: 100, qualityLevel: 6, compressionLevel: 2
};
const mountOptions = (overrides = {}) => shallowMount(NovncViewOptions, { props: { settings: { ...settings, ...overrides } } });
describe('component: NovncViewOptions', () => {
it('should emit the whole settings object with the changed value', () => {
const wrapper = mountOptions();
wrapper.vm.update('qualityLevel', 9);
expect(wrapper.emitted('update')).toStrictEqual([[{ ...settings, qualityLevel: 9 }]]);
});
it('should step the zoom and stop at its limits', () => {
const wrapper = mountOptions({ zoomPercent: 200 });
wrapper.vm.stepZoom(1);
wrapper.vm.stepZoom(-1);
expect(wrapper.emitted('update').map(([value]) => value.zoomPercent)).toStrictEqual([200, 190]);
});
it('should only treat the manual mode as manual', () => {
expect(mountOptions().vm.isManual).toBe(true);
expect(mountOptions({ viewMode: VIEW_MODE.SCALE }).vm.isManual).toBe(false);
});
});
@@ -1,109 +0,0 @@
import ZoomableRFB from '../ZoomableRFB';
const GUEST_POINTER = 'url(guest-pointer) 0 0, default';
jest.mock('@novnc/novnc/core/rfb', () => ({
__esModule: true,
default: class {
constructor() {
this.scaleViewport = true;
this._canvas = { style: {} };
this._cursorImage = { rgbaPixels: new Uint8Array() };
this._display = { autoscale: jest.fn() };
}
_screenSize() {
return { w: 1000, h: 500 };
}
_fixScrollbars() {}
_handleMouse(ev) {
ev.stopPropagation();
}
// As noVNC does: nothing visible hides the mouse, an image is shown as the pointer.
_refreshCursor() {
this._canvas.style.cursor = this._cursorImage.rgbaPixels.length ? 'url(guest-pointer) 0 0, default' : 'none';
}
},
}), { virtual: true });
describe('zoomableRFB', () => {
describe('the pointer over the screen', () => {
it('should be the system one while the guest sends no pointer image', () => {
const rfb = new ZoomableRFB();
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
it('should be the system one when the image the guest sends is fully transparent', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([255, 255, 255, 0, 0, 0, 0, 0]) };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
it('should be the one the guest sends when it has visible pixels', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 255]) };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe(GUEST_POINTER);
});
it('should go back to the system one when the guest stops sending an image', () => {
const rfb = new ZoomableRFB();
rfb._cursorImage = { rgbaPixels: new Uint8Array([0, 0, 0, 255]) };
rfb._refreshCursor();
rfb._cursorImage = { rgbaPixels: [] };
rfb._refreshCursor();
expect(rfb._canvas.style.cursor).toBe('default');
});
});
describe('mouse events on the screen', () => {
it('should let a click through, so an open menu sees it as a click outside', () => {
const rfb = new ZoomableRFB();
const stopPropagation = jest.fn();
rfb._handleMouse({ type: 'click', stopPropagation });
expect(stopPropagation).not.toHaveBeenCalled();
});
it('should leave the others to noVNC', () => {
const rfb = new ZoomableRFB();
const stopPropagation = jest.fn();
rfb._handleMouse({ type: 'mousedown', stopPropagation });
expect(stopPropagation).toHaveBeenCalledTimes(1);
});
});
describe('the fitted screen', () => {
it('should keep room for the focus ring', () => {
const rfb = new ZoomableRFB();
rfb._updateScale();
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(992, 492);
});
it('should take all the room when it is edge to edge', () => {
const rfb = new ZoomableRFB();
rfb.edgeToEdge = true;
expect(rfb._display.autoscale).toHaveBeenLastCalledWith(1000, 500);
});
});
});
-118
View File
@@ -1,118 +0,0 @@
// Saved custom shortcuts live in the Rancher user preference, which every Harvester UI the user opens
// shares. The keys stay a list of recorded keydown events per shortcut, the format older versions read;
// names go in a separate preference so those versions keep working.
export const SHORTCUTS_PREFERENCE = 'prefered-shortcut-keys';
export const SHORTCUT_NAMES_PREFERENCE = 'vnc-shortcut-names';
const KEY_LABELS = {
Control: 'Ctrl',
Escape: 'Esc',
Delete: 'Del',
' ': 'Space',
};
export const MODIFIER_KEYS = ['Control', 'Shift', 'Alt', 'Meta'];
export function keyLabel(key = '') {
if (KEY_LABELS[key]) {
return KEY_LABELS[key];
}
return key.length === 1 ? key.toUpperCase() : key;
}
// macOS Option turns a letter into a symbol (Option+G gives ©, Option+E a dead key). The key that was
// pressed is still in `code`, so in that case the letter is named after it. Only with Alt and no Ctrl:
// AZERTY's comma on KeyM, Dvorak's punctuation or Cyrillic letters are real keys, and Windows AltGr
// reports Ctrl+Alt with a real character.
export function baseKey(K, combination = []) {
const letter = /^Key([A-Z])$/.exec(K?.code || '');
if (!letter || /^[a-z]$/i.test(K.key || '')) {
return K;
}
const held = combination.map((M) => M.key);
const isOptionSymbol = held.includes('Alt') && !held.includes('Control');
return K.key === 'Dead' || isOptionSymbol ? { ...K, key: letter[1].toLowerCase() } : K;
}
export function normalizeShortcut(item) {
if (Array.isArray(item)) {
return { name: '', keys: item };
}
return { name: item?.name || '', keys: Array.isArray(item?.keys) ? item.keys : [] };
}
export function shortcutLabels(shortcut) {
const keys = shortcut?.keys || [];
return keys.map((K) => keyLabel(baseKey(K, keys).key));
}
// Two shortcuts are the same when they press the same keys, whatever they are called.
export function shortcutId(shortcut) {
return (shortcut?.keys || []).map((K) => K.code || K.key).join('+');
}
// Only what sending a shortcut needs, so a recorded KeyboardEvent can be stored.
export function recordKey(event, combination = []) {
const {
key, keyCode, code, location, charCode
} = event;
return baseKey({
key, keyCode, code, location, charCode
}, combination);
}
function parse(value, fallback) {
try {
return value ? JSON.parse(value) : fallback;
} catch (err) {
return fallback;
}
}
export function readShortcuts(preference) {
const list = parse(preference?.data?.[SHORTCUTS_PREFERENCE], []);
const names = parse(preference?.data?.[SHORTCUT_NAMES_PREFERENCE], {});
return (Array.isArray(list) ? list : [])
.map(normalizeShortcut)
.filter((shortcut) => shortcut.keys.length)
.map((shortcut) => ({ ...shortcut, name: shortcut.name || names?.[shortcutId(shortcut)] || '' }));
}
export function writeShortcuts(preference, shortcuts) {
const names = {};
shortcuts.forEach((shortcut) => {
if (shortcut.name) {
names[shortcutId(shortcut)] = shortcut.name;
}
});
const previous = {
[SHORTCUTS_PREFERENCE]: preference.data[SHORTCUTS_PREFERENCE],
[SHORTCUT_NAMES_PREFERENCE]: preference.data[SHORTCUT_NAMES_PREFERENCE],
};
preference.data[SHORTCUTS_PREFERENCE] = JSON.stringify(shortcuts.map((shortcut) => shortcut.keys));
preference.data[SHORTCUT_NAMES_PREFERENCE] = JSON.stringify(names);
// The lists read straight from the preference, so a failed save must not leave the change showing.
return preference.save().catch((err) => {
Object.entries(previous).forEach(([key, value]) => {
if (value === undefined) {
delete preference.data[key];
} else {
preference.data[key] = value;
}
});
throw err;
});
}
@@ -1,102 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import BackupTarget from '../backup-target.vue';
function mountTarget(target) {
const setting = { value: JSON.stringify(target) };
return {
setting,
wrapper: shallowMount(BackupTarget, {
props: { value: setting, mode: 'edit' },
global: {
mocks: {
t: (key) => key,
$store: { getters: { 'harvester-common/getFeatureEnabled': () => true } },
},
},
}),
};
}
describe('component: backup-target', () => {
it('should keep virtualHostedStyle, which is part of the Restic and Kopia repository identity', () => {
const { setting } = mountTarget({ type: 's3', virtualHostedStyle: true });
expect(JSON.parse(setting.value).virtualHostedStyle).toBe(true);
});
it('should default virtualHostedStyle to false', () => {
const { setting } = mountTarget({ type: 's3' });
expect(JSON.parse(setting.value).virtualHostedStyle).toBe(false);
});
it.each([
['kopiaGCEnabled', { kopiaGCEnabled: true, thirdPartyBackupEnabled: true }],
['thirdPartyBackupEnabled', { thirdPartyBackupEnabled: true }],
])('should keep %s on S3 and drop it on NFS, where only S3 uses it', (field, fields) => {
const { wrapper, setting } = mountTarget({ type: 's3', ...fields });
expect(JSON.parse(setting.value)[field]).toBe(true);
wrapper.vm.parseDefaultValue.type = 'nfs';
wrapper.vm.update();
expect(JSON.parse(setting.value)[field]).toBeUndefined();
});
it('should offer the Restic and Kopia switch on S3', () => {
const { wrapper } = mountTarget({ type: 's3' });
expect(wrapper.find('[data-testid="backup-target-third-party-backup"]').exists()).toBe(true);
});
it('should ask for the repository password only while Restic and Kopia are on', () => {
const off = mountTarget({ type: 's3' }).wrapper;
const on = mountTarget({ type: 's3', thirdPartyBackupEnabled: true }).wrapper;
expect(off.find('[data-testid="backup-target-repository-password"]').exists()).toBe(false);
expect(on.find('[data-testid="backup-target-repository-password"]').exists()).toBe(true);
});
it('should offer Kopia garbage collection only while Restic and Kopia are on, the only time the backend runs it', () => {
const off = mountTarget({ type: 's3' }).wrapper;
const on = mountTarget({ type: 's3', thirdPartyBackupEnabled: true }).wrapper;
expect(off.find('[data-testid="backup-target-kopia-gc"]').exists()).toBe(false);
expect(on.find('[data-testid="backup-target-kopia-gc"]').exists()).toBe(true);
});
it('should drop Kopia garbage collection when Restic and Kopia are turned off, so the setting matches what runs', () => {
const { wrapper, setting } = mountTarget({
type: 's3', thirdPartyBackupEnabled: true, kopiaGCEnabled: true
});
expect(JSON.parse(setting.value).kopiaGCEnabled).toBe(true);
wrapper.vm.parseDefaultValue.thirdPartyBackupEnabled = false;
wrapper.vm.update();
expect(JSON.parse(setting.value).kopiaGCEnabled).toBeUndefined();
});
it.each([
['Restic and Kopia are turned off', (vm) => {
vm.parseDefaultValue.thirdPartyBackupEnabled = false;
}],
['the target changes to NFS', (vm) => {
vm.parseDefaultValue.type = 'nfs';
}],
])('should drop the repository password when %s, which the backend rejects', (_, change) => {
const { wrapper, setting } = mountTarget({
type: 's3', thirdPartyBackupEnabled: true, thirdPartyRepositoryPassword: 'secret'
});
expect(JSON.parse(setting.value).thirdPartyRepositoryPassword).toBe('secret');
change(wrapper.vm);
wrapper.vm.update();
expect(JSON.parse(setting.value).thirdPartyRepositoryPassword).toBeUndefined();
});
});
@@ -1,74 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import UnitInput from '@shell/components/form/UnitInput';
import ThirdPartyBackupConfig from '../third-party-backup-config.vue';
const JOB = {
memoryRequest: '1Gi', memoryLimit: '4Gi', cacheSize: '2Gi', maxConcurrentJobs: 5, ephemeralRequest: '512Mi', ephemeralLimit: '3Gi'
};
const DEFAULT = JSON.stringify({ restic: { ...JOB, noCache: false }, kopia: JOB });
function mountConfig(value) {
const setting = { value, default: DEFAULT };
return {
setting,
wrapper: shallowMount(ThirdPartyBackupConfig, {
props: { value: setting, registerBeforeHook: jest.fn() },
global: {
mocks: { t: (key) => key },
stubs: { RcSection: { template: '<section><slot /></section>' } },
},
}),
};
}
describe('component: third-party-backup-config', () => {
it('should fill omitted fields from the default', () => {
const { wrapper } = mountConfig(JSON.stringify({ kopia: { memoryLimit: '8Gi' } }));
expect(wrapper.vm.config.kopia).toStrictEqual({ ...JOB, memoryLimit: '8Gi' });
expect(wrapper.vm.config.restic.noCache).toBe(false);
});
it('should show the default values when the setting is empty', () => {
const { wrapper } = mountConfig('');
expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
});
it('should write the form to the setting before saving', async() => {
const { wrapper, setting } = mountConfig('');
wrapper.vm.config.kopia.maxConcurrentJobs = 0;
await wrapper.vm.willSave();
expect(JSON.parse(setting.value).kopia.maxConcurrentJobs).toBe(0);
});
it('should go back to the default', () => {
const { wrapper, setting } = mountConfig(JSON.stringify({ kopia: { memoryLimit: '8Gi' } }));
wrapper.vm.useDefault();
expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
expect(JSON.parse(setting.value)).toStrictEqual(JSON.parse(DEFAULT));
});
it('should take every size in MiB so a bare number is not saved as bytes', () => {
const { wrapper } = mountConfig('');
const inputs = wrapper.findAllComponents(UnitInput);
expect(inputs).toHaveLength(10);
inputs.forEach((input) => {
expect(input.props()).toMatchObject({
increment: 1024, inputExponent: 2, outputModifier: true
});
});
});
it('should show the default values when the setting is not JSON', () => {
const { wrapper } = mountConfig('{not json');
expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
});
});
@@ -1,79 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import UpgradeConfig from '@pkg/harvester/components/settings/upgrade-config.vue';
const DEFAULT = JSON.stringify({
imagePreloadOption: { strategy: { type: 'sequential' } },
nodeUpgradeOption: { strategy: { mode: 'auto' } },
restoreVM: false,
});
const mountConfig = (config, featureEnabled) => shallowMount(UpgradeConfig, {
props: {
mode: 'edit',
value: { default: DEFAULT, value: config ? JSON.stringify(config) : '' },
},
global: {
mocks: {
$store: {
dispatch: jest.fn(),
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/all': () => [],
'i18n/t': (key) => key,
'harvester-common/getFeatureEnabled': (name) => name === 'shutdownVMOnMigrationFailure' && featureEnabled,
},
},
},
},
});
const savedValue = (wrapper) => JSON.parse(wrapper.props('value').value);
describe('component: upgrade-config', () => {
it('should default shutdownVMOnMigrationFailure to false when the field is missing', () => {
const wrapper = mountConfig(undefined, true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(false);
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').exists()).toBe(true);
});
it('should keep an enabled shutdownVMOnMigrationFailure', () => {
const wrapper = mountConfig({ shutdownVMOnMigrationFailure: true }, true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
});
it('should save the value selected in its radio group', async() => {
const wrapper = mountConfig(undefined, true);
await wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').vm.$emit('update:value', true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
expect(savedValue(wrapper).restoreVM).toBe(false);
await wrapper.findComponent('[name="restoreVM"]').vm.$emit('update:value', true);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
expect(savedValue(wrapper).restoreVM).toBe(true);
});
it('should name the radio groups for screen readers', () => {
const wrapper = mountConfig(undefined, true);
expect(wrapper.findComponent('[name="restoreVM"]').attributes('aria-label')).toBe('harvester.setting.upgrade.restoreVM');
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').attributes('aria-label')).toBe('harvester.setting.upgrade.shutdownVMOnMigrationFailure');
});
it('should hide the control and not add the field on clusters without the feature', () => {
const wrapper = mountConfig(undefined, false);
expect(savedValue(wrapper)).not.toHaveProperty('shutdownVMOnMigrationFailure');
expect(wrapper.findComponent('[name="shutdownVMOnMigrationFailure"]').exists()).toBe(false);
});
it('should keep a field set outside the UI on clusters without the feature', () => {
const wrapper = mountConfig({ shutdownVMOnMigrationFailure: true }, false);
expect(savedValue(wrapper).shutdownVMOnMigrationFailure).toBe(true);
});
});
@@ -3,7 +3,6 @@ import Tip from '@shell/components/Tip';
import Password from '@shell/components/form/Password'; import Password from '@shell/components/form/Password';
import MessageLink from '@shell/components/MessageLink'; import MessageLink from '@shell/components/MessageLink';
import CreateEditView from '@shell/mixins/create-edit-view'; import CreateEditView from '@shell/mixins/create-edit-view';
import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { HCI_SETTING } from '../../config/settings'; import { HCI_SETTING } from '../../config/settings';
@@ -15,7 +14,7 @@ export default {
name: 'HarvesterEditBackupTarget', name: 'HarvesterEditBackupTarget',
components: { components: {
Checkbox, LabeledInput, LabeledSelect, Tip, Password, MessageLink, UnitInput LabeledInput, LabeledSelect, Tip, Password, MessageLink, UnitInput
}, },
mixins: [CreateEditView], mixins: [CreateEditView],
@@ -37,7 +36,7 @@ export default {
} }
// set default virtualHostedStyle to false // set default virtualHostedStyle to false
parseDefaultValue.virtualHostedStyle = !!parseDefaultValue.virtualHostedStyle; parseDefaultValue.virtualHostedStyle = false;
return { return {
parseDefaultValue, parseDefaultValue,
@@ -70,10 +69,6 @@ export default {
return this.$store.getters['harvester-common/getFeatureEnabled']('refreshIntervalInSecond'); return this.$store.getters['harvester-common/getFeatureEnabled']('refreshIntervalInSecond');
}, },
thirdPartyBackupFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
},
isS3() { isS3() {
return this.parseDefaultValue.type === DEFAULT_TYPE; return this.parseDefaultValue.type === DEFAULT_TYPE;
}, },
@@ -119,17 +114,9 @@ export default {
delete this.parseDefaultValue.bucketName; delete this.parseDefaultValue.bucketName;
delete this.parseDefaultValue.bucketRegion; delete this.parseDefaultValue.bucketRegion;
delete this.parseDefaultValue.virtualHostedStyle; delete this.parseDefaultValue.virtualHostedStyle;
delete this.parseDefaultValue.kopiaGCEnabled;
delete this.parseDefaultValue.thirdPartyBackupEnabled;
delete this.parseDefaultValue.cert; delete this.parseDefaultValue.cert;
} }
// While Restic and Kopia are off, the backend rejects a repository password and runs no Kopia garbage collection
if (!this.parseDefaultValue.thirdPartyBackupEnabled) {
delete this.parseDefaultValue.thirdPartyRepositoryPassword;
delete this.parseDefaultValue.kopiaGCEnabled;
}
if (this.isS3 && !this.parseDefaultValue.virtualHostedStyle) { if (this.isS3 && !this.parseDefaultValue.virtualHostedStyle) {
this.parseDefaultValue.virtualHostedStyle = false; this.parseDefaultValue.virtualHostedStyle = false;
} }
@@ -235,45 +222,6 @@ export default {
@update:value="update" @update:value="update"
/> />
<!-- Checkbox is inline, so each gets its own line -->
<template v-if="thirdPartyBackupFeatureEnabled">
<div class="mb-20">
<Checkbox
v-model:value="parseDefaultValue.thirdPartyBackupEnabled"
data-testid="backup-target-third-party-backup"
:label="t('harvester.backup.thirdPartyBackup.label')"
:mode="mode"
:tooltip="t('harvester.backup.thirdPartyBackup.tooltip', {}, true)"
@update:value="update"
/>
</div>
<template v-if="parseDefaultValue.thirdPartyBackupEnabled">
<Password
v-model:value="parseDefaultValue.thirdPartyRepositoryPassword"
data-testid="backup-target-repository-password"
class="mb-5"
:mode="mode"
:label="t('harvester.backup.thirdPartyBackup.password.label')"
required
/>
<Tip
class="mb-20"
icon="icon icon-info"
:text="t('harvester.backup.thirdPartyBackup.password.tip', {}, true)"
/>
<div class="mb-20">
<Checkbox
v-model:value="parseDefaultValue.kopiaGCEnabled"
data-testid="backup-target-kopia-gc"
:label="t('harvester.backup.kopiaGC.label')"
:mode="mode"
:tooltip="t('harvester.backup.kopiaGC.tooltip', {}, true)"
@update:value="update"
/>
</div>
</template>
</template>
<div class="mb-20"> <div class="mb-20">
<Tip icon="icon icon-info"> <Tip icon="icon icon-info">
<MessageLink <MessageLink
@@ -1,149 +0,0 @@
<script>
import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RcSection } from '@components/RcSection';
import UnitInput from '@shell/components/form/UnitInput';
import { BACKUP_TYPE } from '../../config/types';
const ENGINES = [BACKUP_TYPE.RESTIC, BACKUP_TYPE.KOPIA];
const QUANTITY_FIELDS = ['memoryRequest', 'memoryLimit', 'ephemeralRequest', 'ephemeralLimit', 'cacheSize'];
// The webhook only stores JSON objects, so a value that doesn't parse falls back to the default like the other settings forms
function parseJSON(string) {
try {
return JSON.parse(string || '{}');
} catch (e) {
return {};
}
}
// The backend fills omitted fields from the default, so show those values instead of empty inputs
function parseConfig(value, defaultValue) {
const defaults = parseJSON(defaultValue);
const current = parseJSON(value);
return Object.fromEntries(ENGINES.map((engine) => [engine, { ...defaults[engine], ...current[engine] }]));
}
export default {
name: 'ThirdPartyBackupConfig',
components: {
Checkbox,
LabeledInput,
RcSection,
UnitInput,
},
props: {
registerBeforeHook: {
type: Function,
required: true
},
mode: {
type: String,
default: 'edit'
},
value: {
type: Object,
default: () => ({
value: '',
default: '{}'
})
},
},
data() {
return {
ENGINES,
QUANTITY_FIELDS,
RESTIC: BACKUP_TYPE.RESTIC,
config: parseConfig(this.value?.value, this.value?.default),
};
},
created() {
this.registerBeforeHook?.(this.willSave, 'willSave');
},
methods: {
updateValue() {
if (this.value) {
this.value.value = JSON.stringify(this.config);
}
},
useDefault() {
this.config = parseConfig('', this.value?.default);
this.updateValue();
},
willSave() {
this.updateValue();
return Promise.resolve();
},
},
};
</script>
<template>
<div data-testid="third-party-backup-config">
<RcSection
v-for="engine in ENGINES"
:key="engine"
background="secondary"
class="mb-20"
:data-testid="`${ engine }-section`"
:expandable="false"
mode="with-header"
:title="t(`harvester.backup.type.${ engine }`)"
type="secondary"
>
<div class="engine-fields">
<UnitInput
v-for="field in QUANTITY_FIELDS"
:key="field"
v-model:value="config[engine][field]"
:data-testid="`${ engine }-${ field }`"
:disabled="field === 'cacheSize' && !!config[engine].noCache"
:increment="1024"
:input-exponent="2"
:label="t(`harvester.setting.thirdPartyBackupConfig.${ field }`)"
min="1"
:mode="mode"
:output-modifier="true"
:positive="true"
:sub-label="field === 'cacheSize' ? t('harvester.setting.thirdPartyBackupConfig.cacheSizeHint') : ''"
/>
<LabeledInput
v-model:value.number="config[engine].maxConcurrentJobs"
:data-testid="`${ engine }-maxConcurrentJobs`"
:label="t('harvester.setting.thirdPartyBackupConfig.maxConcurrentJobs')"
min="0"
:mode="mode"
:sub-label="t('harvester.setting.thirdPartyBackupConfig.maxConcurrentJobsHint')"
type="number"
/>
</div>
<Checkbox
v-if="engine === RESTIC"
v-model:value="config[engine].noCache"
:data-testid="`${ engine }-noCache`"
:label="t('harvester.setting.thirdPartyBackupConfig.noCache')"
:mode="mode"
/>
</RcSection>
</div>
</template>
<style lang="scss" scoped>
.engine-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
// The hints under the last row overflow the height of their inputs
margin-bottom: 20px;
}
</style>
@@ -74,10 +74,6 @@ export default {
}, },
methods: { methods: {
// A method, as normalizeValue also runs in data(), before computed properties are available
shutdownVMOnMigrationFailureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('shutdownVMOnMigrationFailure');
},
normalizeValue(obj) { normalizeValue(obj) {
// handle nodeUpgradeOption.strategy // handle nodeUpgradeOption.strategy
if (obj?.nodeUpgradeOption?.strategy?.mode === 'auto') { if (obj?.nodeUpgradeOption?.strategy?.mode === 'auto') {
@@ -111,9 +107,6 @@ export default {
if (typeof obj.restoreVM !== 'boolean') { if (typeof obj.restoreVM !== 'boolean') {
obj.restoreVM = false; obj.restoreVM = false;
} }
if (this.shutdownVMOnMigrationFailureEnabled() && typeof obj.shutdownVMOnMigrationFailure !== 'boolean') {
obj.shutdownVMOnMigrationFailure = false;
}
return obj; return obj;
}, },
@@ -186,24 +179,10 @@ export default {
v-model:value="parseDefaultValue.restoreVM" v-model:value="parseDefaultValue.restoreVM"
class="mb-20" class="mb-20"
name="restoreVM" name="restoreVM"
:aria-label="t('harvester.setting.upgrade.restoreVM')"
:options="[true, false]" :options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]" :labels="[t('generic.enabled'), t('generic.disabled')]"
@update:value="update" @update:value="update"
/> />
<div v-if="shutdownVMOnMigrationFailureEnabled()">
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.shutdownVMOnMigrationFailure') }}</b></label>
<RadioGroup
v-model:value="parseDefaultValue.shutdownVMOnMigrationFailure"
class="mb-20"
name="shutdownVMOnMigrationFailure"
:aria-label="t('harvester.setting.upgrade.shutdownVMOnMigrationFailure')"
:mode="mode"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
@update:value="update"
/>
</div>
<div v-if="resumeUpgradePausedNodeEnabled"> <div v-if="resumeUpgradePausedNodeEnabled">
<label class="mb-5"><b>{{ t('harvester.setting.upgrade.nodeUpgradeOption') }}</b></label> <label class="mb-5"><b>{{ t('harvester.setting.upgrade.nodeUpgradeOption') }}</b></label>
<LabeledSelect <LabeledSelect
-6
View File
@@ -85,12 +85,6 @@ const FEATURE_FLAGS = {
'v1.10.0': [ 'v1.10.0': [
'maintenanceModeConditions', 'maintenanceModeConditions',
'maintenanceModeDrainTimeoutSetting', 'maintenanceModeDrainTimeoutSetting',
'componentHealth',
'repositoryStorageClass',
'shutdownVMOnMigrationFailure',
'vmListPagination',
'kubeovnBgp',
'thirdPartyVMBackup',
], ],
}; };
+11 -85
View File
@@ -54,8 +54,6 @@ import {
FORKLIFT_PLAN_TARGET_NS, FORKLIFT_PLAN_TARGET_NS,
FORKLIFT_PLAN_VM_COUNT, FORKLIFT_PLAN_VM_COUNT,
FORKLIFT_MIGRATION_PLAN, FORKLIFT_MIGRATION_PLAN,
VM_HEADERS,
VM_PAGINATION_HEADERS,
} from './table-headers'; } from './table-headers';
import { ADD_ONS } from './harvester-map'; import { ADD_ONS } from './harvester-map';
import { registerAddonSideNav } from '../utils/dynamic-nav'; import { registerAddonSideNav } from '../utils/dynamic-nav';
@@ -77,8 +75,6 @@ const EXTERNAL_IPS_GROUP = `${ NAT_INTERNET_GROUP }::External IPs`;
const RULES_GROUP = `${ NAT_INTERNET_GROUP }::Rules`; const RULES_GROUP = `${ NAT_INTERNET_GROUP }::Rules`;
const SOURCE_RULES_GROUP = `${ RULES_GROUP }::Source Rules`; const SOURCE_RULES_GROUP = `${ RULES_GROUP }::Source Rules`;
const DESTINATION_RULES_GROUP = `${ RULES_GROUP }::Destination 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'; export const PRODUCT_NAME = 'harvester';
@@ -261,7 +257,6 @@ export function init($plugin, store) {
basicType([HCI.VM]); basicType([HCI.VM]);
configureType(HCI.VM, { canYaml: false }); configureType(HCI.VM, { canYaml: false });
headers(HCI.VM, VM_HEADERS, VM_PAGINATION_HEADERS);
virtualType({ virtualType({
labelKey: 'harvester.virtualMachine.label', labelKey: 'harvester.virtualMachine.label',
group: 'root', group: 'root',
@@ -667,12 +662,7 @@ export function init($plugin, store) {
); );
basicType( basicType(
[BGP_SPEAKER], [HCI.VPC_NAT_GATEWAY],
OVERLAY_NETWORKS_GROUP
);
basicType(
[HCI.VPC_NAT_GATEWAY, HCI.VPC_EGRESS_GATEWAY],
GATEWAYS_GROUP GATEWAYS_GROUP
); );
@@ -720,24 +710,16 @@ export function init($plugin, store) {
basicType( basicType(
[ [
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.SR_IOV, HCI.SR_IOV,
HCI.PCI_DEVICE, HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE, HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE, HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION, HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE, HCI.USB_DEVICE,
],
'hardwareDevices'
);
weightGroup('hardwareDevices', 488, true);
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.ADD_ONS, HCI.ADD_ONS,
HCI.SECRET, HCI.SECRET,
HCI.SETTING HCI.SETTING
@@ -863,52 +845,6 @@ export function init($plugin, store) {
ifHaveType: HCI.VPC_NAT_GATEWAY, ifHaveType: HCI.VPC_NAT_GATEWAY,
}); });
configureType(HCI.VPC_EGRESS_GATEWAY, { hiddenNamespaceGroupButton: true, canYaml: false });
headers(HCI.VPC_EGRESS_GATEWAY, [
STATE,
NAME_COL,
NAMESPACE_COL,
{
name: 'vpc',
labelKey: 'harvester.egressGateway.vpc.label',
value: 'spec.vpc',
sort: ['spec.vpc'],
},
{
name: 'replicas',
labelKey: 'harvester.egressGateway.replicas.label',
value: 'spec.replicas',
sort: ['spec.replicas'],
},
{
name: 'externalSubnet',
labelKey: 'harvester.egressGateway.externalSubnet.label',
value: 'spec.externalSubnet',
sort: ['spec.externalSubnet'],
},
{
name: 'externalIPs',
labelKey: 'harvester.egressGateway.ips.external.label',
value: 'status.externalIPs',
formatter: 'List',
},
AGE
]);
virtualType({
labelKey: 'harvester.egressGateway.label',
name: HCI.VPC_EGRESS_GATEWAY,
namespaced: true,
weight: 193,
route: {
name: `${ PRODUCT_NAME }-c-cluster-resource`,
params: { resource: HCI.VPC_EGRESS_GATEWAY }
},
exact: false,
ifHaveType: HCI.VPC_EGRESS_GATEWAY,
});
configureType(HCI.IPTABLES_EIP, { hiddenNamespaceGroupButton: true, canYaml: false }); configureType(HCI.IPTABLES_EIP, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({ virtualType({
@@ -969,16 +905,6 @@ export function init($plugin, store) {
ifHaveType: NETWORK_POLICY, 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 }); configureType(HCI.PROVIDER_NETWORK, { hiddenNamespaceGroupButton: true, canYaml: false });
virtualType({ virtualType({
@@ -1191,7 +1117,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
label: 'PCI Devices', label: 'PCI Devices',
group: 'hardwareDevices', group: 'advanced',
weight: 14, weight: 14,
name: HCI.PCI_DEVICE, name: HCI.PCI_DEVICE,
namespaced: false, namespaced: false,
@@ -1227,7 +1153,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
ifHaveType: HCI.SR_IOV, ifHaveType: HCI.SR_IOV,
labelKey: 'harvester.sriov.label', labelKey: 'harvester.sriov.label',
group: 'hardwareDevices', group: 'advanced',
weight: 15, weight: 15,
name: HCI.SR_IOV, name: HCI.SR_IOV,
namespaced: false, namespaced: false,
@@ -1247,7 +1173,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
ifHaveType: HCI.SR_IOVGPU_DEVICE, ifHaveType: HCI.SR_IOVGPU_DEVICE,
labelKey: 'harvester.sriovgpu.label', labelKey: 'harvester.sriovgpu.label',
group: 'hardwareDevices', group: 'advanced',
weight: 13, weight: 13,
name: HCI.SR_IOVGPU_DEVICE, name: HCI.SR_IOVGPU_DEVICE,
namespaced: false, namespaced: false,
@@ -1266,7 +1192,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.vgpu.label', labelKey: 'harvester.vgpu.label',
group: 'hardwareDevices', group: 'advanced',
weight: 12, weight: 12,
name: HCI.VGPU_DEVICE, name: HCI.VGPU_DEVICE,
namespaced: false, namespaced: false,
@@ -1294,7 +1220,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.migconfiguration.label', labelKey: 'harvester.migconfiguration.label',
group: 'hardwareDevices', group: 'advanced',
weight: 12, weight: 12,
name: HCI.MIG_CONFIGURATION, name: HCI.MIG_CONFIGURATION,
namespaced: false, namespaced: false,
@@ -1314,7 +1240,7 @@ export function init($plugin, store) {
virtualType({ virtualType({
labelKey: 'harvester.usb.label', labelKey: 'harvester.usb.label',
group: 'hardwareDevices', group: 'advanced',
weight: 11, weight: 11,
name: HCI.USB_DEVICE, name: HCI.USB_DEVICE,
namespaced: false, namespaced: false,
@@ -21,7 +21,6 @@ export const HCI = {
VM_NAME: 'harvesterhci.io/vmName', VM_NAME: 'harvesterhci.io/vmName',
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix', VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName', VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
VMI_CREATED_BY: 'kubevirt.io/created-by',
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory', VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0 MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name', HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
@@ -48,7 +47,6 @@ export const HCI = {
OS_UPGRADE_IMAGE: 'harvesterhci.io/os-upgrade-image', OS_UPGRADE_IMAGE: 'harvesterhci.io/os-upgrade-image',
LATEST_UPGRADE: 'harvesterhci.io/latestUpgrade', LATEST_UPGRADE: 'harvesterhci.io/latestUpgrade',
UPGRADE_STATE: 'harvesterhci.io/upgradeState', UPGRADE_STATE: 'harvesterhci.io/upgradeState',
UPGRADE_STORAGE_CLASS: 'harvesterhci.io/upgrade-storage-class',
REAY_MESSAGE: 'harvesterhci.io/read-message', REAY_MESSAGE: 'harvesterhci.io/read-message',
DYNAMIC_SSHKEYS_NAMES: 'harvesterhci.io/dynamic-ssh-key-names', DYNAMIC_SSHKEYS_NAMES: 'harvesterhci.io/dynamic-ssh-key-names',
DYNAMIC_SSHKEYS_USERS: 'harvesterhci.io/dynamic-ssh-key-users', DYNAMIC_SSHKEYS_USERS: 'harvesterhci.io/dynamic-ssh-key-users',
@@ -91,9 +89,7 @@ export const HCI = {
STATIC_IP: 'static-ip.harvesterhci.io', STATIC_IP: 'static-ip.harvesterhci.io',
NODE_UPGRADE_PAUSE_MAP: 'harvesterhci.io/node-upgrade-pause-map', NODE_UPGRADE_PAUSE_MAP: 'harvesterhci.io/node-upgrade-pause-map',
CDI_POPULATOR_KIND: 'cdi.kubevirt.io/storage.populator.kind', CDI_POPULATOR_KIND: 'cdi.kubevirt.io/storage.populator.kind',
CDI_CREATED_FOR_DATA_VOLUME: 'cdi.kubevirt.io/createdForDataVolume',
CNI_NETWORKS: 'k8s.v1.cni.cncf.io/networks', CNI_NETWORKS: 'k8s.v1.cni.cncf.io/networks',
KUBEOVN_BGP: 'ovn.kubernetes.io/bgp',
WINDOWS_SYSPREP: 'harvesterhci.io/windows-sysprep', WINDOWS_SYSPREP: 'harvesterhci.io/windows-sysprep',
SKIP_MIG_CONFIGURATION: 'harvesterhci.io/skip-mig-configuration', SKIP_MIG_CONFIGURATION: 'harvesterhci.io/skip-mig-configuration',
}; };
-4
View File
@@ -30,7 +30,6 @@ export const HCI_SETTING = {
RELEASE_DOWNLOAD_URL: 'release-download-url', RELEASE_DOWNLOAD_URL: 'release-download-url',
CCM_CSI_VERSION: 'harvester-csi-ccm-versions', CCM_CSI_VERSION: 'harvester-csi-ccm-versions',
CSI_DRIVER_CONFIG: 'csi-driver-config', CSI_DRIVER_CONFIG: 'csi-driver-config',
THIRD_PARTY_BACKUP_CONFIG: 'third-party-backup-config',
CSI_ONLINE_EXPAND_VALIDATION: 'csi-online-expand-validation', CSI_ONLINE_EXPAND_VALIDATION: 'csi-online-expand-validation',
VM_TERMINATION_PERIOD: 'default-vm-termination-grace-period-seconds', VM_TERMINATION_PERIOD: 'default-vm-termination-grace-period-seconds',
NTP_SERVERS: 'ntp-servers', NTP_SERVERS: 'ntp-servers',
@@ -145,9 +144,6 @@ export const HCI_ALLOWED_SETTINGS = {
[HCI_SETTING.KUBEVIRT_MIGRATION]: { [HCI_SETTING.KUBEVIRT_MIGRATION]: {
kind: 'json', from: 'import', canReset: true, featureFlag: 'kubevirtMigration', kind: 'json', from: 'import', canReset: true, featureFlag: 'kubevirtMigration',
}, },
[HCI_SETTING.THIRD_PARTY_BACKUP_CONFIG]: {
kind: 'json', from: 'import', canReset: true, featureFlag: 'thirdPartyVMBackup',
},
[HCI_SETTING.INSTANCE_MANAGER_RESOURCES]: { [HCI_SETTING.INSTANCE_MANAGER_RESOURCES]: {
kind: 'json', from: 'import', featureFlag: 'instanceManagerResourcesSetting' kind: 'json', from: 'import', featureFlag: 'instanceManagerResourcesSetting'
}, },
+1 -86
View File
@@ -1,10 +1,7 @@
/** /**
* Harvester * Harvester
*/ */
import { import { DESCRIPTION } from '@shell/config/table-headers';
DESCRIPTION, STATE, AGE, NAME, NAMESPACE
} from '@shell/config/table-headers';
import { HCI as HCI_ANNOTATIONS } from './labels-annotations';
// image // image
export const IMAGE_DOWNLOAD_SIZE = { export const IMAGE_DOWNLOAD_SIZE = {
@@ -300,85 +297,3 @@ export const FORKLIFT_MIGRATION_PLAN = {
sort: 'spec.plan.name', sort: 'spec.plan.name',
align: 'left', align: 'left',
}; };
// Virtual machine list
export const VM_HEADERS = [
STATE,
{
...NAME,
width: 350,
value: 'nameDisplay',
sort: ['nameDisplay'],
},
NAMESPACE,
{
name: 'CPU',
label: 'CPU',
sort: ['displayCPU'],
value: 'displayCPU',
align: 'center',
dashIfEmpty: true,
},
{
name: 'Memory',
value: 'displayMemory',
sort: ['memorySort'],
align: 'center',
labelKey: 'tableHeaders.memory',
formatter: 'Si',
formatterOpts: {
opts: {
increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i',
},
needParseSi: true
},
},
{
name: 'ip',
label: 'IP Address',
value: 'id',
formatter: 'HarvesterIpAddress',
labelKey: 'tableHeaders.ipAddress',
sort: ['id'],
},
// The VM list only shows it when the cluster's nodes can be seen
{
name: 'node',
label: 'Node',
value: 'nodeName',
sort: ['realAttachNodeName'],
formatter: 'HarvesterHost',
labelKey: 'harvester.tableHeaders.vm.node'
},
// The VM list only shows it while a backup is being restored
{
name: 'restoreProgress',
labelKey: 'harvester.tableHeaders.restore',
value: 'restoreProgress',
align: 'left',
formatter: 'HarvesterBackupProgressBar',
width: 200,
},
{
...AGE,
sort: 'metadata.creationTimestamp:desc',
}
];
// With server-side pagination the API sorts and searches, so only the fields it indexes can be used. CPU, memory, IP,
// node and restore progress come from the VM model or other resources. The VM's printer columns are listed as Name, Age, Status, Ready, so its
// Status is `metadata.fields.2`
const VM_PAGINATION_FIELDS = {
[STATE.name]: { sort: ['metadata.fields.2'], search: false },
[NAME.name]: {
sort: ['metadata.name'],
search: ['metadata.name', `metadata.annotations[${ HCI_ANNOTATIONS.VM_DISPLAY_NAME }]`],
},
[NAMESPACE.name]: { sort: ['metadata.namespace'], search: 'metadata.namespace' },
[AGE.name]: { search: false },
};
export const VM_PAGINATION_HEADERS = VM_HEADERS.map((header) => ({
...header,
...(VM_PAGINATION_FIELDS[header.name] || { sort: false, search: false }),
}));
+1 -3
View File
@@ -1,8 +1,6 @@
export const BACKUP_TYPE = { export const BACKUP_TYPE = {
BACKUP: 'backup', BACKUP: 'backup',
SNAPSHOT: 'snapshot', SNAPSHOT: 'snapshot'
RESTIC: 'restic',
KOPIA: 'kopia'
}; };
export const NETWORK_TYPE = { export const NETWORK_TYPE = {
@@ -18,7 +18,6 @@ import { getLatestMigration } from '../../utils/vm';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig'; import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume'; import Volume from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from '../../edit/kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork'; import Network from '../../edit/kubevirt.io.virtualmachine/VirtualMachineNetwork';
import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials'; import AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials';
import Events from './VirtualMachineTabs/VirtualMachineEvents'; import Events from './VirtualMachineTabs/VirtualMachineEvents';
@@ -41,7 +40,6 @@ export default {
OverviewBasics, OverviewBasics,
LabelValue, LabelValue,
Volume, Volume,
VMPerformanceOptions,
Network, Network,
OverviewKeypairs, OverviewKeypairs,
CloudConfig, CloudConfig,
@@ -255,15 +253,9 @@ export default {
:namespace="value.metadata.namespace" :namespace="value.metadata.namespace"
:vm="value" :vm="value"
:resource-type="value.type" :resource-type="value.type"
/>
<VMPerformanceOptions
:block-multi-queue="blockMultiQueue" :block-multi-queue="blockMultiQueue"
:io-threads-policy="ioThreadsPolicy" :io-threads-policy="ioThreadsPolicy"
:io-thread-count="ioThreadCount" :io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
mode="view"
class="mt-20"
/> />
</Tab> </Tab>
@@ -5,7 +5,7 @@ import SortableTable from '@shell/components/SortableTable';
import { HCI } from '@pkg/harvester/types'; import { HCI } from '@pkg/harvester/types';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import { KEY, VALUE } from '@shell/config/table-headers'; import { KEY, VALUE } from '@shell/config/table-headers';
import { VM_HEADERS } from '@pkg/harvester/config/table-headers'; import { VM_HEADERS } from '@pkg/harvester/list/kubevirt.io.virtualmachine';
import { matching } from '@shell/utils/selector'; import { matching } from '@shell/utils/selector';
import { IP_POOL_HEADERS } from '../config/harvester-cluster'; import { IP_POOL_HEADERS } from '../config/harvester-cluster';
@@ -103,7 +103,7 @@ export default {
}, },
vmHeaders() { vmHeaders() {
const filterNames = ['state', 'ip', 'node', 'restoreProgress']; const filterNames = ['state', 'ip', 'node'];
return VM_HEADERS.filter((h) => !filterNames.includes(h.name)); return VM_HEADERS.filter((h) => !filterNames.includes(h.name));
}, },
@@ -30,9 +30,9 @@ export default {
}, },
async fetch() { async fetch() {
this.allPVCs = await this.actionResource.findInNamespace(PVC); this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
this.allStorageClasses = await this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS }); this.allStorageClasses = await this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS });
this.allVMs = await this.actionResource.findInNamespace(HCI.VM); this.allVMs = await this.$store.dispatch('harvester/findAll', { type: HCI.VM });
}, },
data() { data() {
+58 -180
View File
@@ -3,13 +3,10 @@ import { exceptionToErrorsArray } from '@shell/utils/error';
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import { Card } from '@components/Card'; import { Card } from '@components/Card';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import AsyncButton from '@shell/components/AsyncButton';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import { RcButton } from '@components/RcButton';
import { RcHeading } from '@components/RcHeading';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { DEFAULT_FS_FREEZE_DEADLINE, getFsFreezeDeadlineOptions } from '../utils/backup'; import { DEFAULT_FS_FREEZE_DEADLINE, getFsFreezeDeadlineOptions } from '../utils/backup';
import { BACKUP_TYPE } from '../config/types';
import { HCI } from '../types';
export default { export default {
name: 'HarvesterBackupModal', name: 'HarvesterBackupModal',
@@ -17,12 +14,11 @@ export default {
emits: ['close'], emits: ['close'],
components: { components: {
AsyncButton,
Card, Card,
LabeledInput, LabeledInput,
LabeledSelect, LabeledSelect,
Banner, Banner
RcButton,
RcHeading
}, },
props: { props: {
@@ -32,23 +28,11 @@ export default {
} }
}, },
async fetch() {
if (!this.thirdPartyBackupFeatureEnabled) {
return;
}
await this.actionResource.fetchBackupTypeRequirements();
this.backupType = this.backupTypeOptions.find((option) => !option.disabled)?.value;
},
data() { data() {
return { return {
backUpName: '', backUpName: '',
backupType: BACKUP_TYPE.BACKUP,
errors: [], errors: [],
fsFreezeDeadline: DEFAULT_FS_FREEZE_DEADLINE, fsFreezeDeadline: DEFAULT_FS_FREEZE_DEADLINE
saving: false
}; };
}, },
@@ -65,31 +49,6 @@ export default {
fsFreezeDeadlineOptions() { fsFreezeDeadlineOptions() {
return getFsFreezeDeadlineOptions(this.t); return getFsFreezeDeadlineOptions(this.t);
},
thirdPartyBackupFeatureEnabled() {
return !!this.actionResource?.thirdPartyBackupFeatureEnabled;
},
backupTypeOptions() {
return this.thirdPartyBackupFeatureEnabled ? this.actionResource.backupTypeOptions : [];
},
// Shown outside the select too: its disabled options can't be reached by keyboard
unavailableBackupTypeOptions() {
return this.backupTypeOptions.filter((option) => option.disabled);
},
isLoading() {
return this.thirdPartyBackupFeatureEnabled && this.$fetchState.pending;
},
noBackupTypeAvailable() {
return this.thirdPartyBackupFeatureEnabled && !this.isLoading && !this.backupType;
},
canCreate() {
return !!this.backUpName && !this.isLoading && !this.noBackupTypeAvailable && !this.saving;
} }
}, },
@@ -101,69 +60,42 @@ export default {
this.$emit('close'); this.$emit('close');
}, },
backupCreated() { async save(buttonCb) {
this.$store.dispatch( if (this.actionResource) {
'growl/success', try {
{ const res = await this.actionResource.doAction(
title: this.t('generic.notification.title.succeed'), 'backup',
message: this.t('harvester.modal.backup.success', { backUpName: this.backUpName }) { name: this.backUpName, fsFreezeDeadline: this.fsFreezeDeadline },
}, {},
{ root: true } false
); );
this.close(); if (res._status === 200 || res._status === 204) {
}, this.$store.dispatch(
'growl/success',
{
title: this.t('generic.notification.title.succeed'),
message: this.t('harvester.modal.backup.success', { backUpName: this.backUpName })
},
{ root: true }
);
// No ownerReferences, like the backup action: deleting the VM must leave its backups and their remote data this.close();
async createDataMoverBackup() {
const backup = await this.$store.dispatch('harvester/create', {
metadata: {
name: this.backUpName,
namespace: this.actionResource.metadata.namespace,
},
spec: {
fsFreezeDeadline: this.fsFreezeDeadline,
source: {
apiGroup: 'kubevirt.io',
kind: 'VirtualMachine',
name: this.actionResource.metadata.name
},
type: this.backupType
},
type: HCI.BACKUP
});
await backup.save(); buttonCb(true);
}, } else {
const error = [res?.data] || exceptionToErrorsArray(res);
async save() { this['errors'] = error;
this.saving = true; buttonCb(false);
this.errors = []; }
} catch (err) {
const error = err?.data || err;
const message = exceptionToErrorsArray(error);
try { this['errors'] = message;
if (this.backupType !== BACKUP_TYPE.BACKUP) { buttonCb(false);
await this.createDataMoverBackup();
this.backupCreated();
return;
} }
const res = await this.actionResource.doAction(
'backup',
{ name: this.backUpName, fsFreezeDeadline: this.fsFreezeDeadline },
{},
false
);
if (res._status === 200 || res._status === 204) {
this.backupCreated();
} else {
this.errors = [res?.data] || exceptionToErrorsArray(res);
}
} catch (err) {
this.errors = exceptionToErrorsArray(err?.data || err);
} finally {
this.saving = false;
} }
} }
} }
@@ -173,73 +105,27 @@ export default {
<template> <template>
<Card :show-highlight-border="false"> <Card :show-highlight-border="false">
<template #title> <template #title>
<RcHeading :size="3"> <h4
{{ t('harvester.modal.backup.addBackup') }} v-clean-html="t('harvester.modal.backup.addBackup')"
</RcHeading> class="text-default-text"
/>
</template> </template>
<template #body> <template #body>
<Banner <LabeledInput
v-if="noBackupTypeAvailable" v-model:value="backUpName"
class="mt-20" class="mt-20"
color="warning" :label="t('generic.name')"
data-testid="backup-no-type-available" required
> />
<div> <LabeledSelect
<p class="mb-5"> v-if="fsFreezeDeadlineEnabled"
{{ t('harvester.modal.backup.noTypeAvailable') }} v-model:value="fsFreezeDeadline"
</p> class="mt-20"
<ul class="mb-0"> :options="fsFreezeDeadlineOptions"
<li :label="t('harvester.modal.backup.fileSystemFreezeDeadline.label')"
v-for="option in backupTypeOptions" required
:key="option.value" />
>
{{ option.label }}: {{ option.unavailableReason }}
</li>
</ul>
</div>
</Banner>
<template v-else>
<LabeledInput
v-model:value="backUpName"
class="mt-20"
:label="t('generic.name')"
required
/>
<LabeledSelect
v-if="thirdPartyBackupFeatureEnabled"
v-model:value="backupType"
class="mt-20"
data-testid="backup-type-select"
:label="t('harvester.fields.type')"
:loading="isLoading"
:options="backupTypeOptions"
:searchable="false"
required
/>
<Banner
v-if="unavailableBackupTypeOptions.length"
color="info"
data-testid="backup-type-unavailable"
>
<ul class="mb-0">
<li
v-for="option in unavailableBackupTypeOptions"
:key="option.value"
>
{{ option.label }}: {{ option.unavailableReason }}
</li>
</ul>
</Banner>
<LabeledSelect
v-if="fsFreezeDeadlineEnabled"
v-model:value="fsFreezeDeadline"
class="mt-20"
:options="fsFreezeDeadlineOptions"
:label="t('harvester.modal.backup.fileSystemFreezeDeadline.label')"
required
/>
</template>
<Banner <Banner
v-for="(err, i) in errors" v-for="(err, i) in errors"
:key="i" :key="i"
@@ -251,26 +137,18 @@ export default {
<template #actions> <template #actions>
<div class="actions"> <div class="actions">
<div class="buttons"> <div class="buttons">
<RcButton <button
class="mr-10" class="btn role-secondary mr-10"
data-testid="backup-cancel"
size="large"
variant="secondary"
@click="close" @click="close"
> >
{{ t('generic.cancel') }} {{ t('generic.cancel') }}
</RcButton> </button>
<RcButton <AsyncButton
:aria-busy="saving" mode="create"
data-testid="backup-create" :disabled="!backUpName"
:disabled="!canCreate"
size="large"
variant="primary"
@click="save" @click="save"
> />
{{ t('generic.create') }}
</RcButton>
</div> </div>
</div> </div>
</template> </template>
@@ -2,6 +2,7 @@
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import { randomStr } from '@shell/utils/string'; import { randomStr } from '@shell/utils/string';
import { allHash } from '@shell/utils/promise';
import { exceptionToErrorsArray } from '@shell/utils/error'; import { exceptionToErrorsArray } from '@shell/utils/error';
import { Card } from '@components/Card'; import { Card } from '@components/Card';
@@ -23,7 +24,9 @@ export default {
}, },
async fetch() { async fetch() {
this.backups = await this.actionResource.findInNamespace(HCI.BACKUP); const hash = await allHash({ backups: this.$store.dispatch('harvester/findAll', { type: HCI.BACKUP }) });
this.backups = hash.backups;
}, },
props: { props: {
@@ -29,13 +29,7 @@ export default {
}, },
async fetch() { async fetch() {
const [pvcs, vms] = await Promise.all([ this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
this.actionResource.findInNamespace(PVC),
this.actionResource.findInNamespace(HCI.VM),
]);
this.allPVCs = pvcs;
this.namespaceVMs = vms;
}, },
data() { data() {
@@ -44,7 +38,6 @@ export default {
targetVolume: '', targetVolume: '',
errors: [], errors: [],
allPVCs: [], allPVCs: [],
namespaceVMs: [],
}; };
}, },
@@ -75,9 +68,10 @@ export default {
}, },
vmUsedVolumeNames() { vmUsedVolumeNames() {
const allVMs = this.$store.getters['harvester/all'](HCI.VM) || [];
const names = new Set(); const names = new Set();
this.namespaceVMs.forEach((vm) => { allVMs.forEach((vm) => {
// Collect volume names from spec.template.spec.volumes (both PVC and DataVolume references) // Collect volume names from spec.template.spec.volumes (both PVC and DataVolume references)
const volumes = vm.spec?.template?.spec?.volumes || []; const volumes = vm.spec?.template?.spec?.volumes || [];
@@ -1,144 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import HarvesterBackupModal from '../HarvesterBackupModal.vue';
import { HCI } from '../../types';
const OPTIONS = {
backup: {
value: 'backup', label: 'Native', disabled: true, unavailableReason: 'native reason'
},
restic: {
value: 'restic', label: 'Restic', disabled: false
},
kopia: {
value: 'kopia', label: 'Kopia', disabled: false
},
};
function mountModal({
enabled = true, options = Object.values(OPTIONS), doAction = jest.fn().mockResolvedValue({ _status: 204 }), save = jest.fn().mockResolvedValue()
} = {}) {
const vm = {
metadata: { name: 'vm1', namespace: 'ns1' },
thirdPartyBackupFeatureEnabled: enabled,
backupTypeOptions: options,
fetchBackupTypeRequirements: jest.fn().mockResolvedValue(),
doAction,
};
const dispatch = jest.fn((action) => (action === 'harvester/create' ? Promise.resolve({ save }) : Promise.resolve()));
const wrapper = shallowMount(HarvesterBackupModal, {
props: { resources: [vm] },
global: {
stubs: {
Banner: { template: '<div><slot /></div>' },
Card: { template: '<div><slot name="title" /><slot name="body" /><slot name="actions" /></div>' },
},
mocks: {
t: (key) => key,
$fetchState: { pending: false },
$store: {
dispatch,
getters: {
'i18n/t': (key) => key,
'harvester-common/getFeatureEnabled': () => false,
},
},
},
},
});
return {
wrapper, vm, dispatch, doAction, save
};
}
describe('component: HarvesterBackupModal', () => {
it('should keep the plain dialog while the feature is off', async() => {
const { wrapper, doAction, dispatch } = mountModal({ enabled: false });
expect(wrapper.find('[data-testid="backup-type-select"]').exists()).toBe(false);
await wrapper.setData({ backUpName: 'b1' });
await wrapper.vm.save();
expect(doAction).toHaveBeenCalledWith('backup', expect.objectContaining({ name: 'b1' }), {}, false);
expect(dispatch).not.toHaveBeenCalledWith('harvester/create', expect.anything());
expect(wrapper.emitted('close')).toHaveLength(1);
});
it('should load the requirements and select the first available type', async() => {
const { wrapper, vm } = mountModal();
await HarvesterBackupModal.fetch.call(wrapper.vm);
expect(vm.fetchBackupTypeRequirements).toHaveBeenCalledTimes(1);
expect(wrapper.vm.backupType).toBe('restic');
});
it('should keep native on the backup action', async() => {
const { wrapper, doAction, dispatch } = mountModal();
await wrapper.setData({ backUpName: 'b1', backupType: 'backup' });
await wrapper.vm.save();
expect(doAction).toHaveBeenCalledTimes(1);
expect(dispatch).not.toHaveBeenCalledWith('harvester/create', expect.anything());
});
it('should create Kopia directly, without an owner reference on the VM', async() => {
const {
wrapper, doAction, dispatch, save
} = mountModal();
await wrapper.setData({ backUpName: 'b1', backupType: 'kopia' });
await wrapper.vm.save();
expect(doAction).not.toHaveBeenCalled();
expect(save).toHaveBeenCalledTimes(1);
const [, resource] = dispatch.mock.calls.find(([action]) => action === 'harvester/create');
expect(resource.type).toBe(HCI.BACKUP);
expect(resource.metadata).toStrictEqual({ name: 'b1', namespace: 'ns1' });
expect(resource.spec.type).toBe('kopia');
expect(resource.spec.source.name).toBe('vm1');
expect(wrapper.emitted('close')).toHaveLength(1);
});
it('should show the webhook error and stay open', async() => {
const { wrapper } = mountModal({ save: jest.fn().mockRejectedValue({ status: 422, message: 'vm is in migration' }) });
await wrapper.setData({ backUpName: 'b1', backupType: 'kopia' });
await wrapper.vm.save();
expect(wrapper.vm.errors).toStrictEqual(['vm is in migration']);
expect(wrapper.vm.saving).toBe(false);
expect(wrapper.emitted('close')).toBeUndefined();
});
it('should list the reasons of unavailable types next to the select', async() => {
const { wrapper } = mountModal();
await HarvesterBackupModal.fetch.call(wrapper.vm);
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="backup-type-unavailable"]').exists()).toBe(true);
expect(wrapper.findAll('li').map((li) => li.text())).toStrictEqual(['Native: native reason']);
});
it('should explain why when no type is available and hide the form', async() => {
const disabled = Object.values(OPTIONS).map((option) => ({
...option, disabled: true, unavailableReason: `${ option.value } reason`
}));
const { wrapper } = mountModal({ options: disabled });
await HarvesterBackupModal.fetch.call(wrapper.vm);
await wrapper.vm.$nextTick();
expect(wrapper.vm.noBackupTypeAvailable).toBe(true);
expect(wrapper.vm.canCreate).toBe(false);
expect(wrapper.find('[data-testid="backup-type-select"]').exists()).toBe(false);
expect(wrapper.findAll('li').map((li) => li.text())).toStrictEqual([
'Native: backup reason', 'Restic: restic reason', 'Kopia: kopia reason'
]);
});
});
@@ -1,55 +0,0 @@
import { PVC, STORAGE_CLASS } from '@shell/config/types';
import HotplugVolumeModal from '../HarvesterAddHotplugVolumeModal.vue';
import StorageMigrationDialog from '../HarvesterStorageMigrationDialog.vue';
import RestoreDialog from '../HarvesterRestoreDialog.vue';
import { HCI } from '../../types';
// The dialogs of the VM list read the VMs, PVCs and backups of the VM's namespace through the VM, so a paged VM list
// keeps its page (see `findInNamespace` in the VM model)
describe('dialogs of the VM list', () => {
const vm = (claims = []) => ({
metadata: { namespace: 'default', name: 'vm' },
spec: { template: { spec: { volumes: claims.map((claimName) => ({ persistentVolumeClaim: { claimName } })) } } },
findInNamespace: jest.fn((type) => Promise.resolve([{ type }])),
});
it('should load the PVCs and VMs of Add Volume through the VM', async() => {
const actionResource = vm();
const dispatch = jest.fn(() => Promise.resolve([]));
const dialog = { actionResource, $store: { dispatch } };
await HotplugVolumeModal.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.allVMs).toStrictEqual([{ type: HCI.VM }]);
expect(dispatch.mock.calls).toStrictEqual([['harvester/findAll', { type: STORAGE_CLASS }]]);
});
it('should load the PVCs and VMs of Storage Migration through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await StorageMigrationDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.namespaceVMs).toStrictEqual([{ type: HCI.VM }]);
});
it('should exclude the volumes of the loaded VMs from the Storage Migration targets', () => {
const used = StorageMigrationDialog.computed.vmUsedVolumeNames.call({ namespaceVMs: [vm(['a-disk']), vm(['b-disk'])] });
expect([...used]).toStrictEqual(['default/a-disk', 'default/b-disk']);
});
it('should load the backups of Restore through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await RestoreDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[HCI.BACKUP]]);
expect(dialog.backups).toStrictEqual([{ type: HCI.BACKUP }]);
});
});
@@ -1,36 +0,0 @@
import { HCI } from '@pkg/harvester/types';
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
import HarvesterEditTemplateVersion from '../harvesterhci.io.virtualmachinetemplateversion.vue';
async function saveWith(userScript) {
const buttonCb = jest.fn();
const form = {
userScript,
errors: [],
t: (key) => key,
parseVM: jest.fn(),
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
templateValue: { metadata: {} },
$store: { dispatch: jest.fn().mockResolvedValue([]) },
};
await HarvesterEditTemplateVersion.methods.saveVMT.call(form, buttonCb);
return { form, buttonCb };
}
describe('page: harvesterhci.io.virtualmachinetemplateversion edit', () => {
it('should stop the save when the cloud config is invalid', async() => {
const { form, buttonCb } = await saveWith('#cloud-config\nsome words\n');
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(form.$store.dispatch).not.toHaveBeenCalled();
});
it('should go on with the save when the user data is a script', async() => {
const { form } = await saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
expect(form.$store.dispatch).toHaveBeenCalledWith('harvester/findAll', { type: HCI.VM_TEMPLATE });
});
});
@@ -1,99 +0,0 @@
import EditVPC from '../kubeovn.io.vpc/index.vue';
const { validateBfdPort, bfdPortIPError, applyBfdPort } = EditVPC.methods;
const { validationPassed, gatewaysNeedingBfdPort } = EditVPC.computed;
const t = (key) => key;
function createContext(form = {}, spec = {}, model = {}) {
const value = {
metadata: { name: 'commonvpc' }, spec, subnetResources: [], bfdEgressGateways: [], ...model
};
return {
t,
value,
...EditVPC.data.call({ value }),
bfdPortIPError,
...form,
};
}
describe('edit: kubeovn.io.vpc', () => {
it('should load the BFD port of an existing VPC', () => {
const context = createContext({}, { bfdPort: { enabled: true, ip: '10.255.255.255' } });
expect(context.bfdPortEnabled).toBe(true);
expect(context.bfdPortIP).toBe('10.255.255.255');
});
it('should not add a BFD port to a VPC that has none while it stays disabled', () => {
const context = createContext({}, { staticRoutes: [] });
expect(validateBfdPort.call(context)).toStrictEqual([]);
applyBfdPort.call(context);
expect(context.value.spec).toStrictEqual({ staticRoutes: [] });
});
it('should enable the BFD port with its IP and keep its node selector', () => {
const nodeSelector = { matchLabels: { 'kubernetes.io/os': 'linux' } };
const context = createContext({ bfdPortEnabled: true, bfdPortIP: ' 10.255.255.255 , fd00::ffff ' }, { bfdPort: { enabled: false, nodeSelector } });
expect(validateBfdPort.call(context)).toStrictEqual([]);
applyBfdPort.call(context);
expect(context.value.spec.bfdPort).toStrictEqual({
enabled: true, ip: '10.255.255.255,fd00::ffff', nodeSelector
});
});
it('should keep the IP when the BFD port is disabled', () => {
const context = createContext({ bfdPortEnabled: false }, { bfdPort: { enabled: true, ip: '10.255.255.255' } });
applyBfdPort.call(context);
expect(context.value.spec.bfdPort).toStrictEqual({ enabled: false, ip: '10.255.255.255' });
});
it('should reject a BFD port IP inside one of the VPC subnets', () => {
const subnet = {
id: 'subnetinternal', spec: { cidrBlock: '172.20.10.0/24' }, containsIP: (ip) => ip.startsWith('172.20.10.')
};
const context = createContext({ bfdPortEnabled: true, bfdPortIP: '172.20.10.200' }, {}, { subnetResources: [subnet] });
const errors = validateBfdPort.call(context);
expect(errors).toHaveLength(1);
expect(errors[0]).toContain('harvester.vpc.bfdPort.validation.subnet');
});
it.each([
['a name and a valid BFD port', {}, true],
['no name', { value: { metadata: {} } }, false],
['an invalid BFD port', { bfdPortErrors: ['error'] }, false],
])('should allow the save with %s', (_, form, passed) => {
expect(validationPassed.call({
value: { metadata: { name: 'commonvpc' } }, bfdPortErrors: [], ...form
})).toBe(passed);
});
it('should list the gateways that need the BFD port only while it is disabled', () => {
const bfdEgressGateways = [{ id: 'default/gateway1' }];
expect(gatewaysNeedingBfdPort.call({ bfdPortEnabled: false, value: { bfdEgressGateways } })).toStrictEqual(bfdEgressGateways);
expect(gatewaysNeedingBfdPort.call({ bfdPortEnabled: true, value: { bfdEgressGateways } })).toStrictEqual([]);
});
it.each([
['no IP', '', 'validation.required'],
['an invalid IP', '10.255.255.256', 'harvester.vpc.bfdPort.validation.ip'],
['a CIDR', '10.255.255.255/32', 'harvester.vpc.bfdPort.validation.ip'],
['two IPv4 addresses', '10.255.255.254,10.255.255.255', 'harvester.vpc.bfdPort.validation.ip'],
['three addresses', '10.255.255.255,fd00::1,fd00::2', 'harvester.vpc.bfdPort.validation.ip'],
])('should reject an enabled BFD port with %s', (_, bfdPortIP, errorKey) => {
const errors = validateBfdPort.call(createContext({ bfdPortEnabled: true, bfdPortIP }));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain(errorKey);
});
});
@@ -1,452 +0,0 @@
import EditVpcEgressGateway from '../kubeovn.io.vpcegressgateway.vue';
const {
validate, validateTabs, ipError, ipCountError, policyError, policiesSpec, toSpec, bfdSpec, saveGateway
} = EditVpcEgressGateway.methods;
const { vpc: onVpcChange, externalNetworkMode: onExternalNetworkModeChange } = EditVpcEgressGateway.watch;
const {
showExternalNetworkMode, vpcBfdPortDisabled, vpcEditLocation, internalSubnetOptions, externalSubnetOptions, externalSubnetRules, internalSubnetPlaceholder, snatSubnetOptions, noSnatSubnetOptions, policySubnetsPlaceholder
} = EditVpcEgressGateway.computed;
const { requiredError } = EditVpcEgressGateway.methods;
const t = (key, args) => (args ? `${ key } ${ JSON.stringify(args) }` : key);
function createContext(form = {}, spec = {}) {
const value = { metadata: { name: 'gateway1', namespace: 'default' }, spec };
const context = {
t,
value,
...EditVpcEgressGateway.data.call({ value }),
vpc: 'commonvpc',
replicas: 2,
internalSubnet: 'subnetinternal',
externalSubnet: 'subnetexternal',
snatSubnets: ['subnetinternal'],
...form,
};
Object.assign(context, {
bfdSpec, validateTabs, ipError, ipCountError, policyError, policiesSpec
});
return context;
}
// A subnet as the store returns it, with the model getters the form reads
function subnet(id, spec, model = {}) {
return {
id, spec, isOverlayAttachment: false, networkAttachment: null, canAssignIP: () => true, ...model
};
}
describe('edit: kubeovn.io.vpcegressgateway', () => {
it('should start a new gateway with one replica, no subnets and BFD off', () => {
const data = EditVpcEgressGateway.data.call({ value: { metadata: {} } });
expect(data.replicas).toBe(1);
expect([data.snatSubnets, data.noSnatSubnets, data.ipBlockPolicies]).toStrictEqual([[], [], []]);
expect(data.bfd).toStrictEqual({
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
});
});
it('should build the spec from the form and leave out empty optional fields', () => {
const spec = toSpec.call(createContext());
expect(spec).toStrictEqual({
vpc: 'commonvpc',
replicas: 2,
internalSubnet: 'subnetinternal',
externalSubnet: 'subnetexternal',
policies: [{ snat: true, subnets: ['subnetinternal'] }],
bfd: {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
},
});
});
it('should build the spec with IPs, BFD and bandwidth', () => {
const spec = toSpec.call(createContext({
internalIPs: ['172.20.10.41', ' 172.20.10.51 ', ''],
externalIPs: ['10.115.48.220', '10.115.48.221'],
bfd: {
enabled: true, minRX: '50', minTX: 50, multiplier: 3
},
bandwidthIngress: 10,
bandwidthEgress: null,
}));
expect(spec.internalIPs).toStrictEqual(['172.20.10.41', '172.20.10.51']);
expect(spec.externalIPs).toStrictEqual(['10.115.48.220', '10.115.48.221']);
expect(spec.bfd).toStrictEqual({
enabled: true, minRX: 50, minTX: 50, multiplier: 3
});
expect(spec.bandwidth).toStrictEqual({ ingress: 10 });
});
it('should keep a bandwidth quantity as a string and a whole number as Mbps', () => {
const context = createContext({ bandwidthIngress: ' 1Gi ', bandwidthEgress: '100' });
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context).bandwidth).toStrictEqual({ ingress: '1Gi', egress: 100 });
});
it('should send the BFD defaults for intervals cleared while BFD is off', () => {
const context = createContext({
bfd: {
enabled: false, minRX: '', minTX: 50, multiplier: null
}
});
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context).bfd).toStrictEqual({
enabled: false, minRX: 1000, minTX: 50, multiplier: 3
});
});
it('should list only the subnets of the VPC that sit on a virtual machine network as internal subnets', () => {
const vpcSubnets = [
subnet('ovn-default', { vpc: 'ovn-cluster', provider: 'ovn' }),
subnet('subnetinternal', { vpc: 'commonvpc', provider: 'vmnet.default.ovn' }, { isOverlayAttachment: true }),
];
expect(internalSubnetOptions.call({ vpcSubnets })).toStrictEqual([{ label: 'subnetinternal', value: 'subnetinternal' }]);
});
it('should list only the subnets attached to a network as external subnets', () => {
const allSubnets = [
subnet('join', { vpc: 'ovn-cluster', provider: 'ovn' }),
subnet('subnetexternal', { vpc: 'commonvpc', provider: 'extnet.default' }, { networkAttachment: { name: 'extnet', namespace: 'default' } }),
];
expect(externalSubnetOptions.call({ allSubnets })).toStrictEqual([{ label: 'subnetexternal', value: 'subnetexternal' }]);
});
it('should check the IPs against the subnet they belong to', () => {
const internalSubnetResource = subnet('subnetinternal', { cidrBlock: '172.20.10.0/24' }, { canAssignIP: (ip) => ip.startsWith('172.20.10.') });
const errors = validate.call(createContext({ internalSubnetResource, internalIPs: ['172.20.10.41', '10.0.0.1'] }));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain('harvester.egressGateway.validation.ipSubnet');
expect(errors[0]).toContain('172.20.10.0/24');
});
it('should put each error on the tab that holds the field', () => {
const errors = validateTabs.call(createContext({
replicas: 11,
snatSubnets: [],
externalIPs: ['10.115.48.300'],
bfd: {
enabled: true, minRX: 0, minTX: 50, multiplier: 3
},
bandwidthIngress: '10Mbps',
}));
expect(Object.fromEntries(Object.entries(errors).map(([tab, messages]) => [tab, messages.length]))).toStrictEqual({
basic: 1, policies: 1, ips: 1, bfd: 1, bandwidth: 1
});
expect(errors.policies[0]).toContain('harvester.egressGateway.validation.policyRequired');
});
it.each([
['empty', '', 'validation.required'],
['the internal subnet', 'subnetinternal', 'harvester.egressGateway.validation.sameSubnet'],
])('should explain an external subnet that is %s', (_, value, errorKey) => {
const [rule] = externalSubnetRules.call(createContext({ requiredError }));
expect(rule(value)).toContain(errorKey);
});
it('should accept an external subnet other than the internal one', () => {
const [rule] = externalSubnetRules.call(createContext({ requiredError }));
expect(rule('subnetexternal')).toBeUndefined();
});
it('should ask for a VPC before the internal subnet', () => {
expect(internalSubnetPlaceholder.call({
t: (key) => key, vpc: '', internalSubnetOptions: []
})).toBe('harvester.egressGateway.internalSubnet.noVpc');
});
it('should say when the VPC has no subnet on a virtual machine network', () => {
const t = (key, args) => (args ? `${ key } ${ args.vpc }` : key);
expect(internalSubnetPlaceholder.call({
t, vpc: 'ovn-cluster', internalSubnetOptions: []
})).toBe('harvester.egressGateway.internalSubnet.none ovn-cluster');
expect(internalSubnetPlaceholder.call({
t, vpc: 'commonvpc', internalSubnetOptions: [{ value: 'subnetinternal' }]
})).toBe('harvester.egressGateway.internalSubnet.placeholder');
});
it('should leave an empty IP row to the save, which drops it', () => {
expect(ipError.call(createContext(), 'internalIPs', ' ')).toBeUndefined();
});
it('should read the policies as Kube-OVN applies them', () => {
const data = EditVpcEgressGateway.data.call({
value: {
spec: {
policies: [
{ snat: true, subnets: ['a', 'b'] },
{ snat: true, subnets: ['c', 'a'] },
{ snat: false, subnets: ['b', 'd'] },
{ snat: false, ipBlocks: ['10.0.0.0/24'] },
]
}
}
});
expect(data.snatSubnets).toStrictEqual(['a', 'c']);
expect(data.noSnatSubnets).toStrictEqual(['b', 'd']);
expect(data.ipBlockPolicies).toStrictEqual([{ snat: false, ipBlocks: ['10.0.0.0/24'] }]);
});
it('should write one policy for each group and keep the IP block policies', () => {
const context = createContext({
snatSubnets: ['a', 'c'], noSnatSubnets: ['b'], ipBlockPolicies: [{ snat: true, ipBlocks: ['10.0.0.0/24'] }]
});
expect(policiesSpec.call(context)).toStrictEqual([
{ snat: true, subnets: ['a', 'c'] },
{ snat: false, subnets: ['b'] },
{ snat: true, ipBlocks: ['10.0.0.0/24'] },
]);
});
it('should leave out a group without subnets', () => {
expect(policiesSpec.call(createContext({ snatSubnets: [], noSnatSubnets: ['b'] }))).toStrictEqual([{ snat: false, subnets: ['b'] }]);
});
it.each([
['no VPC is chosen', '', [], 'harvester.egressGateway.policies.noVpc'],
['the VPC has no subnets', 'emptyvpc', [], 'harvester.egressGateway.policies.noSubnets emptyvpc'],
['the VPC has subnets', 'commonvpc', [{ value: 'a' }], 'harvester.egressGateway.policies.placeholder'],
])('should explain the policy lists when %s', (_, vpc, vpcSubnetOptions, placeholder) => {
const t = (key, args) => (args ? `${ key } ${ args.vpc }` : key);
expect(policySubnetsPlaceholder.call({
t, vpc, vpcSubnetOptions
})).toBe(placeholder);
});
it('should not offer a subnet of one group in the other, nor the external subnet', () => {
const vpcSubnetOptions = ['a', 'b', 'c', 'ext'].map((value) => ({ label: value, value }));
const context = {
vpcSubnetOptions, snatSubnets: ['a'], noSnatSubnets: ['b'], externalSubnet: 'ext'
};
expect(snatSubnetOptions.call(context).map((option) => option.value)).toStrictEqual(['a', 'c']);
expect(noSnatSubnetOptions.call(context).map((option) => option.value)).toStrictEqual(['b', 'c']);
});
it('should reject the external subnet as a policy source', () => {
const error = policyError.call(createContext({ snatSubnets: ['subnetexternal'] }));
expect(error).toContain('harvester.egressGateway.validation.policyExternalSubnet');
expect(error).toContain('subnetexternal');
});
it.each([
['subnets with SNAT', { snatSubnets: ['a'] }],
['subnets without SNAT', { snatSubnets: [], noSnatSubnets: ['b'] }],
['only IP blocks', { snatSubnets: [], ipBlockPolicies: [{ snat: false, ipBlocks: ['10.0.0.0/24'] }] }],
])('should accept a gateway with %s', (_, form) => {
expect(policyError.call(createContext(form))).toBeUndefined();
});
it('should stop the save when the form has errors', async() => {
const buttonCb = jest.fn();
const context = createContext({
vpc: '', validate, save: jest.fn()
});
await saveGateway.call(context, buttonCb);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(context.save).not.toHaveBeenCalled();
expect(context.errors).toHaveLength(1);
});
it('should save the spec built from the form', async() => {
const buttonCb = jest.fn();
const context = createContext({
validate, toSpec, save: jest.fn()
});
await saveGateway.call(context, buttonCb);
expect(context.save).toHaveBeenCalledWith(buttonCb);
expect(context.value.spec.vpc).toBe('commonvpc');
expect(context.value.spec.policies).toStrictEqual([{ snat: true, subnets: ['subnetinternal'] }]);
});
it('should keep the fields the form does not show', () => {
const existing = {
trafficPolicy: 'Local',
selectors: [{ namespaceSelector: { matchLabels: { app: 'web' } } }],
policies: [{ snat: false, ipBlocks: ['10.0.0.0/24'] }],
};
const context = createContext({ snatSubnets: [] }, existing);
const { snatSubnets, noSnatSubnets, ipBlockPolicies } = EditVpcEgressGateway.data.call({ value: context.value });
Object.assign(context, {
snatSubnets, noSnatSubnets, ipBlockPolicies
});
const spec = toSpec.call(context);
expect(spec.trafficPolicy).toBe('Local');
expect(spec.selectors).toStrictEqual(existing.selectors);
expect(spec.policies).toStrictEqual([{ snat: false, ipBlocks: ['10.0.0.0/24'] }]);
expect(validate.call(context)).toStrictEqual([]);
});
it.each([
['has', true],
['does not have', false],
])('should offer Primary CNI when the CRD %s externalNetworkMode', async(_, hasField) => {
const schema = { fetchResourceFields: jest.fn().mockResolvedValue({}) };
const getters = {
currentProduct: { inStore: 'harvester' },
'harvester/schemaFor': () => schema,
'harvester/pathExistsInSchema': jest.fn(() => hasField),
};
const context = { $store: { getters, dispatch: jest.fn().mockResolvedValue([]) }, supportsPrimaryCNI: false };
await EditVpcEgressGateway.fetch.call(context);
expect(schema.fetchResourceFields).toHaveBeenCalledWith();
expect(getters['harvester/pathExistsInSchema']).toHaveBeenCalledWith('kubeovn.io.vpcegressgateway', 'spec.externalNetworkMode');
expect(context.supportsPrimaryCNI).toBe(hasField);
});
it.each([
['a CRD with the mode', { supportsPrimaryCNI: true, usesPrimaryCNI: false }, true],
['a CRD without the mode', { supportsPrimaryCNI: false, usesPrimaryCNI: false }, false],
['an existing Primary CNI gateway', { supportsPrimaryCNI: false, usesPrimaryCNI: true }, true],
])('should show the external network choice for %s', (_, context, shown) => {
expect(showExternalNetworkMode.call(context)).toBe(shown);
});
it('should start a new gateway on an external subnet and leave the mode to the CRD default', () => {
const context = createContext();
expect(context.externalNetworkMode).toBe('Attachment');
expect(toSpec.call(context)).not.toHaveProperty('externalNetworkMode');
});
it('should write a PrimaryCNI gateway without an external subnet', () => {
const spec = toSpec.call(createContext({ externalNetworkMode: 'PrimaryCNI', externalSubnet: '' }));
expect(spec.externalNetworkMode).toBe('PrimaryCNI');
expect(spec).not.toHaveProperty('externalSubnet');
expect(spec).not.toHaveProperty('externalIPs');
expect(spec).not.toHaveProperty('bandwidth');
});
it('should clear the external fields when PrimaryCNI is chosen', () => {
const context = createContext({
externalIPs: ['10.115.48.220'], bandwidthIngress: 10, bandwidthEgress: '1Gi'
});
onExternalNetworkModeChange.call(context, 'PrimaryCNI');
expect([context.externalSubnet, context.externalIPs, context.bandwidthIngress, context.bandwidthEgress]).toStrictEqual(['', [], '', '']);
});
it('should save a PrimaryCNI gateway made outside the form', () => {
const existing = {
vpc: 'commonvpc',
replicas: 1,
externalNetworkMode: 'PrimaryCNI',
internalSubnet: 'subnetinternal',
policies: [{ snat: true, subnets: ['subnetinternal'] }],
};
const value = { metadata: { name: 'gateway1', namespace: 'default' }, spec: existing };
const context = createContext(EditVpcEgressGateway.data.call({ value }), existing);
expect(context.externalNetworkMode).toBe('PrimaryCNI');
expect(validate.call(context)).toStrictEqual([]);
expect(toSpec.call(context)).toStrictEqual({
...existing,
bfd: {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
},
});
});
it('should accept a complete form', () => {
expect(validate.call(createContext())).toStrictEqual([]);
});
it.each([
['no VPC', { vpc: '' }, 'validation.required'],
['no internal subnet', { internalSubnet: '' }, 'validation.required'],
['no external subnet', { externalSubnet: '' }, 'validation.required'],
['the same internal and external subnet', { externalSubnet: 'subnetinternal', snatSubnets: ['subnetother'] }, 'harvester.egressGateway.validation.sameSubnet'],
['too many replicas', { replicas: 11 }, 'harvester.egressGateway.validation.replicas'],
['no subnet with or without SNAT', { snatSubnets: [] }, 'harvester.egressGateway.validation.policyRequired'],
['an invalid IP', { externalIPs: ['10.115.48.300', '10.115.48.221'] }, 'harvester.egressGateway.validation.ipList'],
['fewer IPs than replicas', { internalIPs: ['172.20.10.41'] }, 'harvester.egressGateway.validation.ipCount'],
['a repeated IP', { externalIPs: ['10.115.48.220', ' 10.115.48.220'] }, 'harvester.egressGateway.validation.ipDuplicate'],
['a BFD interval of 0', {
bfd: {
enabled: true, minRX: 0, minTX: 50, multiplier: 3
}
}, 'harvester.egressGateway.validation.bfd'],
['a BFD multiplier of 0', {
bfd: {
enabled: true, minRX: 50, minTX: 50, multiplier: 0
}
}, 'harvester.egressGateway.validation.bfdMultiplier'],
['a negative bandwidth', { bandwidthEgress: -1 }, 'harvester.egressGateway.validation.bandwidth'],
['a bandwidth with an unknown unit', { bandwidthEgress: '10Mbps' }, 'harvester.egressGateway.validation.bandwidth'],
])('should reject %s', (_, form, errorKey) => {
const errors = validate.call(createContext(form));
expect(errors).toHaveLength(1);
expect(errors[0]).toContain(errorKey);
});
it('should drop the subnets of the previous VPC when the VPC changes', () => {
const context = createContext({
vpc: 'othervpc',
internalSubnet: 'subnetinternal',
snatSubnets: ['subnetinternal', 'othersubnet'],
noSnatSubnets: ['subnetinternal'],
vpcSubnetOptions: [{ label: 'othersubnet', value: 'othersubnet' }],
internalSubnetOptions: [{ label: 'othersubnet', value: 'othersubnet' }],
});
onVpcChange.call(context, 'othervpc', 'commonvpc');
expect(context.internalSubnet).toBe('');
expect(context.snatSubnets).toStrictEqual(['othersubnet']);
expect(context.noSnatSubnets).toStrictEqual([]);
});
it.each([
['has no BFD port', { bfdPortEnabled: false }, true],
['has a BFD port', { bfdPortEnabled: true }, false],
])('should warn about BFD when the selected VPC %s', (_, selectedVpc, warning) => {
expect(vpcBfdPortDisabled.call({ selectedVpc })).toBe(warning);
});
it('should not warn about BFD before a VPC is selected', () => {
expect(vpcBfdPortDisabled.call({ selectedVpc: null })).toBe(false);
});
it('should link the BFD warning to the BFD Port tab of the selected VPC', () => {
const selectedVpc = { detailLocation: { name: 'harvester-c-cluster-resource-id', params: { resource: 'kubeovn.io.vpc', id: 'commonvpc' } } };
expect(vpcEditLocation.call({ selectedVpc })).toStrictEqual({
name: 'harvester-c-cluster-resource-id',
params: { resource: 'kubeovn.io.vpc', id: 'commonvpc' },
query: { mode: 'edit' },
hash: '#bfdPort',
});
});
});
@@ -21,7 +21,6 @@ import { HCI } from '../types';
import VM_MIXIN from '../mixins/harvester-vm'; import VM_MIXIN from '../mixins/harvester-vm';
import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved'; import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved';
import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume'; import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork'; import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory'; import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory';
import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel'; import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel';
@@ -38,7 +37,6 @@ export default {
Tab, Tab,
SSHKey, SSHKey,
Volume, Volume,
VMPerformanceOptions,
Tabbed, Tabbed,
Network, Network,
Checkbox, Checkbox,
@@ -179,17 +177,8 @@ export default {
}, },
async saveVMT(buttonCb) { async saveVMT(buttonCb) {
this.errors = [];
this.parseVM(); this.parseVM();
this.validateCloudInit();
if (this.errors.length) {
buttonCb(false);
return;
}
const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE }); const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE });
const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name); const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name);
@@ -401,6 +390,9 @@ export default {
> >
<Volume <Volume
v-model:value="diskRows" v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode" :mode="mode"
:namespace="value.metadata.namespace" :namespace="value.metadata.namespace"
:existing-volume-disabled="true" :existing-volume-disabled="true"
@@ -586,16 +578,6 @@ export default {
</div> </div>
</div> </div>
<VMPerformanceOptions
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
class="mb-20"
/>
<CloudConfig <CloudConfig
ref="yamlEditor" ref="yamlEditor"
:mode="mode" :mode="mode"
@@ -1,117 +0,0 @@
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' });
});
});
+1 -76
View File
@@ -13,12 +13,8 @@ import { set, remove } from '@shell/utils/object';
import ArrayList from '@shell/components/form/ArrayList'; import ArrayList from '@shell/components/form/ArrayList';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import { HCI } from '../../types'; import { HCI } from '../../types';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import ResourceTabs from '@shell/components/form/ResourceTabs/index'; import ResourceTabs from '@shell/components/form/ResourceTabs/index';
import { Banner } from '@components/Banner'; 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'; import AccessControlList from './AccessControlList';
export default { export default {
@@ -37,7 +33,6 @@ export default {
ArrayList, ArrayList,
ResourceTabs, ResourceTabs,
Loading, Loading,
MessageLink,
AccessControlList AccessControlList
}, },
@@ -45,10 +40,6 @@ export default {
inheritAttrs: false, inheritAttrs: false,
data() {
return { bgpSpeakerOff: false };
},
created() { created() {
const vpc = this.$route.query.vpc || ''; const vpc = this.$route.query.vpc || '';
const enableDHCP = this.value?.spec?.enableDHCP || false; const enableDHCP = this.value?.spec?.enableDHCP || false;
@@ -78,16 +69,7 @@ export default {
vlans: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN }), vlans: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VLAN }),
}; };
// BGP on a subnet only has an effect when some host runs the BGP speaker (Overlay Networks > Settings) await allHash(hash);
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: { computed: {
@@ -151,29 +133,6 @@ export default {
value: n.id, 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() { natOutgoingDisabled() {
// Disable the NAT Outgoing option when the subnet belongs to the ovn-cluster VPC and its name is join or ovn-default. // 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); return this.value?.spec?.vpc === 'ovn-cluster' && ['join', 'ovn-default'].includes(this.value?.metadata?.name);
@@ -410,40 +369,6 @@ export default {
/> />
</div> </div>
</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 <ArrayList
v-if="showAllowSubnets" v-if="showAllowSubnets"
v-model:value="value.spec.allowSubnets" v-model:value="value.spec.allowSubnets"
+1 -151
View File
@@ -5,17 +5,9 @@ import Tab from '@shell/components/Tabbed/Tab';
import Loading from '@shell/components/Loading'; import Loading from '@shell/components/Loading';
import CreateEditView from '@shell/mixins/create-edit-view'; import CreateEditView from '@shell/mixins/create-edit-view';
import ResourceTabs from '@shell/components/form/ResourceTabs/index'; import ResourceTabs from '@shell/components/form/ResourceTabs/index';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import StaticRoutes from './StaticRoutes'; import StaticRoutes from './StaticRoutes';
import VpcPeerings from './VpcPeerings'; import VpcPeerings from './VpcPeerings';
import { set } from '@shell/utils/object'; import { set } from '@shell/utils/object';
import { allHash } from '@shell/utils/promise';
import { isValidIP } from '@shell/utils/validators/cidr';
import { HCI } from '../../types';
const splitIPs = (value) => `${ value || '' }`.split(',').map((ip) => ip.trim()).filter(Boolean);
export default { export default {
name: 'EditVPC', name: 'EditVPC',
@@ -23,11 +15,8 @@ export default {
emits: ['update:value'], emits: ['update:value'],
components: { components: {
Banner,
CruResource, CruResource,
LabeledInput,
NameNsDescription, NameNsDescription,
RadioGroup,
Tab, Tab,
StaticRoutes, StaticRoutes,
ResourceTabs, ResourceTabs,
@@ -39,106 +28,16 @@ export default {
inheritAttrs: false, inheritAttrs: false,
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const hasEgressGateways = !!this.$store.getters[`${ inStore }/schemaFor`](HCI.VPC_EGRESS_GATEWAY);
await allHash({
subnets: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SUBNET }),
gateways: hasEgressGateways ? this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VPC_EGRESS_GATEWAY }) : [],
});
},
data() { data() {
set(this.value, 'spec', this.value.spec || { set(this.value, 'spec', this.value.spec || {
staticRoutes: [], staticRoutes: [],
vpcPeerings: [], vpcPeerings: [],
}); });
const bfdPort = this.value.spec.bfdPort || {}; return { staticRoutes: [] };
return {
staticRoutes: [],
bfdPortEnabled: bfdPort.enabled === true,
bfdPortIP: bfdPort.ip || '',
};
},
computed: {
bfdPortErrors() {
return this.isView ? [] : this.validateBfdPort();
},
validationPassed() {
return !!this.value?.metadata?.name && this.bfdPortErrors.length === 0;
},
// Each field shows its own error once touched, so a disabled Save always has a visible reason
nameRules() {
return {
name: [(value) => (value ? undefined : this.t('validation.required', { key: this.t('generic.name') }, true))], namespace: [], description: []
};
},
bfdPortIPRules() {
return [(value) => this.bfdPortIPError(value)];
},
gatewaysNeedingBfdPort() {
return this.bfdPortEnabled ? [] : this.value.bfdEgressGateways || [];
},
}, },
methods: { methods: {
bfdPortIPError(value) {
if (!this.bfdPortEnabled) {
return undefined;
}
const ips = splitIPs(value);
const ipv6Count = ips.filter((ip) => ip.includes(':')).length;
if (!ips.length) {
return this.t('validation.required', { key: this.t('harvester.vpc.bfdPort.ip.label') }, true);
}
if (ips.length > 2 || ips.some((ip) => !isValidIP(ip)) || (ips.length === 2 && ipv6Count !== 1)) {
return this.t('harvester.vpc.bfdPort.validation.ip', null, true);
}
const subnet = (this.value.subnetResources || []).find((item) => ips.some((ip) => item.containsIP(ip)));
if (subnet) {
return this.t('harvester.vpc.bfdPort.validation.subnet', { subnet: subnet.id, cidr: subnet.spec?.cidrBlock }, true);
}
return undefined;
},
validateBfdPort() {
return [this.bfdPortIPError(this.bfdPortIP)].filter(Boolean);
},
applyBfdPort() {
const current = this.value.spec.bfdPort;
if (!this.bfdPortEnabled && !current) {
return;
}
const bfdPort = {
...(current || {}),
enabled: this.bfdPortEnabled,
ip: splitIPs(this.bfdPortIP).join(','),
};
if (!bfdPort.ip) {
delete bfdPort.ip;
}
this.value.spec.bfdPort = bfdPort;
},
async saveVpc(buttonCb) { async saveVpc(buttonCb) {
const errors = []; const errors = [];
@@ -149,15 +48,12 @@ export default {
errors.push(this.t('validation.required', { key: this.t('generic.name') }, true)); errors.push(this.t('validation.required', { key: this.t('generic.name') }, true));
} }
errors.push(...this.validateBfdPort());
if (errors.length > 0) { if (errors.length > 0) {
buttonCb(false); buttonCb(false);
this.errors = errors; this.errors = errors;
return false; return false;
} }
this.applyBfdPort();
await this.value.save(); await this.value.save();
buttonCb(true); buttonCb(true);
this.done(); this.done();
@@ -180,7 +76,6 @@ export default {
:mode="mode" :mode="mode"
:apply-hooks="applyHooks" :apply-hooks="applyHooks"
:errors="errors" :errors="errors"
:validation-passed="validationPassed"
@finish="saveVpc" @finish="saveVpc"
@error="e=>errors=e" @error="e=>errors=e"
> >
@@ -188,7 +83,6 @@ export default {
:value="value" :value="value"
:mode="mode" :mode="mode"
:namespaced="false" :namespaced="false"
:rules="nameRules"
@update:value="$emit('update:value', $event)" @update:value="$emit('update:value', $event)"
/> />
<ResourceTabs <ResourceTabs
@@ -221,50 +115,6 @@ export default {
:vpc="value" :vpc="value"
/> />
</Tab> </Tab>
<Tab
name="bfdPort"
:label="t('harvester.vpc.bfdPort.label')"
:weight="-3"
:error="bfdPortErrors.length > 0"
:error-icon-tooltip="bfdPortErrors.join(' ')"
>
<Banner
color="info"
:label="t('harvester.vpc.bfdPort.banner')"
/>
<RadioGroup
v-model:value="bfdPortEnabled"
name="bfdPort"
data-testid="vpc-bfd-port-enabled"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
:aria-label="t('harvester.vpc.bfdPort.label')"
:mode="mode"
/>
<Banner
v-if="gatewaysNeedingBfdPort.length"
color="warning"
data-testid="vpc-bfd-port-gateways"
:label="t('harvester.vpc.bfdPort.gatewaysNeedPort', { gateways: gatewaysNeedingBfdPort.map((gateway) => gateway.id).join(', ') }, true)"
/>
<div
v-if="bfdPortEnabled"
class="row mt-20"
>
<div class="col span-6">
<LabeledInput
v-model:value="bfdPortIP"
data-testid="vpc-bfd-port-ip"
required
:rules="bfdPortIPRules"
:mode="mode"
:label="t('harvester.vpc.bfdPort.ip.label')"
:placeholder="t('harvester.vpc.bfdPort.ip.placeholder')"
:tooltip="t('harvester.vpc.bfdPort.ip.tooltip')"
/>
</div>
</div>
</Tab>
</ResourceTabs> </ResourceTabs>
</CruResource> </CruResource>
</template> </template>
@@ -1,864 +0,0 @@
<script>
import CruResource from '@shell/components/CruResource';
import NameNsDescription from '@shell/components/form/NameNsDescription';
import ResourceTabs from '@shell/components/form/ResourceTabs';
import Tab from '@shell/components/Tabbed/Tab';
import ArrayList from '@shell/components/form/ArrayList';
import Loading from '@shell/components/Loading';
import MessageLink from '@shell/components/MessageLink';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import UnitInput from '@shell/components/form/UnitInput';
import { LabeledInput } from '@components/Form/LabeledInput';
import { RadioGroup } from '@components/Form/Radio';
import { Banner } from '@components/Banner';
import CreateEditView from '@shell/mixins/create-edit-view';
import { _EDIT, MODE } from '@shell/config/query-params';
import { allHash } from '@shell/utils/promise';
import { isValidIP } from '@shell/utils/validators/cidr';
import { HCI } from '../types';
// Limits from the VpcEgressGateway CRD
const MAX_REPLICAS = 10;
const MAX_BFD_VALUE = 3600000;
const MAX_BANDWIDTH_MBPS = 9223372036854;
// A whole number in Mbps, or a quantity in bits per second such as 100M or 1Gi
const BANDWIDTH_PATTERN = /^([0-9]+|([0-9]+(\.[0-9]+)?|\.[0-9]+)(M|Mi|G|Gi))$/;
const IP_FIELDS = {
internalIPs: { labelKey: 'harvester.egressGateway.ips.internal.label', subnet: 'internalSubnetResource' },
externalIPs: { labelKey: 'harvester.egressGateway.ips.external.label', subnet: 'externalSubnetResource' },
};
const BFD_DEFAULTS = {
enabled: false, minRX: 1000, minTX: 1000, multiplier: 3
};
// PrimaryCNI sends traffic out through the pod's primary network, so it takes no external subnet, external IPs or bandwidth
const ATTACHMENT = 'Attachment';
const PRIMARY_CNI = 'PrimaryCNI';
const isBlank = (value) => value === null || value === undefined || `${ value }`.trim() === '';
const isWholeNumber = (value, min, max) => /^\d+$/.test(`${ value }`.trim()) && Number(value) >= min && Number(value) <= max;
const isValidBandwidth = (value) => BANDWIDTH_PATTERN.test(`${ value }`.trim()) && (!isWholeNumber(value, 0, Infinity) || Number(value) <= MAX_BANDWIDTH_MBPS);
const toBandwidth = (value) => (isWholeNumber(value, 0, Infinity) ? Number(value) : `${ value }`.trim());
const cleanList = (list) => (list || []).map((item) => `${ item || '' }`.trim()).filter(Boolean);
const isValidBfdValue = (value) => isWholeNumber(value, 1, MAX_BFD_VALUE);
const unique = (list) => [...new Set(list)];
// Kube-OVN puts the sources of every policy into two sets, with SNAT and without, and leaves a source out of
// SNAT when any policy has SNAT off for it. The form edits those two sets; IP blocks set outside it are kept.
const policyGroups = (policies = []) => {
const noSnatSubnets = unique(policies.filter((policy) => !policy.snat).flatMap((policy) => policy.subnets || []));
const snatSubnets = unique(policies.filter((policy) => policy.snat).flatMap((policy) => policy.subnets || []))
.filter((subnet) => !noSnatSubnets.includes(subnet));
const ipBlockPolicies = policies
.filter((policy) => policy.ipBlocks?.length)
.map((policy) => ({ snat: !!policy.snat, ipBlocks: [...policy.ipBlocks] }));
return {
snatSubnets, noSnatSubnets, ipBlockPolicies
};
};
export default {
name: 'EditVpcEgressGateway',
emits: ['update:value'],
components: {
ArrayList,
Banner,
CruResource,
LabeledInput,
LabeledSelect,
Loading,
MessageLink,
NameNsDescription,
RadioGroup,
ResourceTabs,
Tab,
UnitInput,
},
mixins: [CreateEditView],
inheritAttrs: false,
props: {
value: {
type: Object,
required: true,
}
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const schema = this.$store.getters[`${ inStore }/schemaFor`](HCI.VPC_EGRESS_GATEWAY);
await allHash({
vpcs: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VPC }),
subnets: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.SUBNET }),
fields: schema?.fetchResourceFields(),
});
// Kube-OVN v1.16 (Harvester v1.10.0-rc1 and older) has no externalNetworkMode and always needs an external subnet
this.supportsPrimaryCNI = !!schema && this.$store.getters[`${ inStore }/pathExistsInSchema`](HCI.VPC_EGRESS_GATEWAY, 'spec.externalNetworkMode');
},
data() {
const spec = this.value?.spec || {};
return {
...policyGroups(spec.policies),
vpc: spec.vpc || '',
replicas: spec.replicas ?? 1,
externalNetworkMode: spec.externalNetworkMode || ATTACHMENT,
supportsPrimaryCNI: false,
internalSubnet: spec.internalSubnet || '',
externalSubnet: spec.externalSubnet || '',
internalIPs: [...(spec.internalIPs || [])],
externalIPs: [...(spec.externalIPs || [])],
bfd: { ...BFD_DEFAULTS, ...spec.bfd },
bandwidthIngress: spec.bandwidth?.ingress ?? '',
bandwidthEgress: spec.bandwidth?.egress ?? '',
};
},
computed: {
allSubnets() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters[`${ inStore }/all`](HCI.SUBNET) || [];
},
vpcOptions() {
const inStore = this.$store.getters['currentProduct'].inStore;
const vpcs = this.$store.getters[`${ inStore }/all`](HCI.VPC) || [];
return vpcs.map((vpc) => ({ label: vpc.id, value: vpc.id }));
},
vpcSubnets() {
return this.allSubnets.filter((subnet) => subnet.spec?.vpc === this.vpc);
},
vpcSubnetOptions() {
return this.vpcSubnets.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
internalSubnetOptions() {
return this.vpcSubnets
.filter((subnet) => subnet.isOverlayAttachment)
.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
externalSubnetOptions() {
return this.allSubnets
.filter((subnet) => subnet.networkAttachment)
.map((subnet) => ({ label: subnet.id, value: subnet.id }));
},
internalSubnetResource() {
return this.allSubnets.find((subnet) => subnet.id === this.internalSubnet);
},
externalSubnetResource() {
return this.allSubnets.find((subnet) => subnet.id === this.externalSubnet);
},
usesPrimaryCNI() {
return this.externalNetworkMode === PRIMARY_CNI;
},
showExternalNetworkMode() {
return this.supportsPrimaryCNI || this.usesPrimaryCNI;
},
externalNetworkModes() {
return [ATTACHMENT, PRIMARY_CNI];
},
externalNetworkModeLabels() {
return [this.t('harvester.egressGateway.externalNetworkMode.attachment'), this.t('harvester.egressGateway.externalNetworkMode.primaryCNI')];
},
selectedVpc() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.vpc ? this.$store.getters[`${ inStore }/byId`](HCI.VPC, this.vpc) : null;
},
// A subnet goes in one of the two groups only, and the gateway's external subnet in neither
snatSubnetOptions() {
return this.vpcSubnetOptions.filter((option) => option.value !== this.externalSubnet && !this.noSnatSubnets.includes(option.value));
},
noSnatSubnetOptions() {
return this.vpcSubnetOptions.filter((option) => option.value !== this.externalSubnet && !this.snatSubnets.includes(option.value));
},
ipBlocksWithSnat() {
return this.ipBlockPolicies.filter((policy) => policy.snat).flatMap((policy) => policy.ipBlocks);
},
ipBlocksWithoutSnat() {
return this.ipBlockPolicies.filter((policy) => !policy.snat).flatMap((policy) => policy.ipBlocks);
},
tabErrors() {
return this.isView ? {
basic: [], policies: [], ips: [], bfd: [], bandwidth: []
} : this.validateTabs();
},
validationPassed() {
return this.validate().length === 0;
},
// Each field shows its own error once touched, so a disabled Save always has a visible reason
nameRules() {
return {
name: [(value) => (value ? undefined : this.t('validation.required', { key: this.t('generic.name') }, true))], namespace: [], description: []
};
},
vpcRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.vpc.label')];
},
internalSubnetRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.internalSubnet.label')];
},
// The policy lists only offer subnets of the chosen VPC, so say why they're empty
policySubnetsPlaceholder() {
if (!this.vpc) {
return this.t('harvester.egressGateway.policies.noVpc');
}
return this.vpcSubnetOptions.length ? this.t('harvester.egressGateway.policies.placeholder') : this.t('harvester.egressGateway.policies.noSubnets', { vpc: this.vpc }, true);
},
internalSubnetPlaceholder() {
if (!this.vpc) {
return this.t('harvester.egressGateway.internalSubnet.noVpc');
}
return this.internalSubnetOptions.length ? this.t('harvester.egressGateway.internalSubnet.placeholder') : this.t('harvester.egressGateway.internalSubnet.none', { vpc: this.vpc }, true);
},
maxReplicas() {
return MAX_REPLICAS;
},
replicasRules() {
return [(value) => (isWholeNumber(value, 0, MAX_REPLICAS) ? undefined : this.t('harvester.egressGateway.validation.replicas', null, true))];
},
externalSubnetRules() {
return [(value) => this.requiredError(value, 'harvester.egressGateway.externalSubnet.label') || (value === this.internalSubnet ? this.t('harvester.egressGateway.validation.sameSubnet', null, true) : undefined)];
},
internalIPRules() {
return [(ip) => this.ipError('internalIPs', ip)];
},
externalIPRules() {
return [(ip) => this.ipError('externalIPs', ip)];
},
ipCountErrors() {
return Object.keys(IP_FIELDS).map((field) => this.ipCountError(field)).filter(Boolean);
},
bfdIntervalRules() {
return [(value) => (isValidBfdValue(value) ? undefined : this.t('harvester.egressGateway.validation.bfd', null, true))];
},
bfdMultiplierRules() {
return [(value) => (isValidBfdValue(value) ? undefined : this.t('harvester.egressGateway.validation.bfdMultiplier', null, true))];
},
bandwidthRules() {
return [(value) => (isBlank(value) || isValidBandwidth(value) ? undefined : this.t('harvester.egressGateway.validation.bandwidth', null, true))];
},
vpcBfdPortDisabled() {
return !!this.selectedVpc && !this.selectedVpc.bfdPortEnabled;
},
vpcEditLocation() {
const location = this.selectedVpc?.detailLocation;
return location ? {
...location, query: { [MODE]: _EDIT }, hash: '#bfdPort'
} : null;
},
},
watch: {
vpc(neu, old) {
if (!old || neu === old) {
return;
}
const vpcSubnets = this.vpcSubnetOptions.map((option) => option.value);
if (!this.internalSubnetOptions.some((option) => option.value === this.internalSubnet)) {
this.internalSubnet = '';
}
this.snatSubnets = this.snatSubnets.filter((subnet) => vpcSubnets.includes(subnet));
this.noSnatSubnets = this.noSnatSubnets.filter((subnet) => vpcSubnets.includes(subnet));
},
// The mode can only be chosen on create; PrimaryCNI rejects the external fields, so they're cleared
externalNetworkMode(neu) {
if (neu === PRIMARY_CNI) {
this.externalSubnet = '';
this.externalIPs = [];
this.bandwidthIngress = '';
this.bandwidthEgress = '';
}
},
},
methods: {
requiredError(value, labelKey) {
return value ? undefined : this.t('validation.required', { key: this.t(labelKey) }, true);
},
ipError(field, ip) {
const value = `${ ip || '' }`.trim();
const { labelKey, subnet: subnetField } = IP_FIELDS[field];
const key = this.t(labelKey);
const subnet = this[subnetField];
if (!value) {
return undefined;
}
if (!isValidIP(value)) {
return this.t('harvester.egressGateway.validation.ipList', { key }, true);
}
if (cleanList(this[field]).filter((other) => other === value).length > 1) {
return this.t('harvester.egressGateway.validation.ipDuplicate', { key }, true);
}
if (subnet && !subnet.canAssignIP(value)) {
return this.t('harvester.egressGateway.validation.ipSubnet', {
key, subnet: subnet.id, cidr: subnet.spec?.cidrBlock
}, true);
}
return undefined;
},
ipCountError(field) {
const ips = cleanList(this[field]);
const replicas = Number(this.replicas);
if (ips.length && ips.length < replicas) {
return this.t('harvester.egressGateway.validation.ipCount', { key: this.t(IP_FIELDS[field].labelKey), replicas }, true);
}
return undefined;
},
policyError() {
const hasSource = this.snatSubnets.length || this.noSnatSubnets.length || this.ipBlockPolicies.length;
if (!hasSource) {
return this.t('harvester.egressGateway.validation.policyRequired', null, true);
}
// Kube-OVN reroutes a policy's sources to the gateway, so its own external subnet would loop back into it
if (this.externalSubnet && [...this.snatSubnets, ...this.noSnatSubnets].includes(this.externalSubnet)) {
return this.t('harvester.egressGateway.validation.policyExternalSubnet', { subnet: this.externalSubnet }, true);
}
return undefined;
},
// One policy for each group that has subnets, then the IP block policies as they were
policiesSpec() {
return [
...(this.snatSubnets.length ? [{ snat: true, subnets: [...this.snatSubnets] }] : []),
...(this.noSnatSubnets.length ? [{ snat: false, subnets: [...this.noSnatSubnets] }] : []),
...this.ipBlockPolicies.map((policy) => ({ ...policy, ipBlocks: [...policy.ipBlocks] })),
];
},
// The errors of each tab, so each tab can be marked and Save stays disabled until there are none
validateTabs() {
const errors = {
basic: [], policies: [], ips: [], bfd: [], bandwidth: []
};
[
['vpc', 'harvester.egressGateway.vpc.label'],
['internalSubnet', 'harvester.egressGateway.internalSubnet.label'],
...(this.externalNetworkMode === PRIMARY_CNI ? [] : [['externalSubnet', 'harvester.egressGateway.externalSubnet.label']]),
].forEach(([field, labelKey]) => {
if (!this[field]) {
errors.basic.push(this.t('validation.required', { key: this.t(labelKey) }, true));
}
});
if (this.internalSubnet && this.internalSubnet === this.externalSubnet) {
errors.basic.push(this.t('harvester.egressGateway.validation.sameSubnet', null, true));
}
if (!isWholeNumber(this.replicas, 0, MAX_REPLICAS)) {
errors.basic.push(this.t('harvester.egressGateway.validation.replicas', null, true));
}
const policyError = this.policyError();
if (policyError) {
errors.policies.push(policyError);
}
Object.keys(IP_FIELDS).forEach((field) => {
const ipError = cleanList(this[field]).map((ip) => this.ipError(field, ip)).find(Boolean);
const error = ipError || this.ipCountError(field);
if (error) {
errors.ips.push(error);
}
});
if (this.bfd.enabled && ['minRX', 'minTX'].some((field) => !isValidBfdValue(this.bfd[field]))) {
errors.bfd.push(this.t('harvester.egressGateway.validation.bfd', null, true));
}
if (this.bfd.enabled && !isValidBfdValue(this.bfd.multiplier)) {
errors.bfd.push(this.t('harvester.egressGateway.validation.bfdMultiplier', null, true));
}
if ([this.bandwidthIngress, this.bandwidthEgress].some((value) => !isBlank(value) && !isValidBandwidth(value))) {
errors.bandwidth.push(this.t('harvester.egressGateway.validation.bandwidth', null, true));
}
return errors;
},
validate() {
const errors = this.value.metadata?.name ? [] : [this.t('validation.required', { key: this.t('generic.name') }, true)];
return [...errors, ...Object.values(this.validateTabs()).flat()];
},
// The intervals are hidden while BFD is off, so a value cleared there falls back to its default
bfdSpec() {
const bfd = { ...this.bfd };
['minRX', 'minTX', 'multiplier'].forEach((field) => {
bfd[field] = isValidBfdValue(bfd[field]) || this.bfd.enabled ? Number(bfd[field]) : BFD_DEFAULTS[field];
});
return bfd;
},
toSpec() {
const spec = {
...(this.value.spec || {}),
vpc: this.vpc,
replicas: Number(this.replicas),
internalSubnet: this.internalSubnet,
externalSubnet: this.externalSubnet,
internalIPs: cleanList(this.internalIPs),
externalIPs: cleanList(this.externalIPs),
policies: this.policiesSpec(),
bfd: this.bfdSpec(),
bandwidth: {
ingress: isBlank(this.bandwidthIngress) ? undefined : toBandwidth(this.bandwidthIngress),
egress: isBlank(this.bandwidthEgress) ? undefined : toBandwidth(this.bandwidthEgress),
},
};
['internalIPs', 'externalIPs', 'policies'].forEach((field) => {
if (!spec[field].length) {
delete spec[field];
}
});
Object.keys(spec.bandwidth).forEach((direction) => {
if (spec.bandwidth[direction] === undefined) {
delete spec.bandwidth[direction];
}
});
if (!Object.keys(spec.bandwidth).length) {
delete spec.bandwidth;
}
// Attachment is the CRD default, so a new gateway only names the mode when it's PrimaryCNI
if (this.externalNetworkMode === PRIMARY_CNI) {
spec.externalNetworkMode = PRIMARY_CNI;
delete spec.externalSubnet;
}
return spec;
},
async saveGateway(buttonCb) {
this.errors = this.validate();
if (this.errors.length) {
buttonCb(false);
return;
}
this.value.spec = this.toSpec();
await this.save(buttonCb);
},
},
};
</script>
<template>
<Loading v-if="$fetchState.pending" />
<CruResource
v-else
:done-route="doneRoute"
:resource="value"
:mode="mode"
:errors="errors"
:validation-passed="validationPassed"
:apply-hooks="applyHooks"
@finish="saveGateway"
@error="e=>errors=e"
>
<NameNsDescription
:value="value"
:mode="mode"
:rules="nameRules"
@update:value="$emit('update:value', $event)"
/>
<ResourceTabs
class="mt-15"
:need-conditions="false"
:need-related="false"
:need-events="false"
:side-tabs="true"
:mode="mode"
>
<Tab
name="basic"
:label="t('generic.basic')"
:weight="99"
:error="tabErrors.basic.length > 0"
:error-icon-tooltip="tabErrors.basic.join(' ')"
>
<div class="row mt-10">
<div class="col span-6">
<LabeledSelect
v-model:value="vpc"
data-testid="egress-gateway-vpc"
class="mb-20"
required
:rules="vpcRules"
:options="vpcOptions"
:mode="mode"
:label="t('harvester.egressGateway.vpc.label')"
:placeholder="t('harvester.egressGateway.vpc.placeholder')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value.number="replicas"
data-testid="egress-gateway-replicas"
class="mb-20"
type="number"
required
:min="0"
:max="maxReplicas"
:mode="mode"
:rules="replicasRules"
:label="t('harvester.egressGateway.replicas.label')"
:tooltip="t('harvester.egressGateway.replicas.tooltip')"
/>
</div>
</div>
<div
v-if="showExternalNetworkMode"
class="row mb-20"
>
<div class="col span-12">
<!-- The CRD makes the mode immutable -->
<RadioGroup
v-model:value="externalNetworkMode"
data-testid="egress-gateway-external-network-mode"
name="externalNetworkMode"
:options="externalNetworkModes"
:labels="externalNetworkModeLabels"
:label="t('harvester.egressGateway.externalNetworkMode.label')"
:tooltip="t('harvester.egressGateway.externalNetworkMode.tooltip')"
:disabled="!isCreate"
:mode="mode"
/>
</div>
</div>
<div class="row">
<div class="col span-6">
<LabeledSelect
v-model:value="internalSubnet"
data-testid="egress-gateway-internal-subnet"
class="mb-20"
required
:options="internalSubnetOptions"
:rules="internalSubnetRules"
:disabled="!vpc"
:mode="mode"
:label="t('harvester.egressGateway.internalSubnet.label')"
:placeholder="internalSubnetPlaceholder"
:tooltip="t('harvester.egressGateway.internalSubnet.tooltip')"
/>
</div>
<div
v-if="!usesPrimaryCNI"
class="col span-6"
>
<LabeledSelect
v-model:value="externalSubnet"
data-testid="egress-gateway-external-subnet"
class="mb-20"
required
:options="externalSubnetOptions"
:mode="mode"
:rules="externalSubnetRules"
:label="t('harvester.egressGateway.externalSubnet.label')"
:placeholder="t('harvester.egressGateway.externalSubnet.placeholder')"
:tooltip="t('harvester.egressGateway.externalSubnet.tooltip')"
/>
</div>
</div>
</Tab>
<Tab
name="policies"
:label="t('harvester.egressGateway.policies.label')"
:weight="98"
:error="tabErrors.policies.length > 0"
:error-icon-tooltip="tabErrors.policies.join(' ')"
>
<p
v-if="!isView"
class="text-muted mb-20"
>
{{ t('harvester.egressGateway.policies.description') }}
</p>
<!-- One subnet in either list is enough, so the rule is shown once for both lists -->
<Banner
v-if="vpc && tabErrors.policies.length"
color="error"
data-testid="egress-gateway-policy-error"
:label="tabErrors.policies[0]"
/>
<div class="row">
<div class="col span-6">
<LabeledSelect
v-model:value="snatSubnets"
data-testid="egress-gateway-snat-subnets"
:disabled="!vpc"
:append-to-body="false"
:multiple="true"
:options="snatSubnetOptions"
:mode="mode"
:label="t('harvester.egressGateway.policies.snatSubnets.label')"
:placeholder="policySubnetsPlaceholder"
:tooltip="t('harvester.egressGateway.policies.snatSubnets.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledSelect
v-model:value="noSnatSubnets"
data-testid="egress-gateway-no-snat-subnets"
:disabled="!vpc"
:append-to-body="false"
:multiple="true"
:options="noSnatSubnetOptions"
:mode="mode"
:label="t('harvester.egressGateway.policies.noSnatSubnets.label')"
:placeholder="policySubnetsPlaceholder"
:tooltip="t('harvester.egressGateway.policies.noSnatSubnets.tooltip')"
/>
</div>
</div>
<div
v-if="ipBlocksWithSnat.length || ipBlocksWithoutSnat.length"
class="row mt-20"
>
<div class="col span-6">
<LabeledInput
v-if="ipBlocksWithSnat.length"
data-testid="egress-gateway-snat-ip-blocks"
:value="ipBlocksWithSnat.join(', ')"
mode="view"
:label="t('harvester.egressGateway.policies.ipBlocks.snat')"
:tooltip="t('harvester.egressGateway.policies.ipBlocks.tooltip')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-if="ipBlocksWithoutSnat.length"
data-testid="egress-gateway-no-snat-ip-blocks"
:value="ipBlocksWithoutSnat.join(', ')"
mode="view"
:label="t('harvester.egressGateway.policies.ipBlocks.noSnat')"
:tooltip="t('harvester.egressGateway.policies.ipBlocks.tooltip')"
/>
</div>
</div>
</Tab>
<Tab
name="ips"
:label="t('harvester.egressGateway.ips.label')"
:weight="97"
:error="tabErrors.ips.length > 0"
:error-icon-tooltip="tabErrors.ips.join(' ')"
>
<Banner
v-if="!isView"
color="info"
:label="usesPrimaryCNI ? t('harvester.egressGateway.ips.bannerPrimaryCNI') : t('harvester.egressGateway.ips.banner')"
/>
<Banner
v-for="error in ipCountErrors"
:key="error"
color="error"
:label="error"
/>
<ArrayList
v-model:value="internalIPs"
class="mt-20"
:rules="internalIPRules"
:mode="mode"
:title="t('harvester.egressGateway.ips.internal.label')"
:add-label="t('harvester.egressGateway.ips.internal.add')"
:value-placeholder="t('harvester.egressGateway.ips.internal.placeholder')"
/>
<ArrayList
v-if="!usesPrimaryCNI"
v-model:value="externalIPs"
class="mt-20"
:rules="externalIPRules"
:mode="mode"
:title="t('harvester.egressGateway.ips.external.label')"
:add-label="t('harvester.egressGateway.ips.external.add')"
:value-placeholder="t('harvester.egressGateway.ips.external.placeholder')"
/>
</Tab>
<Tab
name="bfd"
:label="t('harvester.egressGateway.bfd.label')"
:weight="96"
:error="tabErrors.bfd.length > 0"
:error-icon-tooltip="tabErrors.bfd.join(' ')"
>
<RadioGroup
v-model:value="bfd.enabled"
name="bfd"
:options="[true, false]"
:labels="[t('generic.enabled'), t('generic.disabled')]"
:label="t('harvester.egressGateway.bfd.enabled')"
:tooltip="t('harvester.egressGateway.bfd.tooltip')"
:mode="mode"
/>
<template v-if="bfd.enabled">
<Banner
v-if="vpcBfdPortDisabled"
color="warning"
>
<MessageLink
:to="vpcEditLocation"
target="_blank"
:prefix="t('harvester.egressGateway.bfd.vpcBfdPort.prefix', { vpc }, true)"
:middle="t('harvester.egressGateway.bfd.vpcBfdPort.middle')"
:suffix="t('harvester.egressGateway.bfd.vpcBfdPort.suffix')"
/>
</Banner>
<div class="row mt-20">
<div class="col span-4">
<UnitInput
v-model:value="bfd.minRX"
:min="1"
:mode="mode"
required
:rules="bfdIntervalRules"
:label="t('harvester.egressGateway.bfd.minRX.label')"
:tooltip="t('harvester.egressGateway.bfd.minRX.tooltip')"
:suffix="t('harvester.egressGateway.bfd.milliseconds')"
/>
</div>
<div class="col span-4">
<UnitInput
v-model:value="bfd.minTX"
:min="1"
:mode="mode"
required
:rules="bfdIntervalRules"
:label="t('harvester.egressGateway.bfd.minTX.label')"
:tooltip="t('harvester.egressGateway.bfd.minTX.tooltip')"
:suffix="t('harvester.egressGateway.bfd.milliseconds')"
/>
</div>
<div class="col span-4">
<LabeledInput
v-model:value.number="bfd.multiplier"
type="number"
:min="1"
:mode="mode"
required
:rules="bfdMultiplierRules"
:label="t('harvester.egressGateway.bfd.multiplier.label')"
:tooltip="t('harvester.egressGateway.bfd.multiplier.tooltip')"
/>
</div>
</div>
</template>
</Tab>
<Tab
v-if="!usesPrimaryCNI"
name="bandwidth"
:label="t('harvester.egressGateway.bandwidth.label')"
:weight="95"
:error="tabErrors.bandwidth.length > 0"
:error-icon-tooltip="tabErrors.bandwidth.join(' ')"
>
<Banner
v-if="!isView"
color="info"
:label="t('harvester.egressGateway.bandwidth.banner')"
/>
<div class="row mt-20">
<div class="col span-6">
<LabeledInput
v-model:value="bandwidthIngress"
data-testid="egress-gateway-bandwidth-ingress"
:mode="mode"
:rules="bandwidthRules"
:label="t('harvester.egressGateway.bandwidth.ingress.label')"
:placeholder="t('harvester.egressGateway.bandwidth.placeholder')"
/>
</div>
<div class="col span-6">
<LabeledInput
v-model:value="bandwidthEgress"
data-testid="egress-gateway-bandwidth-egress"
:mode="mode"
:rules="bandwidthRules"
:label="t('harvester.egressGateway.bandwidth.egress.label')"
:placeholder="t('harvester.egressGateway.bandwidth.placeholder')"
/>
</div>
</div>
</Tab>
</ResourceTabs>
</CruResource>
</template>
@@ -2,6 +2,7 @@
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox'; import { Checkbox } from '@components/Form/Checkbox';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { _VIEW } from '@shell/config/query-params';
import { DISK_CACHE_MODE, DISK_IO_MODE, DISK_PERFORMANCE_PROFILE } from '../../../config/harvester-map'; import { DISK_CACHE_MODE, DISK_IO_MODE, DISK_PERFORMANCE_PROFILE } from '../../../config/harvester-map';
const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE; const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE;
@@ -30,18 +31,23 @@ export default {
}, },
data() { data() {
const hasPerf = !!(this.value.cache || this.value.io || this.value.dedicatedIOThread);
return { return {
DISK_PERFORMANCE_PROFILE, DISK_PERFORMANCE_PROFILE,
expanded: hasPerf,
profile: this.detectProfile(), profile: this.detectProfile(),
// Bus the disk used before the "High Performance" preset switched it to // Bus the disk used before the "High Performance" preset switched it to
// virtio, so returning to "Default" can put it back. // virtio, so returning to "Default" can put it back.
busBeforeHighProfile: null, busBeforeHighProfile: null,
// True only while the user has explicitly picked "Custom" in the selector.
userSelectedCustom: false,
}; };
}, },
computed: { computed: {
isView() {
return this.mode === _VIEW;
},
storagePerformanceEnabled() { storagePerformanceEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage'); return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
}, },
@@ -97,13 +103,13 @@ export default {
watch: { watch: {
// Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM). // Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM).
'value.cache'() { 'value.cache'() {
this.syncProfile(); this.profile = this.detectProfile();
}, },
'value.io'() { 'value.io'() {
this.syncProfile(); this.profile = this.detectProfile();
}, },
'value.dedicatedIOThread'() { 'value.dedicatedIOThread'() {
this.syncProfile(); this.profile = this.detectProfile();
}, },
}, },
@@ -122,16 +128,6 @@ export default {
return CUSTOM; return CUSTOM;
}, },
syncProfile() {
// An explicit "Custom" choice sticks, even if the options happen to
// match the Default or High Performance preset. An inferred "Custom"
// still follows the disk values.
if (this.userSelectedCustom) {
return;
}
this.profile = this.detectProfile();
},
cacheLabel(value) { cacheLabel(value) {
if (value === '') { if (value === '') {
return this.t('harvester.virtualMachine.volume.performance.cacheMode.default'); return this.t('harvester.virtualMachine.volume.performance.cacheMode.default');
@@ -144,7 +140,6 @@ export default {
const previous = this.profile; const previous = this.profile;
this.profile = profile; this.profile = profile;
this.userSelectedCustom = profile === CUSTOM;
if (profile === DEFAULT) { if (profile === DEFAULT) {
this.value.cache = ''; this.value.cache = '';
@@ -198,49 +193,51 @@ export default {
v-if="!isCdRom && storagePerformanceEnabled" v-if="!isCdRom && storagePerformanceEnabled"
class="disk-performance" class="disk-performance"
> >
<div class="row mb-20"> <button
<div v-if="!isView"
class="col span-6" type="button"
data-testid="input-disk-perf-profile" class="btn btn-sm role-link expand-toggle"
> :aria-expanded="expanded"
<LabeledSelect :aria-label="expanded ? t('harvester.virtualMachine.volume.performance.collapse') : t('harvester.virtualMachine.volume.performance.expand')"
:value="profile" @click.prevent="expanded = !expanded"
:label="t('harvester.virtualMachine.volume.performance.profile.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.profile.tip')"
:options="profileOptions"
:mode="mode"
@update:value="onProfileChange"
/>
</div>
</div>
<Banner
v-if="profile === DISK_PERFORMANCE_PROFILE.HIGH"
color="info"
label-key="harvester.virtualMachine.volume.performance.highProfileTip"
/>
<!-- Always rendered, so screen readers announce these warnings when changing the fields below makes them appear
above the focused field -->
<div
role="status"
data-testid="disk-perf-warning-status"
> >
<Banner <i
v-if="showBusTip" class="icon"
color="warning" :class="expanded ? 'icon-chevron-down' : 'icon-chevron-right'"
data-testid="disk-perf-bus-tip"
:label="t('harvester.virtualMachine.volume.performance.busTip', { bus: value.bus }, true)"
/> />
<Banner {{ t('harvester.virtualMachine.volume.performance.title') }}
v-if="showFilesystemCacheWarning" </button>
color="warning"
label-key="harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning"
/>
</div>
<template v-if="isCustom"> <div
v-if="expanded || isView"
class="perf-body mt-10"
>
<div class="row mb-20"> <div class="row mb-20">
<div
class="col span-6"
data-testid="input-disk-perf-profile"
>
<LabeledSelect
:value="profile"
:label="t('harvester.virtualMachine.volume.performance.profile.label')"
:tooltip="t('harvester.virtualMachine.volume.performance.profile.tip')"
:options="profileOptions"
:mode="mode"
@update:value="onProfileChange"
/>
</div>
</div>
<Banner
v-if="profile === DISK_PERFORMANCE_PROFILE.HIGH"
color="info"
:label="t('harvester.virtualMachine.volume.performance.highProfileTip')"
/>
<div
v-if="isCustom || isView"
class="row mb-20"
>
<div <div
class="col span-6" class="col span-6"
data-testid="input-disk-cache" data-testid="input-disk-cache"
@@ -269,7 +266,10 @@ export default {
</div> </div>
</div> </div>
<div class="row mb-20"> <div
v-if="isCustom || isView"
class="row mb-10"
>
<div <div
class="col span-12" class="col span-12"
data-testid="input-disk-dedicated-iothread" data-testid="input-disk-dedicated-iothread"
@@ -283,19 +283,39 @@ export default {
/> />
</div> </div>
</div> </div>
</template>
<!-- Always rendered, also outside Custom, so screen readers announce the tip when picking Native I/O changes
the cache mode, even if the new values switch the profile to High Performance -->
<div
role="status"
data-testid="disk-perf-native-status"
>
<Banner <Banner
v-if="isNativeIo" v-if="isNativeIo"
color="info" color="info"
label-key="harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip" :label="t('harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip')"
/>
<Banner
v-if="showFilesystemCacheWarning"
color="warning"
:label="t('harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning')"
/>
<Banner
v-if="showBusTip"
color="warning"
:label="t('harvester.virtualMachine.volume.performance.busTip')"
/> />
</div> </div>
</div> </div>
</template> </template>
<style lang="scss" scoped>
.disk-performance {
border-top: 1px solid var(--border);
margin-top: 10px;
padding-top: 10px;
.expand-toggle {
padding: 0;
font-weight: 600;
.icon {
margin-right: 4px;
}
}
}
</style>
@@ -1,4 +1,5 @@
<script> <script>
import InfoBox from '@shell/components/InfoBox';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import { Checkbox } from '@components/Form/Checkbox'; import { Checkbox } from '@components/Form/Checkbox';
@@ -10,7 +11,7 @@ export default {
name: 'VMPerformanceOptions', name: 'VMPerformanceOptions',
components: { components: {
LabeledSelect, LabeledInput, Checkbox, Banner InfoBox, LabeledSelect, LabeledInput, Checkbox, Banner
}, },
emits: ['update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'], emits: ['update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
@@ -49,6 +50,12 @@ export default {
}, },
}, },
data() {
// These are specialist tuning options, so keep the panel collapsed unless the
// VM already has something configured.
return { expanded: !!(this.blockMultiQueue || this.ioThreadsPolicy) };
},
computed: { computed: {
isView() { isView() {
return this.mode === _VIEW; return this.mode === _VIEW;
@@ -80,71 +87,105 @@ export default {
</script> </script>
<template> <template>
<div <InfoBox
v-if="storagePerformanceEnabled && (!isView || blockMultiQueue || !!ioThreadsPolicy)" v-if="storagePerformanceEnabled && (!isView || blockMultiQueue || !!ioThreadsPolicy)"
class="vm-perf" class="vm-perf mt-10"
> >
<h3> <button
v-if="!isView"
type="button"
class="btn btn-sm role-link expand-toggle"
:aria-expanded="expanded"
:aria-label="expanded ? t('harvester.virtualMachine.volume.diskPerformance.collapse') : t('harvester.virtualMachine.volume.diskPerformance.expand')"
@click.prevent="expanded = !expanded"
>
<i
class="icon"
:class="expanded ? 'icon-chevron-down' : 'icon-chevron-right'"
/>
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
</button>
<h3
v-else
class="mb-5"
>
{{ t('harvester.virtualMachine.volume.diskPerformance.title') }} {{ t('harvester.virtualMachine.volume.diskPerformance.title') }}
</h3> </h3>
<p class="text-muted mb-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<div <template v-if="expanded || isView">
class="mb-10" <p class="text-muted mb-15 mt-10">
data-testid="input-vm-block-multi-queue" {{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
> </p>
<Checkbox
:value="blockMultiQueue" <div class="row mb-10">
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.label')" <div
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.tip')" class="col span-12"
:mode="mode" data-testid="input-vm-block-multi-queue"
:disabled="!hasVirtioDisk" >
@update:value="$emit('update:blockMultiQueue', $event)" <Checkbox
:value="blockMultiQueue"
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.tip')"
:mode="mode"
:disabled="!hasVirtioDisk"
@update:value="$emit('update:blockMultiQueue', $event)"
/>
</div>
</div>
<Banner
v-if="!hasVirtioDisk && !isView"
color="info"
:label="t('harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip')"
/> />
</div>
<Banner
v-if="!hasVirtioDisk && !isView"
color="info"
label-key="harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip"
/>
<div class="row mb-20"> <div class="row mb-10">
<div <div
class="col span-6" class="col span-6"
data-testid="input-vm-iothreads-policy" data-testid="input-vm-iothreads-policy"
> >
<LabeledSelect <LabeledSelect
:value="ioThreadsPolicy" :value="ioThreadsPolicy"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')" :label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')" :tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
:options="ioThreadsPolicyOptions" :options="ioThreadsPolicyOptions"
:mode="mode" :mode="mode"
@update:value="$emit('update:ioThreadsPolicy', $event)" @update:value="$emit('update:ioThreadsPolicy', $event)"
/> />
</div>
<div
v-if="ioThreadsPolicy === 'supplementalPool'"
class="col span-6"
data-testid="input-vm-iothread-count"
>
<LabeledInput
type="number"
min="1"
:value="ioThreadCount"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.tip')"
:mode="mode"
@update:value="$emit('update:ioThreadCount', Number($event))"
/>
</div>
</div> </div>
<div <Banner
v-if="ioThreadsPolicy === 'supplementalPool'" v-if="hasDedicatedIothread && !ioThreadsPolicy"
class="col span-6" color="info"
data-testid="input-vm-iothread-count" :label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip')"
> />
<LabeledInput </template>
type="integer" </InfoBox>
min="1"
:required="!isView"
:value="ioThreadCount"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadCount.tip')"
:mode="mode"
@update:value="$emit('update:ioThreadCount', Number($event))"
/>
</div>
</div>
<Banner
v-if="hasDedicatedIothread && !ioThreadsPolicy"
color="info"
label-key="harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip"
/>
</div>
</template> </template>
<style lang="scss" scoped>
.vm-perf {
.expand-toggle {
padding: 0;
font-weight: 600;
.icon {
margin-right: 4px;
}
}
}
</style>
@@ -1,10 +1,5 @@
import fs from 'fs';
import path from 'path';
import { load } from 'js-yaml';
import { mount } from '@vue/test-utils'; import { mount } from '@vue/test-utils';
import { nextTick } from 'vue';
import { _EDIT } from '@shell/config/query-params'; import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import DiskPerformanceOptions from '../DiskPerformanceOptions.vue'; import DiskPerformanceOptions from '../DiskPerformanceOptions.vue';
const mountOptions = (value, { featureEnabled = true } = {}) => ({ const mountOptions = (value, { featureEnabled = true } = {}) => ({
@@ -27,12 +22,6 @@ const hardDisk = (overrides = {}) => ({
type: 'disk', bus: 'virtio', cache: '', io: '', dedicatedIOThread: false, ...overrides type: 'disk', bus: 'virtio', cache: '', io: '', dedicatedIOThread: false, ...overrides
}); });
const nativeTip = (wrapper) => wrapper.findAllComponents(Banner)
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.ioMode.nativeRequiresNoCacheTip');
const filesystemWarning = (wrapper) => wrapper.findAllComponents(Banner)
.find((b) => b.props('labelKey') === 'harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning');
describe('component: DiskPerformanceOptions', () => { describe('component: DiskPerformanceOptions', () => {
it('is hidden when the highPerformanceStorage feature is disabled', () => { it('is hidden when the highPerformanceStorage feature is disabled', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(), { featureEnabled: false })); const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(), { featureEnabled: false }));
@@ -46,102 +35,6 @@ describe('component: DiskPerformanceOptions', () => {
expect(wrapper.find('.disk-performance').exists()).toBe(true); expect(wrapper.find('.disk-performance').exists()).toBe(true);
}); });
it('shows the profile without a toggle, and the individual fields only for Custom', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-disk-perf-profile"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(false);
});
it('shows the individual fields for a disk with custom options', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback', io: 'threads' })));
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-io"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-disk-dedicated-iothread"]').exists()).toBe(true);
});
it('is hidden for a CD-ROM', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ type: 'cd-rom' })));
expect(wrapper.find('.disk-performance').exists()).toBe(false);
});
it('names the bus in the bus tip once the disk uses an option', () => {
const plain = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata' })));
const tuned = mount(DiskPerformanceOptions, mountOptions(hardDisk({ bus: 'sata', cache: 'writeback' })));
expect(plain.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
expect(tuned.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
});
it('says in the bus tip that a dedicated I/O thread needs the virtio bus', () => {
const translations = load(fs.readFileSync(path.join(__dirname, '../../../../l10n/en-us.yaml'), 'utf8'));
const { busTip } = translations.harvester.virtualMachine.volume.performance;
expect(busTip).toContain('{bus}');
expect(busTip).toContain('A dedicated I/O thread needs the virtio bus');
});
it('shows the bus tip and the Filesystem warning inside a live region that is there before they appear', async() => {
const disk = { bus: 'sata', volumeMode: 'Filesystem' };
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(disk)));
const status = wrapper.find('[data-testid="disk-perf-warning-status"]');
expect(status.attributes('role')).toBe('status');
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(false);
expect(filesystemWarning(wrapper)).toBeUndefined();
await wrapper.setProps({ value: hardDisk({ ...disk, cache: 'none' }) });
expect(wrapper.find('[data-testid="disk-perf-warning-status"]').element).toBe(status.element);
expect(status.find('[data-testid="disk-perf-bus-tip"]').exists()).toBe(true);
expect(status.element.contains(filesystemWarning(wrapper)?.element)).toBe(true);
});
it('shows the Native I/O tip inside a live region that is there before Native I/O is picked', async() => {
const value = hardDisk({ cache: 'writeback', io: 'threads' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
expect(status.attributes('role')).toBe('status');
expect(nativeTip(wrapper)).toBeUndefined();
wrapper.vm.onIoChange('native');
await wrapper.vm.$nextTick();
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
});
it('keeps the live region and the Native I/O tip when picking Native I/O switches Custom to High Performance', async() => {
const value = hardDisk({
cache: 'writeback', io: 'threads', dedicatedIOThread: true
});
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
const status = wrapper.find('[data-testid="disk-perf-native-status"]');
expect(wrapper.vm.profile).toBe('custom');
wrapper.vm.onIoChange('native');
await wrapper.vm.$nextTick();
expect(wrapper.vm.profile).toBe('highPerformance');
expect(wrapper.find('[data-testid="input-disk-cache"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="disk-perf-native-status"]').element).toBe(status.element);
expect(status.element.contains(nativeTip(wrapper)?.element)).toBe(true);
});
it('passes the Filesystem warning as a label key so its quotes are not double-escaped', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'none', volumeMode: 'Filesystem' })));
const banner = filesystemWarning(wrapper);
expect(banner).toBeDefined();
expect(banner?.props('label')).toBeFalsy();
});
it('applies the High Performance preset and emits update', () => { it('applies the High Performance preset and emits update', () => {
const value = hardDisk(); const value = hardDisk();
const wrapper = mount(DiskPerformanceOptions, mountOptions(value)); const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
@@ -229,58 +122,4 @@ describe('component: DiskPerformanceOptions', () => {
expect(disabledByValue['writeback']).toBe(true); expect(disabledByValue['writeback']).toBe(true);
expect(disabledByValue['writethrough']).toBe(true); expect(disabledByValue['writethrough']).toBe(true);
}); });
it.each([
['Default', {
cache: '', io: '', dedicatedIOThread: false
}],
['High Performance', {
cache: 'none', io: 'native', dedicatedIOThread: true
}],
])('stays on Custom when the options match the %s preset', async(_label, opts) => {
const value = hardDisk({ cache: 'writeback' });
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
wrapper.vm.onProfileChange('custom');
await wrapper.setProps({ value: { ...value, ...opts } });
await nextTick();
expect(wrapper.vm.profile).toBe('custom');
});
it('detects the profile from an existing disk', async() => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk()));
expect(wrapper.vm.profile).toBe('default');
await wrapper.setProps({
value: hardDisk({
cache: 'none', io: 'native', dedicatedIOThread: true
})
});
expect(wrapper.vm.profile).toBe('highPerformance');
});
it('updates an automatically detected Custom profile when preset values are loaded', async() => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ cache: 'writeback' })));
expect(wrapper.vm.profile).toBe('custom');
await wrapper.setProps({
value: hardDisk({
cache: 'none', io: 'native', dedicatedIOThread: true
})
});
expect(wrapper.vm.profile).toBe('highPerformance');
});
it('passes the Native I/O hint as a label key so its quotes are not double-escaped', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk({ io: 'native' })));
const banner = nativeTip(wrapper);
expect(banner).toBeDefined();
expect(banner?.props('label')).toBeFalsy();
});
}); });
@@ -1,105 +0,0 @@
import { mount } from '@vue/test-utils';
import { _CREATE, _VIEW } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import VMPerformanceOptions from '../VMPerformanceOptions.vue';
const AUTO_ENABLED_TIP = 'harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip';
const NO_VIRTIO_TIP = 'harvester.virtualMachine.volume.diskPerformance.blockMultiQueue.noVirtioTip';
function mountOptions(props = {}, { featureEnabled = true } = {}) {
return mount(VMPerformanceOptions, {
props: { mode: _CREATE, ...props },
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => featureEnabled,
'i18n/t': (key) => key,
'i18n/exists': () => true,
}
},
t: (key) => key,
},
},
});
}
function bannerFor(wrapper, labelKey) {
return wrapper.findAllComponents(Banner).find((b) => b.props('labelKey') === labelKey);
}
describe('component: VMPerformanceOptions', () => {
it('should be hidden when the highPerformanceStorage feature is disabled', () => {
const wrapper = mountOptions({}, { featureEnabled: false });
expect(wrapper.find('.vm-perf').exists()).toBe(false);
});
it('should show the section with its title and fields, without a toggle', () => {
const wrapper = mountOptions();
expect(wrapper.find('h3').text()).toBe('harvester.virtualMachine.volume.diskPerformance.title');
expect(wrapper.find('.expand-toggle').exists()).toBe(false);
expect(wrapper.find('[data-testid="input-vm-block-multi-queue"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-vm-iothreads-policy"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="input-vm-iothread-count"]').exists()).toBe(false);
});
it('should only accept whole numbers as the supplemental pool thread count', () => {
const wrapper = mountOptions({ ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4 });
const input = wrapper.find('[data-testid="input-vm-iothread-count"] input');
expect(input.attributes('inputmode')).toBe('numeric');
});
it.each([
[_CREATE, true],
[_VIEW, false],
])('in %s mode, should mark the supplemental pool thread count as required: %p', (mode, required) => {
const wrapper = mountOptions({
mode, ioThreadsPolicy: 'supplementalPool', ioThreadCount: 4
});
expect(wrapper.find('[data-testid="input-vm-iothread-count"] .required').exists()).toBe(required);
});
it.each([
[{}, false],
[{ blockMultiQueue: true }, true],
[{ ioThreadsPolicy: 'auto' }, true],
])('in view mode with %p, should show the section: %p', (props, shown) => {
const wrapper = mountOptions({ ...props, mode: _VIEW });
expect(wrapper.find('.vm-perf').exists()).toBe(shown);
});
it('should clear Block Multi-Queue when the last virtio disk goes away', async() => {
const wrapper = mountOptions({ blockMultiQueue: true, hasVirtioDisk: true });
await wrapper.setProps({ hasVirtioDisk: false });
expect(wrapper.emitted('update:blockMultiQueue')).toStrictEqual([[false]]);
});
it('should pass the I/O threads policy hint as a label key so its quotes are not double-escaped', () => {
const wrapper = mountOptions({ hasDedicatedIothread: true });
const banner = bannerFor(wrapper, AUTO_ENABLED_TIP);
expect(banner).toBeDefined();
expect(banner.props('label')).toBeFalsy();
});
it('should not show the I/O threads policy hint when a policy is set', () => {
const wrapper = mountOptions({ hasDedicatedIothread: true, ioThreadsPolicy: 'shared' });
expect(bannerFor(wrapper, AUTO_ENABLED_TIP)).toBeUndefined();
});
it('should pass the no virtio disk hint as a label key', () => {
const wrapper = mountOptions({ hasVirtioDisk: false });
const banner = bannerFor(wrapper, NO_VIRTIO_TIP);
expect(banner).toBeDefined();
expect(banner.props('label')).toBeFalsy();
});
});
@@ -7,6 +7,7 @@ import UnitInput from '@shell/components/form/UnitInput';
import { LabeledInput } from '@components/Form/LabeledInput'; import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect'; import LabeledSelect from '@shell/components/form/LabeledSelect';
import ModalWithCard from '@shell/components/ModalWithCard'; import ModalWithCard from '@shell/components/ModalWithCard';
import VMPerformanceOptions from './VMPerformanceOptions';
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map'; import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
import { PVC, STORAGE_CLASS } from '@shell/config/types'; import { PVC, STORAGE_CLASS } from '@shell/config/types';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
@@ -23,10 +24,10 @@ import { EMPTY_IMAGE } from '../../../utils/vm';
const { READ_WRITE_MANY } = ACCESS_MODE; const { READ_WRITE_MANY } = ACCESS_MODE;
export default { export default {
emits: ['update:value'], emits: ['update:value', 'update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
components: { components: {
Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard, VMPerformanceOptions
}, },
props: { props: {
@@ -77,6 +78,22 @@ export default {
resourceType: { resourceType: {
type: String, type: String,
default: '' default: ''
},
// KubeVirt high-performance VM-level features
blockMultiQueue: {
type: Boolean,
default: false
},
ioThreadsPolicy: {
type: String,
default: ''
},
ioThreadCount: {
type: Number,
default: 2
} }
}, },
@@ -147,6 +164,14 @@ export default {
isLHV2VolExpansionFeatureEnabled() { isLHV2VolExpansionFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('lhV2VolExpansion'); return this.$store.getters['harvester-common/getFeatureEnabled']('lhV2VolExpansion');
}, },
hasVirtioDisk() {
return this.rows.some((R) => R.type === 'disk' && R.bus === 'virtio');
},
hasDedicatedIOThread() {
return this.rows.some((R) => R.dedicatedIOThread);
},
}, },
watch: { watch: {
@@ -508,6 +533,18 @@ export default {
</button> </button>
</div> </div>
<VMPerformanceOptions
:block-multi-queue="blockMultiQueue"
:io-threads-policy="ioThreadsPolicy"
:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
@update:block-multi-queue="$emit('update:blockMultiQueue', $event)"
@update:io-threads-policy="$emit('update:ioThreadsPolicy', $event)"
@update:io-thread-count="$emit('update:ioThreadCount', $event)"
/>
<ModalWithCard <ModalWithCard
v-if="isOpen" v-if="isOpen"
name="deleteTip" name="deleteTip"
@@ -51,11 +51,4 @@ describe('component: HarvesterEditContainer', () => {
expect(wrapper.emitted('update')).toHaveLength(1); expect(wrapper.emitted('update')).toHaveLength(1);
}); });
it('should not render an empty row when there is no backup to show', () => {
const wrapper = mount(HarvesterEditContainer, mountOptions());
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
expect(emptyRows).toHaveLength(0);
});
}); });
@@ -133,30 +133,4 @@ describe('component: HarvesterEditVMImage', () => {
expect(wrapper.emitted('update')).toHaveLength(1); expect(wrapper.emitted('update')).toHaveLength(1);
}); });
it('should not render an empty row when there is no backup to show', () => {
const wrapper = mount(HarvesterEditVMImage, {
props: {
mode: _CREATE,
isVirtualType: false,
newCreateId: '123',
validateRequired: true,
idx: 1
},
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/all': jest.fn(),
'i18n/t': jest.fn(),
}
},
}
}
});
const emptyRows = wrapper.findAll('.row').filter((row) => row.element.children.length === 0);
expect(emptyRows).toHaveLength(0);
});
}); });
@@ -132,11 +132,11 @@ export default {
</InputOrDisplay> </InputOrDisplay>
</div> </div>
</div> </div>
<div <div class="row mb-20">
v-if="value.volumeBackups" <div
class="row mb-20" v-if="value.volumeBackups"
> class="col span-6"
<div class="col span-6"> >
<InputOrDisplay <InputOrDisplay
:name="t('harvester.virtualMachine.volume.readyToUse')" :name="t('harvester.virtualMachine.volume.readyToUse')"
:value="value.volumeBackups.readyToUse" :value="value.volumeBackups.readyToUse"
@@ -461,11 +461,11 @@ export default {
/> />
</div> </div>
</div> </div>
<div <div class="row mb-20">
v-if="value.volumeBackups && isView" <div
class="row mb-20" v-if="value.volumeBackups && isView"
> class="col span-3"
<div class="col span-3"> >
<LabelValue <LabelValue
:name="t('harvester.virtualMachine.volume.readyToUse')" :name="t('harvester.virtualMachine.volume.readyToUse')"
:value="readyToUse" :value="readyToUse"
@@ -1,143 +0,0 @@
import { readFileSync } from 'fs';
import { resolve } from 'path';
import { STORAGE_CLASS } from '@shell/config/types';
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
import HarvesterEditVM from '../index.vue';
const vmFormSource = readFileSync(resolve(__dirname, '../index.vue'), 'utf8');
const translations = readFileSync(resolve(__dirname, '../../../l10n/en-us.yaml'), 'utf8');
function saveWith(userScript) {
const buttonCb = jest.fn();
const form = {
userScript,
errors: [],
isSingle: true,
t: (key) => key,
validateCPUMemory: jest.fn(),
validateWindowsSysprep: jest.fn(),
validateCloudInit: VM_MIXIN.methods.validateCloudInit,
saveSingle: jest.fn(),
};
HarvesterEditVM.methods.saveVM.call(form, buttonCb);
return { form, buttonCb };
}
describe('page: kubevirt.io.virtualmachine edit', () => {
it('shows the persistent state storage hint only when vmstate-persistence is missing', () => {
const hasVMStateStorageClass = HarvesterEditVM.computed.hasVMStateStorageClass;
const storageClasses = (storageClassNames) => ({
inStore: 'harvester',
$store: { getters: { 'harvester/all': (type) => type === STORAGE_CLASS ? storageClassNames.map((name) => ({ metadata: { name } })) : [] } },
});
expect(hasVMStateStorageClass.call(storageClasses([]))).toBe(false);
expect(hasVMStateStorageClass.call(storageClasses(['vmstate-persistence']))).toBe(true);
});
it('waits for StorageClasses before treating vmstate-persistence as unavailable', () => {
const vmStateStorageClassUnavailable = HarvesterEditVM.computed.vmStateStorageClassUnavailable;
expect(vmStateStorageClassUnavailable.call({ hasVMStateStorageClass: false, storageClassesLoaded: false })).toBe(false);
expect(vmStateStorageClassUnavailable.call({ hasVMStateStorageClass: false, storageClassesLoaded: true })).toBe(true);
expect(vmStateStorageClassUnavailable.call({ hasVMStateStorageClass: true, storageClassesLoaded: true })).toBe(false);
});
it('shows the persistent state storage banner outside view mode when vmstate-persistence is unavailable', () => {
const showPersistentStateStorageBanner = HarvesterEditVM.computed.showPersistentStateStorageBanner;
expect(showPersistentStateStorageBanner.call({ mode: 'create', vmStateStorageClassUnavailable: true })).toBe(true);
expect(showPersistentStateStorageBanner.call({ mode: 'edit', vmStateStorageClassUnavailable: true })).toBe(true);
expect(showPersistentStateStorageBanner.call({ mode: 'create', vmStateStorageClassUnavailable: false })).toBe(false);
expect(showPersistentStateStorageBanner.call({ mode: 'view', vmStateStorageClassUnavailable: true })).toBe(false);
});
it('blocks new persistent state without vmstate-persistence while allowing it to be turned off', () => {
const isPersistentStateControlDisabled = HarvesterEditVM.methods.isPersistentStateControlDisabled;
expect(isPersistentStateControlDisabled.call({ vmStateStorageClassUnavailable: false }, false)).toBe(false);
expect(isPersistentStateControlDisabled.call({ vmStateStorageClassUnavailable: true }, false)).toBe(true);
expect(isPersistentStateControlDisabled.call({ vmStateStorageClassUnavailable: true }, true)).toBe(false);
});
it('marks StorageClasses as loaded after the VM data fetch completes', async() => {
const form = { storageClassesLoaded: false };
const fetch = jest.spyOn(VM_MIXIN, 'fetch').mockImplementation().mockResolvedValue();
await HarvesterEditVM.fetch.call(form);
fetch.mockRestore();
expect(form.storageClassesLoaded).toBe(true);
});
it('links persistent state guidance to Storage Classes', () => {
const toStorageClass = HarvesterEditVM.computed.toStorageClass;
expect(toStorageClass.call({ $store: { getters: { clusterId: 'c-1' } } })).toStrictEqual({
name: 'harvester-c-cluster-resource',
params: { cluster: 'c-1', resource: 'harvesterhci.io.storage' },
});
});
it('describes creating the StorageClass without non-breaking spaces around guidance links', () => {
expect(translations).toContain('middle: or create the class on the');
expect(vmFormSource).not.toContain('&nbsp;');
});
it('clears persistent state selections only for create mode without vmstate-persistence', () => {
const clearPersistentState = HarvesterEditVM.methods.clearPersistentStateWithoutStorageClass;
const createForm = {
efiPersistentStateEnabled: true,
mode: 'create',
tpmPersistentStateEnabled: true,
vmStateStorageClassUnavailable: true,
};
clearPersistentState.call(createForm);
expect(createForm.tpmPersistentStateEnabled).toBe(false);
expect(createForm.efiPersistentStateEnabled).toBe(false);
const editForm = {
efiPersistentStateEnabled: true,
mode: 'edit',
tpmPersistentStateEnabled: true,
vmStateStorageClassUnavailable: true,
};
clearPersistentState.call(editForm);
expect(editForm.tpmPersistentStateEnabled).toBe(true);
expect(editForm.efiPersistentStateEnabled).toBe(true);
const storageClassForm = {
efiPersistentStateEnabled: true,
mode: 'create',
tpmPersistentStateEnabled: true,
vmStateStorageClassUnavailable: false,
};
clearPersistentState.call(storageClassForm);
expect(storageClassForm.tpmPersistentStateEnabled).toBe(true);
expect(storageClassForm.efiPersistentStateEnabled).toBe(true);
});
it('should stop the save when the cloud config is invalid', () => {
const { form, buttonCb } = saveWith('#cloud-config\nsome words\n');
expect(form.errors).toStrictEqual(['harvester.virtualMachine.cloudConfig.user.invalidYaml']);
expect(buttonCb).toHaveBeenCalledWith(false);
expect(form.saveSingle).not.toHaveBeenCalled();
});
it('should save when the user data is a script', () => {
const { form, buttonCb } = saveWith('#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n');
expect(form.errors).toStrictEqual([]);
expect(form.saveSingle).toHaveBeenCalledWith(buttonCb);
});
});
@@ -20,7 +20,6 @@ import { clear } from '@shell/utils/array';
import { saferDump } from '@shell/utils/create-yaml'; import { saferDump } from '@shell/utils/create-yaml';
import { exceptionToErrorsArray } from '@shell/utils/error'; import { exceptionToErrorsArray } from '@shell/utils/error';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations'; import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import { INTERNAL_STORAGE_CLASS } from '../../config/types';
import { BEFORE_SAVE_HOOKS, AFTER_SAVE_HOOKS } from '@shell/mixins/child-hook'; import { BEFORE_SAVE_HOOKS, AFTER_SAVE_HOOKS } from '@shell/mixins/child-hook';
import CreateEditView from '@shell/mixins/create-edit-view'; import CreateEditView from '@shell/mixins/create-edit-view';
import { parseVolumeClaimTemplates } from '@pkg/utils/vm'; import { parseVolumeClaimTemplates } from '@pkg/utils/vm';
@@ -35,13 +34,11 @@ import CpuMemory from './VirtualMachineCpuMemory';
import CpuModel from './VirtualMachineCpuModel'; import CpuModel from './VirtualMachineCpuModel';
import Network from './VirtualMachineNetwork'; import Network from './VirtualMachineNetwork';
import Volume from './VirtualMachineVolume'; import Volume from './VirtualMachineVolume';
import VMPerformanceOptions from './VirtualMachineVolume/VMPerformanceOptions';
import SSHKey from './VirtualMachineSSHKey'; import SSHKey from './VirtualMachineSSHKey';
import Reserved from './VirtualMachineReserved'; import Reserved from './VirtualMachineReserved';
import Filesystem from './VirtualMachineFilesystem'; import Filesystem from './VirtualMachineFilesystem';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import MessageLink from '@shell/components/MessageLink'; import MessageLink from '@shell/components/MessageLink';
import { STORAGE_CLASS } from '@shell/config/types';
export default { export default {
name: 'HarvesterEditVM', name: 'HarvesterEditVM',
@@ -58,7 +55,6 @@ export default {
LabeledSelect, LabeledSelect,
NameNsDescription, NameNsDescription,
Volume, Volume,
VMPerformanceOptions,
SSHKey, SSHKey,
Network, Network,
CpuMemory, CpuMemory,
@@ -91,11 +87,6 @@ export default {
}, },
}, },
async fetch() {
await VM_MIXIN.fetch.call(this);
this.storageClassesLoaded = true;
},
data() { data() {
const cloneVM = clone(this.value); const cloneVM = clone(this.value);
const isRestartImmediately = this.value.actualState === 'Running'; const isRestartImmediately = this.value.actualState === 'Running';
@@ -118,27 +109,12 @@ export default {
hostname, hostname,
isRestartImmediately, isRestartImmediately,
customizeDisplayName, customizeDisplayName,
storageClassesLoaded: false,
}; };
}, },
computed: { computed: {
...mapGetters({ t: 'i18n/t' }), ...mapGetters({ t: 'i18n/t' }),
hasVMStateStorageClass() {
const storageClasses = this.$store.getters[`${ this.inStore }/all`](STORAGE_CLASS) || [];
return storageClasses.some((storageClass) => storageClass.metadata?.name === INTERNAL_STORAGE_CLASS.VMSTATE_PERSISTENCE);
},
vmStateStorageClassUnavailable() {
return this.storageClassesLoaded && !this.hasVMStateStorageClass;
},
showPersistentStateStorageBanner() {
return this.mode !== 'view' && this.vmStateStorageClassUnavailable;
},
// VM display name is stored as an annotation; bind a dedicated input to it // VM display name is stored as an annotation; bind a dedicated input to it
// so we don't have to mutate metadata.name (which would break the k8s PUT). // so we don't have to mutate metadata.name (which would break the k8s PUT).
displayName: { displayName: {
@@ -157,13 +133,6 @@ export default {
}; };
}, },
toStorageClass() {
return {
name: 'harvester-c-cluster-resource',
params: { cluster: this.$store.getters['clusterId'], resource: HCI.STORAGE },
};
},
machineTypeOptions() { machineTypeOptions() {
return this.machineTypes.map((type) => { return this.machineTypes.map((type) => {
if (!type) return { label: 'None', value: '' }; if (!type) return { label: 'None', value: '' };
@@ -274,25 +243,6 @@ export default {
}, },
watch: { watch: {
hasVMStateStorageClass: {
handler() {
this.clearPersistentStateWithoutStorageClass();
},
immediate: true,
},
storageClassesLoaded() {
this.clearPersistentStateWithoutStorageClass();
},
tpmPersistentStateEnabled() {
this.clearPersistentStateWithoutStorageClass();
},
efiPersistentStateEnabled() {
this.clearPersistentStateWithoutStorageClass();
},
templateId: { templateId: {
async handler(id, old) { async handler(id, old) {
if (!id) { if (!id) {
@@ -415,17 +365,6 @@ export default {
}, },
methods: { methods: {
isPersistentStateControlDisabled(persistentStateEnabled) {
return this.vmStateStorageClassUnavailable && !persistentStateEnabled;
},
clearPersistentStateWithoutStorageClass() {
if (this.mode === 'create' && this.vmStateStorageClassUnavailable) {
this.tpmPersistentStateEnabled = false;
this.efiPersistentStateEnabled = false;
}
},
cancelAction() { cancelAction() {
const { fromPage = HCI.VM } = this.$route?.query; // default back to VM list page const { fromPage = HCI.VM } = this.$route?.query; // default back to VM list page
const cancelOverride = { const cancelOverride = {
@@ -440,7 +379,6 @@ export default {
this.validateCPUMemory(); this.validateCPUMemory();
this.validateWindowsSysprep(); this.validateWindowsSysprep();
this.validateCloudInit();
// block create VM flow if has validation errors // block create VM flow if has validation errors
if (this.errors.length) { if (this.errors.length) {
@@ -866,7 +804,6 @@ export default {
<Checkbox <Checkbox
v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled" v-if="value.tpmPersistentStateFeatureEnabled && tpmEnabled"
v-model:value="tpmPersistentStateEnabled" v-model:value="tpmPersistentStateEnabled"
:disabled="isPersistentStateControlDisabled(tpmPersistentStateEnabled)"
class="check" class="check"
type="checkbox" type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')" :label="t('harvester.virtualMachine.systemOptions.tpmPersistentState')"
@@ -884,7 +821,6 @@ export default {
<Checkbox <Checkbox
v-if="value.efiPersistentStateFeatureEnabled && efiEnabled" v-if="value.efiPersistentStateFeatureEnabled && efiEnabled"
v-model:value="efiPersistentStateEnabled" v-model:value="efiPersistentStateEnabled"
:disabled="isPersistentStateControlDisabled(efiPersistentStateEnabled)"
class="check" class="check"
type="checkbox" type="checkbox"
:label="t('harvester.virtualMachine.systemOptions.efiPersistentState')" :label="t('harvester.virtualMachine.systemOptions.efiPersistentState')"
@@ -901,22 +837,6 @@ export default {
/> />
</div> </div>
<Banner
v-if="showPersistentStateStorageBanner"
color="info"
>
<span>
{{ t('harvester.virtualMachine.systemOptions.persistentStateStorageClassUnavailable.prefix') }}
<router-link :to="to">
{{ t('harvester.virtualMachine.systemOptions.persistentStateStorageClassUnavailable.host') }}
</router-link>
{{ t('harvester.virtualMachine.systemOptions.persistentStateStorageClassUnavailable.middle') }}
<router-link :to="toStorageClass">
{{ t('harvester.virtualMachine.systemOptions.persistentStateStorageClassUnavailable.storageClass') }}
</router-link>{{ t('harvester.virtualMachine.systemOptions.persistentStateStorageClassUnavailable.suffix') }}
</span>
</Banner>
<Banner <Banner
v-if="showCpuPinningBanner" v-if="showCpuPinningBanner"
:color="mode === 'create' ? 'info' : 'warning'" :color="mode === 'create' ? 'info' : 'warning'"
@@ -952,6 +872,9 @@ export default {
> >
<Volume <Volume
v-model:value="diskRows" v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode" :mode="mode"
:custom-volume-mode="customVolumeMode" :custom-volume-mode="customVolumeMode"
:namespace="value.metadata.namespace" :namespace="value.metadata.namespace"
@@ -1223,16 +1146,6 @@ export default {
</div> </div>
</div> </div>
<VMPerformanceOptions
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
:mode="mode"
class="mb-20"
/>
<CloudConfig <CloudConfig
ref="yamlEditor" ref="yamlEditor"
:user-script="userScript" :user-script="userScript"
-11
View File
@@ -6,7 +6,6 @@ import harvesterCommonStore from './store/harvester-common';
import harvesterStore from './store/harvester-store'; import harvesterStore from './store/harvester-store';
import customValidators from './validators'; import customValidators from './validators';
import { PRODUCT_NAME } from './config/harvester'; import { PRODUCT_NAME } from './config/harvester';
import { HCI } from './types';
import { import {
hostResolvesL10nGlobals, resolveL10nGlobals, standaloneProductName, PRODUCT_NAME_GLOBAL hostResolvesL10nGlobals, resolveL10nGlobals, standaloneProductName, PRODUCT_NAME_GLOBAL
} from './utils/l10n-globals'; } from './utils/l10n-globals';
@@ -42,16 +41,6 @@ export default function (plugin: IPlugin) {
plugin.addDashboardStore(harvesterStore.config.namespace, harvesterStore.specifics, harvesterStore.config, harvesterStore.init); plugin.addDashboardStore(harvesterStore.config.namespace, harvesterStore.specifics, harvesterStore.config, harvesterStore.init);
plugin.validators = customValidators; plugin.validators = customValidators;
// The store's `paginationEnabled` getter turns it off on clusters whose API can't page the VM list
plugin.enableServerSidePagination?.({
[PRODUCT_NAME]: {
resources: {
enableAll: false,
enableSome: { enabled: [HCI.VM] }
}
}
});
plugin.addRoutes(extensionRoutes); plugin.addRoutes(extensionRoutes);
plugin.register('component', 'NavHeaderRight', defineAsyncComponent(() => plugin.register('component', 'NavHeaderRight', defineAsyncComponent(() =>
+55 -364
View File
@@ -32,7 +32,6 @@ nav:
group: group:
networks: Networks networks: Networks
backupAndSnapshot: Backup and Snapshots backupAndSnapshot: Backup and Snapshots
hardwareDevices: Hardware Devices
Monitoring: Monitoring Monitoring: Monitoring
Logging: Logging Logging: Logging
'Monitoring and Logging': Monitoring and Logging 'Monitoring and Logging': Monitoring and Logging
@@ -96,7 +95,6 @@ harvester:
backup: backup:
success: 'Backup { backUpName } has been initiated.' success: 'Backup { backUpName } has been initiated.'
addBackup: Add Backup addBackup: Add Backup
noTypeAvailable: No backup type can protect this virtual machine.
fileSystemFreezeDeadline: fileSystemFreezeDeadline:
label: 'File System Freeze Deadline' label: 'File System Freeze Deadline'
quota: quota:
@@ -514,57 +512,6 @@ harvester:
label: Events label: Events
vmMetrics: vmMetrics:
label: Virtual Machine Metrics label: Virtual Machine Metrics
healthSummary:
component: Component
severity: Severity
errorCount: Errors
warningCount: Warnings
expandAll: Expand All
collapseAll: Collapse All
componentHealth:
label: Components
errors: '{count, plural, =1 {1 error} other {# errors}}'
component: Component
check: Check
severity: Severity
message: Message
affectedCount: Affected Resources
noAffectedResources: No affected resources
noIssues: No issues detected
checksNotLoaded: Unable to load the checks
showIgnored: Show ignored checks
loadFailed:
healthSummaries: 'Unable to load the health summary: {error}'
componentHealths: 'Unable to load the checks: {error}'
ignoreRules: 'Unable to load the ignore rules: {error}'
ignore:
create: Create Ignore Rule
view: View Ignore Rule
edit: Edit Ignore Rule
delete: Delete Ignore Rule
ignored: Ignored
plusIgnored: '+ {n} ignored'
hideIgnored: Hide ignored
scope: Scope
scopeResources: Selected resources
scopeCheck: All resources
resources: Resources
duration: Expiration
days7: 7 days
days30: 30 days
forever: Forever
expiresOn: 'Expires on {date}'
expiredOn: 'Expired on {date}'
neverExpires: Never expires
willExpireOn: 'Will expire on {date}'
willNeverExpire: Will never expire
expiredBanner: 'This rule expired on {date}. To make any changes, set a new expiration to re-enable this rule.'
reason: Reason
reasonPlaceholder: Why is it ignored? (optional)
created: The ignore rule of {name} is created
updated: The ignore rule of {name} is updated
attemptingToDelete: You are attempting to delete the ignore rule of
reportedAgain: What it ignores will be reported again.
version: Version version: Version
host: host:
@@ -830,12 +777,6 @@ harvester:
tpmPersistentState: TPM Persistent State tpmPersistentState: TPM Persistent State
efiEnabled: Booting in EFI mode efiEnabled: Booting in EFI mode
efiPersistentState: EFI Persistent State efiPersistentState: EFI Persistent State
persistentStateStorageClassUnavailable:
prefix: Persistent TPM and EFI state require the vmstate-persistence StorageClass. Add a Longhorn disk on the
host: Hosts page
middle: or create the class on the
storageClass: Storage Classes page
suffix: .
secureBoot: Secure Boot secureBoot: Secure Boot
usbTip: Provides an absolute pointer device which often helps with getting a consistent mouse cursor position in VNC. usbTip: Provides an absolute pointer device which often helps with getting a consistent mouse cursor position in VNC.
sshTitle: Add Public SSH Key sshTitle: Add Public SSH Key
@@ -862,16 +803,19 @@ harvester:
saveVolume: Update Volume saveVolume: Update Volume
encryption: Encryption encryption: Encryption
performance: performance:
title: Storage Performance Options
expand: Show high-performance options
collapse: Hide high-performance options
profile: profile:
label: Storage Performance Profile label: Performance Profile
tip: '"High Performance" switches the disk to the virtio bus, disables the host cache, uses native AIO and gives the disk a dedicated I/O thread. Choose "Custom" to set each option yourself.' tip: "\"High Performance\" applies a tuned preset (no host cache, native AIO, a dedicated I/O thread on the virtio bus). Choose \"Custom\" to set each option yourself."
default: Default default: Default (Balanced)
highPerformance: High Performance highPerformance: High Performance
custom: Custom custom: Custom
highProfileTip: This disk will use the virtio bus, no host cache, native AIO and a dedicated I/O thread. highProfileTip: This disk will use the virtio bus with host cache disabled, native AIO and a dedicated I/O thread.
cacheMode: cacheMode:
label: Cache Mode label: Cache Mode
tip: 'How the host caches disk I/O. "None" is best for high-throughput guests on block storage, "WriteBack" favors performance and "WriteThrough" favors durability.' tip: "How the host caches disk I/O. \"None\" (host cache disabled) is best for high-throughput guests on block storage; \"WriteBack\" favours performance; \"WriteThrough\" favours durability."
default: Default (hypervisor) default: Default (hypervisor)
none: None (no host cache) none: None (no host cache)
writeback: WriteBack writeback: WriteBack
@@ -879,33 +823,35 @@ harvester:
filesystemWarning: "\"None\" (O_DIRECT) requires storage that supports direct I/O. It is recommended only for Block volume mode; on Filesystem volumes the VM may fail to start." filesystemWarning: "\"None\" (O_DIRECT) requires storage that supports direct I/O. It is recommended only for Block volume mode; on Filesystem volumes the VM may fail to start."
ioMode: ioMode:
label: I/O Mode label: I/O Mode
tip: 'How QEMU submits I/O. "Native" (Linux AIO) has the lowest overhead and needs cache mode "None". "Threads" uses a host thread pool.' tip: "How QEMU submits I/O. \"Native\" (Linux AIO) offers the lowest overhead but requires host cache set to \"None\"; \"Threads\" uses a host thread pool."
default: Default (hypervisor) default: Default (hypervisor)
native: Native (AIO) native: Native (AIO)
threads: Threads threads: Threads
nativeRequiresNoCacheTip: Native I/O mode needs the host cache disabled, so cache mode is set to None. nativeRequiresNoCacheTip: Native I/O mode requires cache mode "None"; it has been set for you.
dedicatedIOThread: dedicatedIOThread:
label: Dedicated I/O Thread label: Dedicated I/O Thread
tip: Give this disk its own I/O thread instead of sharing one. Useful for disks with heavy I/O. tip: Allocate an exclusive libvirt I/O thread to this disk instead of sharing one. Useful for disks with heavy I/O. Enabling this on any disk turns on the VM's I/O threads policy.
busTip: 'This disk uses the {bus} bus. A dedicated I/O thread needs the virtio bus.' busTip: High-performance features work best on the virtio bus.
diskPerformance: diskPerformance:
title: Storage Performance title: High Performance (I/O Threads and Multi-Queue)
description: These options apply to all volumes of the virtual machine. description: These settings apply to all volumes in the Virtual Machine and complement the per-volume options above.
expand: Show VM-wide high-performance options
collapse: Hide VM-wide high-performance options
blockMultiQueue: blockMultiQueue:
label: Virtio Block Multi-Queue label: Virtio Block Multi-Queue
tip: Spread disk I/O over one queue per vCPU so that it is processed on multiple CPUs. tip: Map disk I/O to multiple queues so it is processed across multiple CPUs. Applies to virtio disks and requires a fixed CPU allocation ([[Harvester]] always sets one).
noVirtioTip: Add at least one disk on the virtio bus to enable Block Multi-Queue. noVirtioTip: Add at least one disk on the virtio bus to enable Block Multi-Queue.
ioThreadsPolicy: ioThreadsPolicy:
label: I/O Threads Policy label: I/O Threads Policy
tip: '"Shared" uses one I/O thread for all disks. "Auto" spreads disks over a pool of threads. "Supplemental Pool" uses a fixed number of threads.' tip: "How libvirt allocates I/O threads. \"Shared\" uses one thread for all disks; \"Auto\" pools threads round-robin (up to ~2x vCPUs); \"Supplemental Pool\" lets you pick a fixed thread count and adds matching CPUs to the pod."
default: "Disabled (default)" default: "Disabled (default)"
shared: Shared shared: Shared
auto: Auto auto: Auto
supplementalPool: Supplemental Pool supplementalPool: Supplemental Pool
autoEnabledTip: A volume asks for a dedicated I/O thread, so the Shared policy will be used. autoEnabledTip: A disk requests a dedicated I/O thread, so the policy is enabled (defaults to "Shared").
ioThreadCount: ioThreadCount:
label: I/O Thread Count label: I/O Thread Count
tip: Number of I/O threads in the supplemental pool. tip: Number of I/O threads for the supplemental pool. 4-8 is a common range depending on workload.
shareable: shareable:
label: Shareable label: Shareable
tip: Allow multiple virtual machines to attach and write to this volume simultaneously. tip: Allow multiple virtual machines to attach and write to this volume simultaneously.
@@ -944,12 +890,10 @@ harvester:
label: User Data Template label: User Data Template
title: "User Data:" title: "User Data:"
tip: "You can specify user data to configure an instance or run a configuration script during launch. If you launch more than one instance at a time, the user data is available to all the instances in that reservation. <a href='https://cloudinit.readthedocs.io/en/latest/topics/examples.html' target='_blank'>Learn more</a>" tip: "You can specify user data to configure an instance or run a configuration script during launch. If you launch more than one instance at a time, the user data is available to all the instances in that reservation. <a href='https://cloudinit.readthedocs.io/en/latest/topics/examples.html' target='_blank'>Learn more</a>"
invalidYaml: 'Invalid User Data YAML syntax'
network: network:
label: Network Data Template label: Network Data Template
title: "Network Data:" title: "Network Data:"
tip: "The network-data configuration allows you to customize the instance's networking interfaces by assigning subnet configuration, virtual device creation (bonds, bridges, VLANs) routes and DNS configuration. <a href='https://cloudinit.readthedocs.io/en/latest/reference/network-config-format-v1.html' target='_blank'>Learn more</a>" tip: "The network-data configuration allows you to customize the instance's networking interfaces by assigning subnet configuration, virtual device creation (bonds, bridges, VLANs) routes and DNS configuration. <a href='https://cloudinit.readthedocs.io/en/latest/reference/network-config-format-v1.html' target='_blank'>Learn more</a>"
invalidYaml: 'Invalid Network Data YAML syntax'
sysprep: sysprep:
title: Windows Unattended & Sysprep Configuration title: Windows Unattended & Sysprep Configuration
description: "Configure Windows automated installation using autounattend.xml. The configuration will be stored in a Kubernetes Secret and mounted as a CD-ROM during installation. <a href='https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/automate-windows-setup' target='_blank'>Learn more</a>" description: "Configure Windows automated installation using autounattend.xml. The configuration will be stored in a Kubernetes Secret and mounted as a CD-ROM during installation. <a href='https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/automate-windows-setup' target='_blank'>Learn more</a>"
@@ -1067,100 +1011,58 @@ harvester:
from: Generated from from: Generated from
down: No events in the past hour down: No events in the past hour
console: console:
notRunning: down: This virtual machine is down. Please start it to access its console.
title: This virtual machine is not running shortcutKeys: Shortcut Keys
detail: Start it to use its console. customShortcutKeys: Custom Shortcut Keys
startingTitle: This virtual machine is starting management: Management Shortcut Keys
startingDetail: The console connects once it is running. record:
shortcutKeys: Shortcut keys start: Record
softReboot: Soft reboot recording: Recording
view: View stop: Stop Recording
shortcutMenu: tips: Press the record button to capture your keyboard inputs.
yourShortcuts: Your shortcuts send: Send
holdModifiers: Hold modifiers preferredKeys: Preferred Custom Shortcut Keys
holdHint: 'The next key you pick is sent as {combo}+key.' settings:
keys: Keys label: Settings
printScreen: Print Screen viewMode:
functionKeys: Function keys label: Display
manage: Manage custom shortcuts… scale: Scale the display to fit the window
blockedDisconnected: Keys can be sent once the console is connected. none: Manual zoom
hint: Clicking the console captures your keyboard. To send a shortcut, use the Shortcut keys menu. zoom: Zoom
hintViewOnly: '"View only" mode is on. In this mode, your mouse and keyboard are not sent to the VM.' viewOnly: View only
viewOnly: View only quality: JPEG quality
connection: compression: Compression level
menuLabel: Connection
description: Connected to {name}. If the screen stops updating, reconnecting usually fixes it.
customKeys:
title: Custom shortcuts
description: Save key combinations you send often. They appear at the top of the Shortcut keys menu.
new: New shortcut
combination: Key combination
reserved: Combinations your browser or OS reserves, like Ctrl+Alt+Del or Ctrl+W, can’t be recorded. Send them from the Shortcut keys menu instead, by holding Ctrl or Alt there.
duplicate: This key combination is already saved.
name: Name (optional)
clear: Clear
add: Add shortcut
saved: 'Saved shortcuts ({count})'
delete: 'Delete {name}'
done: Done
saveError: Unable to save the custom shortcuts
recorder:
empty: Click here, then press a key combination
recording: Press a key combination…
recordingStatus: Recording
again: Click to record again
viewOptions:
scaling: Scaling
automatic: Automatic
manual: Manual
automaticHelp: The screen scales to fit the window.
manualHelp: You set the zoom. Scroll to see parts of the screen that do not fit.
zoom: Zoom level
zoomIn: Zoom in
zoomOut: Zoom out
levelOf: '{value} of {max}'
qualityLevel:
label: JPEG quality
help: Higher quality looks sharper and uses more bandwidth.
compressionLevel:
label: Compression
help: Higher compression saves bandwidth but uses more CPU.
reset: Reset to defaults
fullscreen: fullscreen:
enter: Full screen enter: Full Screen
exit: Exit full screen exit: Exit Full Screen
ctrlAltDel: Ctrl+Alt+Del ctrlAltDel: Ctrl+Alt+Del
confirm: confirm:
ctrlAltDel: ctrlAltDel:
title: 'Send Ctrl+Alt+Del to {name}?' title: Send Ctrl+Alt+Del?
message: The key combination goes straight to the guest operating system. On many systems, including most Linux distributions, this restarts the VM immediately. Unsaved work in the VM will be lost. message: Windows opens its sign-in or security screen. Most Linux systems restart the virtual machine.
button: Send Ctrl+Alt+Del button: Send
softReboot: softReboot:
title: 'Soft reboot {name}?' title: Soft reboot this virtual machine?
message: The guest operating system is asked to shut down and restart. Unsaved work in the VM will be lost. message: The guest operating system is asked to restart. Unsaved work inside the virtual machine is lost.
button: Soft reboot button: Soft Reboot
takeOver: takeOver:
label: Take over label: Take Over
title: Take over this console? title: Take over this console?
confirm: The other VNC session connected to this virtual machine will be disconnected. confirm: The other VNC session connected to this virtual machine will be disconnected.
overlay:
connecting: 'Connecting to {name}…'
attempt: 'Attempt {retryTimes} of {maximumRetryTimes}.'
reconnectNow: Reconnect now
failure: failure:
inUse: This console is in use inUse: This console is in use
unavailable: Unable to connect unavailable: Unable to connect
dropped: Connection lost dropped: Disconnected
error: Connection failed error: Connection failed
failureDetail: failureDetail:
inUse: Another VNC session is connected to this virtual machine. Retry once it is released, or take over the console to disconnect the other session. inUse: Another VNC session is connected to this virtual machine. Retry once it is released, or take over the console to disconnect the other session.
unavailable: The console is not available. Check that the virtual machine is running, then retry. unavailable: The console is not available. Check that the virtual machine is running, then retry.
dropped: The console stopped receiving data from the virtual machine. The VM itself may still be running, or another VNC session may have opened this console. dropped: The console connection was closed. Another VNC session may have opened this console.
status: status:
connecting: Connecting… connecting: Connecting
connected: Connected connected: Connected
connectedViewOnly: Connected (view only)
disconnected: Disconnected disconnected: Disconnected
notRunning: Not running
failed: Connection failed failed: Connection failed
reconnecting: 'Reconnecting {retryTimes} of {maximumRetryTimes}' reconnecting: 'Reconnecting {retryTimes} of {maximumRetryTimes}'
credentialsRequired: This console requires credentials that the dashboard cannot provide. credentialsRequired: This console requires credentials that the dashboard cannot provide.
@@ -1280,10 +1182,6 @@ harvester:
currentVersion: CURRENT VERSION currentVersion: CURRENT VERSION
versionLabel: AVAILABLE COMPATIBLE VERSIONS versionLabel: AVAILABLE COMPATIBLE VERSIONS
enableLogging: Enable Logging enableLogging: Enable Logging
repositoryStorageClass: Upgrade Storage Class
repositoryStorageClassTooltip: Select the StorageClass for the temporary upgrade repository volume that stores the ISO during the upgrade.
repositoryStorageClassPlaceholder: Select a StorageClass
repositoryStorageClassNoOptions: No StorageClasses are available.
skipSingleReplicaDetachedVol: Skip checking single-replica detached volumes skipSingleReplicaDetachedVol: Skip checking single-replica detached volumes
upgradeNode: Upgrading Node upgradeNode: Upgrading Node
upgradeSysService: Upgrading System Service upgradeSysService: Upgrading System Service
@@ -1361,31 +1259,6 @@ harvester:
label: Refresh Interval label: Refresh Interval
tip: The interval for the backup target to sync data to [[Harvester]] cluster. Set to 0 to disable refresh mechanism. tip: The interval for the backup target to sync data to [[Harvester]] cluster. Set to 0 to disable refresh mechanism.
backupTargetTip: The endpoint used to access the backupstore. NFS and S3 are supported. backupTargetTip: The endpoint used to access the backupstore. NFS and S3 are supported.
thirdPartyBackup:
label: Enable Restic and Kopia Backups
tooltip: Allows Restic and Kopia virtual machine backups to this S3 target. Native backups and snapshots are not affected.
password:
label: Repository Password
tip: Restic and Kopia encrypt their backups with this password. Enter it every time you save this setting. It can't be changed for an existing repository, so keep a copy.
kopiaGC:
label: Enable Kopia Garbage Collection
tooltip: Runs scheduled Kopia maintenance to remove unused data from the S3 repository.
type:
backup: Native
snapshot: Snapshot
restic: Restic
kopia: Kopia
typeUnavailable:
native: Not supported by the volumes of this virtual machine.
longhornV2: Not supported on Longhorn V2 volumes such as {volume}.
cdi: Not supported on volumes created from a CDI image such as {volume}.
noBackupSnapshotClass: Set a backup volume snapshot class for {driver} in the csi-driver-config setting.
requiresS3: Requires an S3 backup target.
requiresBlock: Requires Block volume mode, but {volume} uses Filesystem.
longhornV1: Not supported on Longhorn V1 volumes such as {volume}.
noSnapshotClass: Set a volume snapshot class for {driver} in the csi-driver-config setting.
snapshot: The volumes of this virtual machine cannot be snapshotted.
thirdPartyBackupOff: Not enabled in the backup-target setting.
message: message:
noSetting: noSetting:
prefix: You must configure the backup target prefix: You must configure the backup target
@@ -1458,14 +1331,6 @@ harvester:
private: private:
label: Private Subnet 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. 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: allowSubnet:
label: Allow Subnets label: Allow Subnets
tooltip: You can specify certain subnets which can communicate with this subnet. tooltip: You can specify certain subnets which can communicate with this subnet.
@@ -1538,76 +1403,8 @@ harvester:
remoteVpc: remoteVpc:
label: Remote VPC label: Remote VPC
infoBanner: The static route destination CIDR must cover all subnets CIDR from remote VPC Peer. Read <a href="{url}" target="_blank">VPC Peering Configuration Examples</a> for more information. infoBanner: The static route destination CIDR must cover all subnets CIDR from remote VPC Peer. Read <a href="{url}" target="_blank">VPC Peering Configuration Examples</a> for more information.
bfdPort:
label: BFD Port
banner: The Egress Gateways of this VPC that have BFD enabled use the BFD port to detect a failed gateway instance quickly.
ip:
label: IP Address
placeholder: e.g. 10.255.255.255
tooltip: An IP address that doesn't conflict with any other address. For dual-stack, enter an IPv4 and an IPv6 address, separated by a comma.
gatewaysNeedPort: 'Egress Gateways of this VPC that have BFD enabled stop working without its BFD port: {gateways}.'
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: natGateway:
label: NAT Gateways label: Gateways
internalTenantNetwork: internalTenantNetwork:
label: Internal Tenant Network label: Internal Tenant Network
placeholder: Select a Virtual Machine Network placeholder: Select a Virtual Machine Network
@@ -1624,95 +1421,6 @@ harvester:
label: External Subnets label: External Subnets
addLabel: Add addLabel: Add
placeholder: Select a subnet placeholder: Select a subnet
egressGateway:
label: Egress Gateways
vpc:
label: VPC
placeholder: Select a VPC
replicas:
label: Replicas
tooltip: The number of gateway instances. Traffic is spread across all instances.
internalSubnet:
label: Internal Subnet
placeholder: Select a subnet of the VPC
noVpc: Select a VPC first
none: VPC {vpc} has no subnet on a virtual machine network
tooltip: The subnet of the VPC that the gateway instances are attached to. Only subnets of a virtual machine network are listed.
externalNetworkMode:
label: External Network
tooltip: How the gateway instances reach the external network. Primary CNI uses the pod network of the cluster, so it needs no external subnet and has no external IPs or bandwidth limits. This can't be changed after the gateway is created.
attachment: External subnet
primaryCNI: Primary CNI
externalSubnet:
label: External Subnet
placeholder: Select a subnet
tooltip: The subnet that connects the gateway instances to the external network. Only subnets of a virtual machine network are listed.
policies:
label: Policies
description: Traffic from these subnets of the VPC goes out through the gateway. Each subnet can be in one list only.
placeholder: Select subnets of the VPC
noVpc: Select a VPC on the Basic tab first
noSubnets: VPC {vpc} has no subnets
snatSubnets:
label: Subnets with SNAT
tooltip: Traffic from these subnets leaves with the gateway's external IP.
noSnatSubnets:
label: Subnets without SNAT
tooltip: Traffic from these subnets keeps its source IP, so the external network needs a route back to them.
ipBlocks:
snat: IP Blocks with SNAT
noSnat: IP Blocks without SNAT
tooltip: Set outside this form, which keeps them as they are.
ips:
label: IP Addresses
banner: Optional. When you set IP addresses, set at least one for each replica. Internal IPs must be in the internal subnet and external IPs in the external subnet.
bannerPrimaryCNI: Optional. When you set internal IPs, set at least one for each replica, in the internal subnet. The external IPs come from the pod network.
internal:
label: Internal IPs
add: Add Internal IP
placeholder: e.g. 172.20.10.41
external:
label: External IPs
add: Add External IP
placeholder: e.g. 10.115.48.220
bfd:
label: BFD
enabled: Bidirectional Forwarding Detection (BFD)
tooltip: Detect a failed gateway instance quickly and move its traffic to the other instances.
vpcBfdPort:
prefix: BFD also needs the BFD port of VPC {vpc}, which isn't enabled.
middle: Edit the VPC
suffix: to enable it.
minRX:
label: Receive Interval
tooltip: The shortest interval at which the gateway accepts BFD packets.
minTX:
label: Transmit Interval
tooltip: The shortest interval at which the gateway sends BFD packets.
multiplier:
label: Multiplier
tooltip: The number of missed packets after which a gateway instance is considered down.
milliseconds: ms
bandwidth:
label: Bandwidth
banner: Optional. Limits the bandwidth of each gateway instance. Enter a whole number in Mbps, such as 10, or a quantity in bits per second, such as 100M or 1Gi.
placeholder: e.g. 10
ingress:
label: Ingress
egress:
label: Egress
validation:
replicas: '"Replicas" must be a whole number from 0 to 10.'
policyRequired: Select at least one subnet, in either list.
policyExternalSubnet: Subnet {subnet} is the external subnet of the gateway, so it can't be in a policy.
sameSubnet: The internal and external subnets must be different.
ipList: '"{key}" must contain valid IP addresses.'
ipDuplicate: '"{key}" must not repeat an address.'
ipSubnet: '"{key}" must be usable addresses of subnet {subnet} ({cidr}), not its network, broadcast or gateway address.'
ipCount: '"{key}" must have at least one address for each replica ({replicas}).'
bfd: The BFD intervals must be whole numbers from 1 to 3600000.
bfdMultiplier: The BFD multiplier must be a whole number from 1 to 3600000.
bandwidth: The bandwidth must be a whole number in Mbps or a quantity such as 100M or 1Gi.
externalIP: externalIP:
label: External IPs label: External IPs
natGateway: natGateway:
@@ -1935,7 +1643,6 @@ harvester:
imagePreloadStrategy: Image Preload Strategy imagePreloadStrategy: Image Preload Strategy
nodeUpgradeOption: Node Upgrade Option nodeUpgradeOption: Node Upgrade Option
restoreVM: Restore VM restoreVM: Restore VM
shutdownVMOnMigrationFailure: Shut Down VM on Migration Failure
strategy: Strategy strategy: Strategy
pauseNodes: Pause Nodes pauseNodes: Pause Nodes
strategyType: Strategy Type strategyType: Strategy Type
@@ -1981,16 +1688,6 @@ harvester:
allowWorkloadDisruption: "Allow Workload Disruption" allowWorkloadDisruption: "Allow Workload Disruption"
disableTLS: "Disable TLS" disableTLS: "Disable TLS"
matchSELinuxLevelOnMigration: "Match SELinux Level On Migration" matchSELinuxLevelOnMigration: "Match SELinux Level On Migration"
thirdPartyBackupConfig:
memoryRequest: Memory Request
memoryLimit: Memory Limit
ephemeralRequest: Ephemeral Storage Request
ephemeralLimit: Ephemeral Storage Limit
cacheSize: Cache Size
cacheSizeHint: Must be less than the ephemeral storage limit.
maxConcurrentJobs: Maximum Concurrent Jobs
maxConcurrentJobsHint: Set to 0 for no limit.
noCache: Disable Cache
cloudTemplate: cloudTemplate:
label: Cloud Configuration Templates label: Cloud Configuration Templates
@@ -2889,7 +2586,6 @@ advancedSettings:
'harv-rancher-cluster': 'Configure Rancher cluster integration settings for guest cluster management.' 'harv-rancher-cluster': 'Configure Rancher cluster integration settings for guest cluster management.'
'harv-max-hotplug-ratio': 'The ratio for kubevirt to limit the maximum CPU and memory that can be hotplugged to a VM. The value could be an integer between 1 and 20, default to 4.' 'harv-max-hotplug-ratio': 'The ratio for kubevirt to limit the maximum CPU and memory that can be hotplugged to a VM. The value could be an integer between 1 and 20, default to 4.'
'harv-kubevirt-migration': 'Configure cluster-wide KubeVirt live migration parameters.' 'harv-kubevirt-migration': 'Configure cluster-wide KubeVirt live migration parameters.'
'harv-third-party-backup-config': 'Configure the resources and concurrency of Restic and Kopia virtual machine backup jobs.'
'harv-instance-manager-resources': 'Configure resource percentage reservations for Longhorn instance manager V1 and V2. Valid instance manager CPU range between 0 - 40.' 'harv-instance-manager-resources': 'Configure resource percentage reservations for Longhorn instance manager V1 and V2. Valid instance manager CPU range between 0 - 40.'
'harv-cluster-pod-security-standard': 'Enforce Kubernetes Pod Security Standards (PSS) at the cluster level.' 'harv-cluster-pod-security-standard': 'Enforce Kubernetes Pod Security Standards (PSS) at the cluster level.'
'harv-maintenance-mode-drain-timeout': 'Maintenance mode drain timeout in minutes. Use 0 to disable the timeout.' 'harv-maintenance-mode-drain-timeout': 'Maintenance mode drain timeout in minutes. Use 0 to disable the timeout.'
@@ -2970,11 +2666,6 @@ typeLabel:
one { NAT Gateway } one { NAT Gateway }
other { NAT Gateways } other { NAT Gateways }
} }
kubeovn.io.vpcegressgateway: |-
{count, plural,
one { Egress Gateway }
other { Egress Gateways }
}
kubeovn.io.iptablessnatrule: |- kubeovn.io.iptablessnatrule: |-
{count, plural, {count, plural,
one { Source Rule } one { Source Rule }
@@ -1,65 +0,0 @@
import { MANAGEMENT } from '@shell/config/types';
import SettingsPage from '../harvesterhci.io.setting.vue';
import { HCI } from '../../types';
import { HCI_SETTING } from '../../config/settings';
describe('list: harvesterhci.io.setting', () => {
async function fetchPage({ visibleSettings = [], isSingleProduct = false } = {}) {
const dispatch = jest.fn(() => Promise.resolve([]));
const page = {
initSettings: [],
$store: {
dispatch,
getters: {
isSingleProduct,
currentProduct: { inStore: 'harvester' },
'harvester/visibleSettings': visibleSettings,
}
}
};
await SettingsPage.fetch.call(page);
return { page, dispatch };
}
const visible = (id, config = {}) => ({
id, config, data: { id }
});
it('should list the visible settings sorted by name, a setting with an alias under its alias', async() => {
const { page } = await fetchPage({ visibleSettings: [visible('z-setting'), visible(HCI_SETTING.UI_PL, { alias: 'branding' })] });
expect(page.initSettings.map(({ id }) => id)).toStrictEqual(['branding', 'z-setting']);
});
it('should keep the config and the resource of a setting', async() => {
const { page } = await fetchPage({ visibleSettings: [visible('a-setting', { kind: 'json', canReset: true })] });
expect(page.initSettings[0]).toMatchObject({
id: 'a-setting', kind: 'json', canReset: true, data: { id: 'a-setting' }, hide: true, canHide: true, hasActions: true
});
});
it('should only allow actions on the server version when it is read only', async() => {
const { page } = await fetchPage({
visibleSettings: [
visible('a-setting', { readOnly: true }),
visible(HCI_SETTING.SERVER_VERSION, { readOnly: true }),
]
});
expect(page.initSettings.map(({ hasActions }) => hasActions)).toStrictEqual([false, true]);
});
it('should load the settings of the management store only in a single product', async() => {
const { dispatch: multiCluster } = await fetchPage();
const { dispatch: singleProduct } = await fetchPage({ isSingleProduct: true });
expect(multiCluster.mock.calls).toStrictEqual([['harvester/findAll', { type: HCI.SETTING }]]);
expect(singleProduct.mock.calls).toStrictEqual([
['harvester/findAll', { type: HCI.SETTING }],
['management/findAll', { type: MANAGEMENT.SETTING }],
]);
});
});
@@ -1,54 +0,0 @@
import { mount } from '@vue/test-utils';
import HarvesterVPC from '../kubeovn.io.vpc.vue';
// A table that renders the page's group header for each of the given groups
function resourceTable(groups) {
return {
data: () => ({ groups }),
template: '<div><div v-for="group in groups" :key="group.key" class="group"><slot name="group-by" :group="group" /></div></div>',
};
}
function mountList(groups) {
return mount(HarvesterVPC, {
props: { schema: { id: 'kubeovn.io.vpc' } },
data: () => ({ enabledKubeOvnAddon: true }),
global: {
stubs: {
ResourceTable: resourceTable(groups),
Masthead: true,
Loading: true,
'router-link': { template: '<a><slot /></a>' },
},
mocks: {
$fetchState: { pending: false },
t: (key) => ({ 'harvester.vpc.label': 'Virtual Private Cloud', 'generic.none': 'None' }[key] || key),
$store: {
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/all': () => [],
'harvester/schemaFor': () => ({ collectionMethods: ['POST'] }),
},
},
},
},
});
}
describe('list: kubeovn.io.vpc', () => {
it('should label a group of subnets without a VPC as None and offer no VPC actions', () => {
const wrapper = mountList([{ key: '' }]);
const group = wrapper.find('.group');
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: None');
expect(group.find('.right').exists()).toBe(false);
});
it('should label a VPC group with its name and offer the VPC actions', () => {
const wrapper = mountList([{ key: 'ovn-cluster' }]);
const group = wrapper.find('.group');
expect(group.find('.group-tab').text()).toBe('Virtual Private Cloud: ovn-cluster');
expect(group.findAll('.right a, .right button')).toHaveLength(3);
});
});
@@ -1,373 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import {
PVC, PV, POD, NODE, STORAGE_CLASS
} from '@shell/config/types';
import VmList from '../kubevirt.io.virtualmachine.vue';
import { VM_HEADERS, VM_PAGINATION_HEADERS } from '../../config/table-headers';
import { HCI } from '../../types';
const schemaWithColumns = (id, columns) => ({
id,
attributes: { columns: columns.map((name, i) => ({ name, field: `$.metadata.fields[${ i }]` })) }
});
const SCHEMAS = {
[HCI.VM]: schemaWithColumns(HCI.VM, ['Name', 'Age', 'Status', 'Ready']),
[HCI.VMIM]: schemaWithColumns(HCI.VMIM, ['Name', 'Phase', 'VMI']),
[HCI.RESTORE]: schemaWithColumns(HCI.RESTORE, ['Name', 'TARGET_KIND', 'TARGET_NAME']),
[HCI.VMI]: { id: HCI.VMI },
[HCI.BACKUP]: { id: HCI.BACKUP },
[POD]: { id: POD },
[PVC]: { id: PVC },
[PV]: { id: PV },
};
// `harvester/paginationEnabled` is the store's getter, which checks the cluster's API (see store/harvester-store/getters.ts)
function createStore({
paginationEnabled = true, havePage = true, found = {}, failing = [], storedVMs = [], storedVMIs = [], namespaceFilters = []
} = {}) {
const dispatch = jest.fn((action, { type } = {}) => (failing.includes(type) ? Promise.reject(new Error('failed')) : Promise.resolve(found[type] || [])));
return {
dispatch,
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/paginationEnabled': jest.fn((args) => paginationEnabled && (args?.id || args) === HCI.VM),
'harvester/havePage': (type) => havePage && type === HCI.VM,
'harvester/schemaFor': (type) => SCHEMAS[type],
'harvester/all': (type) => ({ [HCI.VM]: storedVMs, [HCI.VMI]: storedVMIs }[type] || []),
'type-map/headersFor': (schema, pagination) => (pagination ? VM_PAGINATION_HEADERS : VM_HEADERS),
'action-menu/performCallbackData': undefined,
namespaceFilters,
}
};
}
const call = (name, ctx) => VmList.computed[name].call(ctx);
const byName = (headers) => Object.fromEntries(headers.map((h) => [h.name, { sort: h.sort, search: h.search }]));
const vm = (namespace, name, claimNames = []) => ({
id: `${ namespace }/${ name }`,
metadata: { namespace, name },
persistentVolumeClaimName: claimNames,
});
describe('list: kubevirt.io.virtualmachine', () => {
describe('without server-side pagination', () => {
it('should not page when the store says the cluster\'s API can\'t page the VMs', () => {
const $store = createStore({ paginationEnabled: false });
expect(call('canPaginate', { $store })).toBe(false);
expect($store.getters['harvester/paginationEnabled']).toHaveBeenCalledWith(HCI.VM);
});
it('should show the product\'s VM columns, with node and restore progress when they apply', () => {
const ctx = {
$store: createStore({ paginationEnabled: false }), schema: SCHEMAS[HCI.VM], hasNode: true, hasBackUpRestoreInProgress: true
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
const headers = call('headers', ctx);
expect(headers.map(({ name }) => name)).toStrictEqual(['state', 'name', 'namespace', 'CPU', 'Memory', 'ip', 'node', 'restoreProgress', 'age']);
expect(byName(headers).CPU).toStrictEqual({ sort: ['displayCPU'], search: undefined });
expect(byName(headers).node).toStrictEqual({ sort: ['realAttachNodeName'], search: undefined });
});
it.each([
['node', 'the cluster\'s nodes can\'t be seen', { hasNode: false, hasBackUpRestoreInProgress: true }],
['restoreProgress', 'no backup is being restored', { hasNode: true, hasBackUpRestoreInProgress: false }],
])('should leave out the %s column when %s', (column, _, flags) => {
const ctx = {
$store: createStore(), schema: SCHEMAS[HCI.VM], ...flags
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
expect(call('headers', ctx).map(({ name }) => name)).not.toContain(column);
expect(call('paginationHeaders', ctx).map(({ name }) => name)).not.toContain(column);
expect(call('headers', ctx)).toHaveLength(VM_HEADERS.length - 1);
});
it('should add VMIs without a VM to the rows', () => {
const vms = [{ id: 'default/a' }];
const $store = createStore({ storedVMs: vms, storedVMIs: [{ id: 'default/a' }, { id: 'default/orphan' }] });
const ctx = {
$store, inStore: 'harvester', canPaginate: false, vms
};
ctx.vmisWithoutVM = call('vmisWithoutVM', ctx);
expect(VmList.methods.addVMIsWithoutVM.call(ctx, vms).map(({ id }) => id)).toStrictEqual(['default/a', 'default/orphan']);
expect(call('rows', ctx).map(({ id }) => id)).toStrictEqual(['default/a', 'default/orphan']);
});
it('should load every resource the rows need, the table loads the VMs', async() => {
const $store = createStore({ paginationEnabled: false });
await VmList.methods.fetchSecondaryResources.call({
$store, inStore: 'harvester', hasNode: true
}, { canPaginate: false });
expect($store.dispatch.mock.calls.map(([action, { type }]) => `${ action } ${ type }`).sort()).toStrictEqual([
HCI.BACKUP, HCI.IMAGE, HCI.RESTORE, HCI.VMI, HCI.VMIM, NODE, POD, PV, PVC, STORAGE_CLASS
].map((type) => `harvester/findAll ${ type }`).sort());
});
});
describe('with server-side pagination', () => {
it('should page when the store says the cluster\'s API can page the VMs', () => {
expect(call('canPaginate', { $store: createStore() })).toBe(true);
});
it('should only sort and search on fields the API indexes', () => {
const ctx = {
$store: createStore(), schema: SCHEMAS[HCI.VM], hasNode: true, hasBackUpRestoreInProgress: true
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
expect(byName(call('paginationHeaders', ctx))).toStrictEqual({
state: { sort: ['metadata.fields.2'], search: false },
name: { sort: ['metadata.name'], search: ['metadata.name', 'metadata.annotations[harvesterhci.io/vmDisplayName]'] },
namespace: { sort: ['metadata.namespace'], search: 'metadata.namespace' },
CPU: { sort: false, search: false },
Memory: { sort: false, search: false },
ip: { sort: false, search: false },
node: { sort: false, search: false },
restoreProgress: { sort: false, search: false },
age: { sort: 'metadata.creationTimestamp:desc', search: false },
});
});
it('should take the VMs of the page from the store', () => {
const storedVMs = [vm('default', 'a')];
const $store = createStore({ storedVMs });
expect(call('vms', { $store, inStore: 'harvester' })).toBe(storedVMs);
});
it('should list only the VMs of the page', () => {
const page = [vm('default', 'a')];
const $store = createStore({ storedVMs: page, storedVMIs: [{ id: 'default/orphan' }] });
const ctx = {
$store, inStore: 'harvester', canPaginate: true, vms: page
};
ctx.vmisWithoutVM = call('vmisWithoutVM', ctx);
expect(call('rows', ctx)).toStrictEqual(page);
});
it('should fetch only the resources of the VMs on the page', async() => {
const $store = createStore({
found: {
[PVC]: [{ spec: { volumeName: 'pv-a' } }, { spec: {} }],
[HCI.RESTORE]: [{ spec: { virtualMachineBackupName: 'backup-a' } }],
[HCI.VMI]: [{ metadata: { name: 'a', uid: 'uid-a' } }, { metadata: { name: 'b', uid: 'uid-b' } }],
}
});
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await VmList.methods.fetchPageSecondaryResources.call(ctx, {
force: true,
page: [vm('default', 'a', ['a-disk']), vm('other', 'a'), vm('default', 'b', ['b-disk'])],
});
const filters = Object.fromEntries($store.dispatch.mock.calls.map(([action, { type, opt }]) => {
expect(action).toBe('harvester/findPage');
expect(opt.force).toBe(true);
return [type, opt.pagination.filters[0].fields.map(({ field, value, equality }) => `${ field }${ equality }(${ value })`)];
}));
expect(filters).toStrictEqual({
[PVC]: ['metadata.name IN (a-disk,b-disk)'],
[HCI.RESTORE]: ['metadata.fields.2 IN (a,b)'],
[HCI.VMI]: ['metadata.name IN (a,b)'],
[POD]: ['metadata.labels[kubevirt.io/created-by] IN (uid-a,uid-b)'],
[HCI.VMIM]: ['metadata.fields.2 IN (a,b)'],
[PV]: ['metadata.name IN (pv-a)'],
[HCI.BACKUP]: ['metadata.name IN (backup-a)'],
});
});
it('should fetch the rest when one request fails', async() => {
const $store = createStore({ failing: [HCI.RESTORE], found: { [PVC]: [{ spec: { volumeName: 'pv-a' } }], [HCI.VMI]: [{ metadata: { uid: 'uid-a' } }] } });
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await expect(VmList.methods.fetchPageSecondaryResources.call(ctx, { force: false, page: [vm('default', 'a', ['a-disk'])] })).resolves.toBeUndefined();
const types = $store.dispatch.mock.calls.map(([, { type }]) => type);
expect(types).toStrictEqual(expect.arrayContaining([PVC, HCI.VMI, POD, HCI.VMIM, PV]));
expect(types).not.toContain(HCI.BACKUP);
});
it('should not fetch a type when no VM on the page needs it', async() => {
const $store = createStore();
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await VmList.methods.fetchPageSecondaryResources.call(ctx, { force: false, page: [vm('default', 'a')] });
const types = $store.dispatch.mock.calls.map(([, { type }]) => type);
expect(types).not.toContain(PVC);
expect(types).not.toContain(PV);
expect(types).not.toContain(HCI.BACKUP);
expect(types).not.toContain(POD);
});
it('should load only what every row shares, not the per-VM resources', async() => {
const $store = createStore();
await VmList.methods.fetchSecondaryResources.call({
$store, inStore: 'harvester', hasNode: true
}, { canPaginate: true });
expect($store.dispatch.mock.calls).toStrictEqual([
['harvester/findAll', { type: HCI.IMAGE }],
['harvester/findAll', { type: STORAGE_CLASS }],
['harvester/findAll', { type: NODE }],
]);
});
});
// The header's filter is shared by every list, so Not in a Project can come from a list that doesn't page
it.each([
['ask for another namespace filter while paging when the API can\'t filter by it', { namespaceFilters: ['all://orphans'] }, true],
['show the list while paging with a namespace filter the API can use', { namespaceFilters: ['ns://default'] }, false],
['show the list without pagination, whatever the filter', { paginationEnabled: false, namespaceFilters: ['all://orphans'] }, false],
])('should %s', (_, opts, asks) => {
const wrapper = shallowMount(VmList, {
props: { schema: SCHEMAS[HCI.VM] },
global: { mocks: { $store: createStore(opts), t: (key) => key }, stubs: { 'router-link': true } },
});
expect(wrapper.findComponent({ name: 'IconMessage' }).exists()).toBe(asks);
expect(wrapper.findComponent({ name: 'PaginatedResourceTable' }).exists()).toBe(!asks);
});
it('should hide the masthead loading count only with pagination', () => {
expect(VmList.$loadingResources(null, createStore())).toStrictEqual({ loadResources: [] });
expect(VmList.$loadingResources(null, createStore({ paginationEnabled: false }))).toStrictEqual({});
});
describe('restart required notification', () => {
const rvm = (namespace, name) => ({
id: `${ namespace }/${ name }`, metadata: { namespace, name }, isRestartRequired: true
});
const notify = (ctx, vms, oldVms) => VmList.watch.restartRequiredVMs.handler.call(ctx, vms, oldVms);
const createCtx = (restartNotificationKey) => ({
$store: { dispatch: jest.fn() },
t: (key, args) => `${ key } ${ JSON.stringify(args) }`,
restartNotificationKey,
});
const mountList = ($store) => shallowMount(VmList, {
props: { schema: SCHEMAS[HCI.VM] },
global: { mocks: { $store, t: (key, args) => `${ key } ${ JSON.stringify(args) }` }, stubs: { 'router-link': true } },
});
const warning = (count, vmNames) => ['growl/warning', {
title: `harvester.notification.restartRequired.title ${ JSON.stringify({ count }) }`,
message: `harvester.notification.restartRequired.message ${ JSON.stringify({ vmNames }) }`,
timeout: 10000,
}, { root: true }];
it('should only list the VMs that need a restart', () => {
const a = rvm('default', 'a');
expect(call('restartRequiredVMs', { canPaginate: false, vms: [a, { id: 'default/b', isRestartRequired: false }] })).toStrictEqual([a]);
});
it.each([
['wait for the list\'s page while paging', { havePage: false }, []],
['take the VMs of the page once it is loaded', { havePage: true }, ['a']],
])('should %s', (_, opts, names) => {
const ctx = {
$store: createStore(opts), inStore: 'harvester', canPaginate: true, vms: [rvm('default', 'a')]
};
expect(call('restartRequiredVMs', ctx).map(({ metadata }) => metadata.name)).toStrictEqual(names);
});
// Coming back to the list, the store already holds the VMs, so they never change after the list is created
it.each([
['without pagination', { paginationEnabled: false, havePage: false }],
['with pagination', { paginationEnabled: true, havePage: true }],
])('should notify when the list opens with the VMs already in the store, %s', (_, opts) => {
const $store = createStore({ ...opts, storedVMs: [rvm('default', 'a')] });
mountList($store);
expect($store.dispatch).toHaveBeenCalledWith(...warning(1, 'a'));
});
it('should not notify about VMs another page left in the store while the list is paged', () => {
const $store = createStore({ havePage: false, storedVMs: [rvm('default', 'a')] });
mountList($store);
expect($store.dispatch).not.toHaveBeenCalledWith('growl/warning', expect.anything(), expect.anything());
});
it('should notify when VMs need a restart', () => {
const ctx = createCtx('');
notify(ctx, [rvm('default', 'a'), rvm('default', 'b')], []);
expect(ctx.$store.dispatch).toHaveBeenCalledWith(...warning(2, 'a, b'));
expect(ctx.restartNotificationKey).toBe('default/a,default/b');
});
it('should notify on a new visit to the list, even when the VMs it saw before are the same', () => {
const ctx = createCtx('');
notify(ctx, [rvm('default', 'a')], [rvm('default', 'a')]);
expect(ctx.$store.dispatch).toHaveBeenCalledWith(...warning(1, 'a'));
});
it('should not notify again when a refresh, page or sort brings back the same VMs', () => {
const ctx = createCtx('default/a,default/b');
notify(ctx, [rvm('default', 'b'), rvm('default', 'a')], [rvm('default', 'a'), rvm('default', 'b')]);
expect(ctx.$store.dispatch).not.toHaveBeenCalled();
});
it('should notify again when a VM of the same name in another namespace takes its place', () => {
const ctx = createCtx('');
notify(ctx, [rvm('ns1', 'a')], []);
notify(ctx, [rvm('ns2', 'a')], [rvm('ns1', 'a')]);
expect(ctx.$store.dispatch.mock.calls).toStrictEqual([warning(1, 'a'), ['growl/clear'], warning(1, 'a')]);
});
it('should replace the notification when the VMs change', () => {
const ctx = createCtx('default/a,default/b');
notify(ctx, [rvm('default', 'a'), rvm('default', 'c')], [rvm('default', 'a'), rvm('default', 'b')]);
expect(ctx.$store.dispatch.mock.calls).toStrictEqual([['growl/clear'], warning(2, 'a, c')]);
});
it('should reset when no VM needs a restart', () => {
const ctx = createCtx('default/a');
notify(ctx, [], [rvm('default', 'a')]);
expect(ctx.$store.dispatch).not.toHaveBeenCalled();
expect(ctx.restartNotificationKey).toBe('');
});
});
});
@@ -24,10 +24,8 @@ import { allDashboardsExist } from '@shell/utils/grafana';
import { isEmpty } from '@shell/utils/object'; import { isEmpty } from '@shell/utils/object';
import { HCI } from '../types'; import { HCI } from '../types';
import HarvesterUpgrade from '../components/HarvesterUpgrade'; import HarvesterUpgrade from '../components/HarvesterUpgrade';
import HealthSummaryTable from '../components/health/HealthSummaryTable';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester'; import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { UNIT_SUFFIX } from '../utils/unit'; import { UNIT_SUFFIX } from '../utils/unit';
import { totalErrorCount } from '../utils/component-health';
dayjs.extend(utc); dayjs.extend(utc);
dayjs.extend(minMax); dayjs.extend(minMax);
@@ -127,7 +125,6 @@ export default {
DashboardMetrics, DashboardMetrics,
Banner, Banner,
MessageLink, MessageLink,
HealthSummaryTable,
}, },
async fetch() { async fetch() {
@@ -240,20 +237,6 @@ export default {
computed: { computed: {
...mapGetters(['currentCluster']), ...mapGetters(['currentCluster']),
// the health resources only exist while the resource health addon is installed
componentHealthEnabled() {
const inStore = this.$store.getters['currentProduct'].inStore;
return this.$store.getters['harvester-common/getFeatureEnabled']('componentHealth') &&
!!this.$store.getters[`${ inStore }/schemaFor`](HCI.HEALTH_SUMMARY);
},
componentErrorCount() {
const inStore = this.$store.getters['currentProduct'].inStore;
return totalErrorCount(this.$store.getters[`${ inStore }/all`](HCI.HEALTH_SUMMARY));
},
accessibleResources() { accessibleResources() {
const inStore = this.$store.getters['currentProduct'].inStore; const inStore = this.$store.getters['currentProduct'].inStore;
@@ -838,16 +821,6 @@ export default {
</template> </template>
</SortableTable> </SortableTable>
</Tab> </Tab>
<Tab
v-if="componentHealthEnabled"
name="components"
:label="t('harvester.dashboard.sections.componentHealth.label')"
:weight="95"
:display-alert-icon="componentErrorCount > 0"
:error-icon-tooltip="t('harvester.dashboard.sections.componentHealth.errors', { count: componentErrorCount })"
>
<HealthSummaryTable />
</Tab>
</Tabbed> </Tabbed>
</div> </div>
</section> </section>
+37 -8
View File
@@ -7,7 +7,7 @@ import { allHash } from '@shell/utils/promise';
import Tabbed from '@shell/components/Tabbed/index.vue'; import Tabbed from '@shell/components/Tabbed/index.vue';
import Tab from '@shell/components/Tabbed/Tab.vue'; import Tab from '@shell/components/Tabbed/Tab.vue';
import Settings from '@pkg/harvester/components/SettingList.vue'; import Settings from '@pkg/harvester/components/SettingList.vue';
import { HCI_SETTING } from '../config/settings'; import { HCI_ALLOWED_SETTINGS, HCI_SINGLE_CLUSTER_ALLOWED_SETTING, HCI_SETTING } from '../config/settings';
import { HCI } from '../types'; import { HCI } from '../types';
export default { export default {
@@ -29,19 +29,47 @@ export default {
hash.settings = this.$store.dispatch('management/findAll', { type: MANAGEMENT.SETTING }); hash.settings = this.$store.dispatch('management/findAll', { type: MANAGEMENT.SETTING });
} }
await allHash(hash); const rows = await allHash(hash);
const initSettings = this.$store.getters[`${ inStore }/visibleSettings`].map(({ id, config, data }) => { let allRows = [];
allRows.push(...rows.harvesterSettings);
if (isSingleProduct) {
allRows = [...rows.settings, ...allRows];
}
// Map settings from array to object keyed by id
const settingsMap = allRows.reduce((res, s) => {
res[s.id] = s;
return res;
}, {});
const initSettings = [];
let SETTINGS = HCI_ALLOWED_SETTINGS;
if (this.isStandaloneHarvester) {
SETTINGS = {
...SETTINGS,
...HCI_SINGLE_CLUSTER_ALLOWED_SETTING,
};
}
Object.keys(SETTINGS).forEach((setting) => {
if (!settingsMap[setting]) {
return;
}
const realSetting = SETTINGS[setting]?.alias || setting;
const s = { const s = {
...config, ...SETTINGS[setting],
id: config.alias || id, id: realSetting,
data, data: settingsMap[setting],
}; };
s.hide = s.canHide = (s.kind === 'json' || s.kind === 'multiline' || s.customFormatter === 'json' || s.data.customFormatter === 'json'); s.hide = s.canHide = (s.kind === 'json' || s.kind === 'multiline' || s.customFormatter === 'json' || s.data.customFormatter === 'json');
s.hasActions = s.id === HCI_SETTING.SERVER_VERSION ? true : !s.readOnly; s.hasActions = s.id === HCI_SETTING.SERVER_VERSION ? true : !s.readOnly;
initSettings.push(s);
return s;
}); });
this.initSettings = initSettings.sort((a, b) => { this.initSettings = initSettings.sort((a, b) => {
@@ -62,6 +90,7 @@ export default {
computed: { computed: {
...mapGetters({ t: 'i18n/t' }), ...mapGetters({ t: 'i18n/t' }),
...mapGetters(['isStandaloneHarvester']),
settings() { settings() {
return this.initSettings.map((setting) => { return this.initSettings.map((setting) => {
@@ -112,15 +112,6 @@ export default {
}, },
]; ];
if (this.thirdPartyBackupFeatureEnabled) {
cols.push({
name: 'backupType',
labelKey: 'harvester.fields.type',
value: 'backupTypeLabel',
sort: 'backupTypeLabel',
});
}
if (this.schedulingVMBackupFeatureEnabled) { if (this.schedulingVMBackupFeatureEnabled) {
cols.push({ cols.push({
name: 'backupCreatedFrom', name: 'backupCreatedFrom',
@@ -162,10 +153,6 @@ export default {
return cols; return cols;
}, },
thirdPartyBackupFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
},
schedulingVMBackupFeatureEnabled() { schedulingVMBackupFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('schedulingVMBackup'); return this.$store.getters['harvester-common/getFeatureEnabled']('schedulingVMBackup');
}, },
@@ -177,7 +164,7 @@ export default {
return this.backups.filter((r) => r.spec?.type !== BACKUP_TYPE.SNAPSHOT); return this.backups.filter((r) => r.spec?.type !== BACKUP_TYPE.SNAPSHOT);
}, },
getRawRows() { getRawRows() {
return this.rows.filter((r) => r.spec?.type !== BACKUP_TYPE.SNAPSHOT); return this.rows.filter((r) => r.spec?.type === BACKUP_TYPE.BACKUP);
}, },
backupTargetResource() { backupTargetResource() {
return this.settings.find((O) => O.id === 'backup-target'); return this.settings.find((O) => O.id === 'backup-target');
@@ -114,7 +114,7 @@ export default {
}, },
filteredRows() { filteredRows() {
return this.snapshots.filter((r) => r.spec?.type === BACKUP_TYPE.SNAPSHOT); return this.snapshots.filter((r) => r.spec?.type !== BACKUP_TYPE.BACKUP);
}, },
}, },
+2 -6
View File
@@ -139,8 +139,7 @@ export default {
}, },
methods: { methods: {
groupLabel(group) { groupLabel(group) {
// Kube-OVN sets a subnet's VPC (ovn-cluster when none is given), so an empty one is a subnet it hasn't processed return `${ this.t('harvester.vpc.label') }: ${ group.key }`;
return `${ this.t('harvester.vpc.label') }: ${ group.key || this.t('generic.none') }`;
}, },
slotName(vpc) { slotName(vpc) {
@@ -227,10 +226,7 @@ export default {
{{ groupLabel(group) }} {{ groupLabel(group) }}
</span> </span>
</div> </div>
<div <div class="right">
v-if="group.key"
class="right"
>
<router-link <router-link
v-if="isSubnetCreatable" v-if="isSubnetCreatable"
class="btn btn-sm role-secondary mr-5" class="btn btn-sm role-secondary mr-5"
+141 -214
View File
@@ -1,17 +1,15 @@
<script> <script>
import { mapGetters } from 'vuex'; import { mapGetters } from 'vuex';
import PaginatedResourceTable from '@shell/components/PaginatedResourceTable'; import ResourceTable from '@shell/components/ResourceTable';
import IconMessage from '@shell/components/IconMessage'; import { STATE, AGE, NAME, NAMESPACE } from '@shell/config/table-headers';
import { import {
PVC, PV, NODE, POD, STORAGE_CLASS PVC, PV, NODE, POD, STORAGE_CLASS
} from '@shell/config/types'; } from '@shell/config/types';
import { FilterArgs, PaginationFilterEquality, PaginationParamFilter } from '@shell/types/store/pagination.types';
import { allHash } from '@shell/utils/promise'; import { allHash } from '@shell/utils/promise';
import paginationUtils from '@shell/utils/pagination-utils'; import Loading from '@shell/components/Loading';
import { uniq } from '@shell/utils/array'; import { clone } from '@shell/utils/object';
import { HCI } from '../types'; import { HCI } from '../types';
import { HCI as HCI_ANNOTATIONS } from '../config/labels-annotations';
import HarvesterVmState from '../formatters/HarvesterVmState'; import HarvesterVmState from '../formatters/HarvesterVmState';
import ConsoleBar from '../components/VMConsoleBar'; import ConsoleBar from '../components/VMConsoleBar';
@@ -20,21 +18,58 @@ const ENCRYPTED_VOLUME_TOOLTIP_KEYS = {
partial: 'harvester.virtualMachine.volume.lockTooltip.partial', partial: 'harvester.virtualMachine.volume.lockTooltip.partial',
}; };
// Outside the component because `ResourceList` calls `$loadingResources(route, store)` on the component options, export const VM_HEADERS = [
// where there's no `this`. The store's getter knows whether this cluster's API can page the list STATE,
function canPaginate(store) { {
const inStore = store.getters['currentProduct']?.inStore; ...NAME,
width: 350,
return !!store.getters[`${ inStore }/paginationEnabled`]?.(HCI.VM); value: 'nameDisplay',
} sort: ['nameDisplay'],
},
NAMESPACE,
{
name: 'CPU',
label: 'CPU',
sort: ['displayCPU'],
value: 'displayCPU',
align: 'center',
dashIfEmpty: true,
},
{
name: 'Memory',
value: 'displayMemory',
sort: ['memorySort'],
align: 'center',
labelKey: 'tableHeaders.memory',
formatter: 'Si',
formatterOpts: {
opts: {
increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i',
},
needParseSi: true
},
},
{
name: 'ip',
label: 'IP Address',
value: 'id',
formatter: 'HarvesterIpAddress',
labelKey: 'tableHeaders.ipAddress',
sort: ['id'],
},
{
...AGE,
sort: 'metadata.creationTimestamp:desc',
}
];
export default { export default {
name: 'HarvesterListVM', name: 'HarvesterListVM',
components: { components: {
Loading,
HarvesterVmState, HarvesterVmState,
ConsoleBar, ConsoleBar,
IconMessage, ResourceTable
PaginatedResourceTable
}, },
props: { props: {
@@ -44,9 +79,39 @@ export default {
}, },
}, },
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const _hash = {
vms: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VM, opt: { force: true } }),
pod: this.$store.dispatch(`${ inStore }/findAll`, { type: POD }),
pvcs: this.$store.dispatch(`${ inStore }/findAll`, { type: PVC }),
pvs: this.$store.dispatch(`${ inStore }/findAll`, { type: PV }),
images: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.IMAGE }),
restore: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.RESTORE }),
backups: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.BACKUP }),
storage: this.$store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS }),
};
if (this.$store.getters[`${ inStore }/schemaFor`](HCI.RESOURCE_QUOTA)) {
_hash.resourceQuotas = this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.RESOURCE_QUOTA });
}
if (this.$store.getters[`${ inStore }/schemaFor`](NODE)) {
_hash.nodes = this.$store.dispatch(`${ inStore }/findAll`, { type: NODE });
this.hasNode = true;
}
const hash = await allHash(_hash);
this.allVMs = hash.vms;
},
data() { data() {
return { return {
restartNotificationKey: '', hasNode: false,
allVMs: [],
allVMIs: [],
restartNotificationDisplayed: false,
HCI HCI
}; };
}, },
@@ -54,51 +119,42 @@ export default {
computed: { computed: {
...mapGetters({ actionCb: 'action-menu/performCallbackData' }), ...mapGetters({ actionCb: 'action-menu/performCallbackData' }),
inStore() { headers() {
return this.$store.getters['currentProduct'].inStore; const restoreCol = {
}, name: 'restoreProgress',
labelKey: 'harvester.tableHeaders.restore',
value: 'restoreProgress',
align: 'left',
formatter: 'HarvesterBackupProgressBar',
width: 200,
};
const nodeCol = {
name: 'node',
label: 'Node',
value: 'nodeName',
sort: ['realAttachNodeName'],
formatter: 'HarvesterHost',
labelKey: 'harvester.tableHeaders.vm.node'
};
hasNode() { const cols = clone(VM_HEADERS);
return !!this.$store.getters[`${ this.inStore }/schemaFor`](NODE);
},
canPaginate() { if (this.hasNode) {
return canPaginate(this.$store); cols.splice(-1, 0, nodeCol);
},
// The header's namespace filter is shared by every list, so an option the paged API can't filter by, like Not in a
// Project, can still be selected from another list. Ask for another one, like the shell's generic lists do
namespaceFilterInvalid() {
return this.canPaginate && !paginationUtils.validateNsProjectFilters(this.$store.getters['namespaceFilters']);
},
// The product registers both sets of VM columns (`headers()` in config/harvester-cluster.js)
paginationHeaders() {
return this.applicableColumns(this.$store.getters['type-map/headersFor'](this.schema, true));
},
// With pagination the store only holds the VMs of the current page
vms() {
return this.$store.getters[`${ this.inStore }/all`](HCI.VM);
},
// The paginated API lists VMs only, so VMIs without a VM are only shown without pagination
vmisWithoutVM() {
if (this.canPaginate) {
return [];
} }
const vmIds = new Set(this.vms.map((vm) => vm.id)); if (this.hasBackUpRestoreInProgress) {
cols.splice(-1, 0, restoreCol);
}
return this.$store.getters[`${ this.inStore }/all`](HCI.VMI).filter((vmi) => !vmIds.has(vmi.id)); return cols;
},
headers() {
return this.applicableColumns(this.$store.getters['type-map/headersFor'](this.schema, false));
}, },
rows() { rows() {
return [...this.vms, ...this.vmisWithoutVM]; const vmIds = new Set(this.allVMs.map((VM) => VM.id));
const matchVMIs = this.allVMIs.filter((VMI) => !vmIds.has(VMI.id));
return [...this.allVMs, ...matchVMIs];
}, },
/** /**
@@ -112,16 +168,22 @@ export default {
}); });
}, },
restartRequiredVMs() { vmRestartRequiredNames() {
// While paging, the store can still hold the VMs another view loaded, like every VM after Volumes or a VM's detail return this.allVMs
if (this.canPaginate && !this.$store.getters[`${ this.inStore }/havePage`](HCI.VM)) { .filter((vm) => vm.isRestartRequired)
return []; .map((vm) => vm.metadata.name);
}
return this.vms.filter((vm) => vm.isRestartRequired);
} }
}, },
async created() {
const inStore = this.$store.getters['currentProduct'].inStore;
const vmis = await this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VMI });
await this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VMIM });
this['allVMIs'] = vmis;
},
beforeUnmount() { beforeUnmount() {
// clear restart message before component unmount // clear restart message before component unmount
this.$store.dispatch('growl/clear'); this.$store.dispatch('growl/clear');
@@ -130,41 +192,32 @@ export default {
watch: { watch: {
actionCb(neu) { actionCb(neu) {
if (neu?.clearTableSelection) { if (neu?.clearTableSelection) {
this.$refs.resourceTable?.clearSelection(); this.$refs.resourceTable.clearSelection();
this.$store.dispatch('action-menu/clearCallbackData'); this.$store.dispatch('action-menu/clearCallbackData');
} }
}, },
restartRequiredVMs: { vmRestartRequiredNames(vmNames) {
// Immediate, as the store may already hold the VMs when coming back to the list const count = vmNames.length;
immediate: true,
handler(vms) {
// Rebuilt on every refresh, and when paging on every page, sort and search too, so only notify when the VMs
// change. The key lives on the component, so coming back to the list notifies again
const key = vms.map((vm) => vm.id).sort().join();
if (key === this.restartNotificationKey) { if (count === 0 && this.restartNotificationDisplayed) {
return; this.restartNotificationDisplayed = false;
}
const shown = !!this.restartNotificationKey; return;
}
this.restartNotificationKey = key;
if (!vms.length) {
return;
}
if (count > 0) {
// clear old notification before showing new one // clear old notification before showing new one
if (shown) { if (this.restartNotificationDisplayed) {
this.$store.dispatch('growl/clear'); this.$store.dispatch('growl/clear');
} }
this.$store.dispatch('growl/warning', { this.$store.dispatch('growl/warning', {
title: this.t('harvester.notification.restartRequired.title', { count: vms.length }), title: this.t('harvester.notification.restartRequired.title', { count }),
message: this.t('harvester.notification.restartRequired.message', { vmNames: vms.map((vm) => vm.metadata.name).join(', ') }), message: this.t('harvester.notification.restartRequired.message', { vmNames: vmNames.join(', ') }),
timeout: 10000, timeout: 10000,
}, { root: true }); }, { root: true });
this.restartNotificationDisplayed = true;
} }
} }
}, },
@@ -173,147 +226,21 @@ export default {
const key = ENCRYPTED_VOLUME_TOOLTIP_KEYS[row.encryptedVolumeType]; const key = ENCRYPTED_VOLUME_TOOLTIP_KEYS[row.encryptedVolumeType];
return key ? this.t(key) : ''; return key ? this.t(key) : '';
},
// Called by PaginatedResourceTable before it loads the VMs. With pagination fetchPageSecondaryResources loads the
// resources of the VMs on the page, without it every VM needs its pods, volumes, restores, backups, VMI and migration
async fetchSecondaryResources({ canPaginate }) {
const inStore = this.inStore;
const findAll = (type) => this.$store.dispatch(`${ inStore }/findAll`, { type });
const hash = {
images: findAll(HCI.IMAGE),
storage: findAll(STORAGE_CLASS),
};
if (this.$store.getters[`${ inStore }/schemaFor`](HCI.RESOURCE_QUOTA)) {
hash.resourceQuotas = findAll(HCI.RESOURCE_QUOTA);
}
if (this.hasNode) {
hash.nodes = findAll(NODE);
}
if (!canPaginate) {
Object.assign(hash, {
pods: findAll(POD),
pvcs: findAll(PVC),
pvs: findAll(PV),
restores: findAll(HCI.RESTORE),
backups: findAll(HCI.BACKUP),
vmis: findAll(HCI.VMI),
vmims: findAll(HCI.VMIM),
});
}
await allHash(hash);
},
// The node column only when the cluster's nodes can be seen, the restore progress only while a backup is restored
applicableColumns(headers) {
return headers.filter(({ name }) => {
if (name === 'node') {
return this.hasNode;
}
if (name === 'restoreProgress') {
return this.hasBackUpRestoreInProgress;
}
return true;
});
},
// localFilter of PaginatedResourceTable, which only runs without pagination
addVMIsWithoutVM(rows) {
return [...rows, ...this.vmisWithoutVM];
},
// The VM model looks these up by id or owner, so the ones of the VMs on the page are enough
async fetchPageSecondaryResources({ force, page }) {
if (!page?.length) {
return;
}
const vmNames = uniq(page.map((vm) => vm.metadata.name));
const claimNames = uniq(page.flatMap((vm) => vm.persistentVolumeClaimName));
// One failed request shouldn't stop the others, the rows show what could be loaded
const loaded = (results) => results.map((result) => (result.status === 'fulfilled' ? result.value : []));
const [pvcs, restores, vmis] = loaded(await Promise.allSettled([
this.findPageByField(PVC, 'metadata.name', claimNames, force),
this.findPageByField(HCI.RESTORE, this.printerColumnField(HCI.RESTORE, 'TARGET_NAME'), vmNames, force),
this.findPageByField(HCI.VMI, 'metadata.name', vmNames, force),
this.findPageByField(HCI.VMIM, this.printerColumnField(HCI.VMIM, 'VMI'), vmNames, force),
]));
await Promise.allSettled([
this.findPageByField(PV, 'metadata.name', uniq(pvcs.map((pvc) => pvc.spec?.volumeName)), force),
this.findPageByField(HCI.BACKUP, 'metadata.name', uniq(restores.map((restore) => restore.spec?.virtualMachineBackupName)), force),
// KubeVirt labels every launcher pod with its VMI's UID; Harvester's vmName label is missing on VMs from Forklift or plain manifests
this.findPageByField(POD, `metadata.labels[${ HCI_ANNOTATIONS.VMI_CREATED_BY }]`, uniq(vmis.map((vmi) => vmi.metadata?.uid)), force),
]);
},
async findPageByField(type, field, values, force) {
const wanted = values.filter(Boolean);
if (!field || !wanted.length || !this.$store.getters[`${ this.inStore }/schemaFor`](type)) {
return [];
}
return this.$store.dispatch(`${ this.inStore }/findPage`, {
type,
opt: {
force,
pagination: new FilterArgs({
filters: PaginationParamFilter.createSingleField({
field, value: wanted.join(','), equality: PaginationFilterEquality.IN
})
}),
}
});
},
// The API indexes the printer columns of a CRD by position (`metadata.fields.N`), so look the position up by name
printerColumnField(type, columnName) {
const schema = this.$store.getters[`${ this.inStore }/schemaFor`](type);
const column = schema?.attributes?.columns?.find((col) => col.name === columnName);
return column?.field?.replace('$.', '').replace('[', '.').replace(']', '');
} }
}, }
// With pagination the store never holds every VM, so the masthead's loading count would never finish
$loadingResources(route, store) {
return canPaginate(store) ? { loadResources: [] } : {};
},
}; };
</script> </script>
<template> <template>
<div> <Loading v-if="$fetchState.pending" />
<IconMessage <div v-else>
v-if="namespaceFilterInvalid" <ResourceTable
:vertical="true"
:subtle="false"
icon="icon-filter_alt"
>
<template #message>
{{ t('resourceList.nsFilteringGeneric') }}
</template>
</IconMessage>
<PaginatedResourceTable
v-else
ref="resourceTable" ref="resourceTable"
v-bind="$attrs" v-bind="$attrs"
:schema="schema"
:headers="headers" :headers="headers"
:pagination-headers="paginationHeaders"
:fetch-secondary-resources="fetchSecondaryResources"
:fetch-page-secondary-resources="fetchPageSecondaryResources"
:local-filter="addVMIsWithoutVM"
default-sort-by="age" default-sort-by="age"
:rows="rows"
:schema="schema"
:groupable="true" :groupable="true"
key-field="_key" key-field="_key"
> >
@@ -352,7 +279,7 @@ export default {
/> />
</div> </div>
</template> </template>
</PaginatedResourceTable> </ResourceTable>
</div> </div>
</template> </template>
@@ -1,140 +0,0 @@
import VM_MIXIN from '../index';
import impl from '../impl';
const USER_ERROR = 'harvester.virtualMachine.cloudConfig.user.invalidYaml';
const NETWORK_ERROR = 'harvester.virtualMachine.cloudConfig.network.invalidYaml';
const CLOUD_CONFIG = '#cloud-config\npackage_update: true\npackages:\n - qemu-guest-agent\n';
const YAML_SCRIPT = '#!/bin/bash\napt-get update\napt-get install -y nginx\n';
function validate({
userScript, networkScript, isEdit = false, savedCloudInit = {}
}) {
const form = {
userScript,
networkScript,
isEdit,
savedCloudInit,
errors: [],
t: (key) => key,
};
VM_MIXIN.methods.validateCloudInit.call(form);
return form.errors;
}
function userDataFor(userScript) {
const form = {
userScript,
sshKey: [],
$store: { getters: { 'harvester/byId': () => undefined } },
...impl.methods,
...VM_MIXIN.methods,
};
return form.getUserData({ osType: 'linux', installAgent: false });
}
describe('mixin: harvester-vm', () => {
describe('validateCloudInit', () => {
it.each([
['a word after the mapping', `${ CLOUD_CONFIG }some words\n`],
['only words', '#cloud-config\nsome words\n'],
['only words and no header', 'some words\n'],
['a list', '#cloud-config\n- a\n- b\n'],
['bad indentation', '#cloud-config\nusers:\n - name: a\n bad: b\n'],
['an unclosed quote', '#cloud-config\npassword: "abc\n'],
])('should block cloud-config user data with %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([USER_ERROR]);
});
it.each([
['undefined', undefined],
['empty', ''],
['only the header', '#cloud-config\n'],
['a valid cloud-config', CLOUD_CONFIG],
['a mapping without the header', 'password: test\n'],
])('should allow user data that is %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([]);
});
it.each([
['a script that is not valid YAML', '#!/bin/bash\napt-get update\n# start it\nsystemctl enable --now nginx\n'],
['a script that parses as YAML', YAML_SCRIPT],
['a MIME message with a cloud-config part', 'Content-Type: multipart/mixed; boundary="b"\nMIME-Version: 1.0\n\n--b\nContent-Type: text/cloud-config\n\n#cloud-config\npackages:\n - nginx\n--b--\n'],
['a Jinja template', '## template: jinja\n#cloud-config\n{% if v1.region == "us" %}\npackages:\n - a\n{% endif %}\n'],
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\n# enable RDP\nWrite-Host "done: ok"\n'],
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: |\n #!/bin/sh\n'],
])('should not parse user data that is %s', (_, userScript) => {
expect(validate({ userScript })).toStrictEqual([]);
});
it.each([
['words', 'some words\n'],
['a list', '- a\n- b\n'],
['bad indentation', 'network:\n version: 1\n bad: x\n'],
])('should block network data with %s', (_, networkScript) => {
expect(validate({ networkScript })).toStrictEqual([NETWORK_ERROR]);
});
it.each([
['undefined', undefined],
['empty', ''],
['only whitespace', ' \n'],
['only a comment', '# nothing yet\n'],
['a valid config', 'network:\n version: 1\n config:\n - type: physical\n name: eth0\n'],
])('should allow network data that is %s', (_, networkScript) => {
expect(validate({ networkScript })).toStrictEqual([]);
});
it('should report both fields when both are invalid', () => {
const errors = validate({ userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n' });
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
});
it('should save an edited VM with the cloud-init it already has', () => {
const savedCloudInit = {
userScript: '#cloud-config\n#!/bin/bash\napt-get update apt-get install -y nginx\n',
networkScript: 'some words\n',
};
const errors = validate({
...savedCloudInit, isEdit: true, savedCloudInit
});
expect(errors).toStrictEqual([]);
});
it('should check cloud-init changed while editing', () => {
const savedCloudInit = { userScript: CLOUD_CONFIG, networkScript: '' };
const errors = validate({
userScript: '#cloud-config\nsome words\n', networkScript: 'some words\n', isEdit: true, savedCloudInit
});
expect(errors).toStrictEqual([USER_ERROR, NETWORK_ERROR]);
});
it('should check cloud-init a new VM takes from a template', () => {
const savedCloudInit = { userScript: '#cloud-config\nsome words\n' };
expect(validate({ ...savedCloudInit, savedCloudInit })).toStrictEqual([USER_ERROR]);
});
});
describe('getUserData', () => {
it.each([
['a script that parses as YAML', YAML_SCRIPT],
['a Cloudbase-Init batch script', 'rem cmd\nnet user admin Passw0rd /add\n'],
['a Cloudbase-Init PowerShell script', '#ps1_sysnative\nWrite-Host done\n'],
['a cloud-config archive', '#cloud-config-archive\n- type: text/x-shellscript\n content: echo hi\n'],
])('should save %s as typed', (_, userScript) => {
expect(userDataFor(userScript)).toStrictEqual(userScript);
});
it('should add the header to cloud-config typed without one', () => {
expect(userDataFor('password: test\n')).toBe('#cloud-config\npassword: test\n');
});
});
});
-12
View File
@@ -35,18 +35,6 @@ export const SSH_EXISTING_TYPE = {
EXISTING_ONLY_CLOUD: 'EXISTING_CLOUD', EXISTING_ONLY_CLOUD: 'EXISTING_CLOUD',
}; };
// Cloud-init and Cloudbase-Init run user data starting with one of these as a script, MIME or another format, not as cloud-config.
const OTHER_USER_DATA_FORMATS = [
'#!', '#include', '#cloud-boothook', '#part-handler', '#cloud-config-archive', '#cloud-config-jsonp', '## template:',
'#ps1', 'rem cmd', '<script>', '<powershell>', 'content-type:', 'mime-version:'
];
export function isCloudConfig(userScript) {
const start = (userScript || '').trimStart().toLowerCase();
return !OTHER_USER_DATA_FORMATS.some((format) => start.startsWith(format));
}
export default { export default {
methods: { methods: {
hasCloudConfigComment(userScript) { hasCloudConfigComment(userScript) {
+1 -43
View File
@@ -2,8 +2,6 @@ import YAML from 'yaml';
import jsyaml from 'js-yaml'; import jsyaml from 'js-yaml';
import isEqual from 'lodash/isEqual'; import isEqual from 'lodash/isEqual';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
import isNil from 'lodash/isNil';
import isPlainObject from 'lodash/isPlainObject';
import difference from 'lodash/difference'; import difference from 'lodash/difference';
import { sortBy } from '@shell/utils/sort'; import { sortBy } from '@shell/utils/sort';
import { set } from '@shell/utils/object'; import { set } from '@shell/utils/object';
@@ -25,7 +23,7 @@ import {
import { HCI_SETTING } from '../../config/settings'; import { HCI_SETTING } from '../../config/settings';
import { HCI } from '../../types'; import { HCI } from '../../types';
import { parseVolumeClaimTemplates, EMPTY_IMAGE } from '../../utils/vm'; import { parseVolumeClaimTemplates, EMPTY_IMAGE } from '../../utils/vm';
import impl, { isCloudConfig, QGA_JSON, USB_TABLET } from './impl'; import impl, { QGA_JSON, USB_TABLET } from './impl';
import { GIBIBYTE } from '../../utils/unit'; import { GIBIBYTE } from '../../utils/unit';
import { VOLUME_MODE, ACCESS_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types'; import { VOLUME_MODE, ACCESS_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types';
@@ -159,8 +157,6 @@ export default {
installUSBTablet: true, installUSBTablet: true,
networkScript: '', networkScript: '',
userScript: '', userScript: '',
// The cloud-init the form loaded, so editing a VM never blocks saving it unchanged.
savedCloudInit: {},
imageId: '', imageId: '',
diskRows: [], diskRows: [],
networkRows: [], networkRows: [],
@@ -294,14 +290,6 @@ export default {
return this.osType === 'windows'; return this.osType === 'windows';
}, },
hasVirtioDisk() {
return (this.diskRows || []).some((R) => R.type === 'disk' && R.bus === 'virtio');
},
hasDedicatedIOThread() {
return (this.diskRows || []).some((R) => R.dedicatedIOThread);
},
needNewSecret() { needNewSecret() {
// When creating a template it is always necessary to create a new secret. // When creating a template it is always necessary to create a new secret.
return this.isCreate || this.showYaml ? false : this.resourceType === HCI.VM_VERSION; return this.isCreate || this.showYaml ? false : this.resourceType === HCI.VM_VERSION;
@@ -446,7 +434,6 @@ export default {
this['accessCredentials'] = accessCredentials; this['accessCredentials'] = accessCredentials;
this['userScript'] = userData; this['userScript'] = userData;
this['networkScript'] = networkData; this['networkScript'] = networkData;
this['savedCloudInit'] = { userScript: userData, networkScript: networkData };
this['sshKey'] = sshKey; this['sshKey'] = sshKey;
this['osType'] = osType; this['osType'] = osType;
@@ -1296,11 +1283,6 @@ export default {
* @param config * @param config
*/ */
getUserData(config) { getUserData(config) {
// Scripts, MIME and the other formats are saved as typed: only cloud-config gets the SSH keys, the guest agent and the header.
if (!isCloudConfig(this.userScript)) {
return this.userScript;
}
try { try {
// https://github.com/eemeli/yaml/issues/136 // https://github.com/eemeli/yaml/issues/136
let userDataDoc = this.userScript ? YAML.parseDocument(this.userScript) : YAML.parseDocument({}); let userDataDoc = this.userScript ? YAML.parseDocument(this.userScript) : YAML.parseDocument({});
@@ -1493,30 +1475,6 @@ export default {
this.networkScript = value; this.networkScript = value;
}, },
validateCloudInit() {
const isYamlMapping = (text) => {
try {
const doc = jsyaml.load(text);
return isNil(doc) || isPlainObject(doc);
} catch (e) {
return false;
}
};
// Editing only checks what changed, so a VM can still be saved with the cloud-init it already has.
const isChanged = (key) => !this.isEdit || this[key] !== this.savedCloudInit[key];
// Scripts, MIME and the other formats are valid without being YAML. Anything else is saved as cloud-config.
if (this.userScript && isChanged('userScript') && isCloudConfig(this.userScript) && !isYamlMapping(this.userScript)) {
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.user.invalidYaml'));
}
if (this.networkScript && isChanged('networkScript') && !isYamlMapping(this.networkScript)) {
this.errors.push(this.t('harvester.virtualMachine.cloudConfig.network.invalidYaml'));
}
},
mergeSSHAuthorizedKeys(yaml) { mergeSSHAuthorizedKeys(yaml) {
try { try {
const sshAuthorizedKeys = YAML.parseDocument(yaml) const sshAuthorizedKeys = YAML.parseDocument(yaml)
@@ -1,43 +0,0 @@
import HciVmBackup from '../harvesterhci.io.virtualmachinebackup';
import { HCI } from '../../types';
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({ colorForState: jest.fn() }));
function createBackup(type) {
const backup = Object.create(HciVmBackup.prototype);
const push = jest.fn();
Object.assign(backup, { spec: { type } });
Object.defineProperty(backup, 'name', { value: 'b1' });
Object.defineProperty(backup, 't', { value: (key) => key });
Object.defineProperty(backup, 'currentRouter', { value: () => ({ push }) });
return { backup, push };
}
describe('class HciVmBackup', () => {
it.each([
['backup', HCI.BACKUP],
['restic', HCI.BACKUP],
['kopia', HCI.BACKUP],
[undefined, HCI.BACKUP],
['snapshot', HCI.VM_SNAPSHOT],
])('should restore a %s backup through %s', (type, resource) => {
const { backup, push } = createBackup(type);
backup.restoreNewVM();
backup.restoreExistingVM();
expect(push).toHaveBeenCalledTimes(2);
expect(push.mock.calls[0][0].params.resource).toBe(resource);
expect(push.mock.calls[1][0].params.resource).toBe(resource);
});
it.each([
['kopia', 'harvester.backup.type.kopia'],
[undefined, 'harvester.backup.type.backup'],
])('should label type %s as %s', (type, label) => {
expect(createBackup(type).backup.backupTypeLabel).toBe(label);
});
});
@@ -1,57 +0,0 @@
import HciSubnet from '../kubeovn.io.subnet';
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
function createSubnet(spec) {
return Object.assign(Object.create(HciSubnet.prototype), { spec });
}
describe('class HciSubnet', () => {
it.each([
['ovn', null, false],
['', null, false],
['vmnet.default.ovn', { name: 'vmnet', namespace: 'default' }, true],
['extnet.default', { name: 'extnet', namespace: 'default' }, false],
['extnet.default.other', null, false],
['a.b.ovn.extra', null, false],
])('should read the network attachment of provider "%s"', (provider, attachment, overlay) => {
const subnet = createSubnet({ provider });
expect(subnet.networkAttachment).toStrictEqual(attachment);
expect(subnet.isOverlayAttachment).toBe(overlay);
});
it.each([
['172.20.10.41', true],
['172.20.10.1', false],
['172.20.10.0', false],
['172.20.10.255', false],
['172.20.10.254', true],
['172.20.11.1', false],
['fd00::10', true],
['fd00::1', false],
['fd00::', false],
['fd00::ff', false],
['fd01::10', false],
['not-an-ip', false],
])('should tell whether %s can be assigned in a dual-stack subnet', (ip, assignable) => {
const subnet = createSubnet({ cidrBlock: '172.20.10.0/24,fd00::/120', gateway: '172.20.10.1,fd00::1' });
expect(subnet.canAssignIP(ip)).toBe(assignable);
});
it('should tell whether the subnet contains an IP, its gateway included', () => {
const subnet = createSubnet({ cidrBlock: '172.20.10.0/24', gateway: '172.20.10.1' });
expect(subnet.containsIP('172.20.10.1')).toBe(true);
expect(subnet.containsIP('10.255.255.255')).toBe(false);
});
it.each([
['10.0.0.0/31', '10.0.0.0', true],
['10.0.0.0/31', '10.0.0.1', true],
['10.0.0.5/32', '10.0.0.5', true],
])('should use every address of a point-to-point subnet %s', (cidrBlock, ip, assignable) => {
expect(createSubnet({ cidrBlock }).canAssignIP(ip)).toBe(assignable);
});
});
@@ -1,56 +0,0 @@
import HciVPC from '../kubeovn.io.vpc';
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
function createVpc(spec, { subnets = [], gateways = [], hasGatewayType = true } = {}) {
const $getters = {
all: (type) => (type === 'kubeovn.io.subnet' ? subnets : gateways),
schemaFor: () => hasGatewayType,
};
return Object.assign(Object.create(HciVPC.prototype), {
metadata: { name: 'commonvpc' }, spec, $getters
});
}
describe('class HciVPC', () => {
it.each([
['no BFD port', {}, false],
['a disabled BFD port', { bfdPort: { enabled: false, ip: '10.255.255.255' } }, false],
['an enabled BFD port without an IP', { bfdPort: { enabled: true, ip: ' ' } }, false],
['an enabled BFD port with an IP', { bfdPort: { enabled: true, ip: '10.255.255.255' } }, true],
])('should report a VPC with %s', (_, spec, enabled) => {
expect(createVpc(spec).bfdPortEnabled).toBe(enabled);
});
it('should list the subnets of the VPC', () => {
const subnets = [{ id: 'subnetinternal', spec: { vpc: 'commonvpc' } }, { id: 'ovn-default', spec: { vpc: 'ovn-cluster' } }];
expect(createVpc({}, { subnets }).subnetResources.map((subnet) => subnet.id)).toStrictEqual(['subnetinternal']);
});
it('should list the gateways of the VPC that have BFD on', () => {
const gateways = [
{ id: 'default/bfd-on', spec: { vpc: 'commonvpc', bfd: { enabled: true } } },
{ id: 'default/bfd-off', spec: { vpc: 'commonvpc', bfd: { enabled: false } } },
{ id: 'default/other-vpc', spec: { vpc: 'othervpc', bfd: { enabled: true } } },
];
expect(createVpc({}, { gateways }).bfdEgressGateways.map((gateway) => gateway.id)).toStrictEqual(['default/bfd-on']);
});
it('should count a gateway without a VPC as one of the default VPC', () => {
const gateways = [{ id: 'default/no-vpc', spec: { bfd: { enabled: true } } }];
const vpc = createVpc({}, { gateways });
vpc.metadata.name = 'ovn-cluster';
expect(vpc.bfdEgressGateways.map((gateway) => gateway.id)).toStrictEqual(['default/no-vpc']);
});
it('should list no gateways when the cluster has no Egress Gateway type', () => {
const gateways = [{ id: 'default/bfd-on', spec: { vpc: 'commonvpc', bfd: { enabled: true } } }];
expect(createVpc({}, { gateways, hasGatewayType: false }).bfdEgressGateways).toStrictEqual([]);
});
});
@@ -1,6 +1,6 @@
import { reactive } from 'vue'; import { reactive } from 'vue';
import VirtVm from '../kubevirt.io.virtualmachine'; import VirtVm from '../kubevirt.io.virtualmachine';
import { POD, PV, PVC } from '@shell/config/types'; import { POD, PVC } from '@shell/config/types';
import { HCI } from '../../types'; import { HCI } from '../../types';
// The Steve base model and the shell resource class pull in most of the dashboard, none of that is needed here // The Steve base model and the shell resource class pull in most of the dashboard, none of that is needed here
@@ -15,7 +15,7 @@ const VM_ID = 'ns1/vm1';
// Creates a VM model with mocked store getters. Like the real store, `all` returns the same array that is mutated in place. // Creates a VM model with mocked store getters. Like the real store, `all` returns the same array that is mutated in place.
// Reads from the global `$rootGetters` are recorded in `globalReads`. // Reads from the global `$rootGetters` are recorded in `globalReads`.
function createVm({ function createVm({
vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus, root = {} vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus
} = {}) { } = {}) {
const lists = reactive({ const lists = reactive({
[POD]: pods, [POD]: pods,
@@ -31,7 +31,7 @@ function createVm({
schemaFor: () => undefined, schemaFor: () => undefined,
}; };
const globalReads = []; const globalReads = [];
const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false, ...root }, { const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false }, {
get(target, key) { get(target, key) {
globalReads.push(key); globalReads.push(key);
@@ -86,193 +86,7 @@ const pvc = (name, encrypted, ns = 'ns1') => ({
isEncrypted: encrypted, isEncrypted: encrypted,
}); });
const LONGHORN_CSI = { 'driver.longhorn.io': { volumeSnapshotClassName: 'longhorn-snapshot', backupVolumeSnapshotClassName: 'longhorn' } };
function backupVm({
actions = { backup: '/backup', snapshot: '/snapshot' }, volumes = [{}], target = 's3', thirdPartyBackupEnabled = true, csi = {}
} = {}) {
// target null: a user who can't read backup-target or csi-driver-config
const settings = target === null ? {} : {
'backup-target': { value: JSON.stringify({ type: target, thirdPartyBackupEnabled }) },
'csi-driver-config': { value: JSON.stringify(csi), default: JSON.stringify(LONGHORN_CSI) },
};
const pvcs = volumes.map((volume, i) => ({
id: `ns1/disk-${ i }`, name: `disk-${ i }`, isBlockVolume: true, ...volume
}));
const { vm } = createVm({
pvcs,
claims: pvcs.map((p) => p.name),
root: {
'harvester-common/getFeatureEnabled': (feature) => feature === 'thirdPartyVMBackup',
'harvester/byId': (type, id) => settings[id],
},
});
vm.actions = actions;
return Object.fromEntries(vm.backupTypeOptions.map((option) => [option.value, option.unavailableReason]));
}
const LVM_CSI = { 'lvm.driver.harvesterhci.io': { volumeSnapshotClassName: 'lvm', backupVolumeSnapshotClassName: 'lvm' } };
describe('class VirtVm', () => { describe('class VirtVm', () => {
describe('canTakeBackup', () => {
it.each([
[{ backup: '/b' }, true, true],
[{ snapshot: '/s' }, true, true],
[{ snapshot: '/s' }, false, false],
[{ backup: '/b' }, false, true],
[{}, true, false],
])('with actions %j and the feature %s returns %s', (actions, enabled, expected) => {
const { vm } = createVm({ root: { 'harvester-common/getFeatureEnabled': () => enabled, 'harvester/byId': () => undefined } });
vm.actions = actions;
expect(vm.canTakeBackup).toBe(expected);
});
it.each([
['an NFS target', { type: 'nfs' }, false],
['an S3 target with Restic and Kopia enabled', { type: 's3', thirdPartyBackupEnabled: true }, true],
['an S3 target with Restic and Kopia not enabled', { type: 's3' }, false],
['a target the user cannot read', undefined, true],
])('with only the snapshot action and %s returns %s', (_, target, expected) => {
const { vm } = createVm({
root: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/byId': () => (target ? { value: JSON.stringify(target) } : undefined),
},
});
vm.actions = { snapshot: '/s' };
expect(vm.canTakeBackup).toBe(expected);
});
it.each([
['a Longhorn v1 volume', { isLonghornV1: true, isBlockVolume: true }, false],
['a Filesystem volume', { isBlockVolume: false }, false],
['a CDI Block volume', { isCreatedForDataVolume: true, isBlockVolume: true }, true],
])('with only the snapshot action, a target the user cannot read and %s returns %s', (_, volume, expected) => {
const { vm } = createVm({
pvcs: [{ id: 'ns1/disk-0', ...volume }],
claims: ['disk-0'],
root: { 'harvester-common/getFeatureEnabled': () => true, 'harvester/byId': () => undefined },
});
vm.actions = { snapshot: '/s' };
expect(vm.canTakeBackup).toBe(expected);
});
});
describe('backupTypeOptions', () => {
it('should offer every type when a third-party driver has both snapshot classes', () => {
const reasons = backupVm({ csi: LVM_CSI, volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }] });
expect(reasons).toStrictEqual({
backup: undefined, restic: undefined, kopia: undefined
});
});
it('should explain a driver without a backup snapshot class on native only', () => {
const reasons = backupVm({
csi: { 'lvm.driver.harvesterhci.io': { volumeSnapshotClassName: 'lvm' } },
volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }],
});
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.noBackupSnapshotClass');
expect(reasons.kopia).toBeUndefined();
});
it.each([
['only other drivers', LVM_CSI],
['no drivers', {}],
])('should keep the default Longhorn entry when the configured value has %s', (_, csi) => {
const reasons = backupVm({ csi, volumes: [{ isLonghornV1: true, volumeProvider: 'driver.longhorn.io' }] });
expect(reasons.backup).toBeUndefined();
});
it('should offer only Restic and Kopia on Longhorn v2, where the backend drops the backup action', () => {
const reasons = backupVm({
actions: { snapshot: '/s' },
volumes: [{ isLonghornV2: true, volumeProvider: 'driver.longhorn.io' }],
});
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.longhornV2');
expect(reasons.restic).toBeUndefined();
});
it('should explain a CDI volume on native', () => {
const reasons = backupVm({ actions: { snapshot: '/s' }, volumes: [{ isCreatedForDataVolume: true }] });
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.cdi');
expect(reasons.kopia).toBeUndefined();
});
it.each([
['an NFS target', { target: 'nfs' }, 'requiresS3'],
['a Filesystem volume', { volumes: [{ isBlockVolume: false }] }, 'requiresBlock'],
['a Longhorn v1 volume', { volumes: [{ isLonghornV1: true }] }, 'longhornV1'],
['one bad volume among good ones', { volumes: [{}, { isLonghornV1: true }] }, 'longhornV1'],
['a driver without a snapshot class', {
actions: { backup: '/b' },
csi: { 'lvm.driver.harvesterhci.io': { backupVolumeSnapshotClassName: 'lvm' } },
volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }],
}, 'noSnapshotClass'],
['no snapshot action', { actions: { backup: '/b' } }, 'snapshot'],
['an S3 target with Restic and Kopia not enabled', { thirdPartyBackupEnabled: false }, 'thirdPartyBackupOff'],
])('should block Restic and Kopia with %s', (_, args, reason) => {
const reasons = backupVm(args);
expect(reasons.restic).toBe(`harvester.backup.typeUnavailable.${ reason }`);
expect(reasons.kopia).toBe(`harvester.backup.typeUnavailable.${ reason }`);
});
it('should explain a volume problem before a target that only needs Restic and Kopia enabled', () => {
const reasons = backupVm({ thirdPartyBackupEnabled: false, volumes: [{ isLonghornV1: true }] });
expect(reasons.kopia).toBe('harvester.backup.typeUnavailable.longhornV1');
});
it('should leave the target check to the webhook when the user cannot read it', () => {
const reasons = backupVm({
actions: { snapshot: '/s' }, target: null, volumes: [{ isCreatedForDataVolume: true }]
});
expect(reasons.restic).toBeUndefined();
expect(reasons.kopia).toBeUndefined();
});
it('should leave a driver check to the webhook when the CSI config is unreadable', () => {
const { vm } = createVm({
pvcs: [{ id: 'ns1/disk-pvc', volumeProvider: 'lvm.driver.harvesterhci.io' }],
root: { 'harvester/byId': () => undefined },
});
expect(vm.driverMissingSnapshotClass('backupVolumeSnapshotClassName')).toBeUndefined();
});
});
describe('fetchBackupTypeRequirements', () => {
it('should load only what the VM needs and survive a resource the user cannot read', async() => {
const { vm, lists } = createVm({ pvcs: [{ id: 'ns1/disk-pvc', spec: { volumeName: 'pv-1' } }] });
const dispatch = jest.fn((_, { type }) => (type === PV ? Promise.reject(new Error('forbidden')) : Promise.resolve()));
Object.defineProperty(vm, '$dispatch', { value: dispatch });
await expect(vm.fetchBackupTypeRequirements()).resolves.toBeUndefined();
expect(lists[PVC]).toHaveLength(1);
expect(dispatch).toHaveBeenCalledWith('find', { type: PVC, id: 'ns1/disk-pvc' });
expect(dispatch).toHaveBeenCalledWith('find', { type: HCI.SETTING, id: 'backup-target' });
expect(dispatch).toHaveBeenCalledWith('find', { type: HCI.SETTING, id: 'csi-driver-config' });
expect(dispatch).toHaveBeenCalledWith('find', { type: PV, id: 'pv-1' });
expect(dispatch).toHaveBeenCalledTimes(4);
});
});
describe('restoreResource', () => { describe('restoreResource', () => {
it('should distinguish snapshots from backups and follow backup updates', () => { it('should distinguish snapshots from backups and follow backup updates', () => {
const { vm, lists } = createVm({ const { vm, lists } = createVm({
@@ -293,9 +107,6 @@ describe('class VirtVm', () => {
expect(vm.restoreResource.fromSnapshot).toBe(false); expect(vm.restoreResource.fromSnapshot).toBe(false);
expect(vm.restoreState).toBe(false); expect(vm.restoreState).toBe(false);
lists[HCI.BACKUP][1].spec.type = 'kopia';
expect(vm.restoreResource.fromSnapshot).toBe(false);
lists[HCI.BACKUP][1].spec.type = 'snapshot'; lists[HCI.BACKUP][1].spec.type = 'snapshot';
expect(vm.restoreResource.fromSnapshot).toBe(true); expect(vm.restoreResource.fromSnapshot).toBe(true);
@@ -584,57 +395,4 @@ describe('class VirtVm', () => {
expect(vm.isRestartRequired).toBe(true); expect(vm.isRestartRequired).toBe(true);
}); });
}); });
describe('findInNamespace', () => {
function vmWithStore({ havePage }) {
const vm = Object.create(VirtVm.prototype);
const stored = [{ metadata: { namespace: 'ns1', name: 'a' } }, { metadata: { namespace: 'other', name: 'b' } }];
const dispatch = jest.fn((action) => Promise.resolve(action === 'findPage' ? { data: [{ metadata: { namespace: 'ns1', name: 'page' } }] } : stored));
vm.metadata = { name: 'vm1', namespace: 'ns1' };
Object.defineProperty(vm, '$getters', { value: { havePage: (type) => havePage && type === PVC } });
Object.defineProperty(vm, '$dispatch', { value: dispatch });
return {
vm, dispatch, stored
};
}
it('should load every resource and return a copy with the ones of the namespace when no page of the type is stored', async() => {
const { vm, dispatch, stored } = vmWithStore({ havePage: false });
const out = await vm.findInNamespace(PVC);
expect(dispatch.mock.calls).toStrictEqual([['findAll', { type: PVC }]]);
expect(out.map(({ metadata }) => metadata.name)).toStrictEqual(['a']);
expect(out).not.toBe(stored);
});
it('should read only the namespace, without storing it, when a paged list keeps a page of the type', async() => {
const { vm, dispatch } = vmWithStore({ havePage: true });
const out = await vm.findInNamespace(PVC);
expect(out.map(({ metadata }) => metadata.name)).toStrictEqual(['page']);
expect(dispatch).toHaveBeenCalledTimes(1);
const [action, { type, opt }] = dispatch.mock.calls[0];
expect([action, type, opt.transient]).toStrictEqual(['findPage', PVC, true]);
expect(opt.pagination.filters[0].fields.map(({ field, value }) => `${ field }=${ value }`)).toStrictEqual(['metadata.namespace=ns1']);
});
});
describe('disableResourceDetailDrawerConfigTab', () => {
it.each([
['hide the drawer\'s Config tab while the paged VM list keeps a page of VMs', { paged: true }, true],
['keep the drawer\'s Config tab when every VM is loaded', null, false],
])('should %s', (_, page, hidden) => {
const vm = Object.create(VirtVm.prototype);
const havePage = jest.fn(() => page);
Object.defineProperty(vm, '$getters', { value: { havePage } });
expect(vm.disableResourceDetailDrawerConfigTab).toBe(hidden);
expect(havePage).toHaveBeenCalledWith(HCI.VM);
});
});
}); });
@@ -353,14 +353,6 @@ export default class HciPv extends HarvesterResource {
return this.dataEngine === DATA_ENGINE_V2; return this.dataEngine === DATA_ENGINE_V2;
} }
get isBlockVolume() {
return this.spec?.volumeMode === 'Block';
}
get isCreatedForDataVolume() {
return !!this.metadata?.annotations?.[HCI_ANNOTATIONS.CDI_CREATED_FOR_DATA_VOLUME];
}
get isGoldenImageVolume() { get isGoldenImageVolume() {
return this?.metadata?.annotations?.[HCI_ANNOTATIONS.GOLDEN_IMAGE] === 'true'; return this?.metadata?.annotations?.[HCI_ANNOTATIONS.GOLDEN_IMAGE] === 'true';
} }
@@ -86,7 +86,7 @@ export default class HciVmBackup extends HarvesterResource {
restoreExistingVM(resource = this) { restoreExistingVM(resource = this) {
const router = this.currentRouter(); const router = this.currentRouter();
const targetResource = resource.spec.type === BACKUP_TYPE.SNAPSHOT ? HCI.VM_SNAPSHOT : HCI.BACKUP; const targetResource = resource.spec.type === BACKUP_TYPE.BACKUP ? HCI.BACKUP : HCI.VM_SNAPSHOT;
router.push({ router.push({
name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`, name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`,
@@ -100,7 +100,7 @@ export default class HciVmBackup extends HarvesterResource {
restoreNewVM(resource = this) { restoreNewVM(resource = this) {
const router = this.currentRouter(); const router = this.currentRouter();
const targetResource = resource.spec.type === BACKUP_TYPE.SNAPSHOT ? HCI.VM_SNAPSHOT : HCI.BACKUP; const targetResource = resource.spec.type === BACKUP_TYPE.BACKUP ? HCI.BACKUP : HCI.VM_SNAPSHOT;
router.push({ router.push({
name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`, name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`,
@@ -143,10 +143,6 @@ export default class HciVmBackup extends HarvesterResource {
return this.spec.source.name; return this.spec.source.name;
} }
get backupTypeLabel() {
return this.t(`harvester.backup.type.${ this.spec?.type || BACKUP_TYPE.BACKUP }`);
}
get backupContentName() { get backupContentName() {
return this?.status?.virtualMachineBackupContentName || ''; return this?.status?.virtualMachineBackupContentName || '';
} }
@@ -1,74 +0,0 @@
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;
}
}
-60
View File
@@ -1,72 +1,12 @@
import ipaddr from 'ipaddr.js';
import { clone } from '@shell/utils/object'; import { clone } from '@shell/utils/object';
import { HCI } from '../types'; import { HCI } from '../types';
import HarvesterResource from './harvester'; import HarvesterResource from './harvester';
const splitList = (value) => `${ value || '' }`.split(',').map((item) => item.trim()).filter(Boolean);
const parseIP = (ip) => {
try {
return ipaddr.parse(ip);
} catch (e) {
return null;
}
};
const parseCIDR = (cidr) => {
try {
return ipaddr.parseCIDR(cidr);
} catch (e) {
return null;
}
};
export default class HciSubnet extends HarvesterResource { export default class HciSubnet extends HarvesterResource {
get groupByVpc() { get groupByVpc() {
return this.spec?.vpc || ''; return this.spec?.vpc || '';
} }
// The provider names the NetworkAttachmentDefinition the subnet is attached to, as <nad>.<namespace>
// or <nad>.<namespace>.ovn. Kube-OVN's own subnets (join, ovn-default) use "ovn" and have none.
get networkAttachment() {
const [name, namespace, type, ...rest] = `${ this.spec?.provider || '' }`.split('.');
if (!name || !namespace || rest.length || (type !== undefined && type !== 'ovn')) {
return null;
}
return { name, namespace };
}
// Kube-OVN, as Harvester runs it (a secondary CNI), only puts a gateway's internal network on a
// subnet whose provider is <nad>.<namespace>.ovn
get isOverlayAttachment() {
return !!this.networkAttachment && `${ this.spec?.provider }`.endsWith('.ovn');
}
containsIP(ip) {
const address = parseIP(ip);
return !!address && splitList(this.spec?.cidrBlock).map(parseCIDR).some((range) => range?.[0].kind() === address.kind() && address.match(range));
}
// Kube-OVN assigns static IPs from the network address + 1 to the broadcast address - 1 of the subnet's
// CIDR (a /31 or /127 uses both), and never the gateway
canAssignIP(ip) {
const address = parseIP(ip);
const range = address && splitList(this.spec?.cidrBlock).map(parseCIDR).find((item) => item?.[0].kind() === address.kind() && address.match(item));
if (!range) {
return false;
}
const [base, prefix] = range;
const family = address.kind() === 'ipv4' ? ipaddr.IPv4 : ipaddr.IPv6;
const cidr = `${ base.toString() }/${ prefix }`;
const edges = prefix < (address.kind() === 'ipv4' ? 31 : 127) ? [family.networkAddressFromCIDR(cidr), family.broadcastAddressFromCIDR(cidr)] : [];
const gateways = splitList(this.spec?.gateway).map(parseIP).filter((gateway) => gateway?.kind() === address.kind());
return ![...edges, ...gateways].some((other) => other.toNormalizedString() === address.toNormalizedString());
}
get doneOverride() { get doneOverride() {
const detailLocation = clone(this.listLocation); const detailLocation = clone(this.listLocation);
-23
View File
@@ -2,9 +2,6 @@ import { clone } from '@shell/utils/object';
import { HCI } from '../types'; import { HCI } from '../types';
import HarvesterResource from './harvester'; import HarvesterResource from './harvester';
// Kube-OVN's cluster router, which a gateway without spec.vpc uses
const DEFAULT_VPC = 'ovn-cluster';
export default class HciVPC extends HarvesterResource { export default class HciVPC extends HarvesterResource {
get parentNameOverride() { get parentNameOverride() {
return this.$rootGetters['i18n/t'](`typeLabel."${ HCI.VPC }"`, { count: 1 })?.trim(); return this.$rootGetters['i18n/t'](`typeLabel."${ HCI.VPC }"`, { count: 1 })?.trim();
@@ -18,26 +15,6 @@ export default class HciVPC extends HarvesterResource {
return detailLocation; return detailLocation;
} }
get subnetResources() {
return (this.$getters['all'](HCI.SUBNET) || []).filter((subnet) => subnet.spec?.vpc === this.metadata?.name);
}
// The Egress Gateways of this VPC that have BFD on, which need its BFD port
get bfdEgressGateways() {
if (!this.$getters['schemaFor'](HCI.VPC_EGRESS_GATEWAY)) {
return [];
}
return (this.$getters['all'](HCI.VPC_EGRESS_GATEWAY) || [])
.filter((gateway) => (gateway.spec?.vpc || DEFAULT_VPC) === this.metadata?.name && gateway.spec?.bfd?.enabled);
}
get bfdPortEnabled() {
const bfdPort = this.spec?.bfdPort;
return bfdPort?.enabled === true && !!`${ bfdPort.ip || '' }`.trim();
}
get parentLocationOverride() { get parentLocationOverride() {
return { return {
...this.listLocation, ...this.listLocation,
@@ -2,8 +2,7 @@ import { load } from 'js-yaml';
import { omitBy, pickBy } from 'lodash'; import { omitBy, pickBy } from 'lodash';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester'; import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { colorForState, stateSort } from '@shell/plugins/dashboard-store/resource-class'; import { colorForState, stateSort } from '@shell/plugins/dashboard-store/resource-class';
import { POD, NODE, PV, PVC } from '@shell/config/types'; import { POD, NODE, PVC } from '@shell/config/types';
import { FilterArgs, PaginationParamFilter } from '@shell/types/store/pagination.types';
import { findBy } from '@shell/utils/array'; import { findBy } from '@shell/utils/array';
import { parseSi } from '@shell/utils/units'; import { parseSi } from '@shell/utils/units';
import { get, set } from '@shell/utils/object'; import { get, set } from '@shell/utils/object';
@@ -16,7 +15,7 @@ import { HCI } from '../types';
import HarvesterResource from './harvester'; import HarvesterResource from './harvester';
import { getVmCPUMemoryValues } from '../utils/cpuMemory'; import { getVmCPUMemoryValues } from '../utils/cpuMemory';
import { sharedComputed } from '../utils/shared-computed'; import { sharedComputed } from '../utils/shared-computed';
import { getBackupTarget, isBackupTargetSettingUnavailable } from '../utils/setting'; import { isBackupTargetSettingUnavailable } from '../utils/setting';
export const OFF = 'Off'; export const OFF = 'Off';
@@ -202,7 +201,7 @@ export default class VirtVm extends HarvesterResource {
}, },
{ {
action: 'backupVM', action: 'backupVM',
enabled: this.canTakeBackup && !this.isBackupTargetUnavailable, enabled: !!this.actions?.backup && !this.isBackupTargetUnavailable,
icon: 'icon icon-backup', icon: 'icon icon-backup',
label: this.t('harvester.action.backup') label: this.t('harvester.action.backup')
}, },
@@ -976,7 +975,7 @@ export default class VirtVm extends HarvesterResource {
const backup = this.$getters['byId'](HCI.BACKUP, backupId); const backup = this.$getters['byId'](HCI.BACKUP, backupId);
// Snapshots and backups are told apart by spec.type // Snapshots and backups are told apart by spec.type
res.fromSnapshot = !!backup && backup.spec?.type === BACKUP_TYPE.SNAPSHOT; res.fromSnapshot = !!backup && backup.spec?.type !== BACKUP_TYPE.BACKUP;
} }
return res; return res;
@@ -1163,35 +1162,6 @@ export default class VirtVm extends HarvesterResource {
.filter((name) => !!name); .filter((name) => !!name);
} }
// The resources of `type` in this VM's namespace, for the dialogs of the VM list. When the paged list keeps a page of
// `type` in the store, loading every resource would replace that page, and the next page load would shrink a list
// shared with the store, so read the namespace without storing it then.
async findInNamespace(type) {
const namespace = this.metadata.namespace;
if (!this.$getters['havePage'](type)) {
const all = await this.$dispatch('findAll', { type });
return all.filter((resource) => resource.metadata?.namespace === namespace);
}
const res = await this.$dispatch('findPage', {
type,
opt: {
transient: true,
pagination: new FilterArgs({ filters: PaginationParamFilter.createSingleField({ field: 'metadata.namespace', value: namespace }) }),
}
});
return res?.data || [];
}
// The configuration form loads every VM, volume, VMI and migration, which would replace the page the paged VM list
// keeps in the store, so the drawer only shows the YAML then. The VM's own page still shows its configuration
get disableResourceDetailDrawerConfigTab() {
return !!this.$getters['havePage'](HCI.VM);
}
get rootImageId() { get rootImageId() {
let imageId = ''; let imageId = '';
@@ -1396,123 +1366,6 @@ export default class VirtVm extends HarvesterResource {
return this.$rootGetters['harvester-common/getFeatureEnabled']('hotplugCdRom'); return this.$rootGetters['harvester-common/getFeatureEnabled']('hotplugCdRom');
} }
get thirdPartyBackupFeatureEnabled() {
return this.$rootGetters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
}
// The backend drops the backup action on Longhorn v2 and CDI volumes, which Restic and Kopia can still protect on S3.
// Without it, offer the menu only on VMs whose volumes Restic and Kopia support, as the snapshot action isn't gated on a target
get canTakeBackup() {
return !!this.actions?.backup || (this.thirdPartyBackupFeatureEnabled && !!this.actions?.snapshot && !this.dataMoverBackupUnavailableReason);
}
// Only users who can read backup-target know its type and whether it allows Restic and Kopia, for everyone else the webhook decides
get isBackupTargetNotS3() {
const { type } = getBackupTarget(this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target'));
return !!type && type !== 's3';
}
// The backend rejects Restic and Kopia until thirdPartyBackupEnabled is set on the S3 target
get isThirdPartyBackupOffOnTarget() {
const { type, thirdPartyBackupEnabled } = getBackupTarget(this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target'));
return type === 's3' && !thirdPartyBackupEnabled;
}
async fetchBackupTypeRequirements() {
const claimNames = this.spec.template.spec.volumes?.map((v) => v.persistentVolumeClaim?.claimName).filter((v) => !!v) || [];
// Each rule is enforced by the webhook too, so a resource this user can't read must not block the dialog
await Promise.allSettled([
...claimNames.map((name) => this.$dispatch('find', { type: PVC, id: `${ this.metadata.namespace }/${ name }` })),
this.$dispatch('find', { type: HCI.SETTING, id: 'backup-target' }),
this.$dispatch('find', { type: HCI.SETTING, id: 'csi-driver-config' }),
]);
await Promise.allSettled(
this.volumes.filter((pvc) => pvc.spec?.volumeName).map((pvc) => this.$dispatch('find', { type: PV, id: pvc.spec.volumeName }))
);
}
get backupTypeOptions() {
const nativeReason = this.nativeBackupUnavailableReason;
const dataMoverReason = this.dataMoverBackupUnavailableReason;
return [BACKUP_TYPE.BACKUP, BACKUP_TYPE.RESTIC, BACKUP_TYPE.KOPIA].map((value) => {
const unavailableReason = value === BACKUP_TYPE.BACKUP ? nativeReason : dataMoverReason;
return {
value,
label: this.t(`harvester.backup.type.${ value }`),
disabled: !!unavailableReason,
unavailableReason,
};
});
}
get nativeBackupUnavailableReason() {
if (!this.actions?.backup) {
const longhornV2 = this.longhornV2Volumes[0];
const cdi = this.volumes.find((pvc) => pvc.isCreatedForDataVolume);
if (longhornV2) {
return this.t('harvester.backup.typeUnavailable.longhornV2', { volume: longhornV2.name });
}
return cdi ? this.t('harvester.backup.typeUnavailable.cdi', { volume: cdi.name }) : this.t('harvester.backup.typeUnavailable.native');
}
const driver = this.driverMissingSnapshotClass('backupVolumeSnapshotClassName');
return driver ? this.t('harvester.backup.typeUnavailable.noBackupSnapshotClass', { driver }) : undefined;
}
get dataMoverBackupUnavailableReason() {
if (this.isBackupTargetNotS3) {
return this.t('harvester.backup.typeUnavailable.requiresS3');
}
const filesystem = this.volumes.find((pvc) => !pvc.isBlockVolume);
if (filesystem) {
return this.t('harvester.backup.typeUnavailable.requiresBlock', { volume: filesystem.name });
}
const longhornV1 = this.volumes.find((pvc) => pvc.isLonghornV1);
if (longhornV1) {
return this.t('harvester.backup.typeUnavailable.longhornV1', { volume: longhornV1.name });
}
if (!this.actions?.snapshot) {
const driver = this.driverMissingSnapshotClass('volumeSnapshotClassName');
return driver ? this.t('harvester.backup.typeUnavailable.noSnapshotClass', { driver }) : this.t('harvester.backup.typeUnavailable.snapshot');
}
// Last, so a reason that turning it on wouldn't fix is shown first
if (this.isThirdPartyBackupOffOnTarget) {
return this.t('harvester.backup.typeUnavailable.thirdPartyBackupOff');
}
return undefined;
}
driverMissingSnapshotClass(classKey) {
const setting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'csi-driver-config');
let config;
// Like the backend's LoadCSIDriverConfig: value adds drivers, the default's entries win
try {
config = { ...JSON.parse(setting?.value || '{}'), ...JSON.parse(setting?.default) };
} catch (e) {
return undefined;
}
return this.volumes.map((pvc) => pvc.volumeProvider).find((driver) => driver && !config[driver]?.[classKey]);
}
get isBackupTargetUnavailable() { get isBackupTargetUnavailable() {
const backupTargetSetting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target'); const backupTargetSetting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target');
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "harvester", "name": "harvester",
"description": "Rancher UI Extension for Harvester", "description": "Rancher UI Extension for Harvester",
"version": "1.10.0-dev", "version": "1.10.0-rc2",
"private": false, "private": false,
"rancher": { "rancher": {
"annotations": { "annotations": {
@@ -1,175 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import { HCI as HCI_ANNOTATIONS } from '@pkg/harvester/config/labels-annotations';
import HarvesterAirgapUpgrade from '../index.vue';
function createForm(overrides = {}) {
const image = {
metadata: { annotations: {} },
spec: {
displayName: 'upgrade.iso',
url: 'https://example.com/upgrade.iso',
},
save: jest.fn(),
};
const imageResult = {
id: 'harvester-system/upgrade-image',
notifyGeneratedName: jest.fn(),
uploadImage: jest.fn().mockResolvedValue({}),
};
image.save.mockResolvedValue(imageResult);
return {
imageSource: 'new',
sourceType: 'upload',
storageClassName: 'fast',
repositoryStorageClassEnabled: true,
uploadImageId: '',
imageId: '',
imageValue: image,
value: {
metadata: { annotations: {} }, spec: {}, save: jest.fn().mockResolvedValue(), notifyGeneratedName: jest.fn()
},
canEnableLogging: false,
skipSingleReplicaDetachedVolFeatureEnabled: false,
skipSingleReplicaDetachedVol: false,
allOSImages: [],
errors: [],
file: {},
done: jest.fn(),
preprocessImageName: HarvesterAirgapUpgrade.methods.preprocessImageName,
$store: { getters: { 'i18n/t': (key) => key } },
...overrides,
};
}
describe('page: HarvesterAirgapUpgrade', () => {
it('uses the shared Upgrade Repository StorageClass selector', () => {
expect(HarvesterAirgapUpgrade.components.UpgradeRepositoryStorageClass).toBeDefined();
});
it('leaves the default empty when it is unavailable for upgrade repositories', async() => {
const form = {
storageClassName: 'previous',
initImageValue: jest.fn(),
$store: {
dispatch: jest.fn()
.mockResolvedValueOnce([])
.mockResolvedValueOnce([
{
name: 'lvm-local', isDefault: true, provisioner: 'lvm.driver.harvesterhci.io'
},
{ name: 'fast' }
])
.mockResolvedValueOnce({})
}
};
await HarvesterAirgapUpgrade.fetch.call(form);
expect(form.storageClassName).toBe('');
});
it('prevents file upload until an upgrade StorageClass is selected', () => {
const disableUploadButton = HarvesterAirgapUpgrade.computed.disableUploadButton;
expect(disableUploadButton.call({
sourceType: 'upload',
isUploading: false,
repositoryStorageClassEnabled: true,
storageClassName: ''
})).toBe(true);
});
it('unlocks the StorageClass selector after switching an uploaded image to URL', async() => {
const wrapper = shallowMount(HarvesterAirgapUpgrade, {
global: {
mocks: {
$store: {
getters: {
'harvester-common/getFeatureEnabled': (feature) => feature === 'repositoryStorageClass',
'harvester/all': () => [],
'harvester/schemaFor': () => false,
},
dispatch: jest.fn().mockResolvedValue({
metadata: { annotations: {} },
spec: {
checksum: '', displayName: '', sourceType: 'upload', url: ''
},
}),
},
t: (key) => key,
},
stubs: {
CruResource: { template: '<div><slot /></div>' },
UpgradeRepositoryStorageClass: {
props: ['disabled'],
template: '<div data-testid="storage-class" :data-disabled="disabled" />',
},
},
},
});
await wrapper.setData({
value: {},
imageValue: {
spec: {
checksum: '', displayName: '', sourceType: 'upload', url: ''
},
remove: jest.fn().mockResolvedValue(),
},
sourceType: 'upload',
uploadController: { abort: jest.fn() },
uploadImageId: 'harvester-system/upgrade-image',
});
expect(wrapper.find('[data-testid="storage-class"]').attributes('data-disabled')).toBe('true');
await wrapper.setData({ sourceType: 'download' });
expect(wrapper.find('[data-testid="storage-class"]').attributes('data-disabled')).toBe('false');
});
it('saves an uploaded upgrade image on the selected StorageClass', async() => {
const form = createForm();
await HarvesterAirgapUpgrade.methods.uploadFile.call(form, { name: 'upgrade.iso' });
expect(form.imageValue.spec.targetStorageClassName).toBe('fast');
expect(form.uploadImageId).toBe('harvester-system/upgrade-image');
});
it('saves a downloaded upgrade image on the selected StorageClass', async() => {
const form = createForm({ sourceType: 'download' });
await HarvesterAirgapUpgrade.methods.save.call(form, jest.fn());
expect(form.imageValue.spec.targetStorageClassName).toBe('fast');
});
it('keeps the legacy StorageClass when the feature is disabled', async() => {
const form = createForm({ repositoryStorageClassEnabled: false });
await HarvesterAirgapUpgrade.methods.uploadFile.call(form, { name: 'upgrade.iso' });
expect(form.imageValue.spec.targetStorageClassName).toBe('longhorn-static');
});
it('does not change the StorageClass of an existing image', async() => {
const form = createForm({
imageSource: 'exist',
imageId: 'harvester-system/existing-image',
});
form.imageValue.spec.targetStorageClassName = 'existing-class';
await HarvesterAirgapUpgrade.methods.save.call(form, jest.fn());
expect(form.imageValue.spec.targetStorageClassName).toBe('existing-class');
});
it('does not add an Upgrade StorageClass annotation when the image selects the class', async() => {
const form = createForm({ uploadImageId: 'harvester-system/upgrade-image' });
await HarvesterAirgapUpgrade.methods.save.call(form, jest.fn());
expect(form.value.metadata.annotations[HCI_ANNOTATIONS.UPGRADE_STORAGE_CLASS]).toBeUndefined();
});
});
@@ -11,8 +11,6 @@ import { HCI } from '../../../../types';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../../config/harvester'; import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../../../../config/harvester';
import ImagePercentageBar from '@shell/components/formatter/ImagePercentageBar'; import ImagePercentageBar from '@shell/components/formatter/ImagePercentageBar';
import { Banner } from '@components/Banner'; import { Banner } from '@components/Banner';
import { STORAGE_CLASS } from '@shell/config/types';
import UpgradeRepositoryStorageClass, { getUpgradeRepositoryStorageClassDefault } from '../../../../components/UpgradeRepositoryStorageClass';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
const IMAGE_METHOD = { const IMAGE_METHOD = {
@@ -27,18 +25,13 @@ const UPLOAD = 'upload';
export default { export default {
name: 'HarvesterAirgapUpgrade', name: 'HarvesterAirgapUpgrade',
components: { components: {
Checkbox, CruResource, LabeledSelect, LabeledInput, RadioGroup, UpgradeInfo, UpgradeRepositoryStorageClass, ImagePercentageBar, Banner Checkbox, CruResource, LabeledSelect, LabeledInput, RadioGroup, UpgradeInfo, ImagePercentageBar, Banner
}, },
inheritAttrs: false, inheritAttrs: false,
async fetch() { async fetch() {
const [, storageClasses] = await Promise.all([ await this.$store.dispatch('harvester/findAll', { type: HCI.IMAGE });
this.$store.dispatch('harvester/findAll', { type: HCI.IMAGE }),
this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS })
]);
this.storageClassName = getUpgradeRepositoryStorageClassDefault(storageClasses);
const value = await this.$store.dispatch('harvester/create', { const value = await this.$store.dispatch('harvester/create', {
type: HCI.UPGRADE, type: HCI.UPGRADE,
@@ -72,7 +65,6 @@ export default {
uploadResult: null, uploadResult: null,
imageValue: null, imageValue: null,
enableLogging: true, enableLogging: true,
storageClassName: '',
IMAGE_METHOD, IMAGE_METHOD,
skipSingleReplicaDetachedVol: false, skipSingleReplicaDetachedVol: false,
errors: [], errors: [],
@@ -130,18 +122,6 @@ export default {
return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG); return this.$store.getters['harvester/schemaFor'](HCI.UPGRADE_LOG);
}, },
storageClasses() {
return this.$store.getters['harvester/all'](STORAGE_CLASS) || [];
},
canSubmitUpgrade() {
return this.enableUpgrade && (!this.repositoryStorageClassEnabled || !this.createNewImage || !!this.storageClassName);
},
repositoryStorageClassEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('repositoryStorageClass');
},
uploadProgress() { uploadProgress() {
const image = this.$store.getters['harvester/byId'](HCI.IMAGE, this.imageValue.id); const image = this.$store.getters['harvester/byId'](HCI.IMAGE, this.imageValue.id);
@@ -185,7 +165,7 @@ export default {
}, },
disableUploadButton() { disableUploadButton() {
return this.sourceType === UPLOAD && (this.isUploading || (this.repositoryStorageClassEnabled && !this.storageClassName)); return this.sourceType === UPLOAD && this.isUploading;
}, },
}, },
@@ -249,7 +229,7 @@ export default {
} }
this.imageValue.spec.sourceType = DOWNLOAD; this.imageValue.spec.sourceType = DOWNLOAD;
this.imageValue.spec.targetStorageClassName = this.repositoryStorageClassEnabled ? this.storageClassName : 'longhorn-static'; this.imageValue.spec.targetStorageClassName = 'longhorn-static';
res = await this.imageValue.save(); res = await this.imageValue.save();
res.notifyGeneratedName?.(); res.notifyGeneratedName?.();
@@ -271,10 +251,7 @@ export default {
this.value.spec.logEnabled = this.enableLogging; this.value.spec.logEnabled = this.enableLogging;
} }
if (this.skipSingleReplicaDetachedVolFeatureEnabled) { if (this.skipSingleReplicaDetachedVolFeatureEnabled) {
this.value.metadata.annotations = { this.value.metadata.annotations = { [HCI_ANNOTATIONS.SKIP_SINGLE_REPLICA_DETACHED_VOL]: JSON.stringify(this.skipSingleReplicaDetachedVol) };
...this.value.metadata.annotations,
[HCI_ANNOTATIONS.SKIP_SINGLE_REPLICA_DETACHED_VOL]: JSON.stringify(this.skipSingleReplicaDetachedVol)
};
} }
await this.value.save(); await this.value.save();
this.value.notifyGeneratedName?.(); this.value.notifyGeneratedName?.();
@@ -311,7 +288,7 @@ export default {
this.imageValue.spec.url = ''; this.imageValue.spec.url = '';
try { try {
this.imageValue.spec.targetStorageClassName = this.repositoryStorageClassEnabled ? this.storageClassName : 'longhorn-static'; this.imageValue.spec.targetStorageClassName = 'longhorn-static';
const res = await this.imageValue.save(); const res = await this.imageValue.save();
@@ -377,10 +354,6 @@ export default {
watch: { watch: {
async sourceType(neu) { async sourceType(neu) {
if (neu === DOWNLOAD) {
this.uploadImageId = '';
}
if (neu === DOWNLOAD && this.imageValue && this.uploadController) { if (neu === DOWNLOAD && this.imageValue && this.uploadController) {
if (this.uploadController) { if (this.uploadController) {
this.uploadController.abort(); this.uploadController.abort();
@@ -439,7 +412,7 @@ export default {
:errors="errors" :errors="errors"
:can-yaml="false" :can-yaml="false"
finish-button-mode="upgrade" finish-button-mode="upgrade"
:validation-passed="canSubmitUpgrade" :validation-passed="enableUpgrade"
:cancel-event="true" :cancel-event="true"
@finish="save" @finish="save"
@cancel="done" @cancel="done"
@@ -508,14 +481,6 @@ export default {
required required
/> />
<UpgradeRepositoryStorageClass
v-if="repositoryStorageClassEnabled"
v-model:value="storageClassName"
class="mb-20"
:disabled="uploadImageId !== ''"
:storage-classes="storageClasses"
/>
<LabeledInput <LabeledInput
v-model:value="imageValue.spec.checksum" v-model:value="imageValue.spec.checksum"
class="mb-10" class="mb-10"
@@ -1,441 +0,0 @@
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');
});
});
@@ -1,588 +0,0 @@
<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>
@@ -1,49 +0,0 @@
import { mount, flushPromises } from '@vue/test-utils';
import Banner from '@components/Banner/Banner.vue';
import PromptRemoveIgnoreRule from '../health.harvesterhci.io.healthignorerule.vue';
function ruleOf(checkKey, remove = () => {}) {
return { spec: { componentHealth: 'h', checkKey }, remove: jest.fn(remove) };
}
function mountPrompt(value) {
const close = jest.fn();
const prompt = mount(PromptRemoveIgnoreRule, {
props: { value, close },
global: { mocks: { $store: { getters: { 'i18n/t': (key) => key } } } },
});
return { prompt, close };
}
describe('promptRemove: health.harvesterhci.io.healthignorerule', () => {
it('names the check the rule is for, not the rule', () => {
const { prompt } = mountPrompt([ruleOf('ImageRetryLimitExceeded')]);
expect(prompt.find('b').text()).toBe('ImageRetryLimitExceeded');
});
it('deletes the rule and closes', async() => {
const rule = ruleOf('a');
const { prompt, close } = mountPrompt([rule]);
const buttonDone = jest.fn();
await prompt.vm.remove(buttonDone);
expect(rule.remove).toHaveBeenCalledTimes(1);
expect(close).toHaveBeenCalledWith(buttonDone);
expect(buttonDone).not.toHaveBeenCalled();
});
it('shows why the rule could not be deleted and stays open', async() => {
const { prompt, close } = mountPrompt([ruleOf('a', () => Promise.reject(new Error('forbidden')))]);
const buttonDone = jest.fn();
await prompt.vm.remove(buttonDone);
await flushPromises();
expect(prompt.findComponent(Banner).text()).toContain('forbidden');
expect(close).not.toHaveBeenCalled();
expect(buttonDone).toHaveBeenCalledWith(false);
});
});
@@ -1,119 +0,0 @@
import { mount } from '@vue/test-utils';
import PromptRemoveVm from '../kubevirt.io.virtualmachine.vue';
import { HCI } from '../../types';
function createVm(name, disks) {
return {
id: `default/${ name }`,
type: HCI.VM,
links: { self: `https://harvester/v1/harvester/kubevirt.io.virtualmachines/default/${ name }` },
spec: {
template: {
spec: {
volumes: [
...disks.map((disk) => ({ name: disk, persistentVolumeClaim: { claimName: `${ name }-${ disk }` } })),
{ name: 'cloudinitdisk', cloudInitNoCloud: {} },
],
},
},
},
remove: jest.fn(),
};
}
function mountPrompt(value) {
return mount(PromptRemoveVm, {
props: {
value,
names: value.map((vm) => vm.id),
type: 'Virtual Machine',
close: jest.fn(),
},
global: { mocks: { $store: { getters: { 'i18n/t': (key) => key }, commit: jest.fn() } } },
});
}
// Toggles the checkbox like a click does: flips `checked` and fires `change`
function click(input) {
return input.setValue(!input.element.checked);
}
function removeUrls(prompt, vms) {
prompt.vm.remove();
return vms.map((vm) => vm.remove.mock.calls[0][0].url);
}
describe('promptRemove: kubevirt.io.virtualmachine', () => {
describe('when several VMs are removed', () => {
it('should check "Delete All" by default and remove the disks of every VM', () => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0', 'disk-1'])];
const prompt = mountPrompt(vms);
expect(prompt.find('input[type="checkbox"]').element.checked).toBe(true);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-0&propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?removedDisks=disk-0&removedDisks=disk-1&propagationPolicy=Foreground',
]);
});
it('should uncheck "Delete All" with one click and keep the disks', async() => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0'])];
const prompt = mountPrompt(vms);
const input = prompt.find('input[type="checkbox"]');
await click(input);
expect(input.element.checked).toBe(false);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?propagationPolicy=Foreground',
]);
});
it('should toggle "Delete All" on every click and remove the disks once it is checked again', async() => {
const vms = [createVm('vm1', ['disk-0']), createVm('vm2', ['disk-0'])];
const prompt = mountPrompt(vms);
const input = prompt.find('input[type="checkbox"]');
const states = [input.element.checked];
await click(input);
states.push(input.element.checked);
await click(input);
states.push(input.element.checked);
expect(states).toStrictEqual([true, false, true]);
expect(removeUrls(prompt, vms)).toStrictEqual([
'/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-0&propagationPolicy=Foreground',
'/v1/harvester/kubevirt.io.virtualmachines/default/vm2?removedDisks=disk-0&propagationPolicy=Foreground',
]);
});
});
describe('when one VM is removed', () => {
it('should list its disks with the first one checked by default', () => {
const prompt = mountPrompt([createVm('vm1', ['disk-0', 'disk-1'])]);
const inputs = prompt.findAll('input[type="checkbox"]');
expect(inputs.map((input) => input.element.value)).toStrictEqual(['disk-0', 'disk-1']);
expect(inputs.map((input) => input.element.checked)).toStrictEqual([true, false]);
});
it('should remove only the checked disks', async() => {
const vm = createVm('vm1', ['disk-0', 'disk-1']);
const prompt = mountPrompt([vm]);
const [first, second] = prompt.findAll('input[type="checkbox"]');
await click(first);
await click(second);
expect([first.element.checked, second.element.checked]).toStrictEqual([false, true]);
expect(removeUrls(prompt, [vm])).toStrictEqual(['/v1/harvester/kubevirt.io.virtualmachines/default/vm1?removedDisks=disk-1&propagationPolicy=Foreground']);
});
});
});
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more