Compare commits

..
Author SHA1 Message Date
Harvester Bot 3322162d9a chore: bump version to 1.10.0-rc1 (#1213)
Signed-off-by: Harvester Bot <94133267+harvesterhci-io-github-bot@users.noreply.github.com>
2026-10-29 17:31:29 +01:00
49 changed files with 1187 additions and 5744 deletions
+4 -14
View File
@@ -1,6 +1,6 @@
{
"name": "harvester-ui-extension",
"version": "1.10.0-dev",
"version": "1.10.0-rc1",
"private": false,
"engines": {
"node": ">=24.0.0"
@@ -29,31 +29,21 @@
},
"resolutions": {
"@novnc/novnc": "1.7.0",
"@tootallnate/once": "^2.0.1",
"@types/lodash": "4.17.25",
"@types/node": "25.3.3",
"cookie": "0.7.2",
"@types/node": "25.9.6",
"cronstrue": "2.59.0",
"d3-color": "3.1.0",
"**/diff2html/diff": "5.2.2",
"ejs": "3.1.10",
"follow-redirects": "1.16.0",
"glob": "7.2.3",
"glob-parent": "6.0.2",
"json5": "2.2.3",
"markdown-it": "14.3.1",
"@types/lodash": "4.17.25",
"merge": "2.1.1",
"node-forge": "1.4.0",
"nth-check": "2.1.1",
"postcss": "8.5.26",
"postcss-selector-parser": "7.1.6",
"qs": "6.16.0",
"roarr": "7.21.7",
"semver": "7.5.4",
"serialize-javascript": "7.1.3",
"uuid": "11.1.1",
"webpack-dev-server": "5.2.6",
"ws": "8.21.0",
"semver": "7.8.5",
"@vue/cli-service/html-webpack-plugin": "^5.0.0"
},
"scripts": {
+8
View File
@@ -141,6 +141,10 @@ export default {
filterCategorySettings() {
return this.settings.filter((s) => {
if (!this.getFeatureEnabled(s.featureFlag)) {
return false;
}
if (this.category !== 'advanced') {
return (CATEGORY[this.category] || []).find((item) => item === s.id);
} 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) {
return HCI_ALLOWED_SETTINGS.find((setting) => setting.id === id);
},
@@ -1,336 +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, ignoreRuleName, ignoredResourceCount, resourceIgnoredBy, severityColor
} from '../../utils/component-health';
const props = defineProps({
rows: {
type: Array,
required: true,
},
ignoreRules: {
type: Array,
default: () => [],
},
showIgnored: {
type: Boolean,
default: false,
},
// 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([]);
function affectedResourceNames(row) {
return props.showIgnored ? allAffectedResourceNames(row) : activeAffectedResourceNames(row);
}
// 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);
}
function visibleAffectedResourceNames(row) {
const names = affectedResourceNames(row);
return expandedResourceIds.value.includes(row.id) ? names : names.slice(0, AFFECTED_RESOURCES_TRUNCATE_COUNT);
}
function remainingAffectedResourcesCount(row) {
return Math.max(affectedResourceNames(row).length - AFFECTED_RESOURCES_TRUNCATE_COUNT, 0);
}
function isResourceIgnored(row, name) {
return row.ignored || !!resourceIgnoredBy(row, name);
}
// the ignored resources that are left out of the list
function hiddenIgnoredCount(row) {
return props.showIgnored ? 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 }">
{{ 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="affectedResourceNames(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>
<RcButton
v-if="remainingAffectedResourcesCount(row)"
variant="link"
size="small"
class="compact-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>
<span
v-if="hiddenIgnoredCount(row)"
class="hidden-ignored text-muted"
>
{{ t('harvester.dashboard.sections.componentHealth.ignore.plusIgnored', { n: hiddenIgnoredCount(row) }) }}
</span>
</div>
<span v-else>
{{ t('harvester.dashboard.sections.componentHealth.noAffectedResources') }}
</span>
</template>
</SortableTable>
</template>
<style lang="scss" scoped>
// 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;
}
// the same size as the "+ N more" link above it
.hidden-ignored {
font-size: 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,342 +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 { 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, activeAffectedResourceNames, affectedResourceKind,
affectedResourceLabel, allAffectedResourceNames, componentOf, healthSummarySeverity, ignoredCounts, 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),
...(showIgnored.value ? allAffectedResourceNames(check) : activeAffectedResourceNames(check)),
].join(' ').toLowerCase(),
})));
const ignored = computed(() => ignoredCounts(checks.value));
const hasIgnored = computed(() => ignored.value.checks + ignored.value.resources > 0);
// says what turning it on brings back, the same whether it is on or off
const showIgnoredLabel = computed(() => {
const counts = [
ignored.value.checks && t('harvester.dashboard.sections.componentHealth.ignoredChecks', { count: ignored.value.checks }),
ignored.value.resources && t('harvester.dashboard.sections.componentHealth.ignoredResources', { count: ignored.value.resources }),
].filter(Boolean).join(', ');
return t('harvester.dashboard.sections.componentHealth.showIgnored', { counts });
});
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="hasIgnored"
class="show-ignored"
>
<Checkbox
v-model:value="showIgnored"
type="checkbox"
:label="showIgnoredLabel"
/>
</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"
:show-ignored="showIgnored"
: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%;
}
.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,320 +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'),
set: (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)));
// a rule that lists no resource would ignore the entire check
const canSave = computed(() => (scope.value === 'check' || selectedResources.value.length > 0) && hasChanges.value);
// saving something else on an expired rule leaves it expired
const staysExpired = computed(() => hasExpired && !duration.value && 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"
>
<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>
<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"
: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"
@update:value="selected = $event"
/>
</div>
</div>
<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>
<LabeledInput
v-model:value="reason"
:label="t('harvester.dashboard.sections.componentHealth.ignore.reason')"
:placeholder="isView ? '' : t('harvester.dashboard.sections.componentHealth.ignore.reasonPlaceholder')"
:mode="mode"
/>
<Banner
v-for="(err, i) in errors"
:key="i"
class="m-0"
color="error"
:label="err"
/>
<Banner
v-if="staysExpired"
class="m-0"
color="warning"
data-testid="component-health-ignore-stays-expired"
:label="t('harvester.dashboard.sections.componentHealth.ignore.staysExpired', { date: dateTimeFormat(expiresAt, store) })"
/>
<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,912 +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, ignoreRuleName, ignoredCounts, 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'),
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'].forEach((text) => expect(filterText()).toContain(text));
expect(filterText()).not.toContain('vm-hidden');
await w.findComponent(Checkbox).vm.$emit('update:value', true);
expect(filterText()).toContain('vm-hidden');
});
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.text()).toContain('showIgnored');
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' } })],
});
expect(clean.text()).not.toContain('showIgnored');
});
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 says how many ignored resources it leaves out', () => {
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 hidden = mountChecks({ rows: [row] }, { SortableTable: table });
const shown = mountChecks({ rows: [row], showIgnored: true }, { SortableTable: table });
expect(hidden.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(hidden.find('.hidden-ignored').text()).toContain('ignore.plusIgnored');
expect(shown.findComponent(RcCounterBadge).props('count')).toBe(2);
expect(shown.find('.hidden-ignored').exists()).toBe(false);
});
it('counts what "Show ignored" brings back, each thing once', () => {
const check = (ignored, names) => ({ ignored, affectedResources: { names } });
expect(ignoredCounts([
check(true, { a: { ignored: true }, b: { ignored: true } }),
check(false, { c: { ignored: true }, d: {} }),
check(false, {
e: { ignored: true }, f: { ignored: true }, g: {}
}),
check(false, { h: {} }),
])).toStrictEqual({ checks: 1, resources: 3 });
expect(ignoredCounts(undefined)).toStrictEqual({ checks: 0, resources: 0 });
});
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', () => {
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], showIgnored: true }, { SortableTable: table });
const whole = mountChecks({ rows: [wholeRow], showIgnored: true }, { SortableTable: table });
expect(tags(partly)).toStrictEqual([
{
ignored: true, disabled: true, says: true
},
{
ignored: false, disabled: false, says: false
},
]);
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', () => {
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 = (props) => mountChecks({ showIgnored: true, ...props }, { SortableTable: table }).text().replace(/\s+/g, ' ');
expect(textOf({ rows: [row] })).toMatch(/one ?\(%harvester\.dashboard\.sections\.componentHealth\.ignore\.ignored%\) ?two/);
expect(textOf({ rows: [row] })).not.toContain('a (%harvester');
expect(textOf({ rows: [{ ...row, ignored: true }] })).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 { w, confirm } = mountRuleModal();
const [scope, duration] = w.findAllComponents(RadioGroup);
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
} = mountRuleModal({ rule, mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
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);
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('warns that an expired rule stays expired when only something else changes', async() => {
const { w, duration, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: LAST_WEEK }), mode: 'edit' });
expect(warning()).toBeUndefined();
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning().props('label')).toContain('ignore.staysExpired');
await duration().vm.$emit('update:value', 'days7');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('does not warn about a rule that has not expired', async() => {
const { w, warning } = mountRuleModal({ rule: ruleOf({ expiresAt: IN_A_WEEK }), mode: 'edit' });
await w.findComponent(LabeledInput).vm.$emit('update:value', 'known issue');
await flushPromises();
expect(warning()).toBeUndefined();
});
it('opens a rule without resources on the entire check, and selects them all when asked', async() => {
const {
w, confirm, duration, currentExpiry
} = mountRuleModal({ rule: ruleOf(), mode: 'edit' });
const [scope] = w.findAllComponents(RadioGroup);
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
} = mountRuleModal({
rule: ruleOf({
resources: ['two'], expiresAt: IN_A_WEEK, reason: 'known issue'
}),
mode: 'view'
});
[...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();
});
});
});
@@ -136,15 +136,20 @@ export default {
this.addedShortcutKeys.push([].concat(this.keysRecord));
},
// The index is the one in displayedKeys, which lists the added shortcuts first.
removeKey(index) {
const added = this.addedShortcutKeys.length;
removeKey(keys) {
const key = keys.replace(/(\s*)<code>|<\/code>/g, '').replace(/\s*,\s*/g, ',');
if (index < added) {
this.addedShortcutKeys.splice(index, 1);
} else {
this.preferredShortcutKeys.splice(index - added, 1);
}
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) {
@@ -215,8 +220,6 @@ export default {
<Banner
v-for="(keys,index) in displayedKeys"
:key="index"
:closable="true"
@close="removeKey(index)"
>
<span v-clean-html="keys"></span>
</Banner>
@@ -230,10 +233,10 @@ export default {
class="btn role-secondary mr-20"
@click.prevent="closeRecordingModal"
>
<t k="generic.cancel" />
<t k="generic.close" />
</button>
<AsyncButton
mode="edit"
mode="done"
@click="saveKeys"
/>
</div>
@@ -428,8 +428,7 @@ export default {
if (document.fullscreenElement) {
await document.exitFullscreen();
} else {
// The whole page and not only the console, because dialogs render outside of it.
await document.documentElement.requestFullscreen();
await this.$refs.consoleContainer.requestFullscreen();
// Keyboard lock lets shortcuts such as Ctrl+W and F11 reach the guest.
await navigator.keyboard?.lock?.(['KeyW', 'F11']);
}
@@ -455,7 +454,10 @@ export default {
<template>
<div id="app">
<div class="vm-console">
<div
ref="consoleContainer"
class="vm-console"
>
<div class="combination-keys">
<div class="toolbar-group">
<v-dropdown
@@ -516,7 +518,6 @@ export default {
<div
v-for="(keys, index) in preferredShortcutKeys"
:key="index"
class="custom-shortcut"
>
<button
class="btn btn-sm bg-primary"
@@ -734,11 +735,6 @@ export default {
width: 100%;
}
// The space around the separator above the list.
.custom-shortcut + .custom-shortcut {
margin-top: 7px;
}
.console-status {
color: #fff;
font-size: 12px;
@@ -1,92 +0,0 @@
import { shallowMount } from '@vue/test-utils';
import Banner from '@components/Banner/Banner.vue';
import NovncConsoleCustomKeys from '../NovncConsoleCustomKeys.vue';
const PREFERED_SHORTCUT_KEYS = 'prefered-shortcut-keys';
const key = (value) => ({ key: value, code: value });
const CTRL_F2 = [key('Control'), key('F2')];
const CTRL_SPACE = [key('Control'), key(' ')];
const ALT_T = [key('Alt'), key('t')];
const mountKeys = (saved = []) => {
const preference = {
data: { [PREFERED_SHORTCUT_KEYS]: JSON.stringify(saved) },
save: jest.fn().mockResolvedValue(),
};
const wrapper = shallowMount(NovncConsoleCustomKeys, {
global: {
mocks: { $store: { getters: { 'management/all': () => [preference] } } },
stubs: { ModalWithCard: { template: '<div><slot name="content" /></div>' } },
},
});
return { wrapper, preference };
};
const listed = (wrapper) => wrapper.find('.displayed-banners').findAllComponents(Banner);
const closeBanner = async(wrapper, index) => {
listed(wrapper)[index].vm.$emit('close');
await wrapper.vm.$nextTick();
};
const savedAfterDone = async(wrapper, preference) => {
await wrapper.vm.saveKeys(jest.fn());
return JSON.parse(preference.data[PREFERED_SHORTCUT_KEYS]);
};
describe('component: NovncConsoleCustomKeys', () => {
it('should offer to remove every listed shortcut', () => {
const { wrapper } = mountKeys([CTRL_F2, ALT_T]);
expect(listed(wrapper).map((banner) => banner.props('closable'))).toStrictEqual([true, true]);
});
it('should save without the shortcut that was removed', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await closeBanner(wrapper, 0);
expect(listed(wrapper)).toHaveLength(1);
expect(preference.save).not.toHaveBeenCalled();
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
expect(preference.save).toHaveBeenCalledTimes(1);
});
it('should remove a shortcut with the Space key in it', async() => {
const { wrapper, preference } = mountKeys([CTRL_SPACE, ALT_T]);
await closeBanner(wrapper, 0);
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
});
it('should tell a shortcut that was just added from the saved ones', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2]);
wrapper.vm.keysRecord = ALT_T;
wrapper.vm.addShortcutKey();
await wrapper.vm.$nextTick();
// Just added shortcuts are listed first.
await closeBanner(wrapper, 1);
await expect(savedAfterDone(wrapper, preference)).resolves.toStrictEqual([ALT_T]);
});
it('should keep the saved shortcuts when it is closed without saving', async() => {
const { wrapper, preference } = mountKeys([CTRL_F2, ALT_T]);
await closeBanner(wrapper, 0);
wrapper.vm.closeRecordingModal();
expect(wrapper.emitted('close')).toHaveLength(1);
expect(preference.save).not.toHaveBeenCalled();
expect(JSON.parse(preference.data[PREFERED_SHORTCUT_KEYS])).toStrictEqual([CTRL_F2, ALT_T]);
});
});
@@ -92,17 +92,4 @@ describe('component: NovncConsoleWrapper', () => {
expect(wrapper.vm.confirmAction).toBeNull();
});
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
View File
@@ -85,7 +85,6 @@ const FEATURE_FLAGS = {
'v1.10.0': [
'maintenanceModeConditions',
'maintenanceModeDrainTimeoutSetting',
'componentHealth',
],
};
+10 -18
View File
@@ -710,24 +710,16 @@ export function init($plugin, store) {
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.SR_IOV,
HCI.PCI_DEVICE,
HCI.SR_IOVGPU_DEVICE,
HCI.VGPU_DEVICE,
HCI.MIG_CONFIGURATION,
HCI.USB_DEVICE,
],
'hardwareDevices'
);
weightGroup('hardwareDevices', 488, true);
basicType(
[
TEMPLATE,
HCI.SSH,
HCI.CLOUD_TEMPLATE,
HCI.STORAGE,
HCI.ADD_ONS,
HCI.SECRET,
HCI.SETTING
@@ -1125,7 +1117,7 @@ export function init($plugin, store) {
virtualType({
label: 'PCI Devices',
group: 'hardwareDevices',
group: 'advanced',
weight: 14,
name: HCI.PCI_DEVICE,
namespaced: false,
@@ -1161,7 +1153,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOV,
labelKey: 'harvester.sriov.label',
group: 'hardwareDevices',
group: 'advanced',
weight: 15,
name: HCI.SR_IOV,
namespaced: false,
@@ -1181,7 +1173,7 @@ export function init($plugin, store) {
virtualType({
ifHaveType: HCI.SR_IOVGPU_DEVICE,
labelKey: 'harvester.sriovgpu.label',
group: 'hardwareDevices',
group: 'advanced',
weight: 13,
name: HCI.SR_IOVGPU_DEVICE,
namespaced: false,
@@ -1200,7 +1192,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.vgpu.label',
group: 'hardwareDevices',
group: 'advanced',
weight: 12,
name: HCI.VGPU_DEVICE,
namespaced: false,
@@ -1228,7 +1220,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.migconfiguration.label',
group: 'hardwareDevices',
group: 'advanced',
weight: 12,
name: HCI.MIG_CONFIGURATION,
namespaced: false,
@@ -1248,7 +1240,7 @@ export function init($plugin, store) {
virtualType({
labelKey: 'harvester.usb.label',
group: 'hardwareDevices',
group: 'advanced',
weight: 11,
name: HCI.USB_DEVICE,
namespaced: false,
@@ -18,7 +18,6 @@ import { getLatestMigration } from '../../utils/vm';
import CloudConfig from '../../edit/kubevirt.io.virtualmachine/VirtualMachineCloudConfig';
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 AccessCredentials from '../../edit/kubevirt.io.virtualmachine/VirtualMachineAccessCredentials';
import Events from './VirtualMachineTabs/VirtualMachineEvents';
@@ -41,7 +40,6 @@ export default {
OverviewBasics,
LabelValue,
Volume,
VMPerformanceOptions,
Network,
OverviewKeypairs,
CloudConfig,
@@ -255,15 +253,9 @@ export default {
:namespace="value.metadata.namespace"
:vm="value"
:resource-type="value.type"
/>
<VMPerformanceOptions
:block-multi-queue="blockMultiQueue"
:io-threads-policy="ioThreadsPolicy"
:io-thread-count="ioThreadCount"
:has-virtio-disk="hasVirtioDisk"
:has-dedicated-iothread="hasDedicatedIOThread"
mode="view"
class="mt-20"
/>
</Tab>
@@ -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 });
});
});
@@ -21,7 +21,6 @@ import { HCI } from '../types';
import VM_MIXIN from '../mixins/harvester-vm';
import Reserved from './kubevirt.io.virtualmachine/VirtualMachineReserved';
import Volume from './kubevirt.io.virtualmachine/VirtualMachineVolume';
import VMPerformanceOptions from './kubevirt.io.virtualmachine/VirtualMachineVolume/VMPerformanceOptions';
import Network from './kubevirt.io.virtualmachine/VirtualMachineNetwork';
import CpuMemory from './kubevirt.io.virtualmachine/VirtualMachineCpuMemory';
import CpuModel from './kubevirt.io.virtualmachine/VirtualMachineCpuModel';
@@ -38,7 +37,6 @@ export default {
Tab,
SSHKey,
Volume,
VMPerformanceOptions,
Tabbed,
Network,
Checkbox,
@@ -179,17 +177,8 @@ export default {
},
async saveVMT(buttonCb) {
this.errors = [];
this.parseVM();
this.validateCloudInit();
if (this.errors.length) {
buttonCb(false);
return;
}
const templates = await this.$store.dispatch('harvester/findAll', { type: HCI.VM_TEMPLATE });
const template = templates.find( (O) => O.metadata.name === this.templateValue.metadata.name);
@@ -401,6 +390,9 @@ export default {
>
<Volume
v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode"
:namespace="value.metadata.namespace"
:existing-volume-disabled="true"
@@ -586,16 +578,6 @@ export default {
</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
ref="yamlEditor"
:mode="mode"
@@ -2,6 +2,7 @@
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { Checkbox } from '@components/Form/Checkbox';
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';
const { DEFAULT, HIGH, CUSTOM } = DISK_PERFORMANCE_PROFILE;
@@ -30,18 +31,23 @@ export default {
},
data() {
const hasPerf = !!(this.value.cache || this.value.io || this.value.dedicatedIOThread);
return {
DISK_PERFORMANCE_PROFILE,
expanded: hasPerf,
profile: this.detectProfile(),
// Bus the disk used before the "High Performance" preset switched it to
// virtio, so returning to "Default" can put it back.
busBeforeHighProfile: null,
// True only while the user has explicitly picked "Custom" in the selector.
userSelectedCustom: false,
};
},
computed: {
isView() {
return this.mode === _VIEW;
},
storagePerformanceEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('highPerformanceStorage');
},
@@ -97,13 +103,13 @@ export default {
watch: {
// Keep the profile selector in sync if the row is repopulated (e.g. editing an existing VM).
'value.cache'() {
this.syncProfile();
this.profile = this.detectProfile();
},
'value.io'() {
this.syncProfile();
this.profile = this.detectProfile();
},
'value.dedicatedIOThread'() {
this.syncProfile();
this.profile = this.detectProfile();
},
},
@@ -122,16 +128,6 @@ export default {
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) {
if (value === '') {
return this.t('harvester.virtualMachine.volume.performance.cacheMode.default');
@@ -144,7 +140,6 @@ export default {
const previous = this.profile;
this.profile = profile;
this.userSelectedCustom = profile === CUSTOM;
if (profile === DEFAULT) {
this.value.cache = '';
@@ -198,49 +193,51 @@ export default {
v-if="!isCdRom && storagePerformanceEnabled"
class="disk-performance"
>
<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-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"
<button
v-if="!isView"
type="button"
class="btn btn-sm role-link expand-toggle"
:aria-expanded="expanded"
:aria-label="expanded ? t('harvester.virtualMachine.volume.performance.collapse') : t('harvester.virtualMachine.volume.performance.expand')"
@click.prevent="expanded = !expanded"
>
<Banner
v-if="showBusTip"
color="warning"
data-testid="disk-perf-bus-tip"
:label="t('harvester.virtualMachine.volume.performance.busTip', { bus: value.bus }, true)"
<i
class="icon"
:class="expanded ? 'icon-chevron-down' : 'icon-chevron-right'"
/>
<Banner
v-if="showFilesystemCacheWarning"
color="warning"
label-key="harvester.virtualMachine.volume.performance.cacheMode.filesystemWarning"
/>
</div>
{{ t('harvester.virtualMachine.volume.performance.title') }}
</button>
<template v-if="isCustom">
<div
v-if="expanded || isView"
class="perf-body mt-10"
>
<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
class="col span-6"
data-testid="input-disk-cache"
@@ -269,7 +266,10 @@ export default {
</div>
</div>
<div class="row mb-20">
<div
v-if="isCustom || isView"
class="row mb-10"
>
<div
class="col span-12"
data-testid="input-disk-dedicated-iothread"
@@ -283,19 +283,39 @@ export default {
/>
</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
v-if="isNativeIo"
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>
</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>
import InfoBox from '@shell/components/InfoBox';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { LabeledInput } from '@components/Form/LabeledInput';
import { Checkbox } from '@components/Form/Checkbox';
@@ -10,7 +11,7 @@ export default {
name: 'VMPerformanceOptions',
components: {
LabeledSelect, LabeledInput, Checkbox, Banner
InfoBox, LabeledSelect, LabeledInput, Checkbox, Banner
},
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: {
isView() {
return this.mode === _VIEW;
@@ -80,71 +87,105 @@ export default {
</script>
<template>
<div
<InfoBox
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') }}
</h3>
<p class="text-muted mb-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<div
class="mb-10"
data-testid="input-vm-block-multi-queue"
>
<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)"
<template v-if="expanded || isView">
<p class="text-muted mb-15 mt-10">
{{ t('harvester.virtualMachine.volume.diskPerformance.description') }}
</p>
<div class="row mb-10">
<div
class="col span-12"
data-testid="input-vm-block-multi-queue"
>
<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="col span-6"
data-testid="input-vm-iothreads-policy"
>
<LabeledSelect
:value="ioThreadsPolicy"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
:options="ioThreadsPolicyOptions"
:mode="mode"
@update:value="$emit('update:ioThreadsPolicy', $event)"
/>
<div class="row mb-10">
<div
class="col span-6"
data-testid="input-vm-iothreads-policy"
>
<LabeledSelect
:value="ioThreadsPolicy"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.label')"
:tooltip="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.tip')"
:options="ioThreadsPolicyOptions"
:mode="mode"
@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
v-if="ioThreadsPolicy === 'supplementalPool'"
class="col span-6"
data-testid="input-vm-iothread-count"
>
<LabeledInput
type="integer"
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>
<Banner
v-if="hasDedicatedIothread && !ioThreadsPolicy"
color="info"
:label="t('harvester.virtualMachine.volume.diskPerformance.ioThreadsPolicy.autoEnabledTip')"
/>
</template>
</InfoBox>
</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 { nextTick } from 'vue';
import { _EDIT } from '@shell/config/query-params';
import { Banner } from '@components/Banner';
import DiskPerformanceOptions from '../DiskPerformanceOptions.vue';
const mountOptions = (value, { featureEnabled = true } = {}) => ({
@@ -27,12 +22,6 @@ const hardDisk = (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', () => {
it('is hidden when the highPerformanceStorage feature is disabled', () => {
const wrapper = mount(DiskPerformanceOptions, mountOptions(hardDisk(), { featureEnabled: false }));
@@ -46,102 +35,6 @@ describe('component: DiskPerformanceOptions', () => {
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', () => {
const value = hardDisk();
const wrapper = mount(DiskPerformanceOptions, mountOptions(value));
@@ -229,58 +122,4 @@ describe('component: DiskPerformanceOptions', () => {
expect(disabledByValue['writeback']).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 LabeledSelect from '@shell/components/form/LabeledSelect';
import ModalWithCard from '@shell/components/ModalWithCard';
import VMPerformanceOptions from './VMPerformanceOptions';
import { VOLUME_HOTPLUG_ACTION, SOURCE_TYPE } from '../../../config/harvester-map';
import { PVC, STORAGE_CLASS } from '@shell/config/types';
import { clone } from '@shell/utils/object';
@@ -23,10 +24,10 @@ import { EMPTY_IMAGE } from '../../../utils/vm';
const { READ_WRITE_MANY } = ACCESS_MODE;
export default {
emits: ['update:value'],
emits: ['update:value', 'update:blockMultiQueue', 'update:ioThreadsPolicy', 'update:ioThreadCount'],
components: {
Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard
Banner, BadgeStateFormatter, VueDraggableNext, InfoBox, LabeledInput, UnitInput, LabeledSelect, ModalWithCard, VMPerformanceOptions
},
props: {
@@ -77,6 +78,22 @@ export default {
resourceType: {
type: String,
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() {
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: {
@@ -508,6 +533,18 @@ export default {
</button>
</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
v-if="isOpen"
name="deleteTip"
@@ -51,11 +51,4 @@ describe('component: HarvesterEditContainer', () => {
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);
});
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>
</div>
</div>
<div
v-if="value.volumeBackups"
class="row mb-20"
>
<div class="col span-6">
<div class="row mb-20">
<div
v-if="value.volumeBackups"
class="col span-6"
>
<InputOrDisplay
:name="t('harvester.virtualMachine.volume.readyToUse')"
:value="value.volumeBackups.readyToUse"
@@ -461,11 +461,11 @@ export default {
/>
</div>
</div>
<div
v-if="value.volumeBackups && isView"
class="row mb-20"
>
<div class="col span-3">
<div class="row mb-20">
<div
v-if="value.volumeBackups && isView"
class="col span-3"
>
<LabelValue
:name="t('harvester.virtualMachine.volume.readyToUse')"
:value="readyToUse"
@@ -1,37 +0,0 @@
import VM_MIXIN from '@pkg/harvester/mixins/harvester-vm';
import HarvesterEditVM from '../index.vue';
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('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);
});
});
@@ -34,7 +34,6 @@ import CpuMemory from './VirtualMachineCpuMemory';
import CpuModel from './VirtualMachineCpuModel';
import Network from './VirtualMachineNetwork';
import Volume from './VirtualMachineVolume';
import VMPerformanceOptions from './VirtualMachineVolume/VMPerformanceOptions';
import SSHKey from './VirtualMachineSSHKey';
import Reserved from './VirtualMachineReserved';
import Filesystem from './VirtualMachineFilesystem';
@@ -56,7 +55,6 @@ export default {
LabeledSelect,
NameNsDescription,
Volume,
VMPerformanceOptions,
SSHKey,
Network,
CpuMemory,
@@ -381,7 +379,6 @@ export default {
this.validateCPUMemory();
this.validateWindowsSysprep();
this.validateCloudInit();
// block create VM flow if has validation errors
if (this.errors.length) {
@@ -875,6 +872,9 @@ export default {
>
<Volume
v-model:value="diskRows"
v-model:block-multi-queue="blockMultiQueue"
v-model:io-threads-policy="ioThreadsPolicy"
v-model:io-thread-count="ioThreadCount"
:mode="mode"
:custom-volume-mode="customVolumeMode"
:namespace="value.metadata.namespace"
@@ -1146,16 +1146,6 @@ export default {
</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
ref="yamlEditor"
:user-script="userScript"
+20 -70
View File
@@ -32,7 +32,6 @@ nav:
group:
networks: Networks
backupAndSnapshot: Backup and Snapshots
hardwareDevices: Hardware Devices
Monitoring: Monitoring
Logging: Logging
'Monitoring and Logging': Monitoring and Logging
@@ -513,58 +512,6 @@ harvester:
label: Events
vmMetrics:
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 ({counts})'
ignoredChecks: '{count, plural, =1 {1 check} other {# checks}}'
ignoredResources: '{count, plural, =1 {1 resource} other {# resources}}'
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'
scope: Scope
scopeResources: Selected resources
scopeCheck: Entire check
resources: Resources
duration: Ignore for
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
staysExpired: 'This rule expired on {date} and stays expired unless you choose how long to ignore for.'
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
host:
@@ -856,16 +803,19 @@ harvester:
saveVolume: Update Volume
encryption: Encryption
performance:
title: Storage Performance Options
expand: Show high-performance options
collapse: Hide high-performance options
profile:
label: Storage 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.'
default: Default
label: Performance Profile
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 (Balanced)
highPerformance: High Performance
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:
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)
none: None (no host cache)
writeback: WriteBack
@@ -873,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."
ioMode:
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)
native: Native (AIO)
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:
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.
busTip: 'This disk uses the {bus} bus. A dedicated I/O thread needs the virtio bus.'
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: High-performance features work best on the virtio bus.
diskPerformance:
title: Storage Performance
description: These options apply to all volumes of the virtual machine.
title: High Performance (I/O Threads and Multi-Queue)
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:
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.
ioThreadsPolicy:
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)"
shared: Shared
auto: Auto
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:
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:
label: Shareable
tip: Allow multiple virtual machines to attach and write to this volume simultaneously.
@@ -938,12 +890,10 @@ harvester:
label: User Data Template
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>"
invalidYaml: 'Invalid User Data YAML syntax'
network:
label: Network Data Template
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>"
invalidYaml: 'Invalid Network Data YAML syntax'
sysprep:
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>"
@@ -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);
});
});
@@ -24,10 +24,8 @@ import { allDashboardsExist } from '@shell/utils/grafana';
import { isEmpty } from '@shell/utils/object';
import { HCI } from '../types';
import HarvesterUpgrade from '../components/HarvesterUpgrade';
import HealthSummaryTable from '../components/health/HealthSummaryTable';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { UNIT_SUFFIX } from '../utils/unit';
import { totalErrorCount } from '../utils/component-health';
dayjs.extend(utc);
dayjs.extend(minMax);
@@ -127,7 +125,6 @@ export default {
DashboardMetrics,
Banner,
MessageLink,
HealthSummaryTable,
},
async fetch() {
@@ -240,20 +237,6 @@ export default {
computed: {
...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() {
const inStore = this.$store.getters['currentProduct'].inStore;
@@ -838,16 +821,6 @@ export default {
</template>
</SortableTable>
</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>
</div>
</section>
+37 -8
View File
@@ -7,7 +7,7 @@ import { allHash } from '@shell/utils/promise';
import Tabbed from '@shell/components/Tabbed/index.vue';
import Tab from '@shell/components/Tabbed/Tab.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';
export default {
@@ -29,19 +29,47 @@ export default {
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 = {
...config,
id: config.alias || id,
data,
...SETTINGS[setting],
id: realSetting,
data: settingsMap[setting],
};
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;
return s;
initSettings.push(s);
});
this.initSettings = initSettings.sort((a, b) => {
@@ -62,6 +90,7 @@ export default {
computed: {
...mapGetters({ t: 'i18n/t' }),
...mapGetters(['isStandaloneHarvester']),
settings() {
return this.initSettings.map((setting) => {
+2 -6
View File
@@ -139,8 +139,7 @@ export default {
},
methods: {
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 || this.t('generic.none') }`;
return `${ this.t('harvester.vpc.label') }: ${ group.key }`;
},
slotName(vpc) {
@@ -227,10 +226,7 @@ export default {
{{ groupLabel(group) }}
</span>
</div>
<div
v-if="group.key"
class="right"
>
<div class="right">
<router-link
v-if="isSubnetCreatable"
class="btn btn-sm role-secondary mr-5"
@@ -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',
};
// 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 {
methods: {
hasCloudConfigComment(userScript) {
+1 -43
View File
@@ -2,8 +2,6 @@ import YAML from 'yaml';
import jsyaml from 'js-yaml';
import isEqual from 'lodash/isEqual';
import isEmpty from 'lodash/isEmpty';
import isNil from 'lodash/isNil';
import isPlainObject from 'lodash/isPlainObject';
import difference from 'lodash/difference';
import { sortBy } from '@shell/utils/sort';
import { set } from '@shell/utils/object';
@@ -25,7 +23,7 @@ import {
import { HCI_SETTING } from '../../config/settings';
import { HCI } from '../../types';
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 { VOLUME_MODE, ACCESS_MODE, FILESYSTEM_SOURCE_TYPE } from '@pkg/harvester/config/types';
@@ -159,8 +157,6 @@ export default {
installUSBTablet: true,
networkScript: '',
userScript: '',
// The cloud-init the form loaded, so editing a VM never blocks saving it unchanged.
savedCloudInit: {},
imageId: '',
diskRows: [],
networkRows: [],
@@ -294,14 +290,6 @@ export default {
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() {
// When creating a template it is always necessary to create a new secret.
return this.isCreate || this.showYaml ? false : this.resourceType === HCI.VM_VERSION;
@@ -446,7 +434,6 @@ export default {
this['accessCredentials'] = accessCredentials;
this['userScript'] = userData;
this['networkScript'] = networkData;
this['savedCloudInit'] = { userScript: userData, networkScript: networkData };
this['sshKey'] = sshKey;
this['osType'] = osType;
@@ -1296,11 +1283,6 @@ export default {
* @param 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 {
// https://github.com/eemeli/yaml/issues/136
let userDataDoc = this.userScript ? YAML.parseDocument(this.userScript) : YAML.parseDocument({});
@@ -1493,30 +1475,6 @@ export default {
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) {
try {
const sshAuthorizedKeys = YAML.parseDocument(yaml)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "harvester",
"description": "Rancher UI Extension for Harvester",
"version": "1.10.0-dev",
"version": "1.10.0-rc1",
"private": false,
"rancher": {
"annotations": {
@@ -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']);
});
});
});
@@ -1,68 +0,0 @@
<script>
import { mapGetters } from 'vuex';
import Banner from '@components/Banner/Banner.vue';
import { exceptionToErrorsArray } from '@shell/utils/error';
export default {
name: 'PromptRemoveHealthIgnoreRuleDialog',
components: { Banner },
// the prompt binds all of its own data to this body, none of it belongs on the element
inheritAttrs: false,
props: {
value: {
type: Array,
default: () => {
return [];
}
},
close: {
type: Function,
required: true
},
},
data() {
return { errors: [] };
},
computed: {
...mapGetters({ t: 'i18n/t' }),
// a rule's name means little, the check it is for is what the user knows
checkNames() {
return this.value.map((rule) => rule.spec?.checkKey).join(', ');
},
},
methods: {
// the prompt does not show the errors of a body that removes by itself
async remove(buttonDone) {
try {
await Promise.all(this.value.map((rule) => rule.remove()));
this.close(buttonDone);
} catch (err) {
this.errors = exceptionToErrorsArray(err);
buttonDone(false);
}
}
}
};
</script>
<template>
<div class="mt-10">
<div class="mb-5">
{{ t('harvester.dashboard.sections.componentHealth.ignore.attemptingToDelete') }} <b>{{ checkNames }}</b>. {{ t('harvester.dashboard.sections.componentHealth.ignore.reportedAgain') }}
</div>
<Banner
v-for="(error, i) in errors"
:key="i"
color="error"
:label="error"
/>
</div>
</template>
@@ -164,7 +164,7 @@ export default {
<div v-else>
<label class="checkbox-container mr-15">
<input
v-model="checkAll"
v-model="checkedList"
type="checkbox"
/>
<span
@@ -1,421 +0,0 @@
import {
CONFIG_MAP, COUNT, NETWORK_ATTACHMENT, PVC, STORAGE_CLASS
} from '@shell/config/types';
import harvesterStore from '../index';
import harvesterActions from '../actions';
import harvesterMutations from '../mutations';
import { SERVER_FILTERED_COUNTS, filteredCountRequest } from '../getters';
import { HCI, DATA_VOLUME, VOLUME_SNAPSHOT } from '../../../types';
import { PRODUCT_NAME } from '../../../config/harvester';
const BASE = 'https://harvester/v1/harvester';
// Nav item -> resource type, like `configureType(..., { resource })` in config/harvester-cluster.js
const RESOURCE_MAP: Record<string, string> = {
[HCI.BACKUP]: HCI.BACKUP,
[HCI.VM_SNAPSHOT]: HCI.BACKUP,
[HCI.SNAPSHOT]: VOLUME_SNAPSHOT,
[HCI.STORAGE]: STORAGE_CLASS,
[HCI.CLOUD_TEMPLATE]: CONFIG_MAP,
[HCI.NETWORK_ATTACHMENT]: NETWORK_ATTACHMENT,
[HCI.VOLUME]: PVC,
[DATA_VOLUME]: DATA_VOLUME,
};
const CLUSTER_SCOPED = [STORAGE_CLASS];
const schemaFor = (name: string) => {
const id = RESOURCE_MAP[name];
return id ? {
id, attributes: { namespaced: !CLUSTER_SCOPED.includes(id) }, links: { collection: `${ BASE }/${ id }s` }
} : null;
};
function createGetters({ counts = {} }: any = {}) {
return {
schemaFor,
urlFor: (type: string) => `${ BASE }/${ type }s`,
all: (type: string) => (type === COUNT ? [{ counts }] : []),
};
}
function createRootGetters({
isAllNamespaces = true, hideSystemResources = true, namespaces = { default: true, test: true }, clusterId = 'local'
}: any = {}) {
return {
isAllNamespaces,
currentProduct: { hideSystemResources, inStore: PRODUCT_NAME },
namespaces: () => namespaces,
clusterId,
};
}
function createState() {
return {
filteredCounts: {}, filteredCountRequests: {}, filteredCountWatchers: []
};
}
/**
* A minimal store context for the actions: `commit` runs the real mutations,
* `request` resolves with `responses[url]` (or rejects for an Error).
*/
function createContext({ responses = {}, getters = createGetters(), rootGetters = createRootGetters() }: any = {}) {
const state: any = createState();
const commit = jest.fn((type: string, payload: any) => (harvesterMutations as any)[type](state, payload));
const request = jest.fn(({ url }: any) => {
const res = Object.entries(responses).find(([part]) => url.includes(part))?.[1];
return res instanceof Error ? Promise.reject(res) : Promise.resolve(res || {});
});
const dispatch = jest.fn((action: string, payload: any) => {
if (action === 'request') {
return request(payload);
}
return (harvesterActions as any)[action](context, payload);
});
const context: any = {
state, commit, dispatch, getters, rootGetters
};
return { context, state, request };
}
describe('harvester store: side navigation counts', () => {
it('should have the state of the counts in the store', () => {
expect((harvesterStore.specifics as any).state()).toMatchObject({
filteredCounts: {}, filteredCountRequests: {}, filteredCountWatchers: []
});
});
it('should start the counts when the cluster is loaded', async() => {
const dispatch = jest.fn((action: string) => Promise.resolve(action === 'management/findAll' ? [{ metadata: { name: 'local' } }] : { id: 'local' }));
const context: any = {
state: {},
commit: jest.fn(),
dispatch,
getters: { schemaFor: () => null, filterNamespace: () => [] },
rootGetters: {
'management/schemaFor': () => null,
'harvester-common/getFeatureEnabled': () => true,
'prefs/get': () => ({}),
},
rootState: { managementReady: true },
};
await (harvesterActions as any).loadCluster(context, { id: 'local' });
expect(dispatch).toHaveBeenCalledWith('watchFilteredCounts', { clusterId: 'local' });
});
describe('filteredCountRequest', () => {
it('should request the filtered list with a page size of 1', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.BACKUP);
expect(req).toStrictEqual({ url: `${ BASE }/${ HCI.BACKUP }s?filter=spec.type!%3Dsnapshot&pagesize=1` });
});
it.each(Object.keys(SERVER_FILTERED_COUNTS))('should build a request for %s', (name) => {
const url = filteredCountRequest(createGetters(), createRootGetters(), name)?.url || '';
expect(url.startsWith(`${ BASE }/${ RESOURCE_MAP[name] }s?`)).toBe(true);
expect(url).toContain('pagesize=1');
});
it('should only request the selected namespaces', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true, b: true } }), HCI.VM_SNAPSHOT);
expect(req?.url).toContain('projectsornamespaces=a%2Cb');
});
it('should leave out system namespaces with "All Namespaces" when system resources are hidden', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ namespaces: { default: true } }), HCI.CLOUD_TEMPLATE);
expect(req?.url).toContain('projectsornamespaces=default');
});
it('should not filter by namespace with "All Namespaces" when system resources are shown', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.SNAPSHOT);
expect(req?.url).not.toContain('projectsornamespaces');
});
it.each([HCI.STORAGE, HCI.NETWORK_ATTACHMENT])('should ignore the namespace filter for %s', (name) => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true } }), name);
expect(req?.url).not.toContain('projectsornamespaces');
});
it('should not send a request for an empty namespace selection', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: {} }), HCI.BACKUP);
expect(req).toStrictEqual({ count: 0 });
});
it('should request the volumes without the temporary volumes of CDI', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ hideSystemResources: false }), HCI.VOLUME);
expect(req).toStrictEqual({ url: `${ BASE }/${ PVC }s?filter=metadata.ownerReferences.kind!%3DPersistentVolumeClaim&pagesize=1` });
});
it('should request the golden image volumes through the DataVolumes owned by a VM image, in the selected namespaces', () => {
const req = filteredCountRequest(createGetters(), createRootGetters({ isAllNamespaces: false, namespaces: { a: true } }), DATA_VOLUME);
expect(req).toStrictEqual({ url: `${ BASE }/${ DATA_VOLUME }s?filter=metadata.ownerReferences.kind%3DVirtualMachineImage&pagesize=1&projectsornamespaces=a` });
});
it('should not send a request for an unknown resource type', () => {
expect(filteredCountRequest(createGetters(), createRootGetters(), 'unknown')).toBeNull();
});
});
describe('fetchFilteredCounts', () => {
it('should save the count of each response', async() => {
const { context, state, request } = createContext({ responses: { 'spec.type!%3D': { count: 9 }, 'spec.type%3D': { count: 2 } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP, HCI.VM_SNAPSHOT]);
expect(request).toHaveBeenCalledTimes(2);
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 9, [HCI.VM_SNAPSHOT]: 2 });
});
it('should request all nav items by default', async() => {
const { context, state, request } = createContext();
await harvesterActions.fetchFilteredCounts(context as any);
expect(request).toHaveBeenCalledTimes(Object.keys(SERVER_FILTERED_COUNTS).length);
expect(Object.keys(state.filteredCounts)).toStrictEqual(Object.keys(SERVER_FILTERED_COUNTS));
});
it('should save 0 when the response has no count, as Steve leaves it out when nothing matches', async() => {
const { context, state } = createContext({ responses: { [STORAGE_CLASS]: { data: [] } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.STORAGE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.STORAGE]: 0 });
});
it('should save no count when the response has resources but no count, as Harvester v1.3 ignores the query', async() => {
const { context, state } = createContext({ responses: { [STORAGE_CLASS]: { data: [{}, {}] } } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.STORAGE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.STORAGE]: null });
});
it('should save no count when the request fails', async() => {
const { context, state } = createContext({ responses: { [CONFIG_MAP]: new Error('500') } });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.CLOUD_TEMPLATE]);
expect(state.filteredCounts).toStrictEqual({ [HCI.CLOUD_TEMPLATE]: null });
});
it('should save 0 without a request for an empty namespace selection', async() => {
const { context, state, request } = createContext({ rootGetters: createRootGetters({ isAllNamespaces: false, namespaces: {} }) });
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
expect(request).not.toHaveBeenCalled();
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 0 });
});
it('should ignore the response of an outdated request', async() => {
const { context, state } = createContext();
let resolveFirst: any;
context.dispatch = jest.fn()
.mockImplementationOnce(() => new Promise((resolve) => {
resolveFirst = resolve;
}))
.mockImplementationOnce(() => Promise.resolve({ count: 5 }));
const first = harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
resolveFirst({ count: 3 });
await first;
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 5 });
});
it('should ignore the response of a request of the previous cluster', async() => {
const { context, state } = createContext();
let resolveFirst: any;
context.dispatch = jest.fn()
.mockImplementationOnce(() => new Promise((resolve) => {
resolveFirst = resolve;
}))
.mockImplementationOnce(() => Promise.resolve({ count: 5 }));
const first = harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
context.commit('resetFilteredCounts');
await harvesterActions.fetchFilteredCounts(context as any, [HCI.BACKUP]);
resolveFirst({ count: 3 });
await first;
expect(state.filteredCounts).toStrictEqual({ [HCI.BACKUP]: 5 });
});
});
describe('watchFilteredCounts', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
/**
* Runs `watchFilteredCounts` with a fake `store.watch`, which records the
* watch callbacks by the value of their getter.
*/
function watch(contextArgs: any = {}) {
const { context, state, request } = createContext(contextArgs);
const watchers: { getter: () => any, cb: () => void }[] = [];
const unwatch = jest.fn();
const store = {
watch: jest.fn((getter: () => any, cb: () => void) => {
watchers.push({ getter, cb });
return unwatch;
})
};
const done = harvesterActions.watchFilteredCounts.call(store, context, { clusterId: 'local' });
return {
context, state, request, watchers, unwatch, done
};
}
it('should request all counts right away', async() => {
const { request, done } = watch();
await done;
expect(request).toHaveBeenCalledTimes(Object.keys(SERVER_FILTERED_COUNTS).length);
});
it('should watch the counts endpoint per resource type, and the namespace filter', async() => {
const { watchers, done } = watch({ getters: createGetters({ counts: { [STORAGE_CLASS]: { summary: { count: 4 } } } }) });
await done;
// VirtualMachineBackup, VolumeSnapshot, StorageClass, ConfigMap, NAD, PVC, DataVolume + the namespace filter
expect(watchers).toHaveLength(8);
expect(watchers.map(({ getter }) => getter())).toContain(JSON.stringify({ summary: { count: 4 } }));
});
it('should request the counts of a resource type again, once, when its numbers change', async() => {
const { watchers, request, done } = watch();
await done;
request.mockClear();
// The first watcher is the one of VirtualMachineBackup, the type of the first nav items
const backupWatcher = watchers[0];
backupWatcher.cb();
backupWatcher.cb();
jest.advanceTimersByTime(1000);
await Promise.resolve();
// VM backups and VM snapshots, both VirtualMachineBackup resources
expect(request).toHaveBeenCalledTimes(2);
});
it('should request the namespaced counts again when the namespace filter changes', async() => {
const { watchers, request, done } = watch();
await done;
request.mockClear();
watchers[watchers.length - 1].cb();
await Promise.resolve();
const urls = request.mock.calls.map(([{ url }]: any) => url);
expect(urls).toHaveLength(6);
expect(urls.some((url: string) => url.includes(STORAGE_CLASS) || url.includes(NETWORK_ATTACHMENT))).toBe(false);
});
it('should not request anything once another cluster is shown', async() => {
const rootGetters = createRootGetters();
const { watchers, request, done } = watch({ rootGetters });
await done;
request.mockClear();
rootGetters.clusterId = 'c-other';
watchers[watchers.length - 1].cb();
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should not request anything once another product is shown', async() => {
const rootGetters = createRootGetters();
const { watchers, request, done } = watch({ rootGetters });
await done;
request.mockClear();
rootGetters.currentProduct = { inStore: 'cluster' };
watchers[watchers.length - 1].cb();
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should not request anything for a change seen just before the watchers were stopped', async() => {
const { context, watchers, request, done } = watch();
await done;
request.mockClear();
watchers[0].cb();
await harvesterActions.watchFilteredCounts.call({ watch: jest.fn(() => jest.fn()) }, context, { clusterId: 'local' });
request.mockClear();
jest.advanceTimersByTime(1000);
await Promise.resolve();
expect(request).not.toHaveBeenCalled();
});
it('should cope with the store module being unregistered when logging out', async() => {
const getters: any = createGetters();
const { watchers, done } = watch({ getters });
await done;
delete getters.all;
expect(watchers[0].getter()).toBe('null');
});
it('should keep the watchers when a cluster left while it was loading finishes loading', async() => {
const { context, unwatch, request, done } = watch();
await done;
request.mockClear();
const store = { watch: jest.fn() };
await harvesterActions.watchFilteredCounts.call(store, context, { clusterId: 'c-left' });
expect(store.watch).not.toHaveBeenCalled();
expect(unwatch).not.toHaveBeenCalled();
expect(request).not.toHaveBeenCalled();
});
it('should stop the watchers of the previous cluster', async() => {
const { context, unwatch, done } = watch();
await done;
await harvesterActions.watchFilteredCounts.call({ watch: jest.fn(() => jest.fn()) }, context, { clusterId: 'local' });
expect(unwatch).toHaveBeenCalledTimes(8);
});
});
});
@@ -1,290 +0,0 @@
import {
CONFIG_MAP, COUNT, NAMESPACE, NETWORK_ATTACHMENT, NODE, PVC, STORAGE_CLASS
} from '@shell/config/types';
import harvesterGetters from '../getters';
import { HCI, DATA_VOLUME, VOLUME_SNAPSHOT } from '../../../types';
import { HCI_SETTING } from '../../../config/settings';
// Nav item -> resource type, like `configureType(..., { resource })` in config/harvester-cluster.js
const RESOURCE_MAP: Record<string, string> = {
[HCI.HOST]: NODE,
[HCI.VOLUME]: PVC,
[HCI.NETWORK_ATTACHMENT]: NETWORK_ATTACHMENT,
[HCI.VM_SNAPSHOT]: HCI.BACKUP,
[HCI.SNAPSHOT]: VOLUME_SNAPSHOT,
[HCI.CLOUD_TEMPLATE]: CONFIG_MAP,
[HCI.STORAGE]: STORAGE_CLASS,
};
const CLUSTER_SCOPED = [NODE, STORAGE_CLASS, NAMESPACE];
const counts = (byNamespace: Record<string, number>) => ({
summary: { count: Object.values(byNamespace).reduce((sum, count) => sum + count, 0) },
namespaces: Object.fromEntries(Object.entries(byNamespace).map(([ns, count]) => [ns, { count }])),
});
/**
* Creates the `count` getter with a minimal store. `counts` is the result of
* Steve's counts endpoint, `filteredCounts` the counts requested by
* `fetchFilteredCounts` and `lists` the loaded store lists.
*/
function createCount({
counts = {}, filteredCounts = {}, lists = {}, visibleSettings = [], isAllNamespaces = true, hideSystemResources = false, namespaces = {}
}: any = {}) {
const schemas = new Map<string, any>();
// Schemas of the resource types used below. `count` only filters by namespace if the
// schema marks the type as namespaced, so a namespaced type without a schema here would be
// counted in all namespaces. RESOURCE_MAP contains the resource types of nav items with a
// different name, the others are nav items named like the resource type they list.
[...Object.values(RESOURCE_MAP), HCI.BACKUP, HCI.SCHEDULE_VM_BACKUP, HCI.VM, HCI.FLOW, NAMESPACE].forEach((id) => {
schemas.set(id, { id, attributes: { namespaced: !CLUSTER_SCOPED.includes(id) } });
});
const state = { types: { schema: { map: schemas } }, filteredCounts };
const rootGetters = {
isAllNamespaces,
namespaces: () => namespaces,
// Empty on purpose: this cache is not necessarily filled yet when the side navigation is
// rendered, e.g. right after loading the dashboard. `count` must use `namespaces()`;
// reading this cache would make the tests that select namespaces fail.
activeNamespaceCache: {},
currentProduct: { hideSystemResources },
'type-map/optionsFor': (type: string) => (RESOURCE_MAP[type] ? { resource: RESOURCE_MAP[type] } : {}),
};
const getters: any = {
normalizeType: (type: string) => type,
haveAll: jest.fn((type: string) => !!lists[type]),
all: jest.fn((type: string) => (type === COUNT ? [{ counts }] : lists[type] || [])),
visibleSettings,
};
getters.schemaFor = harvesterGetters.schemaFor(state, getters, {}, rootGetters);
const count = harvesterGetters.count(state, getters, {}, rootGetters);
return (name: string) => count({ name });
}
describe('harvester store: count', () => {
describe('nav items listing all resources of a type', () => {
it('should look up the count of the underlying resource type', () => {
const count = createCount({ counts: { [NODE]: counts({ '': 3 }) } });
expect(count(HCI.HOST)).toBe(3);
});
it('should only count the selected namespaces', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, test: 2 }) },
isAllNamespaces: false,
namespaces: { test: true },
});
expect(count(HCI.VM)).toBe(2);
});
it('should not count system namespaces with "All Namespaces" when system resources are hidden', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, 'cattle-monitoring-system': 2 }) },
hideSystemResources: true,
namespaces: { default: true },
});
expect(count(HCI.VM)).toBe(4);
});
it('should count nothing for an empty namespace selection, e.g. a project without namespaces', () => {
const count = createCount({
counts: { [HCI.VM]: counts({ default: 4, test: 2 }) },
isAllNamespaces: false,
namespaces: {},
});
expect(count(HCI.VM)).toBe(0);
});
it('should count all namespaces for lists that ignore the namespace filter', () => {
const count = createCount({
counts: { [HCI.FLOW]: counts({ a: 2, b: 1 }) },
isAllNamespaces: false,
namespaces: { a: true },
});
expect(count(HCI.FLOW)).toBe(3);
});
it('should ignore the namespace filter for cluster-scoped resources', () => {
const count = createCount({
counts: { [NODE]: counts({ '': 3 }) },
isAllNamespaces: false,
namespaces: { test: true },
});
expect(count(HCI.HOST)).toBe(3);
});
it('should count all VM Schedules, whatever their type', () => {
const count = createCount({ counts: { [HCI.SCHEDULE_VM_BACKUP]: counts({ default: 2 }) } });
expect(count(HCI.SCHEDULE_VM_BACKUP)).toBe(2);
});
it('should return null for nav items without counts', () => {
expect(createCount()(HCI.DASHBOARD)).toBeNull();
});
});
describe('nav items listing a subset of a resource type', () => {
it('should show the count requested from the server', () => {
const count = createCount({
counts: { [HCI.BACKUP]: counts({ default: 3 }) },
filteredCounts: { [HCI.BACKUP]: 1, [HCI.VM_SNAPSHOT]: 2 },
});
expect(count(HCI.BACKUP)).toBe(1);
expect(count(HCI.VM_SNAPSHOT)).toBe(2);
});
it.each([
HCI.BACKUP, HCI.VM_SNAPSHOT, HCI.SNAPSHOT, HCI.STORAGE, HCI.CLOUD_TEMPLATE, HCI.NETWORK_ATTACHMENT
])('should not use the total of the counts endpoint for %s before the server count arrives', (name) => {
const count = createCount({ counts: Object.fromEntries(Object.values(RESOURCE_MAP).concat(HCI.BACKUP).map((type) => [type, counts({ default: 3 })])) });
expect(count(name)).toBeNull();
});
it('should show 0 when the server count is 0', () => {
expect(createCount({ filteredCounts: { [HCI.STORAGE]: 0 } })(HCI.STORAGE)).toBe(0);
});
});
describe('volumes', () => {
it('should subtract the golden image volumes from the requested volumes', () => {
const count = createCount({
counts: { [PVC]: counts({ default: 99 }) },
filteredCounts: { [HCI.VOLUME]: 19, [DATA_VOLUME]: 2 },
});
expect(count(HCI.VOLUME)).toBe(17);
});
it('should show 0 when there are no volumes', () => {
expect(createCount({ filteredCounts: { [HCI.VOLUME]: 0, [DATA_VOLUME]: 0 } })(HCI.VOLUME)).toBe(0);
});
it.each([
[{}],
[{ [HCI.VOLUME]: 19 }],
[{ [DATA_VOLUME]: 2 }],
[{ [HCI.VOLUME]: null, [DATA_VOLUME]: 2 }],
[{ [HCI.VOLUME]: 19, [DATA_VOLUME]: null }],
])('should not show a count until both numbers are known: %j', (filteredCounts) => {
expect(createCount({ filteredCounts })(HCI.VOLUME)).toBeNull();
});
it('should not go below 0, as a DataVolume exists briefly before its volume', () => {
expect(createCount({ filteredCounts: { [HCI.VOLUME]: 0, [DATA_VOLUME]: 1 } })(HCI.VOLUME)).toBe(0);
});
});
describe('settings', () => {
it('should count the settings shown by the page, not all the settings', () => {
const count = createCount({
counts: { [HCI.SETTING]: counts({ '': 5 }) },
lists: { [HCI.SETTING]: [{}] },
visibleSettings: [{}, {}],
});
expect(count(HCI.SETTING)).toBe(2);
});
it('should return null until the settings are loaded', () => {
expect(createCount({ visibleSettings: [{}] })(HCI.SETTING)).toBeNull();
});
});
describe('namespaces', () => {
const namespace = (isSystem = false, isFleetManaged = false) => ({ isSystem, isFleetManaged });
it('should not count system and Fleet managed namespaces when system resources are hidden', () => {
const count = createCount({
counts: { [NAMESPACE]: counts({ '': 4 }) },
lists: { [NAMESPACE]: [namespace(), namespace(), namespace(true), namespace(false, true)] },
hideSystemResources: true,
});
expect(count(NAMESPACE)).toBe(2);
});
it('should return null until the namespaces are loaded when system resources are hidden', () => {
const count = createCount({ counts: { [NAMESPACE]: counts({ '': 4 }) }, hideSystemResources: true });
expect(count(NAMESPACE)).toBeNull();
});
it('should count all namespaces when system resources are shown', () => {
const count = createCount({ counts: { [NAMESPACE]: counts({ '': 4 }) } });
expect(count(NAMESPACE)).toBe(4);
});
});
});
describe('harvester store: visibleSettings', () => {
const { BACKUP_TARGET, MAX_HOTPLUG_RATIO, UI_PL } = HCI_SETTING;
const setting = (id: string, source = 'harvester') => ({ id, source });
function visibleSettings({
harvester = [] as string[], management = [] as string[], isSingleProduct = false, isStandaloneHarvester = false, enabledFeatures = [] as string[]
} = {}) {
const rootGetters = {
isSingleProduct,
isStandaloneHarvester,
'management/all': () => management.map((id) => setting(id, 'management')),
'harvester-common/getFeatureEnabled': (feature: string) => enabledFeatures.includes(feature),
};
return harvesterGetters.visibleSettings({}, { all: () => harvester.map((id) => setting(id)) }, {}, rootGetters);
}
const ids = (args: any) => visibleSettings(args).map(({ id }: any) => id);
it('should only show the allowed settings', () => {
expect(ids({ harvester: [BACKUP_TARGET, 'api-ui-version'] })).toStrictEqual([BACKUP_TARGET]);
});
it('should return the config and the resource of a setting', () => {
const [shown] = visibleSettings({ harvester: [BACKUP_TARGET] });
expect(shown.data).toStrictEqual(setting(BACKUP_TARGET));
expect(shown.config.kind).toBe('json');
});
it('should not show allowed settings that do not exist in the cluster', () => {
expect(ids({ harvester: [] })).toStrictEqual([]);
});
it('should only show settings with a feature flag when the version supports it', () => {
expect(ids({ harvester: [MAX_HOTPLUG_RATIO] })).toStrictEqual([]);
expect(ids({ harvester: [MAX_HOTPLUG_RATIO], enabledFeatures: ['cpuMemoryHotplug'] })).toStrictEqual([MAX_HOTPLUG_RATIO]);
});
it('should only show the single cluster settings on a standalone Harvester', () => {
expect(ids({ harvester: [UI_PL] })).toStrictEqual([]);
expect(ids({ harvester: [UI_PL], isStandaloneHarvester: true })).toStrictEqual([UI_PL]);
});
it('should only use the settings of the management store in a single product', () => {
expect(ids({ management: [BACKUP_TARGET] })).toStrictEqual([]);
expect(ids({ management: [BACKUP_TARGET], isSingleProduct: true })).toStrictEqual([BACKUP_TARGET]);
});
it('should prefer the Harvester setting over the management setting with the same id', () => {
const [shown] = visibleSettings({
harvester: [BACKUP_TARGET], management: [BACKUP_TARGET], isSingleProduct: true
});
expect(shown.data.source).toBe('harvester');
});
});
@@ -5,12 +5,7 @@ import { COUNT, NAMESPACE, MANAGEMENT } from '@shell/config/types';
import { allHash } from '@shell/utils/promise';
import { DEV, NAMESPACE_FILTERS } from '@shell/store/prefs';
import { createNamespaceFilterKeyWithId } from '@shell/utils/namespace-filter';
import debounce from 'lodash/debounce';
import { HCI } from '../../types';
import { PRODUCT_NAME } from '../../config/harvester';
import {
SERVER_FILTERED_COUNTS, countedNamespaces, filteredCountRequest, isFilteredByNamespace
} from './getters';
export default {
async loadCluster({
@@ -136,8 +131,6 @@ export default {
getters
}, { root: true });
dispatch('watchFilteredCounts', { clusterId: id });
// Solve compatibility with Rancher v2.6.x, fell remove these codes after not support v2.6.x
const definition = {
def: false,
@@ -173,95 +166,4 @@ export default {
}, { root: true });
}
},
/**
* Requests the side navigation counts of the nav items in SERVER_FILTERED_COUNTS
* (all of them by default), see getters.ts. Responses of an outdated request
* of a nav item (e.g. before a namespace filter change, or of the previous
* cluster) are ignored.
*/
async fetchFilteredCounts({
state, commit, dispatch, getters, rootGetters
}: any, names: string[] = Object.keys(SERVER_FILTERED_COUNTS)) {
await Promise.all(names.map(async(name: string) => {
commit('filteredCountRequested', name);
const requestId = state.filteredCountRequests[name];
const request = filteredCountRequest(getters, rootGetters, name);
let count = request?.count ?? null;
if (request?.url) {
try {
const res = await dispatch('request', { url: request.url });
// Steve leaves out `count` when nothing matches. Harvester v1.3 ignores the query and
// sends all resources without a `count`, which says nothing about the subset.
count = res?.count ?? (res?.data?.length ? null : 0);
} catch (e) {
count = null;
}
}
if (state.filteredCountRequests[name] === requestId) {
commit('setFilteredCount', { name, count });
}
}));
},
/**
* Requests the counts of SERVER_FILTERED_COUNTS, and requests them again when
* they may have changed: when the counts endpoint reports other numbers for
* their resource type (it is kept up to date through the websocket), and when
* the namespace filter changes. A change that leaves these numbers as they are
* (e.g. adding the cloud-init template label to an existing ConfigMap) shows up
* with the next change of that resource type.
*/
watchFilteredCounts({
state, commit, dispatch, getters, rootGetters
}: any, { clusterId }: any) {
// The `loadCluster` of a cluster left while it was loading can finish after the one of the new cluster
if (rootGetters.clusterId !== clusterId) {
return;
}
state.filteredCountWatchers.forEach((unwatch: () => void) => unwatch());
commit('resetFilteredCounts');
// The watchers stay registered after leaving the cluster or the product, until the next `loadCluster`
const refresh = (names: string[]) => {
if (rootGetters.clusterId === clusterId && rootGetters.currentProduct?.inStore === PRODUCT_NAME) {
dispatch('fetchFilteredCounts', names);
}
};
const names = Object.keys(SERVER_FILTERED_COUNTS);
const namesByType: Record<string, string[]> = {};
names.forEach((name) => {
const type = getters.schemaFor(name)?.id;
if (type) {
namesByType[type] = [...(namesByType[type] || []), name];
}
});
const unwatchers = Object.entries(namesByType).map(([type, namesOfType]) => {
const refreshType = debounce(() => refresh(namesOfType), 1000);
// `all` is gone once the store module is unregistered when logging out
const unwatch = this.watch(() => JSON.stringify(getters.all?.(COUNT)?.[0]?.counts?.[type] || null), refreshType);
return () => {
unwatch();
refreshType.cancel();
};
});
unwatchers.push(this.watch(
() => JSON.stringify(countedNamespaces(rootGetters)),
() => refresh(names.filter((name) => isFilteredByNamespace(name, getters.schemaFor(name))))
));
commit('setFilteredCountWatchers', unwatchers);
return dispatch('fetchFilteredCounts');
},
};
+1 -256
View File
@@ -4,229 +4,9 @@ import {
NAMESPACE_FILTER_ALL as ALL,
NAMESPACE_FILTER_ALL_ORPHANS as ALL_ORPHANS,
} from '@shell/utils/namespace-filter';
import { COUNT, MANAGEMENT, NAMESPACE } from '@shell/config/types';
import { MANAGEMENT } from '@shell/config/types';
import { sortBy } from '@shell/utils/sort';
import { filterBy } from '@shell/utils/array';
import { addParams } from '@shell/utils/url';
import { HCI, DATA_VOLUME } from '../../types';
import { BACKUP_TYPE } from '../../config/types';
import { HCI as HCI_ANNOTATIONS } from '../../config/labels-annotations';
import { HCI_ALLOWED_SETTINGS, HCI_SINGLE_CLUSTER_ALLOWED_SETTING } from '../../config/settings';
// ---------------------------------------------------------------------------
// Side navigation counts
//
// The side navigation (`Type.vue`, `type-map/getTree`) shows the number of
// resources of a nav item by calling `harvester/count({ name: <nav item> })`.
// Many Harvester nav items are named differently than the K8s resource they
// list (e.g. `harvesterhci.io.volume` lists `persistentvolumeclaim`, see
// `configureType(..., { resource })` in config/harvester-cluster.js). Some
// list views additionally show only a subset of that resource type.
//
// All counts come from the server: Steve's counts endpoint for nav items
// listing all resources of a type, and a filtered request with a page size of 1
// for the nav items in SERVER_FILTERED_COUNTS. Resource lists are not loaded
// for the counts: only Namespaces and Settings count their list, which is always
// loaded with the cluster.
// ---------------------------------------------------------------------------
/**
* Nav items whose list view shows only a subset of the underlying resource
* type, with the query parameters of that subset. Each query must match the
* filter of the list view, so keep them in sync with the files in list/.
*
* Steve's counts endpoint only knows the total per resource type, so these
* counts are requested from Harvester's API (`/v1/harvester`) with the query
* and a page size of 1: the `count` of the response is the number of matches
* (see `fetchFilteredCounts` in actions.ts).
*
* The queries rely on the filtering of Harvester's API, which does not use
* Steve's SQL cache: `filter=a.b=c` matches when the field contains the value,
* `filter=a.b!=` when the field is not set, and a list field matches when any
* of its items matches. Rewrite them when Harvester's API moves to the SQL
* cache: it only filters on indexed fields, and it ignores `labelSelector`
* without an error, so these counts would silently become the totals.
*/
export const SERVER_FILTERED_COUNTS: Record<string, Record<string, string>> = {
// VM backups and VM snapshots are both VirtualMachineBackup resources
[HCI.BACKUP]: { filter: `spec.type!=${ BACKUP_TYPE.SNAPSHOT }` },
[HCI.VM_SNAPSHOT]: { filter: `spec.type=${ BACKUP_TYPE.SNAPSHOT }` },
// VM backups and snapshots also create VolumeSnapshots, owned by the VirtualMachineBackup
[HCI.SNAPSHOT]: { filter: 'metadata.ownerReferences.kind=PersistentVolumeClaim' },
// Every VM image creates an internal backing image StorageClass
[HCI.STORAGE]: { filter: 'parameters.backingImage!=' },
// Only ConfigMaps labeled as cloud-init template
[HCI.CLOUD_TEMPLATE]: { labelSelector: HCI_ANNOTATIONS.CLOUD_INIT },
// Hides the storage network: Harvester creates it with this generated name, and its annotation cannot be filtered on
[HCI.NETWORK_ATTACHMENT]: { filter: 'metadata.generateName!=storagenetwork-' },
// Hides the temporary volumes CDI uses to populate a volume, which are owned by that volume
[HCI.VOLUME]: { filter: 'metadata.ownerReferences.kind!=PersistentVolumeClaim' },
// Not a nav item: the golden image volumes that the list of Volumes also hides, see `volumeCount`
[DATA_VOLUME]: { filter: 'metadata.ownerReferences.kind=VirtualMachineImage' },
};
/**
* Nav items whose list view lists the resources of all namespaces whatever the
* namespace filter is (`:ignore-filter="true"` or `:namespaced="false"` on
* `ResourceTable`). Keep in sync with the files in list/.
*/
export const IGNORE_NAMESPACE_FILTER = new Set<string>([
HCI.NETWORK_ATTACHMENT,
HCI.CLUSTER_FLOW,
HCI.CLUSTER_OUTPUT,
HCI.FLOW,
HCI.OUTPUT,
HCI.ADD_ONS,
]);
/**
* The namespaces to count for a namespaced resource type, or `null` to count
* all of them. Mirrors the namespace filter of `ResourceTable`: even with
* "All Namespaces" selected, the Harvester product (`hideSystemResources`)
* does not list resources in system namespaces, e.g. the PVCs of
* cattle-monitoring-system.
*/
export function countedNamespaces(rootGetters: any): string[] | null {
if (rootGetters.isAllNamespaces && !rootGetters.currentProduct?.hideSystemResources) {
return null;
}
// `namespaces()` computes the active namespaces on demand, so a count is available right
// away instead of only once something else has triggered that computation.
// An empty result is a valid selection (e.g. a project without namespaces): keep the
// empty array so that nothing is counted instead of the cluster-wide total.
return Object.keys(rootGetters.namespaces());
}
/**
* Whether the count of a nav item depends on the namespace filter.
*/
export function isFilteredByNamespace(name: string, schema: any): boolean {
return !!schema?.attributes?.namespaced && !IGNORE_NAMESPACE_FILTER.has(name);
}
/**
* The request for the count of a nav item in SERVER_FILTERED_COUNTS:
* - `{ url }` to request it,
* - `{ count: 0 }` if nothing can match (no namespace selected),
* - `null` if the resource type is unknown or cannot be listed.
*/
export function filteredCountRequest(getters: any, rootGetters: any, name: string): { url?: string, count?: number } | null {
const schema = getters.schemaFor(name);
if (!schema?.links?.collection) {
return null;
}
const params: Record<string, string> = { ...SERVER_FILTERED_COUNTS[name], pagesize: '1' };
if (isFilteredByNamespace(name, schema)) {
const namespaces = countedNamespaces(rootGetters);
if (namespaces?.length === 0) {
return { count: 0 };
}
if (namespaces) {
params.projectsornamespaces = namespaces.join(',');
}
}
return { url: addParams(getters.urlFor(schema.id), params) };
}
/**
* Count of all resources of `resourceType`, taken from Steve's counts
* endpoint. It is loaded with the cluster, so the count is available right
* away. `null` if the resource type is unknown.
*/
function unfilteredCount(getters: any, resourceType: string, namespaces: string[] | null): number | null {
const count = getters.all(COUNT)?.[0]?.counts?.[resourceType];
if (!count) {
return null;
}
if (!namespaces) {
return count.summary?.count || 0;
}
return namespaces.reduce((sum, namespace) => sum + (count.namespaces?.[namespace]?.count || 0), 0);
}
/**
* Count of the Namespaces list. With `hideSystemResources` it hides system and
* Fleet managed namespaces (`list/namespace.vue` of the shell), which the
* counts endpoint cannot tell apart. The namespaces are always loaded with the
* cluster (namespace filter), so the count comes from them. `null` while they
* are not loaded.
*/
function namespaceCount(getters: any): number | null {
if (!getters.haveAll(NAMESPACE)) {
return null;
}
return getters.all(NAMESPACE).filter((namespace: any) => !namespace.isSystem && !namespace.isFleetManaged).length;
}
/**
* Count of the Volumes list, which also hides golden image volumes. These are
* only marked by an annotation, which Harvester's API cannot filter on, but each
* one belongs to a DataVolume owned by its VM image. So they are counted through
* these DataVolumes and subtracted. `null` until both numbers are known.
*/
function volumeCount(state: any): number | null {
const volumes = state.filteredCounts?.[HCI.VOLUME] ?? null;
const goldenImageVolumes = state.filteredCounts?.[DATA_VOLUME] ?? null;
if (volumes === null || goldenImageVolumes === null) {
return null;
}
// A DataVolume exists briefly before its volume
return Math.max(volumes - goldenImageVolumes, 0);
}
/**
* Count of the Settings page, which shows only some of the settings (see the
* `visibleSettings` getter). `null` while the settings are not loaded.
*/
function settingCount(getters: any): number | null {
return getters.haveAll(HCI.SETTING) ? getters.visibleSettings.length : null;
}
function resourceCount(state: any, rootGetters: any, getters: any, typeObj: any): number | null {
const type = typeObj?.name;
if (!type) {
throw new Error(`Resource type required to calc count: ${ JSON.stringify(typeObj) }`);
}
if (type === HCI.VOLUME) {
return volumeCount(state);
}
// Requested by `fetchFilteredCounts` (actions.ts), `null` until the response arrives
if (SERVER_FILTERED_COUNTS[type]) {
return state.filteredCounts?.[type] ?? null;
}
if (type === NAMESPACE && rootGetters.currentProduct?.hideSystemResources) {
return namespaceCount(getters);
}
if (type === HCI.SETTING) {
return settingCount(getters);
}
// schemaFor falls back to the resource of `configureType`, so this resolves
// the nav item to the K8s resource type it lists
const schema = getters.schemaFor(type);
const resourceType = schema?.id || type;
const namespaces = isFilteredByNamespace(type, schema) ? countedNamespaces(rootGetters) : null;
return unfilteredCount(getters, resourceType, namespaces);
}
export default {
namespaceFilterOptions: (state: any, getters: any, rootState: any, rootGetters: any) => ({
@@ -345,26 +125,6 @@ export default {
return projectsInAllClusters.filter((project: any) => project.spec.clusterName === clusterId && project.nameDisplay !== 'System');
},
/**
* The settings shown by the Settings page: the allowed ones that exist in the
* cluster and are supported by its version. The page and the count of its nav
* item both use this, so that they always agree.
*/
visibleSettings(state: any, getters: any, rootState: any, rootGetters: any) {
const settings = [
...(rootGetters.isSingleProduct ? rootGetters['management/all'](MANAGEMENT.SETTING) : []),
...getters.all(HCI.SETTING),
];
const settingsById = Object.fromEntries(settings.map((setting: any) => [setting.id, setting]));
const allowed = rootGetters.isStandaloneHarvester ? { ...HCI_ALLOWED_SETTINGS, ...HCI_SINGLE_CLUSTER_ALLOWED_SETTING } : HCI_ALLOWED_SETTINGS;
return Object.entries(allowed)
.filter(([id, config]: any) => settingsById[id] && (!config.featureFlag || rootGetters['harvester-common/getFeatureEnabled'](config.featureFlag)))
.map(([id, config]: any) => ({
id, config, data: settingsById[id]
}));
},
// Few harvester resources name and REAL resource are different. E.g. HCI.NETWORK_ATTACHMENT page resource is NETWORK_ATTACHMENT.
// Check in config/harvester-cluster.js for more details.
// We need to look up the schema by resource name, and fallback to find using real resource name
@@ -385,19 +145,4 @@ export default {
return null;
},
// Overrides the `count` getter of the dashboard store, which looks up the
// count by the nav item name only. See "Side navigation counts" above.
count: (state: any, getters: any, rootState: any, rootGetters: any) => (typeObj: any) => {
// Like the `count` getter of the dashboard store: a nav item configured with `subTypes`
// shows the sum of the counts of these types, e.g. the Migration Overview
// (`forklift-create`) shows the number of Migration Plans.
const subTypes = rootGetters['type-map/optionsFor']?.(typeObj?.name)?.subTypes || [];
if (subTypes.length) {
return subTypes.reduce((acc: number, type: string) => acc + resourceCount(state, rootGetters, getters, { name: type }), 0);
}
return resourceCount(state, rootGetters, getters, typeObj);
},
};
@@ -9,15 +9,6 @@ import actions from './actions';
const harvesterFactory = (): CoreStoreSpecifics => {
const steveFactory = SteveFactory(null, null);
const steveState = steveFactory.state;
steveFactory.state = () => ({
...steveState(),
// Side navigation counts requested by `fetchFilteredCounts`, see getters.ts
filteredCounts: {},
filteredCountRequests: {},
filteredCountWatchers: [],
});
steveFactory.getters = {
...steveFactory.getters,
@@ -1,22 +1 @@
//@ts-nocheck
import { markRaw } from 'vue';
// Side navigation counts requested by `fetchFilteredCounts`, see getters.ts
export default {
filteredCountRequested(state: any, name: string) {
state.filteredCountRequests[name] = (state.filteredCountRequests[name] || 0) + 1;
},
setFilteredCount(state: any, { name, count }: any) {
state.filteredCounts = { ...state.filteredCounts, [name]: count };
},
// Keeps `filteredCountRequests`, so that a response of the previous cluster is still outdated
resetFilteredCounts(state: any) {
state.filteredCounts = {};
},
setFilteredCountWatchers(state: any, unwatchers: (() => void)[]) {
state.filteredCountWatchers = markRaw(unwatchers);
},
};
export default {};
-4
View File
@@ -37,9 +37,6 @@ export const HCI = {
NETWORK_ATTACHMENT: 'harvesterhci.io.networkattachmentdefinition',
CLUSTER: 'harvesterhci.io.management.cluster',
DASHBOARD: 'harvesterhci.io.dashboard',
COMPONENT_HEALTH: 'health.harvesterhci.io.componenthealth',
HEALTH_SUMMARY: 'health.harvesterhci.io.healthsummary',
HEALTH_IGNORE_RULE: 'health.harvesterhci.io.healthignorerule',
BLOCK_DEVICE: 'harvesterhci.io.blockdevice',
CLOUD_TEMPLATE: 'harvesterhci.io.cloudtemplate',
HOST: 'harvesterhci.io.host',
@@ -87,6 +84,5 @@ export const HCI = {
};
export const VOLUME_SNAPSHOT = 'snapshot.storage.k8s.io.volumesnapshot';
export const DATA_VOLUME = 'cdi.kubevirt.io.datavolume';
export const CSI_DRIVER = 'storage.k8s.io.csidriver';
export const VOLUME_SNAPSHOT_CLASS = 'snapshot.storage.k8s.io.volumesnapshotclass';
-108
View File
@@ -1,108 +0,0 @@
export const COMPONENT_LABEL = 'health.harvesterhci.io/component';
export const IGNORE_RULE_SOURCE_LABEL = 'health.harvesterhci.io/source';
export const IGNORE_DURATION_DAYS = {
days7: 7,
days30: 30,
forever: 0,
};
export const AFFECTED_RESOURCES_TRUNCATE_COUNT = 3;
export const MESSAGE_TRUNCATE_LENGTH = 100;
export const SEVERITY_COLORS = {
Error: 'bg-error',
Warning: 'bg-warning',
Info: 'bg-info',
Healthy: 'bg-success',
};
export const HEALTH_SUMMARY_SEVERITY_RANK = {
Error: 0,
Warning: 1,
Healthy: 2,
};
export const COMPONENT_HEALTH_SEVERITIES = ['Error', 'Warning', 'Info'];
export function severityColor(severity) {
return SEVERITY_COLORS[severity] || 'bg-info';
}
export function healthSummarySeverity(row) {
if (row.errorCount > 0) {
return 'Error';
}
if (row.warningCount > 0) {
return 'Warning';
}
return 'Healthy';
}
// the summaries already leave out what is ignored
export function totalErrorCount(healthSummaries) {
return (healthSummaries || []).reduce((total, summary) => {
return Object.values(summary?.status?.components || {}).reduce((sum, counts) => sum + (counts?.errorCount || 0), total);
}, 0);
}
export function componentOf(componentHealth) {
return componentHealth?.metadata?.labels?.[COMPONENT_LABEL] || componentHealth?.metadata?.name;
}
export function allAffectedResourceNames(row) {
return Object.keys(row?.affectedResources?.names || {});
}
// the resources that no HealthIgnoreRule ignores
export function activeAffectedResourceNames(row) {
const names = row?.affectedResources?.names || {};
return Object.keys(names).filter((name) => !names[name]?.ignored);
}
export function resourceIgnoredBy(row, name) {
const detail = row?.affectedResources?.names?.[name];
return detail?.ignored ? detail.ignoredBy : '';
}
export function ignoredResourceCount(row) {
return allAffectedResourceNames(row).length - activeAffectedResourceNames(row).length;
}
// what "Show ignored" brings back: the checks ignored as a whole, and the ignored resources of the other checks
export function ignoredCounts(checks) {
return (checks || []).reduce((counts, check) => {
if (check.ignored) {
counts.checks += 1;
} else {
counts.resources += ignoredResourceCount(check);
}
return counts;
}, { checks: 0, resources: 0 });
}
// the UI keeps one rule per check under this name, so Kubernetes refuses a second one for the same check.
// Some checks are named after a condition reason with spaces, like "Proactive Schedule Suspend", which a name can't have
export function ignoreRuleName(componentHealthName, checkName) {
const check = checkName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
return `${ componentHealthName }.${ check }`;
}
export function affectedResourceKind(row) {
return row?.affectedResources?.kind || '';
}
// what the UI calls that kind, in the singular or plural of how many there are
export function affectedResourceLabel(row, store) {
const { apiVersion = '', kind = '' } = row?.affectedResources || {};
const group = apiVersion.includes('/') ? `${ apiVersion.split('/')[0] }.` : '';
const schema = store.getters['harvester/schemaFor'](`${ group }${ kind.toLowerCase() }`);
return schema ? store.getters['type-map/labelFor'](schema, row.affectedCount) : kind;
}
+841 -1254
View File
File diff suppressed because it is too large Load Diff