feat: page the VM list on the server when the API supports it (#1261)

* feat: page the VM list on the server when the API supports it

On clusters whose API serves lists from the Steve SQL cache, the VM list
uses PaginatedResourceTable: it loads one page of VMs, and the VMIs, pods,
PVCs, PVs, migrations, restores and backups of those VMs only. Sorting,
search and the namespace filter run on the server, so CPU, memory, IP and
node can't be sorted or searched there.

The feature is gated by the vmListPagination feature flag and enabled for
the VM list only, through a pagination context. Older clusters keep the
current list.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* feat: enable the VM list pagination from v1.10.0

The backend change that serves API lists from the SQL cache has to be on
the v1.10 branch before this is merged.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the paged VM list when adding a volume

The Add Volume dialog loaded every VM to find the volumes in use, which
replaced the page the VM list keeps in the store and emptied the list.
When the list is paged, the dialog now reads only the VMs of the
namespace and doesn't store them.

The requests for the resources of a page use one IN filter instead of
one filter per value, which keeps the URLs about a third as long.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the paged VM list intact in its dialogs and on older APIs

The Add Volume, Storage Migration and Restore dialogs read the VMs, PVCs
and backups of the VM's namespace through the VM. While the list keeps a
page of a type in the store they read the namespace without storing it,
so the list keeps its page and the dialogs' own lists don't shrink when
the page reloads. Storage Migration no longer offers volumes of VMs on
other pages as targets.

The list is paged only when the API lists the VM's printer columns as
metadata.fields, which the SQL cache does, so a missing or non-semver
server version can't turn it on against an API that can't filter.

One failed request for a page's resources no longer stops the others.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: show the restart notice only when its VMs change

The list rebuilds the names of the VMs that need a restart on every
refresh, and when it pages also on every page, sort and search, so the
notice popped up again each time even when nothing new needed a
restart. Show it only when the set of VMs changes.

While paging it still covers only the VMs on the current page: the API
can't filter VMs by their RestartRequired condition.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: find the launcher pods of every VM on the page

The paged list loaded the page's launcher pods by the harvesterhci.io/vmName
label, which only the Harvester VM form writes into a VM's template. VMs
created any other way, like an imported VM or one applied with kubectl,
got no pod, so their rows lost View Logs and the starting and pod error
states.

Load the pods after the page's VMIs instead, by the kubevirt.io/created-by
label KubeVirt puts on every launcher pod (the VMI's UID).

Also cover the paged mode in the tests: it must not load every VMI,
migration or pod, and a forced refresh must reach every request.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: notify about restarts again when coming back to the VM list

The restart notice compared the VMs that need a restart with the
previous value of the list. Coming back from a page that loads every VM,
like Volumes or a VM's detail page, that previous value already held the
same VMs, so the notice didn't show. Remember what was notified on the
list itself instead, so each visit starts fresh, and compare by namespace
and name, so a VM of the same name in another namespace counts as a
change.

Also say which VMs lack Harvester's vmName label: the ones from Forklift
or plain manifests, not every VM created outside the UI.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: keep the VM list's paging helpers in the component

Only canPaginate stays outside, because ResourceList calls
$loadingResources(route, store) on the component options, where there is
no `this`. The pagination headers become a computed property and the
printer column lookup a method.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: always list VMs with PaginatedResourceTable

PaginatedResourceTable handles both modes. fetchSecondaryResources loads
every pod, volume, restore, backup, VMI and migration when the list isn't
paged, and only what every row shares when it is. VMIs without a VM are
added back through localFilter, which only runs without pagination.

The list passes the pagination context only when the cluster's API can
page, so older clusters keep the full list.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: register the VM list's columns with the product

Both column sets go through the product's headers(), with the paged set
next to the unpaged one in config/table-headers.js. The list only adds the
node and restore progress columns, which the API can't sort or search when
paging. State sorts by the VM's Status printer column, metadata.fields.2.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: show the restart notice when coming back to the VM list

Since the list always uses PaginatedResourceTable it reads the VMs from
the store. Coming back to the list the store already holds them, so the
restart watcher never saw a change and the notice didn't show. Run it
when the list is created too.

While paging, the store can still hold the VMs another view loaded, like
every VM after Volumes or a VM's detail, so wait for the list's own page
before notifying.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: let the namespace filter know the VM list is paged

The VMs were registered for pagination with a context that only the VM
list passed. The header's namespace filter asks without one, so it didn't
know the list was paged and kept offering "Not in a Project", which the
paged API can't filter by: picking it hid every VM.

Register the VMs in every context and answer per cluster in the store's
paginationEnabled getter instead: only when the feature is on and the
API lists the VM's printer columns as metadata.fields, as the SQL cache
does. The filter, the list and the store now agree, and clusters whose
API can't page keep the full list.

The filter is shared by every list, so Not in a Project can still be
picked on a list that doesn't page. The paged VM list then asks for
another option, like the shell's generic lists do, instead of showing
no rows.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* fix: keep the paged VM list when showing a VM's configuration

The Config tab of the Show Configuration drawer renders the VM form,
which loads every VM, PVC, PV, VMI and migration, and its device tabs
every VM again. On a paged list that replaced the list's page in the
store and emptied the list.

Hide the Config tab while the store keeps a page of VMs, so the drawer
shows the YAML. The VM's own page still shows its configuration, and a
drawer opened where every VM is loaded keeps its Config tab.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

* refactor: define the VM list's node and restore columns with the others

The node and restore progress columns are now in VM_HEADERS, so the paged
set turns their sort and search off through VM_PAGINATION_FIELDS, like the
other columns the API can't index. The list only leaves them out when they
don't apply: the node column when the cluster's nodes can't be seen, the
restore progress while no backup is being restored.

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>

---------

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
This commit is contained in:
Marcelo Fukumoto authored and GitHub committed 2026-11-20 17:49:19 +01:00
1 parent e66b61d0d1
commit 0c6eee1744
18 files changed
+937 -160

No files matched your search

+1
View File
@@ -88,6 +88,7 @@ const FEATURE_FLAGS = {
'componentHealth',
'repositoryStorageClass',
'shutdownVMOnMigrationFailure',
'vmListPagination',
],
};
@@ -54,6 +54,8 @@ import {
FORKLIFT_PLAN_TARGET_NS,
FORKLIFT_PLAN_VM_COUNT,
FORKLIFT_MIGRATION_PLAN,
VM_HEADERS,
VM_PAGINATION_HEADERS,
} from './table-headers';
import { ADD_ONS } from './harvester-map';
import { registerAddonSideNav } from '../utils/dynamic-nav';
@@ -257,6 +259,7 @@ export function init($plugin, store) {
basicType([HCI.VM]);
configureType(HCI.VM, { canYaml: false });
headers(HCI.VM, VM_HEADERS, VM_PAGINATION_HEADERS);
virtualType({
labelKey: 'harvester.virtualMachine.label',
group: 'root',
@@ -21,6 +21,7 @@ export const HCI = {
VM_NAME: 'harvesterhci.io/vmName',
VM_NAME_PREFIX: 'harvesterhci.io/vmNamePrefix',
VM_DISPLAY_NAME: 'harvesterhci.io/vmDisplayName',
VMI_CREATED_BY: 'kubevirt.io/created-by',
VM_RESERVED_MEMORY: 'harvesterhci.io/reservedMemory',
MAINTENANCE_STATUS: 'harvesterhci.io/maintain-status', // Deprecated >= v1.10.0
HOST_CUSTOM_NAME: 'harvesterhci.io/host-custom-name',
+86 -1
View File
@@ -1,7 +1,10 @@
/**
* Harvester
*/
import { DESCRIPTION } from '@shell/config/table-headers';
import {
DESCRIPTION, STATE, AGE, NAME, NAMESPACE
} from '@shell/config/table-headers';
import { HCI as HCI_ANNOTATIONS } from './labels-annotations';
// image
export const IMAGE_DOWNLOAD_SIZE = {
@@ -297,3 +300,85 @@ export const FORKLIFT_MIGRATION_PLAN = {
sort: 'spec.plan.name',
align: 'left',
};
// Virtual machine list
export const VM_HEADERS = [
STATE,
{
...NAME,
width: 350,
value: 'nameDisplay',
sort: ['nameDisplay'],
},
NAMESPACE,
{
name: 'CPU',
label: 'CPU',
sort: ['displayCPU'],
value: 'displayCPU',
align: 'center',
dashIfEmpty: true,
},
{
name: 'Memory',
value: 'displayMemory',
sort: ['memorySort'],
align: 'center',
labelKey: 'tableHeaders.memory',
formatter: 'Si',
formatterOpts: {
opts: {
increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i',
},
needParseSi: true
},
},
{
name: 'ip',
label: 'IP Address',
value: 'id',
formatter: 'HarvesterIpAddress',
labelKey: 'tableHeaders.ipAddress',
sort: ['id'],
},
// The VM list only shows it when the cluster's nodes can be seen
{
name: 'node',
label: 'Node',
value: 'nodeName',
sort: ['realAttachNodeName'],
formatter: 'HarvesterHost',
labelKey: 'harvester.tableHeaders.vm.node'
},
// The VM list only shows it while a backup is being restored
{
name: 'restoreProgress',
labelKey: 'harvester.tableHeaders.restore',
value: 'restoreProgress',
align: 'left',
formatter: 'HarvesterBackupProgressBar',
width: 200,
},
{
...AGE,
sort: 'metadata.creationTimestamp:desc',
}
];
// With server-side pagination the API sorts and searches, so only the fields it indexes can be used. CPU, memory, IP,
// node and restore progress come from the VM model or other resources. The VM's printer columns are listed as Name, Age, Status, Ready, so its
// Status is `metadata.fields.2`
const VM_PAGINATION_FIELDS = {
[STATE.name]: { sort: ['metadata.fields.2'], search: false },
[NAME.name]: {
sort: ['metadata.name'],
search: ['metadata.name', `metadata.annotations[${ HCI_ANNOTATIONS.VM_DISPLAY_NAME }]`],
},
[NAMESPACE.name]: { sort: ['metadata.namespace'], search: 'metadata.namespace' },
[AGE.name]: { search: false },
};
export const VM_PAGINATION_HEADERS = VM_HEADERS.map((header) => ({
...header,
...(VM_PAGINATION_FIELDS[header.name] || { sort: false, search: false }),
}));
@@ -5,7 +5,7 @@ import SortableTable from '@shell/components/SortableTable';
import { HCI } from '@pkg/harvester/types';
import { allHash } from '@shell/utils/promise';
import { KEY, VALUE } from '@shell/config/table-headers';
import { VM_HEADERS } from '@pkg/harvester/list/kubevirt.io.virtualmachine';
import { VM_HEADERS } from '@pkg/harvester/config/table-headers';
import { matching } from '@shell/utils/selector';
import { IP_POOL_HEADERS } from '../config/harvester-cluster';
@@ -103,7 +103,7 @@ export default {
},
vmHeaders() {
const filterNames = ['state', 'ip', 'node'];
const filterNames = ['state', 'ip', 'node', 'restoreProgress'];
return VM_HEADERS.filter((h) => !filterNames.includes(h.name));
},
@@ -30,9 +30,9 @@ export default {
},
async fetch() {
this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
this.allPVCs = await this.actionResource.findInNamespace(PVC);
this.allStorageClasses = await this.$store.dispatch('harvester/findAll', { type: STORAGE_CLASS });
this.allVMs = await this.$store.dispatch('harvester/findAll', { type: HCI.VM });
this.allVMs = await this.actionResource.findInNamespace(HCI.VM);
},
data() {
@@ -2,7 +2,6 @@
import { mapGetters } from 'vuex';
import { randomStr } from '@shell/utils/string';
import { allHash } from '@shell/utils/promise';
import { exceptionToErrorsArray } from '@shell/utils/error';
import { Card } from '@components/Card';
@@ -24,9 +23,7 @@ export default {
},
async fetch() {
const hash = await allHash({ backups: this.$store.dispatch('harvester/findAll', { type: HCI.BACKUP }) });
this.backups = hash.backups;
this.backups = await this.actionResource.findInNamespace(HCI.BACKUP);
},
props: {
@@ -29,7 +29,13 @@ export default {
},
async fetch() {
this.allPVCs = await this.$store.dispatch('harvester/findAll', { type: PVC });
const [pvcs, vms] = await Promise.all([
this.actionResource.findInNamespace(PVC),
this.actionResource.findInNamespace(HCI.VM),
]);
this.allPVCs = pvcs;
this.namespaceVMs = vms;
},
data() {
@@ -38,6 +44,7 @@ export default {
targetVolume: '',
errors: [],
allPVCs: [],
namespaceVMs: [],
};
},
@@ -68,10 +75,9 @@ export default {
},
vmUsedVolumeNames() {
const allVMs = this.$store.getters['harvester/all'](HCI.VM) || [];
const names = new Set();
allVMs.forEach((vm) => {
this.namespaceVMs.forEach((vm) => {
// Collect volume names from spec.template.spec.volumes (both PVC and DataVolume references)
const volumes = vm.spec?.template?.spec?.volumes || [];
@@ -0,0 +1,55 @@
import { PVC, STORAGE_CLASS } from '@shell/config/types';
import HotplugVolumeModal from '../HarvesterAddHotplugVolumeModal.vue';
import StorageMigrationDialog from '../HarvesterStorageMigrationDialog.vue';
import RestoreDialog from '../HarvesterRestoreDialog.vue';
import { HCI } from '../../types';
// The dialogs of the VM list read the VMs, PVCs and backups of the VM's namespace through the VM, so a paged VM list
// keeps its page (see `findInNamespace` in the VM model)
describe('dialogs of the VM list', () => {
const vm = (claims = []) => ({
metadata: { namespace: 'default', name: 'vm' },
spec: { template: { spec: { volumes: claims.map((claimName) => ({ persistentVolumeClaim: { claimName } })) } } },
findInNamespace: jest.fn((type) => Promise.resolve([{ type }])),
});
it('should load the PVCs and VMs of Add Volume through the VM', async() => {
const actionResource = vm();
const dispatch = jest.fn(() => Promise.resolve([]));
const dialog = { actionResource, $store: { dispatch } };
await HotplugVolumeModal.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.allVMs).toStrictEqual([{ type: HCI.VM }]);
expect(dispatch.mock.calls).toStrictEqual([['harvester/findAll', { type: STORAGE_CLASS }]]);
});
it('should load the PVCs and VMs of Storage Migration through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await StorageMigrationDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[PVC], [HCI.VM]]);
expect(dialog.allPVCs).toStrictEqual([{ type: PVC }]);
expect(dialog.namespaceVMs).toStrictEqual([{ type: HCI.VM }]);
});
it('should exclude the volumes of the loaded VMs from the Storage Migration targets', () => {
const used = StorageMigrationDialog.computed.vmUsedVolumeNames.call({ namespaceVMs: [vm(['a-disk']), vm(['b-disk'])] });
expect([...used]).toStrictEqual(['default/a-disk', 'default/b-disk']);
});
it('should load the backups of Restore through the VM', async() => {
const actionResource = vm();
const dialog = { actionResource };
await RestoreDialog.fetch.call(dialog);
expect(actionResource.findInNamespace.mock.calls).toStrictEqual([[HCI.BACKUP]]);
expect(dialog.backups).toStrictEqual([{ type: HCI.BACKUP }]);
});
});
+11
View File
@@ -6,6 +6,7 @@ import harvesterCommonStore from './store/harvester-common';
import harvesterStore from './store/harvester-store';
import customValidators from './validators';
import { PRODUCT_NAME } from './config/harvester';
import { HCI } from './types';
import {
hostResolvesL10nGlobals, resolveL10nGlobals, standaloneProductName, PRODUCT_NAME_GLOBAL
} from './utils/l10n-globals';
@@ -41,6 +42,16 @@ export default function (plugin: IPlugin) {
plugin.addDashboardStore(harvesterStore.config.namespace, harvesterStore.specifics, harvesterStore.config, harvesterStore.init);
plugin.validators = customValidators;
// The store's `paginationEnabled` getter turns it off on clusters whose API can't page the VM list
plugin.enableServerSidePagination?.({
[PRODUCT_NAME]: {
resources: {
enableAll: false,
enableSome: { enabled: [HCI.VM] }
}
}
});
plugin.addRoutes(extensionRoutes);
plugin.register('component', 'NavHeaderRight', defineAsyncComponent(() =>
@@ -0,0 +1,373 @@
import { shallowMount } from '@vue/test-utils';
import {
PVC, PV, POD, NODE, STORAGE_CLASS
} from '@shell/config/types';
import VmList from '../kubevirt.io.virtualmachine.vue';
import { VM_HEADERS, VM_PAGINATION_HEADERS } from '../../config/table-headers';
import { HCI } from '../../types';
const schemaWithColumns = (id, columns) => ({
id,
attributes: { columns: columns.map((name, i) => ({ name, field: `$.metadata.fields[${ i }]` })) }
});
const SCHEMAS = {
[HCI.VM]: schemaWithColumns(HCI.VM, ['Name', 'Age', 'Status', 'Ready']),
[HCI.VMIM]: schemaWithColumns(HCI.VMIM, ['Name', 'Phase', 'VMI']),
[HCI.RESTORE]: schemaWithColumns(HCI.RESTORE, ['Name', 'TARGET_KIND', 'TARGET_NAME']),
[HCI.VMI]: { id: HCI.VMI },
[HCI.BACKUP]: { id: HCI.BACKUP },
[POD]: { id: POD },
[PVC]: { id: PVC },
[PV]: { id: PV },
};
// `harvester/paginationEnabled` is the store's getter, which checks the cluster's API (see store/harvester-store/getters.ts)
function createStore({
paginationEnabled = true, havePage = true, found = {}, failing = [], storedVMs = [], storedVMIs = [], namespaceFilters = []
} = {}) {
const dispatch = jest.fn((action, { type } = {}) => (failing.includes(type) ? Promise.reject(new Error('failed')) : Promise.resolve(found[type] || [])));
return {
dispatch,
getters: {
currentProduct: { inStore: 'harvester' },
'harvester/paginationEnabled': jest.fn((args) => paginationEnabled && (args?.id || args) === HCI.VM),
'harvester/havePage': (type) => havePage && type === HCI.VM,
'harvester/schemaFor': (type) => SCHEMAS[type],
'harvester/all': (type) => ({ [HCI.VM]: storedVMs, [HCI.VMI]: storedVMIs }[type] || []),
'type-map/headersFor': (schema, pagination) => (pagination ? VM_PAGINATION_HEADERS : VM_HEADERS),
'action-menu/performCallbackData': undefined,
namespaceFilters,
}
};
}
const call = (name, ctx) => VmList.computed[name].call(ctx);
const byName = (headers) => Object.fromEntries(headers.map((h) => [h.name, { sort: h.sort, search: h.search }]));
const vm = (namespace, name, claimNames = []) => ({
id: `${ namespace }/${ name }`,
metadata: { namespace, name },
persistentVolumeClaimName: claimNames,
});
describe('list: kubevirt.io.virtualmachine', () => {
describe('without server-side pagination', () => {
it('should not page when the store says the cluster\'s API can\'t page the VMs', () => {
const $store = createStore({ paginationEnabled: false });
expect(call('canPaginate', { $store })).toBe(false);
expect($store.getters['harvester/paginationEnabled']).toHaveBeenCalledWith(HCI.VM);
});
it('should show the product\'s VM columns, with node and restore progress when they apply', () => {
const ctx = {
$store: createStore({ paginationEnabled: false }), schema: SCHEMAS[HCI.VM], hasNode: true, hasBackUpRestoreInProgress: true
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
const headers = call('headers', ctx);
expect(headers.map(({ name }) => name)).toStrictEqual(['state', 'name', 'namespace', 'CPU', 'Memory', 'ip', 'node', 'restoreProgress', 'age']);
expect(byName(headers).CPU).toStrictEqual({ sort: ['displayCPU'], search: undefined });
expect(byName(headers).node).toStrictEqual({ sort: ['realAttachNodeName'], search: undefined });
});
it.each([
['node', 'the cluster\'s nodes can\'t be seen', { hasNode: false, hasBackUpRestoreInProgress: true }],
['restoreProgress', 'no backup is being restored', { hasNode: true, hasBackUpRestoreInProgress: false }],
])('should leave out the %s column when %s', (column, _, flags) => {
const ctx = {
$store: createStore(), schema: SCHEMAS[HCI.VM], ...flags
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
expect(call('headers', ctx).map(({ name }) => name)).not.toContain(column);
expect(call('paginationHeaders', ctx).map(({ name }) => name)).not.toContain(column);
expect(call('headers', ctx)).toHaveLength(VM_HEADERS.length - 1);
});
it('should add VMIs without a VM to the rows', () => {
const vms = [{ id: 'default/a' }];
const $store = createStore({ storedVMs: vms, storedVMIs: [{ id: 'default/a' }, { id: 'default/orphan' }] });
const ctx = {
$store, inStore: 'harvester', canPaginate: false, vms
};
ctx.vmisWithoutVM = call('vmisWithoutVM', ctx);
expect(VmList.methods.addVMIsWithoutVM.call(ctx, vms).map(({ id }) => id)).toStrictEqual(['default/a', 'default/orphan']);
expect(call('rows', ctx).map(({ id }) => id)).toStrictEqual(['default/a', 'default/orphan']);
});
it('should load every resource the rows need, the table loads the VMs', async() => {
const $store = createStore({ paginationEnabled: false });
await VmList.methods.fetchSecondaryResources.call({
$store, inStore: 'harvester', hasNode: true
}, { canPaginate: false });
expect($store.dispatch.mock.calls.map(([action, { type }]) => `${ action } ${ type }`).sort()).toStrictEqual([
HCI.BACKUP, HCI.IMAGE, HCI.RESTORE, HCI.VMI, HCI.VMIM, NODE, POD, PV, PVC, STORAGE_CLASS
].map((type) => `harvester/findAll ${ type }`).sort());
});
});
describe('with server-side pagination', () => {
it('should page when the store says the cluster\'s API can page the VMs', () => {
expect(call('canPaginate', { $store: createStore() })).toBe(true);
});
it('should only sort and search on fields the API indexes', () => {
const ctx = {
$store: createStore(), schema: SCHEMAS[HCI.VM], hasNode: true, hasBackUpRestoreInProgress: true
};
ctx.applicableColumns = VmList.methods.applicableColumns.bind(ctx);
expect(byName(call('paginationHeaders', ctx))).toStrictEqual({
state: { sort: ['metadata.fields.2'], search: false },
name: { sort: ['metadata.name'], search: ['metadata.name', 'metadata.annotations[harvesterhci.io/vmDisplayName]'] },
namespace: { sort: ['metadata.namespace'], search: 'metadata.namespace' },
CPU: { sort: false, search: false },
Memory: { sort: false, search: false },
ip: { sort: false, search: false },
node: { sort: false, search: false },
restoreProgress: { sort: false, search: false },
age: { sort: 'metadata.creationTimestamp:desc', search: false },
});
});
it('should take the VMs of the page from the store', () => {
const storedVMs = [vm('default', 'a')];
const $store = createStore({ storedVMs });
expect(call('vms', { $store, inStore: 'harvester' })).toBe(storedVMs);
});
it('should list only the VMs of the page', () => {
const page = [vm('default', 'a')];
const $store = createStore({ storedVMs: page, storedVMIs: [{ id: 'default/orphan' }] });
const ctx = {
$store, inStore: 'harvester', canPaginate: true, vms: page
};
ctx.vmisWithoutVM = call('vmisWithoutVM', ctx);
expect(call('rows', ctx)).toStrictEqual(page);
});
it('should fetch only the resources of the VMs on the page', async() => {
const $store = createStore({
found: {
[PVC]: [{ spec: { volumeName: 'pv-a' } }, { spec: {} }],
[HCI.RESTORE]: [{ spec: { virtualMachineBackupName: 'backup-a' } }],
[HCI.VMI]: [{ metadata: { name: 'a', uid: 'uid-a' } }, { metadata: { name: 'b', uid: 'uid-b' } }],
}
});
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await VmList.methods.fetchPageSecondaryResources.call(ctx, {
force: true,
page: [vm('default', 'a', ['a-disk']), vm('other', 'a'), vm('default', 'b', ['b-disk'])],
});
const filters = Object.fromEntries($store.dispatch.mock.calls.map(([action, { type, opt }]) => {
expect(action).toBe('harvester/findPage');
expect(opt.force).toBe(true);
return [type, opt.pagination.filters[0].fields.map(({ field, value, equality }) => `${ field }${ equality }(${ value })`)];
}));
expect(filters).toStrictEqual({
[PVC]: ['metadata.name IN (a-disk,b-disk)'],
[HCI.RESTORE]: ['metadata.fields.2 IN (a,b)'],
[HCI.VMI]: ['metadata.name IN (a,b)'],
[POD]: ['metadata.labels[kubevirt.io/created-by] IN (uid-a,uid-b)'],
[HCI.VMIM]: ['metadata.fields.2 IN (a,b)'],
[PV]: ['metadata.name IN (pv-a)'],
[HCI.BACKUP]: ['metadata.name IN (backup-a)'],
});
});
it('should fetch the rest when one request fails', async() => {
const $store = createStore({ failing: [HCI.RESTORE], found: { [PVC]: [{ spec: { volumeName: 'pv-a' } }], [HCI.VMI]: [{ metadata: { uid: 'uid-a' } }] } });
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await expect(VmList.methods.fetchPageSecondaryResources.call(ctx, { force: false, page: [vm('default', 'a', ['a-disk'])] })).resolves.toBeUndefined();
const types = $store.dispatch.mock.calls.map(([, { type }]) => type);
expect(types).toStrictEqual(expect.arrayContaining([PVC, HCI.VMI, POD, HCI.VMIM, PV]));
expect(types).not.toContain(HCI.BACKUP);
});
it('should not fetch a type when no VM on the page needs it', async() => {
const $store = createStore();
const ctx = { $store, inStore: 'harvester' };
ctx.findPageByField = VmList.methods.findPageByField.bind(ctx);
ctx.printerColumnField = VmList.methods.printerColumnField.bind(ctx);
await VmList.methods.fetchPageSecondaryResources.call(ctx, { force: false, page: [vm('default', 'a')] });
const types = $store.dispatch.mock.calls.map(([, { type }]) => type);
expect(types).not.toContain(PVC);
expect(types).not.toContain(PV);
expect(types).not.toContain(HCI.BACKUP);
expect(types).not.toContain(POD);
});
it('should load only what every row shares, not the per-VM resources', async() => {
const $store = createStore();
await VmList.methods.fetchSecondaryResources.call({
$store, inStore: 'harvester', hasNode: true
}, { canPaginate: true });
expect($store.dispatch.mock.calls).toStrictEqual([
['harvester/findAll', { type: HCI.IMAGE }],
['harvester/findAll', { type: STORAGE_CLASS }],
['harvester/findAll', { type: NODE }],
]);
});
});
// The header's filter is shared by every list, so Not in a Project can come from a list that doesn't page
it.each([
['ask for another namespace filter while paging when the API can\'t filter by it', { namespaceFilters: ['all://orphans'] }, true],
['show the list while paging with a namespace filter the API can use', { namespaceFilters: ['ns://default'] }, false],
['show the list without pagination, whatever the filter', { paginationEnabled: false, namespaceFilters: ['all://orphans'] }, false],
])('should %s', (_, opts, asks) => {
const wrapper = shallowMount(VmList, {
props: { schema: SCHEMAS[HCI.VM] },
global: { mocks: { $store: createStore(opts), t: (key) => key }, stubs: { 'router-link': true } },
});
expect(wrapper.findComponent({ name: 'IconMessage' }).exists()).toBe(asks);
expect(wrapper.findComponent({ name: 'PaginatedResourceTable' }).exists()).toBe(!asks);
});
it('should hide the masthead loading count only with pagination', () => {
expect(VmList.$loadingResources(null, createStore())).toStrictEqual({ loadResources: [] });
expect(VmList.$loadingResources(null, createStore({ paginationEnabled: false }))).toStrictEqual({});
});
describe('restart required notification', () => {
const rvm = (namespace, name) => ({
id: `${ namespace }/${ name }`, metadata: { namespace, name }, isRestartRequired: true
});
const notify = (ctx, vms, oldVms) => VmList.watch.restartRequiredVMs.handler.call(ctx, vms, oldVms);
const createCtx = (restartNotificationKey) => ({
$store: { dispatch: jest.fn() },
t: (key, args) => `${ key } ${ JSON.stringify(args) }`,
restartNotificationKey,
});
const mountList = ($store) => shallowMount(VmList, {
props: { schema: SCHEMAS[HCI.VM] },
global: { mocks: { $store, t: (key, args) => `${ key } ${ JSON.stringify(args) }` }, stubs: { 'router-link': true } },
});
const warning = (count, vmNames) => ['growl/warning', {
title: `harvester.notification.restartRequired.title ${ JSON.stringify({ count }) }`,
message: `harvester.notification.restartRequired.message ${ JSON.stringify({ vmNames }) }`,
timeout: 10000,
}, { root: true }];
it('should only list the VMs that need a restart', () => {
const a = rvm('default', 'a');
expect(call('restartRequiredVMs', { canPaginate: false, vms: [a, { id: 'default/b', isRestartRequired: false }] })).toStrictEqual([a]);
});
it.each([
['wait for the list\'s page while paging', { havePage: false }, []],
['take the VMs of the page once it is loaded', { havePage: true }, ['a']],
])('should %s', (_, opts, names) => {
const ctx = {
$store: createStore(opts), inStore: 'harvester', canPaginate: true, vms: [rvm('default', 'a')]
};
expect(call('restartRequiredVMs', ctx).map(({ metadata }) => metadata.name)).toStrictEqual(names);
});
// Coming back to the list, the store already holds the VMs, so they never change after the list is created
it.each([
['without pagination', { paginationEnabled: false, havePage: false }],
['with pagination', { paginationEnabled: true, havePage: true }],
])('should notify when the list opens with the VMs already in the store, %s', (_, opts) => {
const $store = createStore({ ...opts, storedVMs: [rvm('default', 'a')] });
mountList($store);
expect($store.dispatch).toHaveBeenCalledWith(...warning(1, 'a'));
});
it('should not notify about VMs another page left in the store while the list is paged', () => {
const $store = createStore({ havePage: false, storedVMs: [rvm('default', 'a')] });
mountList($store);
expect($store.dispatch).not.toHaveBeenCalledWith('growl/warning', expect.anything(), expect.anything());
});
it('should notify when VMs need a restart', () => {
const ctx = createCtx('');
notify(ctx, [rvm('default', 'a'), rvm('default', 'b')], []);
expect(ctx.$store.dispatch).toHaveBeenCalledWith(...warning(2, 'a, b'));
expect(ctx.restartNotificationKey).toBe('default/a,default/b');
});
it('should notify on a new visit to the list, even when the VMs it saw before are the same', () => {
const ctx = createCtx('');
notify(ctx, [rvm('default', 'a')], [rvm('default', 'a')]);
expect(ctx.$store.dispatch).toHaveBeenCalledWith(...warning(1, 'a'));
});
it('should not notify again when a refresh, page or sort brings back the same VMs', () => {
const ctx = createCtx('default/a,default/b');
notify(ctx, [rvm('default', 'b'), rvm('default', 'a')], [rvm('default', 'a'), rvm('default', 'b')]);
expect(ctx.$store.dispatch).not.toHaveBeenCalled();
});
it('should notify again when a VM of the same name in another namespace takes its place', () => {
const ctx = createCtx('');
notify(ctx, [rvm('ns1', 'a')], []);
notify(ctx, [rvm('ns2', 'a')], [rvm('ns1', 'a')]);
expect(ctx.$store.dispatch.mock.calls).toStrictEqual([warning(1, 'a'), ['growl/clear'], warning(1, 'a')]);
});
it('should replace the notification when the VMs change', () => {
const ctx = createCtx('default/a,default/b');
notify(ctx, [rvm('default', 'a'), rvm('default', 'c')], [rvm('default', 'a'), rvm('default', 'b')]);
expect(ctx.$store.dispatch.mock.calls).toStrictEqual([['growl/clear'], warning(2, 'a, c')]);
});
it('should reset when no VM needs a restart', () => {
const ctx = createCtx('default/a');
notify(ctx, [], [rvm('default', 'a')]);
expect(ctx.$store.dispatch).not.toHaveBeenCalled();
expect(ctx.restartNotificationKey).toBe('');
});
});
});
+219 -146
View File
@@ -1,15 +1,17 @@
<script>
import { mapGetters } from 'vuex';
import ResourceTable from '@shell/components/ResourceTable';
import { STATE, AGE, NAME, NAMESPACE } from '@shell/config/table-headers';
import PaginatedResourceTable from '@shell/components/PaginatedResourceTable';
import IconMessage from '@shell/components/IconMessage';
import {
PVC, PV, NODE, POD, STORAGE_CLASS
} from '@shell/config/types';
import { FilterArgs, PaginationFilterEquality, PaginationParamFilter } from '@shell/types/store/pagination.types';
import { allHash } from '@shell/utils/promise';
import Loading from '@shell/components/Loading';
import { clone } from '@shell/utils/object';
import paginationUtils from '@shell/utils/pagination-utils';
import { uniq } from '@shell/utils/array';
import { HCI } from '../types';
import { HCI as HCI_ANNOTATIONS } from '../config/labels-annotations';
import HarvesterVmState from '../formatters/HarvesterVmState';
import ConsoleBar from '../components/VMConsoleBar';
@@ -18,58 +20,21 @@ const ENCRYPTED_VOLUME_TOOLTIP_KEYS = {
partial: 'harvester.virtualMachine.volume.lockTooltip.partial',
};
export const VM_HEADERS = [
STATE,
{
...NAME,
width: 350,
value: 'nameDisplay',
sort: ['nameDisplay'],
},
NAMESPACE,
{
name: 'CPU',
label: 'CPU',
sort: ['displayCPU'],
value: 'displayCPU',
align: 'center',
dashIfEmpty: true,
},
{
name: 'Memory',
value: 'displayMemory',
sort: ['memorySort'],
align: 'center',
labelKey: 'tableHeaders.memory',
formatter: 'Si',
formatterOpts: {
opts: {
increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i',
},
needParseSi: true
},
},
{
name: 'ip',
label: 'IP Address',
value: 'id',
formatter: 'HarvesterIpAddress',
labelKey: 'tableHeaders.ipAddress',
sort: ['id'],
},
{
...AGE,
sort: 'metadata.creationTimestamp:desc',
}
];
// Outside the component because `ResourceList` calls `$loadingResources(route, store)` on the component options,
// where there's no `this`. The store's getter knows whether this cluster's API can page the list
function canPaginate(store) {
const inStore = store.getters['currentProduct']?.inStore;
return !!store.getters[`${ inStore }/paginationEnabled`]?.(HCI.VM);
}
export default {
name: 'HarvesterListVM',
components: {
Loading,
HarvesterVmState,
ConsoleBar,
ResourceTable
IconMessage,
PaginatedResourceTable
},
props: {
@@ -79,39 +44,9 @@ export default {
},
},
async fetch() {
const inStore = this.$store.getters['currentProduct'].inStore;
const _hash = {
vms: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VM, opt: { force: true } }),
pod: this.$store.dispatch(`${ inStore }/findAll`, { type: POD }),
pvcs: this.$store.dispatch(`${ inStore }/findAll`, { type: PVC }),
pvs: this.$store.dispatch(`${ inStore }/findAll`, { type: PV }),
images: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.IMAGE }),
restore: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.RESTORE }),
backups: this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.BACKUP }),
storage: this.$store.dispatch(`${ inStore }/findAll`, { type: STORAGE_CLASS }),
};
if (this.$store.getters[`${ inStore }/schemaFor`](HCI.RESOURCE_QUOTA)) {
_hash.resourceQuotas = this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.RESOURCE_QUOTA });
}
if (this.$store.getters[`${ inStore }/schemaFor`](NODE)) {
_hash.nodes = this.$store.dispatch(`${ inStore }/findAll`, { type: NODE });
this.hasNode = true;
}
const hash = await allHash(_hash);
this.allVMs = hash.vms;
},
data() {
return {
hasNode: false,
allVMs: [],
allVMIs: [],
restartNotificationDisplayed: false,
restartNotificationKey: '',
HCI
};
},
@@ -119,42 +54,51 @@ export default {
computed: {
...mapGetters({ actionCb: 'action-menu/performCallbackData' }),
inStore() {
return this.$store.getters['currentProduct'].inStore;
},
hasNode() {
return !!this.$store.getters[`${ this.inStore }/schemaFor`](NODE);
},
canPaginate() {
return canPaginate(this.$store);
},
// The header's namespace filter is shared by every list, so an option the paged API can't filter by, like Not in a
// Project, can still be selected from another list. Ask for another one, like the shell's generic lists do
namespaceFilterInvalid() {
return this.canPaginate && !paginationUtils.validateNsProjectFilters(this.$store.getters['namespaceFilters']);
},
// The product registers both sets of VM columns (`headers()` in config/harvester-cluster.js)
paginationHeaders() {
return this.applicableColumns(this.$store.getters['type-map/headersFor'](this.schema, true));
},
// With pagination the store only holds the VMs of the current page
vms() {
return this.$store.getters[`${ this.inStore }/all`](HCI.VM);
},
// The paginated API lists VMs only, so VMIs without a VM are only shown without pagination
vmisWithoutVM() {
if (this.canPaginate) {
return [];
}
const vmIds = new Set(this.vms.map((vm) => vm.id));
return this.$store.getters[`${ this.inStore }/all`](HCI.VMI).filter((vmi) => !vmIds.has(vmi.id));
},
headers() {
const restoreCol = {
name: 'restoreProgress',
labelKey: 'harvester.tableHeaders.restore',
value: 'restoreProgress',
align: 'left',
formatter: 'HarvesterBackupProgressBar',
width: 200,
};
const nodeCol = {
name: 'node',
label: 'Node',
value: 'nodeName',
sort: ['realAttachNodeName'],
formatter: 'HarvesterHost',
labelKey: 'harvester.tableHeaders.vm.node'
};
const cols = clone(VM_HEADERS);
if (this.hasNode) {
cols.splice(-1, 0, nodeCol);
}
if (this.hasBackUpRestoreInProgress) {
cols.splice(-1, 0, restoreCol);
}
return cols;
return this.applicableColumns(this.$store.getters['type-map/headersFor'](this.schema, false));
},
rows() {
const vmIds = new Set(this.allVMs.map((VM) => VM.id));
const matchVMIs = this.allVMIs.filter((VMI) => !vmIds.has(VMI.id));
return [...this.allVMs, ...matchVMIs];
return [...this.vms, ...this.vmisWithoutVM];
},
/**
@@ -168,22 +112,16 @@ export default {
});
},
vmRestartRequiredNames() {
return this.allVMs
.filter((vm) => vm.isRestartRequired)
.map((vm) => vm.metadata.name);
restartRequiredVMs() {
// While paging, the store can still hold the VMs another view loaded, like every VM after Volumes or a VM's detail
if (this.canPaginate && !this.$store.getters[`${ this.inStore }/havePage`](HCI.VM)) {
return [];
}
return this.vms.filter((vm) => vm.isRestartRequired);
}
},
async created() {
const inStore = this.$store.getters['currentProduct'].inStore;
const vmis = await this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VMI });
await this.$store.dispatch(`${ inStore }/findAll`, { type: HCI.VMIM });
this['allVMIs'] = vmis;
},
beforeUnmount() {
// clear restart message before component unmount
this.$store.dispatch('growl/clear');
@@ -192,32 +130,41 @@ export default {
watch: {
actionCb(neu) {
if (neu?.clearTableSelection) {
this.$refs.resourceTable.clearSelection();
this.$refs.resourceTable?.clearSelection();
this.$store.dispatch('action-menu/clearCallbackData');
}
},
vmRestartRequiredNames(vmNames) {
const count = vmNames.length;
restartRequiredVMs: {
// Immediate, as the store may already hold the VMs when coming back to the list
immediate: true,
handler(vms) {
// Rebuilt on every refresh, and when paging on every page, sort and search too, so only notify when the VMs
// change. The key lives on the component, so coming back to the list notifies again
const key = vms.map((vm) => vm.id).sort().join();
if (count === 0 && this.restartNotificationDisplayed) {
this.restartNotificationDisplayed = false;
if (key === this.restartNotificationKey) {
return;
}
return;
}
const shown = !!this.restartNotificationKey;
this.restartNotificationKey = key;
if (!vms.length) {
return;
}
if (count > 0) {
// clear old notification before showing new one
if (this.restartNotificationDisplayed) {
if (shown) {
this.$store.dispatch('growl/clear');
}
this.$store.dispatch('growl/warning', {
title: this.t('harvester.notification.restartRequired.title', { count }),
message: this.t('harvester.notification.restartRequired.message', { vmNames: vmNames.join(', ') }),
title: this.t('harvester.notification.restartRequired.title', { count: vms.length }),
message: this.t('harvester.notification.restartRequired.message', { vmNames: vms.map((vm) => vm.metadata.name).join(', ') }),
timeout: 10000,
}, { root: true });
this.restartNotificationDisplayed = true;
}
}
},
@@ -226,21 +173,147 @@ export default {
const key = ENCRYPTED_VOLUME_TOOLTIP_KEYS[row.encryptedVolumeType];
return key ? this.t(key) : '';
},
// Called by PaginatedResourceTable before it loads the VMs. With pagination fetchPageSecondaryResources loads the
// resources of the VMs on the page, without it every VM needs its pods, volumes, restores, backups, VMI and migration
async fetchSecondaryResources({ canPaginate }) {
const inStore = this.inStore;
const findAll = (type) => this.$store.dispatch(`${ inStore }/findAll`, { type });
const hash = {
images: findAll(HCI.IMAGE),
storage: findAll(STORAGE_CLASS),
};
if (this.$store.getters[`${ inStore }/schemaFor`](HCI.RESOURCE_QUOTA)) {
hash.resourceQuotas = findAll(HCI.RESOURCE_QUOTA);
}
if (this.hasNode) {
hash.nodes = findAll(NODE);
}
if (!canPaginate) {
Object.assign(hash, {
pods: findAll(POD),
pvcs: findAll(PVC),
pvs: findAll(PV),
restores: findAll(HCI.RESTORE),
backups: findAll(HCI.BACKUP),
vmis: findAll(HCI.VMI),
vmims: findAll(HCI.VMIM),
});
}
await allHash(hash);
},
// The node column only when the cluster's nodes can be seen, the restore progress only while a backup is restored
applicableColumns(headers) {
return headers.filter(({ name }) => {
if (name === 'node') {
return this.hasNode;
}
if (name === 'restoreProgress') {
return this.hasBackUpRestoreInProgress;
}
return true;
});
},
// localFilter of PaginatedResourceTable, which only runs without pagination
addVMIsWithoutVM(rows) {
return [...rows, ...this.vmisWithoutVM];
},
// The VM model looks these up by id or owner, so the ones of the VMs on the page are enough
async fetchPageSecondaryResources({ force, page }) {
if (!page?.length) {
return;
}
const vmNames = uniq(page.map((vm) => vm.metadata.name));
const claimNames = uniq(page.flatMap((vm) => vm.persistentVolumeClaimName));
// One failed request shouldn't stop the others, the rows show what could be loaded
const loaded = (results) => results.map((result) => (result.status === 'fulfilled' ? result.value : []));
const [pvcs, restores, vmis] = loaded(await Promise.allSettled([
this.findPageByField(PVC, 'metadata.name', claimNames, force),
this.findPageByField(HCI.RESTORE, this.printerColumnField(HCI.RESTORE, 'TARGET_NAME'), vmNames, force),
this.findPageByField(HCI.VMI, 'metadata.name', vmNames, force),
this.findPageByField(HCI.VMIM, this.printerColumnField(HCI.VMIM, 'VMI'), vmNames, force),
]));
await Promise.allSettled([
this.findPageByField(PV, 'metadata.name', uniq(pvcs.map((pvc) => pvc.spec?.volumeName)), force),
this.findPageByField(HCI.BACKUP, 'metadata.name', uniq(restores.map((restore) => restore.spec?.virtualMachineBackupName)), force),
// KubeVirt labels every launcher pod with its VMI's UID; Harvester's vmName label is missing on VMs from Forklift or plain manifests
this.findPageByField(POD, `metadata.labels[${ HCI_ANNOTATIONS.VMI_CREATED_BY }]`, uniq(vmis.map((vmi) => vmi.metadata?.uid)), force),
]);
},
async findPageByField(type, field, values, force) {
const wanted = values.filter(Boolean);
if (!field || !wanted.length || !this.$store.getters[`${ this.inStore }/schemaFor`](type)) {
return [];
}
return this.$store.dispatch(`${ this.inStore }/findPage`, {
type,
opt: {
force,
pagination: new FilterArgs({
filters: PaginationParamFilter.createSingleField({
field, value: wanted.join(','), equality: PaginationFilterEquality.IN
})
}),
}
});
},
// The API indexes the printer columns of a CRD by position (`metadata.fields.N`), so look the position up by name
printerColumnField(type, columnName) {
const schema = this.$store.getters[`${ this.inStore }/schemaFor`](type);
const column = schema?.attributes?.columns?.find((col) => col.name === columnName);
return column?.field?.replace('$.', '').replace('[', '.').replace(']', '');
}
}
},
// With pagination the store never holds every VM, so the masthead's loading count would never finish
$loadingResources(route, store) {
return canPaginate(store) ? { loadResources: [] } : {};
},
};
</script>
<template>
<Loading v-if="$fetchState.pending" />
<div v-else>
<ResourceTable
<div>
<IconMessage
v-if="namespaceFilterInvalid"
:vertical="true"
:subtle="false"
icon="icon-filter_alt"
>
<template #message>
{{ t('resourceList.nsFilteringGeneric') }}
</template>
</IconMessage>
<PaginatedResourceTable
v-else
ref="resourceTable"
v-bind="$attrs"
:headers="headers"
default-sort-by="age"
:rows="rows"
:schema="schema"
:headers="headers"
:pagination-headers="paginationHeaders"
:fetch-secondary-resources="fetchSecondaryResources"
:fetch-page-secondary-resources="fetchPageSecondaryResources"
:local-filter="addVMIsWithoutVM"
default-sort-by="age"
:groupable="true"
key-field="_key"
>
@@ -279,7 +352,7 @@ export default {
/>
</div>
</template>
</ResourceTable>
</PaginatedResourceTable>
</div>
</template>
@@ -395,4 +395,57 @@ describe('class VirtVm', () => {
expect(vm.isRestartRequired).toBe(true);
});
});
describe('findInNamespace', () => {
function vmWithStore({ havePage }) {
const vm = Object.create(VirtVm.prototype);
const stored = [{ metadata: { namespace: 'ns1', name: 'a' } }, { metadata: { namespace: 'other', name: 'b' } }];
const dispatch = jest.fn((action) => Promise.resolve(action === 'findPage' ? { data: [{ metadata: { namespace: 'ns1', name: 'page' } }] } : stored));
vm.metadata = { name: 'vm1', namespace: 'ns1' };
Object.defineProperty(vm, '$getters', { value: { havePage: (type) => havePage && type === PVC } });
Object.defineProperty(vm, '$dispatch', { value: dispatch });
return {
vm, dispatch, stored
};
}
it('should load every resource and return a copy with the ones of the namespace when no page of the type is stored', async() => {
const { vm, dispatch, stored } = vmWithStore({ havePage: false });
const out = await vm.findInNamespace(PVC);
expect(dispatch.mock.calls).toStrictEqual([['findAll', { type: PVC }]]);
expect(out.map(({ metadata }) => metadata.name)).toStrictEqual(['a']);
expect(out).not.toBe(stored);
});
it('should read only the namespace, without storing it, when a paged list keeps a page of the type', async() => {
const { vm, dispatch } = vmWithStore({ havePage: true });
const out = await vm.findInNamespace(PVC);
expect(out.map(({ metadata }) => metadata.name)).toStrictEqual(['page']);
expect(dispatch).toHaveBeenCalledTimes(1);
const [action, { type, opt }] = dispatch.mock.calls[0];
expect([action, type, opt.transient]).toStrictEqual(['findPage', PVC, true]);
expect(opt.pagination.filters[0].fields.map(({ field, value }) => `${ field }=${ value }`)).toStrictEqual(['metadata.namespace=ns1']);
});
});
describe('disableResourceDetailDrawerConfigTab', () => {
it.each([
['hide the drawer\'s Config tab while the paged VM list keeps a page of VMs', { paged: true }, true],
['keep the drawer\'s Config tab when every VM is loaded', null, false],
])('should %s', (_, page, hidden) => {
const vm = Object.create(VirtVm.prototype);
const havePage = jest.fn(() => page);
Object.defineProperty(vm, '$getters', { value: { havePage } });
expect(vm.disableResourceDetailDrawerConfigTab).toBe(hidden);
expect(havePage).toHaveBeenCalledWith(HCI.VM);
});
});
});
@@ -3,6 +3,7 @@ import { omitBy, pickBy } from 'lodash';
import { PRODUCT_NAME as HARVESTER_PRODUCT } from '../config/harvester';
import { colorForState, stateSort } from '@shell/plugins/dashboard-store/resource-class';
import { POD, NODE, PVC } from '@shell/config/types';
import { FilterArgs, PaginationParamFilter } from '@shell/types/store/pagination.types';
import { findBy } from '@shell/utils/array';
import { parseSi } from '@shell/utils/units';
import { get, set } from '@shell/utils/object';
@@ -1162,6 +1163,35 @@ export default class VirtVm extends HarvesterResource {
.filter((name) => !!name);
}
// The resources of `type` in this VM's namespace, for the dialogs of the VM list. When the paged list keeps a page of
// `type` in the store, loading every resource would replace that page, and the next page load would shrink a list
// shared with the store, so read the namespace without storing it then.
async findInNamespace(type) {
const namespace = this.metadata.namespace;
if (!this.$getters['havePage'](type)) {
const all = await this.$dispatch('findAll', { type });
return all.filter((resource) => resource.metadata?.namespace === namespace);
}
const res = await this.$dispatch('findPage', {
type,
opt: {
transient: true,
pagination: new FilterArgs({ filters: PaginationParamFilter.createSingleField({ field: 'metadata.namespace', value: namespace }) }),
}
});
return res?.data || [];
}
// The configuration form loads every VM, volume, VMI and migration, which would replace the page the paged VM list
// keeps in the store, so the drawer only shows the YAML then. The VM's own page still shows its configuration
get disableResourceDetailDrawerConfigTab() {
return !!this.$getters['havePage'](HCI.VM);
}
get rootImageId() {
let imageId = '';
@@ -1,7 +1,7 @@
import {
CONFIG_MAP, COUNT, NAMESPACE, NETWORK_ATTACHMENT, NODE, PVC, STORAGE_CLASS
} from '@shell/config/types';
import harvesterGetters from '../getters';
import harvesterGetters, { vmAwarePaginationEnabled } from '../getters';
import { HCI, DATA_VOLUME, VOLUME_SNAPSHOT } from '../../../types';
import { HCI_SETTING } from '../../../config/settings';
@@ -288,3 +288,38 @@ describe('harvester store: visibleSettings', () => {
expect(shown.data.source).toBe('harvester');
});
});
describe('harvester store: paginationEnabled', () => {
const SQL_CACHE_COLUMNS = [{ name: 'Name', field: '$.metadata.fields[0]' }, { name: 'Status', field: '$.metadata.fields[2]' }];
const OLD_API_COLUMNS = [{ name: 'Status', field: '.status.printableStatus' }];
// `shellEnabled` is what the store's own getter answers, from the extension's registration and Rancher's settings
function paginationEnabled(args: any, { shellEnabled = true, featureEnabled = true, columns = SQL_CACHE_COLUMNS } = {}) {
const base = jest.fn(() => () => shellEnabled);
const getters = { schemaFor: (type: string) => (type === HCI.VM ? { id: HCI.VM, attributes: { columns } } : undefined) };
const rootGetters = { 'harvester-common/getFeatureEnabled': (name: string) => featureEnabled && name === 'vmListPagination' };
return vmAwarePaginationEnabled(base)({}, getters, {}, rootGetters)(args);
}
it.each([
['the VM id', HCI.VM],
['the VM id and a context', { id: HCI.VM, context: 'any' }],
['the VM id without a context, like the header\'s namespace filter', { id: HCI.VM }],
])('should page the VMs when the cluster\'s API can, asked with %s', (_, args) => {
expect(paginationEnabled(args)).toBe(true);
});
// The list's table asks with an object, the header's namespace filter with the type
it.each([HCI.VM, { id: HCI.VM, context: 'any' }])('should not page the VMs when the cluster can\'t, asked with %j', (args) => {
expect(paginationEnabled(args, { shellEnabled: false })).toBe(false);
expect(paginationEnabled(args, { featureEnabled: false })).toBe(false);
expect(paginationEnabled(args, { columns: OLD_API_COLUMNS })).toBe(false);
});
it('should leave the other types and the question without a type to the store\'s getter', () => {
expect(paginationEnabled(HCI.VMI, { featureEnabled: false, columns: OLD_API_COLUMNS })).toBe(true);
expect(paginationEnabled(undefined, { featureEnabled: false })).toBe(true);
expect(paginationEnabled(HCI.VMI, { shellEnabled: false })).toBe(false);
});
});
@@ -0,0 +1,17 @@
import { HCI } from '../../../types';
import harvesterStore from '../index';
// The shell answers yes for every type here, so only the store's own check can keep a cluster off pagination
jest.mock('@shell/utils/pagination-utils', () => ({ __esModule: true, default: { isEnabled: () => true } }));
describe('harvester store', () => {
it('should not page the VMs on a cluster whose API can\'t, whatever the shell answers', () => {
const { paginationEnabled } = harvesterStore.specifics.getters as any;
const getters = { schemaFor: () => ({ id: HCI.VM, attributes: { columns: [{ name: 'Status', field: '.status.printableStatus' }] } }) };
const rootGetters = { 'harvester-common/getFeatureEnabled': () => true };
const state = { config: { namespace: 'harvester' } };
expect(paginationEnabled(state, getters, {}, rootGetters)({ id: HCI.VM, context: 'any' })).toBe(false);
expect(paginationEnabled(state, getters, {}, rootGetters)(HCI.VMI)).toBe(true);
});
});
@@ -228,7 +228,43 @@ function resourceCount(state: any, rootGetters: any, getters: any, typeObj: any)
return unfilteredCount(getters, resourceType, namespaces);
}
/**
* Whether this cluster's API can page the VM list. Only an API served from
* Steve's SQL cache can filter it, and that API lists the printer columns of a
* CRD as `metadata.fields[N]`. The server version alone can't tell, as it can
* be missing or not semver.
*/
function canPaginateVMs(getters: any, rootGetters: any): boolean {
if (!rootGetters['harvester-common/getFeatureEnabled']?.('vmListPagination')) {
return false;
}
const columns = getters.schemaFor(HCI.VM)?.attributes?.columns || [];
return columns.some((col: any) => col.field?.startsWith('$.metadata.fields['));
}
/**
* Wraps the store's `paginationEnabled` getter. The VM list is registered for
* pagination on every cluster (index.ts), so answer for this cluster here.
* Every caller then agrees, like the header's namespace filter, which disables
* the options a paged list can't filter by.
*/
export function vmAwarePaginationEnabled(paginationEnabled: any) {
return (state: any, getters: any, rootState: any, rootGetters: any) => (args: any) => {
const enabled = paginationEnabled(state, getters, rootState, rootGetters)(args);
const id = typeof args === 'object' ? args?.id : args;
if (!enabled || id !== HCI.VM) {
return enabled;
}
return canPaginateVMs(getters, rootGetters);
};
}
export default {
namespaceFilterOptions: (state: any, getters: any, rootState: any, rootGetters: any) => ({
addNamespace,
divider,
+2 -1
View File
@@ -3,7 +3,7 @@ import { CoreStoreSpecifics, CoreStoreConfig } from '@shell/core/types';
import { SteveFactory, steveStoreInit } from '@shell/plugins/steve/index';
import { PRODUCT_NAME } from '../../config/harvester';
import getters from './getters';
import getters, { vmAwarePaginationEnabled } from './getters';
import mutations from './mutations';
import actions from './actions';
@@ -22,6 +22,7 @@ const harvesterFactory = (): CoreStoreSpecifics => {
steveFactory.getters = {
...steveFactory.getters,
...getters,
paginationEnabled: vmAwarePaginationEnabled(steveFactory.getters.paginationEnabled),
};
steveFactory.mutations = {