feat: add Restic and Kopia VM backups (#1226) (#1275)

* feat: add Restic and Kopia VM backups

Add a type to Take Backup so VMs on third-party storage or Longhorn v2
can be backed up to S3. Native stays on the backup action, which has no
type field. Restic and Kopia create the VirtualMachineBackup directly.

Types a VM can't use stay in the dropdown, disabled, with the reason.

Treat Restic and Kopia as remote backups in the restore routes, the
schedule filter and the snapshot list. Show the type in the backup list.

Add a form for the third-party-backup-config setting and the Kopia
garbage collection option on the backup target, and stop resetting
virtualHostedStyle when the backup target form opens.

All of it sits behind a v1.10 feature flag.



* fix: refine Take Backup for NFS targets and non-admin users

Hide Take Backup on VMs that only have the snapshot action when the
backup target is known not to be S3. Nothing can back those VMs up
there, so they match the menu on main again.

Only block Restic and Kopia on a backup target type the user can read.
Non-admin users can't read the backup-target setting, so they were
always told an S3 target was required. The webhook still decides.

List why a type is unavailable under the Type select. Disabled options
can't be reached by keyboard, so the reasons inside them were hidden
from screen readers.

Fall back to the default when third-party-backup-config doesn't parse,
like the other settings forms, instead of showing a parse error banner.



* fix: tighten Take Backup and backup config inputs after review

- Offer Take Backup without the backup action only on VMs whose volumes
  Restic and Kopia support. The snapshot action isn't gated on a backup
  target, so users who can't read backup-target saw the menu on every VM.
- Take the third-party-backup-config sizes in MiB, so a bare number is no
  longer saved as bytes.
- Merge csi-driver-config value and default like the backend does, with
  the default's entries winning.



* feat: add the Restic and Kopia switch to the backup target

The backend now rejects Restic and Kopia backups unless the S3 backup
target has thirdPartyBackupEnabled set, and it is off by default. While
it is on, every save of the target needs the repository password.

- Add an "Enable Restic and Kopia Backups" checkbox to the S3 backup
  target form, dropped on NFS like Kopia garbage collection.
- Show a required Repository Password field while the switch is on, and
  drop the password when the switch is off or the target is NFS, where
  the backend rejects it.
- When the target is readable and the switch is off, Restic and Kopia
  are unavailable with a reason, after any volume reason, and Take
  Backup follows the same rule.
- Rename the feature flag getter in the form and the dialog so it isn't
  confused with the setting field.



* fix: offer Kopia garbage collection only while Restic and Kopia are on

The backend removes the Kopia maintenance jobs whenever Restic and Kopia
are turned off, so the option could be saved as on while nothing ran.
Show it only while the switch is ticked, and drop it from the setting
when the switch is turned off, like the repository password.



---------


(cherry picked from commit 0a49829658)

Signed-off-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
Co-authored-by: Marcelo Fukumoto <marcelo.fukumoto@suse.com>
This commit is contained in:
mergify[bot]andMarcelo Fukumoto authored and GitHub committed 2026-11-23 17:00:22 +01:00
1 parent 8b3585c501
commit 235ddb8a94
19 files changed
+1142 -72

No files matched your search

@@ -0,0 +1,43 @@
import HciVmBackup from '../harvesterhci.io.virtualmachinebackup';
import { HCI } from '../../types';
jest.mock('../harvester', () => ({ __esModule: true, default: class {} }));
jest.mock('@shell/plugins/dashboard-store/resource-class', () => ({ colorForState: jest.fn() }));
function createBackup(type) {
const backup = Object.create(HciVmBackup.prototype);
const push = jest.fn();
Object.assign(backup, { spec: { type } });
Object.defineProperty(backup, 'name', { value: 'b1' });
Object.defineProperty(backup, 't', { value: (key) => key });
Object.defineProperty(backup, 'currentRouter', { value: () => ({ push }) });
return { backup, push };
}
describe('class HciVmBackup', () => {
it.each([
['backup', HCI.BACKUP],
['restic', HCI.BACKUP],
['kopia', HCI.BACKUP],
[undefined, HCI.BACKUP],
['snapshot', HCI.VM_SNAPSHOT],
])('should restore a %s backup through %s', (type, resource) => {
const { backup, push } = createBackup(type);
backup.restoreNewVM();
backup.restoreExistingVM();
expect(push).toHaveBeenCalledTimes(2);
expect(push.mock.calls[0][0].params.resource).toBe(resource);
expect(push.mock.calls[1][0].params.resource).toBe(resource);
});
it.each([
['kopia', 'harvester.backup.type.kopia'],
[undefined, 'harvester.backup.type.backup'],
])('should label type %s as %s', (type, label) => {
expect(createBackup(type).backup.backupTypeLabel).toBe(label);
});
});
@@ -1,6 +1,6 @@
import { reactive } from 'vue';
import VirtVm from '../kubevirt.io.virtualmachine';
import { POD, PVC } from '@shell/config/types';
import { POD, PV, PVC } from '@shell/config/types';
import { HCI } from '../../types';
// The Steve base model and the shell resource class pull in most of the dashboard, none of that is needed here
@@ -15,7 +15,7 @@ const VM_ID = 'ns1/vm1';
// Creates a VM model with mocked store getters. Like the real store, `all` returns the same array that is mutated in place.
// Reads from the global `$rootGetters` are recorded in `globalReads`.
function createVm({
vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus
vm = {}, vmi, pods = [], pvcs = [], restores = [], backups = [], claims = ['disk-pvc'], printableStatus, root = {}
} = {}) {
const lists = reactive({
[POD]: pods,
@@ -31,7 +31,7 @@ function createVm({
schemaFor: () => undefined,
};
const globalReads = [];
const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false }, {
const rootGetters = new Proxy({ 'harvester-common/getFeatureEnabled': () => false, ...root }, {
get(target, key) {
globalReads.push(key);
@@ -86,7 +86,193 @@ const pvc = (name, encrypted, ns = 'ns1') => ({
isEncrypted: encrypted,
});
const LONGHORN_CSI = { 'driver.longhorn.io': { volumeSnapshotClassName: 'longhorn-snapshot', backupVolumeSnapshotClassName: 'longhorn' } };
function backupVm({
actions = { backup: '/backup', snapshot: '/snapshot' }, volumes = [{}], target = 's3', thirdPartyBackupEnabled = true, csi = {}
} = {}) {
// target null: a user who can't read backup-target or csi-driver-config
const settings = target === null ? {} : {
'backup-target': { value: JSON.stringify({ type: target, thirdPartyBackupEnabled }) },
'csi-driver-config': { value: JSON.stringify(csi), default: JSON.stringify(LONGHORN_CSI) },
};
const pvcs = volumes.map((volume, i) => ({
id: `ns1/disk-${ i }`, name: `disk-${ i }`, isBlockVolume: true, ...volume
}));
const { vm } = createVm({
pvcs,
claims: pvcs.map((p) => p.name),
root: {
'harvester-common/getFeatureEnabled': (feature) => feature === 'thirdPartyVMBackup',
'harvester/byId': (type, id) => settings[id],
},
});
vm.actions = actions;
return Object.fromEntries(vm.backupTypeOptions.map((option) => [option.value, option.unavailableReason]));
}
const LVM_CSI = { 'lvm.driver.harvesterhci.io': { volumeSnapshotClassName: 'lvm', backupVolumeSnapshotClassName: 'lvm' } };
describe('class VirtVm', () => {
describe('canTakeBackup', () => {
it.each([
[{ backup: '/b' }, true, true],
[{ snapshot: '/s' }, true, true],
[{ snapshot: '/s' }, false, false],
[{ backup: '/b' }, false, true],
[{}, true, false],
])('with actions %j and the feature %s returns %s', (actions, enabled, expected) => {
const { vm } = createVm({ root: { 'harvester-common/getFeatureEnabled': () => enabled, 'harvester/byId': () => undefined } });
vm.actions = actions;
expect(vm.canTakeBackup).toBe(expected);
});
it.each([
['an NFS target', { type: 'nfs' }, false],
['an S3 target with Restic and Kopia enabled', { type: 's3', thirdPartyBackupEnabled: true }, true],
['an S3 target with Restic and Kopia not enabled', { type: 's3' }, false],
['a target the user cannot read', undefined, true],
])('with only the snapshot action and %s returns %s', (_, target, expected) => {
const { vm } = createVm({
root: {
'harvester-common/getFeatureEnabled': () => true,
'harvester/byId': () => (target ? { value: JSON.stringify(target) } : undefined),
},
});
vm.actions = { snapshot: '/s' };
expect(vm.canTakeBackup).toBe(expected);
});
it.each([
['a Longhorn v1 volume', { isLonghornV1: true, isBlockVolume: true }, false],
['a Filesystem volume', { isBlockVolume: false }, false],
['a CDI Block volume', { isCreatedForDataVolume: true, isBlockVolume: true }, true],
])('with only the snapshot action, a target the user cannot read and %s returns %s', (_, volume, expected) => {
const { vm } = createVm({
pvcs: [{ id: 'ns1/disk-0', ...volume }],
claims: ['disk-0'],
root: { 'harvester-common/getFeatureEnabled': () => true, 'harvester/byId': () => undefined },
});
vm.actions = { snapshot: '/s' };
expect(vm.canTakeBackup).toBe(expected);
});
});
describe('backupTypeOptions', () => {
it('should offer every type when a third-party driver has both snapshot classes', () => {
const reasons = backupVm({ csi: LVM_CSI, volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }] });
expect(reasons).toStrictEqual({
backup: undefined, restic: undefined, kopia: undefined
});
});
it('should explain a driver without a backup snapshot class on native only', () => {
const reasons = backupVm({
csi: { 'lvm.driver.harvesterhci.io': { volumeSnapshotClassName: 'lvm' } },
volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }],
});
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.noBackupSnapshotClass');
expect(reasons.kopia).toBeUndefined();
});
it.each([
['only other drivers', LVM_CSI],
['no drivers', {}],
])('should keep the default Longhorn entry when the configured value has %s', (_, csi) => {
const reasons = backupVm({ csi, volumes: [{ isLonghornV1: true, volumeProvider: 'driver.longhorn.io' }] });
expect(reasons.backup).toBeUndefined();
});
it('should offer only Restic and Kopia on Longhorn v2, where the backend drops the backup action', () => {
const reasons = backupVm({
actions: { snapshot: '/s' },
volumes: [{ isLonghornV2: true, volumeProvider: 'driver.longhorn.io' }],
});
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.longhornV2');
expect(reasons.restic).toBeUndefined();
});
it('should explain a CDI volume on native', () => {
const reasons = backupVm({ actions: { snapshot: '/s' }, volumes: [{ isCreatedForDataVolume: true }] });
expect(reasons.backup).toBe('harvester.backup.typeUnavailable.cdi');
expect(reasons.kopia).toBeUndefined();
});
it.each([
['an NFS target', { target: 'nfs' }, 'requiresS3'],
['a Filesystem volume', { volumes: [{ isBlockVolume: false }] }, 'requiresBlock'],
['a Longhorn v1 volume', { volumes: [{ isLonghornV1: true }] }, 'longhornV1'],
['one bad volume among good ones', { volumes: [{}, { isLonghornV1: true }] }, 'longhornV1'],
['a driver without a snapshot class', {
actions: { backup: '/b' },
csi: { 'lvm.driver.harvesterhci.io': { backupVolumeSnapshotClassName: 'lvm' } },
volumes: [{ volumeProvider: 'lvm.driver.harvesterhci.io' }],
}, 'noSnapshotClass'],
['no snapshot action', { actions: { backup: '/b' } }, 'snapshot'],
['an S3 target with Restic and Kopia not enabled', { thirdPartyBackupEnabled: false }, 'thirdPartyBackupOff'],
])('should block Restic and Kopia with %s', (_, args, reason) => {
const reasons = backupVm(args);
expect(reasons.restic).toBe(`harvester.backup.typeUnavailable.${ reason }`);
expect(reasons.kopia).toBe(`harvester.backup.typeUnavailable.${ reason }`);
});
it('should explain a volume problem before a target that only needs Restic and Kopia enabled', () => {
const reasons = backupVm({ thirdPartyBackupEnabled: false, volumes: [{ isLonghornV1: true }] });
expect(reasons.kopia).toBe('harvester.backup.typeUnavailable.longhornV1');
});
it('should leave the target check to the webhook when the user cannot read it', () => {
const reasons = backupVm({
actions: { snapshot: '/s' }, target: null, volumes: [{ isCreatedForDataVolume: true }]
});
expect(reasons.restic).toBeUndefined();
expect(reasons.kopia).toBeUndefined();
});
it('should leave a driver check to the webhook when the CSI config is unreadable', () => {
const { vm } = createVm({
pvcs: [{ id: 'ns1/disk-pvc', volumeProvider: 'lvm.driver.harvesterhci.io' }],
root: { 'harvester/byId': () => undefined },
});
expect(vm.driverMissingSnapshotClass('backupVolumeSnapshotClassName')).toBeUndefined();
});
});
describe('fetchBackupTypeRequirements', () => {
it('should load only what the VM needs and survive a resource the user cannot read', async() => {
const { vm, lists } = createVm({ pvcs: [{ id: 'ns1/disk-pvc', spec: { volumeName: 'pv-1' } }] });
const dispatch = jest.fn((_, { type }) => (type === PV ? Promise.reject(new Error('forbidden')) : Promise.resolve()));
Object.defineProperty(vm, '$dispatch', { value: dispatch });
await expect(vm.fetchBackupTypeRequirements()).resolves.toBeUndefined();
expect(lists[PVC]).toHaveLength(1);
expect(dispatch).toHaveBeenCalledWith('find', { type: PVC, id: 'ns1/disk-pvc' });
expect(dispatch).toHaveBeenCalledWith('find', { type: HCI.SETTING, id: 'backup-target' });
expect(dispatch).toHaveBeenCalledWith('find', { type: HCI.SETTING, id: 'csi-driver-config' });
expect(dispatch).toHaveBeenCalledWith('find', { type: PV, id: 'pv-1' });
expect(dispatch).toHaveBeenCalledTimes(4);
});
});
describe('restoreResource', () => {
it('should distinguish snapshots from backups and follow backup updates', () => {
const { vm, lists } = createVm({
@@ -107,6 +293,9 @@ describe('class VirtVm', () => {
expect(vm.restoreResource.fromSnapshot).toBe(false);
expect(vm.restoreState).toBe(false);
lists[HCI.BACKUP][1].spec.type = 'kopia';
expect(vm.restoreResource.fromSnapshot).toBe(false);
lists[HCI.BACKUP][1].spec.type = 'snapshot';
expect(vm.restoreResource.fromSnapshot).toBe(true);
@@ -353,6 +353,14 @@ export default class HciPv extends HarvesterResource {
return this.dataEngine === DATA_ENGINE_V2;
}
get isBlockVolume() {
return this.spec?.volumeMode === 'Block';
}
get isCreatedForDataVolume() {
return !!this.metadata?.annotations?.[HCI_ANNOTATIONS.CDI_CREATED_FOR_DATA_VOLUME];
}
get isGoldenImageVolume() {
return this?.metadata?.annotations?.[HCI_ANNOTATIONS.GOLDEN_IMAGE] === 'true';
}
@@ -86,7 +86,7 @@ export default class HciVmBackup extends HarvesterResource {
restoreExistingVM(resource = this) {
const router = this.currentRouter();
const targetResource = resource.spec.type === BACKUP_TYPE.BACKUP ? HCI.BACKUP : HCI.VM_SNAPSHOT;
const targetResource = resource.spec.type === BACKUP_TYPE.SNAPSHOT ? HCI.VM_SNAPSHOT : HCI.BACKUP;
router.push({
name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`,
@@ -100,7 +100,7 @@ export default class HciVmBackup extends HarvesterResource {
restoreNewVM(resource = this) {
const router = this.currentRouter();
const targetResource = resource.spec.type === BACKUP_TYPE.BACKUP ? HCI.BACKUP : HCI.VM_SNAPSHOT;
const targetResource = resource.spec.type === BACKUP_TYPE.SNAPSHOT ? HCI.VM_SNAPSHOT : HCI.BACKUP;
router.push({
name: `${ HARVESTER_PRODUCT }-c-cluster-resource-create`,
@@ -143,6 +143,10 @@ export default class HciVmBackup extends HarvesterResource {
return this.spec.source.name;
}
get backupTypeLabel() {
return this.t(`harvester.backup.type.${ this.spec?.type || BACKUP_TYPE.BACKUP }`);
}
get backupContentName() {
return this?.status?.virtualMachineBackupContentName || '';
}
@@ -2,7 +2,7 @@ import { load } from 'js-yaml';
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 { POD, NODE, PV, 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';
@@ -16,7 +16,7 @@ import { HCI } from '../types';
import HarvesterResource from './harvester';
import { getVmCPUMemoryValues } from '../utils/cpuMemory';
import { sharedComputed } from '../utils/shared-computed';
import { isBackupTargetSettingUnavailable } from '../utils/setting';
import { getBackupTarget, isBackupTargetSettingUnavailable } from '../utils/setting';
export const OFF = 'Off';
@@ -202,7 +202,7 @@ export default class VirtVm extends HarvesterResource {
},
{
action: 'backupVM',
enabled: !!this.actions?.backup && !this.isBackupTargetUnavailable,
enabled: this.canTakeBackup && !this.isBackupTargetUnavailable,
icon: 'icon icon-backup',
label: this.t('harvester.action.backup')
},
@@ -976,7 +976,7 @@ export default class VirtVm extends HarvesterResource {
const backup = this.$getters['byId'](HCI.BACKUP, backupId);
// Snapshots and backups are told apart by spec.type
res.fromSnapshot = !!backup && backup.spec?.type !== BACKUP_TYPE.BACKUP;
res.fromSnapshot = !!backup && backup.spec?.type === BACKUP_TYPE.SNAPSHOT;
}
return res;
@@ -1396,6 +1396,123 @@ export default class VirtVm extends HarvesterResource {
return this.$rootGetters['harvester-common/getFeatureEnabled']('hotplugCdRom');
}
get thirdPartyBackupFeatureEnabled() {
return this.$rootGetters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
}
// The backend drops the backup action on Longhorn v2 and CDI volumes, which Restic and Kopia can still protect on S3.
// Without it, offer the menu only on VMs whose volumes Restic and Kopia support, as the snapshot action isn't gated on a target
get canTakeBackup() {
return !!this.actions?.backup || (this.thirdPartyBackupFeatureEnabled && !!this.actions?.snapshot && !this.dataMoverBackupUnavailableReason);
}
// Only users who can read backup-target know its type and whether it allows Restic and Kopia, for everyone else the webhook decides
get isBackupTargetNotS3() {
const { type } = getBackupTarget(this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target'));
return !!type && type !== 's3';
}
// The backend rejects Restic and Kopia until thirdPartyBackupEnabled is set on the S3 target
get isThirdPartyBackupOffOnTarget() {
const { type, thirdPartyBackupEnabled } = getBackupTarget(this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target'));
return type === 's3' && !thirdPartyBackupEnabled;
}
async fetchBackupTypeRequirements() {
const claimNames = this.spec.template.spec.volumes?.map((v) => v.persistentVolumeClaim?.claimName).filter((v) => !!v) || [];
// Each rule is enforced by the webhook too, so a resource this user can't read must not block the dialog
await Promise.allSettled([
...claimNames.map((name) => this.$dispatch('find', { type: PVC, id: `${ this.metadata.namespace }/${ name }` })),
this.$dispatch('find', { type: HCI.SETTING, id: 'backup-target' }),
this.$dispatch('find', { type: HCI.SETTING, id: 'csi-driver-config' }),
]);
await Promise.allSettled(
this.volumes.filter((pvc) => pvc.spec?.volumeName).map((pvc) => this.$dispatch('find', { type: PV, id: pvc.spec.volumeName }))
);
}
get backupTypeOptions() {
const nativeReason = this.nativeBackupUnavailableReason;
const dataMoverReason = this.dataMoverBackupUnavailableReason;
return [BACKUP_TYPE.BACKUP, BACKUP_TYPE.RESTIC, BACKUP_TYPE.KOPIA].map((value) => {
const unavailableReason = value === BACKUP_TYPE.BACKUP ? nativeReason : dataMoverReason;
return {
value,
label: this.t(`harvester.backup.type.${ value }`),
disabled: !!unavailableReason,
unavailableReason,
};
});
}
get nativeBackupUnavailableReason() {
if (!this.actions?.backup) {
const longhornV2 = this.longhornV2Volumes[0];
const cdi = this.volumes.find((pvc) => pvc.isCreatedForDataVolume);
if (longhornV2) {
return this.t('harvester.backup.typeUnavailable.longhornV2', { volume: longhornV2.name });
}
return cdi ? this.t('harvester.backup.typeUnavailable.cdi', { volume: cdi.name }) : this.t('harvester.backup.typeUnavailable.native');
}
const driver = this.driverMissingSnapshotClass('backupVolumeSnapshotClassName');
return driver ? this.t('harvester.backup.typeUnavailable.noBackupSnapshotClass', { driver }) : undefined;
}
get dataMoverBackupUnavailableReason() {
if (this.isBackupTargetNotS3) {
return this.t('harvester.backup.typeUnavailable.requiresS3');
}
const filesystem = this.volumes.find((pvc) => !pvc.isBlockVolume);
if (filesystem) {
return this.t('harvester.backup.typeUnavailable.requiresBlock', { volume: filesystem.name });
}
const longhornV1 = this.volumes.find((pvc) => pvc.isLonghornV1);
if (longhornV1) {
return this.t('harvester.backup.typeUnavailable.longhornV1', { volume: longhornV1.name });
}
if (!this.actions?.snapshot) {
const driver = this.driverMissingSnapshotClass('volumeSnapshotClassName');
return driver ? this.t('harvester.backup.typeUnavailable.noSnapshotClass', { driver }) : this.t('harvester.backup.typeUnavailable.snapshot');
}
// Last, so a reason that turning it on wouldn't fix is shown first
if (this.isThirdPartyBackupOffOnTarget) {
return this.t('harvester.backup.typeUnavailable.thirdPartyBackupOff');
}
return undefined;
}
driverMissingSnapshotClass(classKey) {
const setting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'csi-driver-config');
let config;
// Like the backend's LoadCSIDriverConfig: value adds drivers, the default's entries win
try {
config = { ...JSON.parse(setting?.value || '{}'), ...JSON.parse(setting?.default) };
} catch (e) {
return undefined;
}
return this.volumes.map((pvc) => pvc.volumeProvider).find((driver) => driver && !config[driver]?.[classKey]);
}
get isBackupTargetUnavailable() {
const backupTargetSetting = this.$rootGetters['harvester/byId'](HCI.SETTING, 'backup-target');