diff --git a/pkg/harvester/components/settings/__tests__/backup-target.test.js b/pkg/harvester/components/settings/__tests__/backup-target.test.js
new file mode 100644
index 00000000..ca1f8d9c
--- /dev/null
+++ b/pkg/harvester/components/settings/__tests__/backup-target.test.js
@@ -0,0 +1,102 @@
+import { shallowMount } from '@vue/test-utils';
+import BackupTarget from '../backup-target.vue';
+
+function mountTarget(target) {
+ const setting = { value: JSON.stringify(target) };
+
+ return {
+ setting,
+ wrapper: shallowMount(BackupTarget, {
+ props: { value: setting, mode: 'edit' },
+ global: {
+ mocks: {
+ t: (key) => key,
+ $store: { getters: { 'harvester-common/getFeatureEnabled': () => true } },
+ },
+ },
+ }),
+ };
+}
+
+describe('component: backup-target', () => {
+ it('should keep virtualHostedStyle, which is part of the Restic and Kopia repository identity', () => {
+ const { setting } = mountTarget({ type: 's3', virtualHostedStyle: true });
+
+ expect(JSON.parse(setting.value).virtualHostedStyle).toBe(true);
+ });
+
+ it('should default virtualHostedStyle to false', () => {
+ const { setting } = mountTarget({ type: 's3' });
+
+ expect(JSON.parse(setting.value).virtualHostedStyle).toBe(false);
+ });
+
+ it.each([
+ ['kopiaGCEnabled', { kopiaGCEnabled: true, thirdPartyBackupEnabled: true }],
+ ['thirdPartyBackupEnabled', { thirdPartyBackupEnabled: true }],
+ ])('should keep %s on S3 and drop it on NFS, where only S3 uses it', (field, fields) => {
+ const { wrapper, setting } = mountTarget({ type: 's3', ...fields });
+
+ expect(JSON.parse(setting.value)[field]).toBe(true);
+
+ wrapper.vm.parseDefaultValue.type = 'nfs';
+ wrapper.vm.update();
+
+ expect(JSON.parse(setting.value)[field]).toBeUndefined();
+ });
+
+ it('should offer the Restic and Kopia switch on S3', () => {
+ const { wrapper } = mountTarget({ type: 's3' });
+
+ expect(wrapper.find('[data-testid="backup-target-third-party-backup"]').exists()).toBe(true);
+ });
+
+ it('should ask for the repository password only while Restic and Kopia are on', () => {
+ const off = mountTarget({ type: 's3' }).wrapper;
+ const on = mountTarget({ type: 's3', thirdPartyBackupEnabled: true }).wrapper;
+
+ expect(off.find('[data-testid="backup-target-repository-password"]').exists()).toBe(false);
+ expect(on.find('[data-testid="backup-target-repository-password"]').exists()).toBe(true);
+ });
+
+ it('should offer Kopia garbage collection only while Restic and Kopia are on, the only time the backend runs it', () => {
+ const off = mountTarget({ type: 's3' }).wrapper;
+ const on = mountTarget({ type: 's3', thirdPartyBackupEnabled: true }).wrapper;
+
+ expect(off.find('[data-testid="backup-target-kopia-gc"]').exists()).toBe(false);
+ expect(on.find('[data-testid="backup-target-kopia-gc"]').exists()).toBe(true);
+ });
+
+ it('should drop Kopia garbage collection when Restic and Kopia are turned off, so the setting matches what runs', () => {
+ const { wrapper, setting } = mountTarget({
+ type: 's3', thirdPartyBackupEnabled: true, kopiaGCEnabled: true
+ });
+
+ expect(JSON.parse(setting.value).kopiaGCEnabled).toBe(true);
+
+ wrapper.vm.parseDefaultValue.thirdPartyBackupEnabled = false;
+ wrapper.vm.update();
+
+ expect(JSON.parse(setting.value).kopiaGCEnabled).toBeUndefined();
+ });
+
+ it.each([
+ ['Restic and Kopia are turned off', (vm) => {
+ vm.parseDefaultValue.thirdPartyBackupEnabled = false;
+ }],
+ ['the target changes to NFS', (vm) => {
+ vm.parseDefaultValue.type = 'nfs';
+ }],
+ ])('should drop the repository password when %s, which the backend rejects', (_, change) => {
+ const { wrapper, setting } = mountTarget({
+ type: 's3', thirdPartyBackupEnabled: true, thirdPartyRepositoryPassword: 'secret'
+ });
+
+ expect(JSON.parse(setting.value).thirdPartyRepositoryPassword).toBe('secret');
+
+ change(wrapper.vm);
+ wrapper.vm.update();
+
+ expect(JSON.parse(setting.value).thirdPartyRepositoryPassword).toBeUndefined();
+ });
+});
diff --git a/pkg/harvester/components/settings/__tests__/third-party-backup-config.test.js b/pkg/harvester/components/settings/__tests__/third-party-backup-config.test.js
new file mode 100644
index 00000000..eb6b10dd
--- /dev/null
+++ b/pkg/harvester/components/settings/__tests__/third-party-backup-config.test.js
@@ -0,0 +1,74 @@
+import { shallowMount } from '@vue/test-utils';
+import UnitInput from '@shell/components/form/UnitInput';
+import ThirdPartyBackupConfig from '../third-party-backup-config.vue';
+
+const JOB = {
+ memoryRequest: '1Gi', memoryLimit: '4Gi', cacheSize: '2Gi', maxConcurrentJobs: 5, ephemeralRequest: '512Mi', ephemeralLimit: '3Gi'
+};
+const DEFAULT = JSON.stringify({ restic: { ...JOB, noCache: false }, kopia: JOB });
+
+function mountConfig(value) {
+ const setting = { value, default: DEFAULT };
+
+ return {
+ setting,
+ wrapper: shallowMount(ThirdPartyBackupConfig, {
+ props: { value: setting, registerBeforeHook: jest.fn() },
+ global: {
+ mocks: { t: (key) => key },
+ stubs: { RcSection: { template: '' } },
+ },
+ }),
+ };
+}
+
+describe('component: third-party-backup-config', () => {
+ it('should fill omitted fields from the default', () => {
+ const { wrapper } = mountConfig(JSON.stringify({ kopia: { memoryLimit: '8Gi' } }));
+
+ expect(wrapper.vm.config.kopia).toStrictEqual({ ...JOB, memoryLimit: '8Gi' });
+ expect(wrapper.vm.config.restic.noCache).toBe(false);
+ });
+
+ it('should show the default values when the setting is empty', () => {
+ const { wrapper } = mountConfig('');
+
+ expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
+ });
+
+ it('should write the form to the setting before saving', async() => {
+ const { wrapper, setting } = mountConfig('');
+
+ wrapper.vm.config.kopia.maxConcurrentJobs = 0;
+ await wrapper.vm.willSave();
+
+ expect(JSON.parse(setting.value).kopia.maxConcurrentJobs).toBe(0);
+ });
+
+ it('should go back to the default', () => {
+ const { wrapper, setting } = mountConfig(JSON.stringify({ kopia: { memoryLimit: '8Gi' } }));
+
+ wrapper.vm.useDefault();
+
+ expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
+ expect(JSON.parse(setting.value)).toStrictEqual(JSON.parse(DEFAULT));
+ });
+
+ it('should take every size in MiB so a bare number is not saved as bytes', () => {
+ const { wrapper } = mountConfig('');
+ const inputs = wrapper.findAllComponents(UnitInput);
+
+ expect(inputs).toHaveLength(10);
+ inputs.forEach((input) => {
+ expect(input.props()).toMatchObject({
+ increment: 1024, inputExponent: 2, outputModifier: true
+ });
+ });
+ });
+
+ it('should show the default values when the setting is not JSON', () => {
+ const { wrapper } = mountConfig('{not json');
+
+ expect(wrapper.vm.config).toStrictEqual(JSON.parse(DEFAULT));
+ });
+});
diff --git a/pkg/harvester/components/settings/backup-target.vue b/pkg/harvester/components/settings/backup-target.vue
index 9a4a4a56..7012d8a4 100644
--- a/pkg/harvester/components/settings/backup-target.vue
+++ b/pkg/harvester/components/settings/backup-target.vue
@@ -3,6 +3,7 @@ import Tip from '@shell/components/Tip';
import Password from '@shell/components/form/Password';
import MessageLink from '@shell/components/MessageLink';
import CreateEditView from '@shell/mixins/create-edit-view';
+import { Checkbox } from '@components/Form/Checkbox';
import { LabeledInput } from '@components/Form/LabeledInput';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { HCI_SETTING } from '../../config/settings';
@@ -14,7 +15,7 @@ export default {
name: 'HarvesterEditBackupTarget',
components: {
- LabeledInput, LabeledSelect, Tip, Password, MessageLink, UnitInput
+ Checkbox, LabeledInput, LabeledSelect, Tip, Password, MessageLink, UnitInput
},
mixins: [CreateEditView],
@@ -36,7 +37,7 @@ export default {
}
// set default virtualHostedStyle to false
- parseDefaultValue.virtualHostedStyle = false;
+ parseDefaultValue.virtualHostedStyle = !!parseDefaultValue.virtualHostedStyle;
return {
parseDefaultValue,
@@ -69,6 +70,10 @@ export default {
return this.$store.getters['harvester-common/getFeatureEnabled']('refreshIntervalInSecond');
},
+ thirdPartyBackupFeatureEnabled() {
+ return this.$store.getters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
+ },
+
isS3() {
return this.parseDefaultValue.type === DEFAULT_TYPE;
},
@@ -114,9 +119,17 @@ export default {
delete this.parseDefaultValue.bucketName;
delete this.parseDefaultValue.bucketRegion;
delete this.parseDefaultValue.virtualHostedStyle;
+ delete this.parseDefaultValue.kopiaGCEnabled;
+ delete this.parseDefaultValue.thirdPartyBackupEnabled;
delete this.parseDefaultValue.cert;
}
+ // While Restic and Kopia are off, the backend rejects a repository password and runs no Kopia garbage collection
+ if (!this.parseDefaultValue.thirdPartyBackupEnabled) {
+ delete this.parseDefaultValue.thirdPartyRepositoryPassword;
+ delete this.parseDefaultValue.kopiaGCEnabled;
+ }
+
if (this.isS3 && !this.parseDefaultValue.virtualHostedStyle) {
this.parseDefaultValue.virtualHostedStyle = false;
}
@@ -222,6 +235,45 @@ export default {
@update:value="update"
/>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+import { Checkbox } from '@components/Form/Checkbox';
+import { LabeledInput } from '@components/Form/LabeledInput';
+import { RcSection } from '@components/RcSection';
+import UnitInput from '@shell/components/form/UnitInput';
+import { BACKUP_TYPE } from '../../config/types';
+
+const ENGINES = [BACKUP_TYPE.RESTIC, BACKUP_TYPE.KOPIA];
+const QUANTITY_FIELDS = ['memoryRequest', 'memoryLimit', 'ephemeralRequest', 'ephemeralLimit', 'cacheSize'];
+
+// The webhook only stores JSON objects, so a value that doesn't parse falls back to the default like the other settings forms
+function parseJSON(string) {
+ try {
+ return JSON.parse(string || '{}');
+ } catch (e) {
+ return {};
+ }
+}
+
+// The backend fills omitted fields from the default, so show those values instead of empty inputs
+function parseConfig(value, defaultValue) {
+ const defaults = parseJSON(defaultValue);
+ const current = parseJSON(value);
+
+ return Object.fromEntries(ENGINES.map((engine) => [engine, { ...defaults[engine], ...current[engine] }]));
+}
+
+export default {
+ name: 'ThirdPartyBackupConfig',
+
+ components: {
+ Checkbox,
+ LabeledInput,
+ RcSection,
+ UnitInput,
+ },
+
+ props: {
+ registerBeforeHook: {
+ type: Function,
+ required: true
+ },
+ mode: {
+ type: String,
+ default: 'edit'
+ },
+ value: {
+ type: Object,
+ default: () => ({
+ value: '',
+ default: '{}'
+ })
+ },
+ },
+
+ data() {
+ return {
+ ENGINES,
+ QUANTITY_FIELDS,
+ RESTIC: BACKUP_TYPE.RESTIC,
+ config: parseConfig(this.value?.value, this.value?.default),
+ };
+ },
+
+ created() {
+ this.registerBeforeHook?.(this.willSave, 'willSave');
+ },
+
+ methods: {
+ updateValue() {
+ if (this.value) {
+ this.value.value = JSON.stringify(this.config);
+ }
+ },
+
+ useDefault() {
+ this.config = parseConfig('', this.value?.default);
+ this.updateValue();
+ },
+
+ willSave() {
+ this.updateValue();
+
+ return Promise.resolve();
+ },
+ },
+};
+
+
+
+
+
+
+
diff --git a/pkg/harvester/config/feature-flags.js b/pkg/harvester/config/feature-flags.js
index 240ccfda..80d91d9f 100644
--- a/pkg/harvester/config/feature-flags.js
+++ b/pkg/harvester/config/feature-flags.js
@@ -90,6 +90,7 @@ const FEATURE_FLAGS = {
'shutdownVMOnMigrationFailure',
'vmListPagination',
'kubeovnBgp',
+ 'thirdPartyVMBackup',
],
};
diff --git a/pkg/harvester/config/labels-annotations.js b/pkg/harvester/config/labels-annotations.js
index 9fa784c2..3f4436eb 100644
--- a/pkg/harvester/config/labels-annotations.js
+++ b/pkg/harvester/config/labels-annotations.js
@@ -91,6 +91,7 @@ export const HCI = {
STATIC_IP: 'static-ip.harvesterhci.io',
NODE_UPGRADE_PAUSE_MAP: 'harvesterhci.io/node-upgrade-pause-map',
CDI_POPULATOR_KIND: 'cdi.kubevirt.io/storage.populator.kind',
+ CDI_CREATED_FOR_DATA_VOLUME: 'cdi.kubevirt.io/createdForDataVolume',
CNI_NETWORKS: 'k8s.v1.cni.cncf.io/networks',
KUBEOVN_BGP: 'ovn.kubernetes.io/bgp',
WINDOWS_SYSPREP: 'harvesterhci.io/windows-sysprep',
diff --git a/pkg/harvester/config/settings.ts b/pkg/harvester/config/settings.ts
index 6dd981d0..4300cd96 100644
--- a/pkg/harvester/config/settings.ts
+++ b/pkg/harvester/config/settings.ts
@@ -30,6 +30,7 @@ export const HCI_SETTING = {
RELEASE_DOWNLOAD_URL: 'release-download-url',
CCM_CSI_VERSION: 'harvester-csi-ccm-versions',
CSI_DRIVER_CONFIG: 'csi-driver-config',
+ THIRD_PARTY_BACKUP_CONFIG: 'third-party-backup-config',
CSI_ONLINE_EXPAND_VALIDATION: 'csi-online-expand-validation',
VM_TERMINATION_PERIOD: 'default-vm-termination-grace-period-seconds',
NTP_SERVERS: 'ntp-servers',
@@ -144,6 +145,9 @@ export const HCI_ALLOWED_SETTINGS = {
[HCI_SETTING.KUBEVIRT_MIGRATION]: {
kind: 'json', from: 'import', canReset: true, featureFlag: 'kubevirtMigration',
},
+ [HCI_SETTING.THIRD_PARTY_BACKUP_CONFIG]: {
+ kind: 'json', from: 'import', canReset: true, featureFlag: 'thirdPartyVMBackup',
+ },
[HCI_SETTING.INSTANCE_MANAGER_RESOURCES]: {
kind: 'json', from: 'import', featureFlag: 'instanceManagerResourcesSetting'
},
diff --git a/pkg/harvester/config/types.js b/pkg/harvester/config/types.js
index 62799a10..717f9e88 100644
--- a/pkg/harvester/config/types.js
+++ b/pkg/harvester/config/types.js
@@ -1,6 +1,8 @@
export const BACKUP_TYPE = {
BACKUP: 'backup',
- SNAPSHOT: 'snapshot'
+ SNAPSHOT: 'snapshot',
+ RESTIC: 'restic',
+ KOPIA: 'kopia'
};
export const NETWORK_TYPE = {
diff --git a/pkg/harvester/dialog/HarvesterBackupModal.vue b/pkg/harvester/dialog/HarvesterBackupModal.vue
index 40bc208e..fa2a47a9 100644
--- a/pkg/harvester/dialog/HarvesterBackupModal.vue
+++ b/pkg/harvester/dialog/HarvesterBackupModal.vue
@@ -3,10 +3,13 @@ import { exceptionToErrorsArray } from '@shell/utils/error';
import { mapGetters } from 'vuex';
import { Card } from '@components/Card';
import { Banner } from '@components/Banner';
-import AsyncButton from '@shell/components/AsyncButton';
import { LabeledInput } from '@components/Form/LabeledInput';
+import { RcButton } from '@components/RcButton';
+import { RcHeading } from '@components/RcHeading';
import LabeledSelect from '@shell/components/form/LabeledSelect';
import { DEFAULT_FS_FREEZE_DEADLINE, getFsFreezeDeadlineOptions } from '../utils/backup';
+import { BACKUP_TYPE } from '../config/types';
+import { HCI } from '../types';
export default {
name: 'HarvesterBackupModal',
@@ -14,11 +17,12 @@ export default {
emits: ['close'],
components: {
- AsyncButton,
Card,
LabeledInput,
LabeledSelect,
- Banner
+ Banner,
+ RcButton,
+ RcHeading
},
props: {
@@ -28,11 +32,23 @@ export default {
}
},
+ async fetch() {
+ if (!this.thirdPartyBackupFeatureEnabled) {
+ return;
+ }
+
+ await this.actionResource.fetchBackupTypeRequirements();
+
+ this.backupType = this.backupTypeOptions.find((option) => !option.disabled)?.value;
+ },
+
data() {
return {
backUpName: '',
+ backupType: BACKUP_TYPE.BACKUP,
errors: [],
- fsFreezeDeadline: DEFAULT_FS_FREEZE_DEADLINE
+ fsFreezeDeadline: DEFAULT_FS_FREEZE_DEADLINE,
+ saving: false
};
},
@@ -49,6 +65,31 @@ export default {
fsFreezeDeadlineOptions() {
return getFsFreezeDeadlineOptions(this.t);
+ },
+
+ thirdPartyBackupFeatureEnabled() {
+ return !!this.actionResource?.thirdPartyBackupFeatureEnabled;
+ },
+
+ backupTypeOptions() {
+ return this.thirdPartyBackupFeatureEnabled ? this.actionResource.backupTypeOptions : [];
+ },
+
+ // Shown outside the select too: its disabled options can't be reached by keyboard
+ unavailableBackupTypeOptions() {
+ return this.backupTypeOptions.filter((option) => option.disabled);
+ },
+
+ isLoading() {
+ return this.thirdPartyBackupFeatureEnabled && this.$fetchState.pending;
+ },
+
+ noBackupTypeAvailable() {
+ return this.thirdPartyBackupFeatureEnabled && !this.isLoading && !this.backupType;
+ },
+
+ canCreate() {
+ return !!this.backUpName && !this.isLoading && !this.noBackupTypeAvailable && !this.saving;
}
},
@@ -60,42 +101,69 @@ export default {
this.$emit('close');
},
- async save(buttonCb) {
- if (this.actionResource) {
- try {
- const res = await this.actionResource.doAction(
- 'backup',
- { name: this.backUpName, fsFreezeDeadline: this.fsFreezeDeadline },
- {},
- false
- );
+ backupCreated() {
+ this.$store.dispatch(
+ 'growl/success',
+ {
+ title: this.t('generic.notification.title.succeed'),
+ message: this.t('harvester.modal.backup.success', { backUpName: this.backUpName })
+ },
+ { root: true }
+ );
- if (res._status === 200 || res._status === 204) {
- this.$store.dispatch(
- 'growl/success',
- {
- title: this.t('generic.notification.title.succeed'),
- message: this.t('harvester.modal.backup.success', { backUpName: this.backUpName })
- },
- { root: true }
- );
+ this.close();
+ },
- this.close();
+ // No ownerReferences, like the backup action: deleting the VM must leave its backups and their remote data
+ async createDataMoverBackup() {
+ const backup = await this.$store.dispatch('harvester/create', {
+ metadata: {
+ name: this.backUpName,
+ namespace: this.actionResource.metadata.namespace,
+ },
+ spec: {
+ fsFreezeDeadline: this.fsFreezeDeadline,
+ source: {
+ apiGroup: 'kubevirt.io',
+ kind: 'VirtualMachine',
+ name: this.actionResource.metadata.name
+ },
+ type: this.backupType
+ },
+ type: HCI.BACKUP
+ });
- buttonCb(true);
- } else {
- const error = [res?.data] || exceptionToErrorsArray(res);
+ await backup.save();
+ },
- this['errors'] = error;
- buttonCb(false);
- }
- } catch (err) {
- const error = err?.data || err;
- const message = exceptionToErrorsArray(error);
+ async save() {
+ this.saving = true;
+ this.errors = [];
- this['errors'] = message;
- buttonCb(false);
+ try {
+ if (this.backupType !== BACKUP_TYPE.BACKUP) {
+ await this.createDataMoverBackup();
+ this.backupCreated();
+
+ return;
}
+
+ const res = await this.actionResource.doAction(
+ 'backup',
+ { name: this.backUpName, fsFreezeDeadline: this.fsFreezeDeadline },
+ {},
+ false
+ );
+
+ if (res._status === 200 || res._status === 204) {
+ this.backupCreated();
+ } else {
+ this.errors = [res?.data] || exceptionToErrorsArray(res);
+ }
+ } catch (err) {
+ this.errors = exceptionToErrorsArray(err?.data || err);
+ } finally {
+ this.saving = false;
}
}
}
@@ -105,27 +173,73 @@ export default {
-
+
+ {{ t('harvester.modal.backup.addBackup') }}
+
-
-
+ color="warning"
+ data-testid="backup-no-type-available"
+ >
+
+
+ {{ t('harvester.modal.backup.noTypeAvailable') }}
+
+
+ -
+ {{ option.label }}: {{ option.unavailableReason }}
+
+
+
+
+
+
+
+
+
+ -
+ {{ option.label }}: {{ option.unavailableReason }}
+
+
+
+
+
diff --git a/pkg/harvester/dialog/__tests__/HarvesterBackupModal.test.js b/pkg/harvester/dialog/__tests__/HarvesterBackupModal.test.js
new file mode 100644
index 00000000..0b3fc1f2
--- /dev/null
+++ b/pkg/harvester/dialog/__tests__/HarvesterBackupModal.test.js
@@ -0,0 +1,144 @@
+import { shallowMount } from '@vue/test-utils';
+import HarvesterBackupModal from '../HarvesterBackupModal.vue';
+import { HCI } from '../../types';
+
+const OPTIONS = {
+ backup: {
+ value: 'backup', label: 'Native', disabled: true, unavailableReason: 'native reason'
+ },
+ restic: {
+ value: 'restic', label: 'Restic', disabled: false
+ },
+ kopia: {
+ value: 'kopia', label: 'Kopia', disabled: false
+ },
+};
+
+function mountModal({
+ enabled = true, options = Object.values(OPTIONS), doAction = jest.fn().mockResolvedValue({ _status: 204 }), save = jest.fn().mockResolvedValue()
+} = {}) {
+ const vm = {
+ metadata: { name: 'vm1', namespace: 'ns1' },
+ thirdPartyBackupFeatureEnabled: enabled,
+ backupTypeOptions: options,
+ fetchBackupTypeRequirements: jest.fn().mockResolvedValue(),
+ doAction,
+ };
+ const dispatch = jest.fn((action) => (action === 'harvester/create' ? Promise.resolve({ save }) : Promise.resolve()));
+ const wrapper = shallowMount(HarvesterBackupModal, {
+ props: { resources: [vm] },
+ global: {
+ stubs: {
+ Banner: { template: '
' },
+ Card: { template: '
' },
+ },
+ mocks: {
+ t: (key) => key,
+ $fetchState: { pending: false },
+ $store: {
+ dispatch,
+ getters: {
+ 'i18n/t': (key) => key,
+ 'harvester-common/getFeatureEnabled': () => false,
+ },
+ },
+ },
+ },
+ });
+
+ return {
+ wrapper, vm, dispatch, doAction, save
+ };
+}
+
+describe('component: HarvesterBackupModal', () => {
+ it('should keep the plain dialog while the feature is off', async() => {
+ const { wrapper, doAction, dispatch } = mountModal({ enabled: false });
+
+ expect(wrapper.find('[data-testid="backup-type-select"]').exists()).toBe(false);
+
+ await wrapper.setData({ backUpName: 'b1' });
+ await wrapper.vm.save();
+
+ expect(doAction).toHaveBeenCalledWith('backup', expect.objectContaining({ name: 'b1' }), {}, false);
+ expect(dispatch).not.toHaveBeenCalledWith('harvester/create', expect.anything());
+ expect(wrapper.emitted('close')).toHaveLength(1);
+ });
+
+ it('should load the requirements and select the first available type', async() => {
+ const { wrapper, vm } = mountModal();
+
+ await HarvesterBackupModal.fetch.call(wrapper.vm);
+
+ expect(vm.fetchBackupTypeRequirements).toHaveBeenCalledTimes(1);
+ expect(wrapper.vm.backupType).toBe('restic');
+ });
+
+ it('should keep native on the backup action', async() => {
+ const { wrapper, doAction, dispatch } = mountModal();
+
+ await wrapper.setData({ backUpName: 'b1', backupType: 'backup' });
+ await wrapper.vm.save();
+
+ expect(doAction).toHaveBeenCalledTimes(1);
+ expect(dispatch).not.toHaveBeenCalledWith('harvester/create', expect.anything());
+ });
+
+ it('should create Kopia directly, without an owner reference on the VM', async() => {
+ const {
+ wrapper, doAction, dispatch, save
+ } = mountModal();
+
+ await wrapper.setData({ backUpName: 'b1', backupType: 'kopia' });
+ await wrapper.vm.save();
+
+ expect(doAction).not.toHaveBeenCalled();
+ expect(save).toHaveBeenCalledTimes(1);
+
+ const [, resource] = dispatch.mock.calls.find(([action]) => action === 'harvester/create');
+
+ expect(resource.type).toBe(HCI.BACKUP);
+ expect(resource.metadata).toStrictEqual({ name: 'b1', namespace: 'ns1' });
+ expect(resource.spec.type).toBe('kopia');
+ expect(resource.spec.source.name).toBe('vm1');
+ expect(wrapper.emitted('close')).toHaveLength(1);
+ });
+
+ it('should show the webhook error and stay open', async() => {
+ const { wrapper } = mountModal({ save: jest.fn().mockRejectedValue({ status: 422, message: 'vm is in migration' }) });
+
+ await wrapper.setData({ backUpName: 'b1', backupType: 'kopia' });
+ await wrapper.vm.save();
+
+ expect(wrapper.vm.errors).toStrictEqual(['vm is in migration']);
+ expect(wrapper.vm.saving).toBe(false);
+ expect(wrapper.emitted('close')).toBeUndefined();
+ });
+
+ it('should list the reasons of unavailable types next to the select', async() => {
+ const { wrapper } = mountModal();
+
+ await HarvesterBackupModal.fetch.call(wrapper.vm);
+ await wrapper.vm.$nextTick();
+
+ expect(wrapper.find('[data-testid="backup-type-unavailable"]').exists()).toBe(true);
+ expect(wrapper.findAll('li').map((li) => li.text())).toStrictEqual(['Native: native reason']);
+ });
+
+ it('should explain why when no type is available and hide the form', async() => {
+ const disabled = Object.values(OPTIONS).map((option) => ({
+ ...option, disabled: true, unavailableReason: `${ option.value } reason`
+ }));
+ const { wrapper } = mountModal({ options: disabled });
+
+ await HarvesterBackupModal.fetch.call(wrapper.vm);
+ await wrapper.vm.$nextTick();
+
+ expect(wrapper.vm.noBackupTypeAvailable).toBe(true);
+ expect(wrapper.vm.canCreate).toBe(false);
+ expect(wrapper.find('[data-testid="backup-type-select"]').exists()).toBe(false);
+ expect(wrapper.findAll('li').map((li) => li.text())).toStrictEqual([
+ 'Native: backup reason', 'Restic: restic reason', 'Kopia: kopia reason'
+ ]);
+ });
+});
diff --git a/pkg/harvester/l10n/en-us.yaml b/pkg/harvester/l10n/en-us.yaml
index c8e97887..4c778b63 100644
--- a/pkg/harvester/l10n/en-us.yaml
+++ b/pkg/harvester/l10n/en-us.yaml
@@ -96,6 +96,7 @@ harvester:
backup:
success: 'Backup { backUpName } has been initiated.'
addBackup: Add Backup
+ noTypeAvailable: No backup type can protect this virtual machine.
fileSystemFreezeDeadline:
label: 'File System Freeze Deadline'
quota:
@@ -1360,6 +1361,31 @@ harvester:
label: Refresh Interval
tip: The interval for the backup target to sync data to [[Harvester]] cluster. Set to 0 to disable refresh mechanism.
backupTargetTip: The endpoint used to access the backupstore. NFS and S3 are supported.
+ thirdPartyBackup:
+ label: Enable Restic and Kopia Backups
+ tooltip: Allows Restic and Kopia virtual machine backups to this S3 target. Native backups and snapshots are not affected.
+ password:
+ label: Repository Password
+ tip: Restic and Kopia encrypt their backups with this password. Enter it every time you save this setting. It can't be changed for an existing repository, so keep a copy.
+ kopiaGC:
+ label: Enable Kopia Garbage Collection
+ tooltip: Runs scheduled Kopia maintenance to remove unused data from the S3 repository.
+ type:
+ backup: Native
+ snapshot: Snapshot
+ restic: Restic
+ kopia: Kopia
+ typeUnavailable:
+ native: Not supported by the volumes of this virtual machine.
+ longhornV2: Not supported on Longhorn V2 volumes such as {volume}.
+ cdi: Not supported on volumes created from a CDI image such as {volume}.
+ noBackupSnapshotClass: Set a backup volume snapshot class for {driver} in the csi-driver-config setting.
+ requiresS3: Requires an S3 backup target.
+ requiresBlock: Requires Block volume mode, but {volume} uses Filesystem.
+ longhornV1: Not supported on Longhorn V1 volumes such as {volume}.
+ noSnapshotClass: Set a volume snapshot class for {driver} in the csi-driver-config setting.
+ snapshot: The volumes of this virtual machine cannot be snapshotted.
+ thirdPartyBackupOff: Not enabled in the backup-target setting.
message:
noSetting:
prefix: You must configure the backup target
@@ -1955,6 +1981,16 @@ harvester:
allowWorkloadDisruption: "Allow Workload Disruption"
disableTLS: "Disable TLS"
matchSELinuxLevelOnMigration: "Match SELinux Level On Migration"
+ thirdPartyBackupConfig:
+ memoryRequest: Memory Request
+ memoryLimit: Memory Limit
+ ephemeralRequest: Ephemeral Storage Request
+ ephemeralLimit: Ephemeral Storage Limit
+ cacheSize: Cache Size
+ cacheSizeHint: Must be less than the ephemeral storage limit.
+ maxConcurrentJobs: Maximum Concurrent Jobs
+ maxConcurrentJobsHint: Set to 0 for no limit.
+ noCache: Disable Cache
cloudTemplate:
label: Cloud Configuration Templates
@@ -2853,6 +2889,7 @@ advancedSettings:
'harv-rancher-cluster': 'Configure Rancher cluster integration settings for guest cluster management.'
'harv-max-hotplug-ratio': 'The ratio for kubevirt to limit the maximum CPU and memory that can be hotplugged to a VM. The value could be an integer between 1 and 20, default to 4.'
'harv-kubevirt-migration': 'Configure cluster-wide KubeVirt live migration parameters.'
+ 'harv-third-party-backup-config': 'Configure the resources and concurrency of Restic and Kopia virtual machine backup jobs.'
'harv-instance-manager-resources': 'Configure resource percentage reservations for Longhorn instance manager V1 and V2. Valid instance manager CPU range between 0 - 40.'
'harv-cluster-pod-security-standard': 'Enforce Kubernetes Pod Security Standards (PSS) at the cluster level.'
'harv-maintenance-mode-drain-timeout': 'Maintenance mode drain timeout in minutes. Use 0 to disable the timeout.'
diff --git a/pkg/harvester/list/harvesterhci.io.virtualmachinebackup.vue b/pkg/harvester/list/harvesterhci.io.virtualmachinebackup.vue
index 1d6fd491..bc54134d 100644
--- a/pkg/harvester/list/harvesterhci.io.virtualmachinebackup.vue
+++ b/pkg/harvester/list/harvesterhci.io.virtualmachinebackup.vue
@@ -112,6 +112,15 @@ export default {
},
];
+ if (this.thirdPartyBackupFeatureEnabled) {
+ cols.push({
+ name: 'backupType',
+ labelKey: 'harvester.fields.type',
+ value: 'backupTypeLabel',
+ sort: 'backupTypeLabel',
+ });
+ }
+
if (this.schedulingVMBackupFeatureEnabled) {
cols.push({
name: 'backupCreatedFrom',
@@ -153,6 +162,10 @@ export default {
return cols;
},
+ thirdPartyBackupFeatureEnabled() {
+ return this.$store.getters['harvester-common/getFeatureEnabled']('thirdPartyVMBackup');
+ },
+
schedulingVMBackupFeatureEnabled() {
return this.$store.getters['harvester-common/getFeatureEnabled']('schedulingVMBackup');
},
@@ -164,7 +177,7 @@ export default {
return this.backups.filter((r) => r.spec?.type !== BACKUP_TYPE.SNAPSHOT);
},
getRawRows() {
- return this.rows.filter((r) => r.spec?.type === BACKUP_TYPE.BACKUP);
+ return this.rows.filter((r) => r.spec?.type !== BACKUP_TYPE.SNAPSHOT);
},
backupTargetResource() {
return this.settings.find((O) => O.id === 'backup-target');
diff --git a/pkg/harvester/list/harvesterhci.io.vmsnapshot.vue b/pkg/harvester/list/harvesterhci.io.vmsnapshot.vue
index 8509170c..1938aefb 100644
--- a/pkg/harvester/list/harvesterhci.io.vmsnapshot.vue
+++ b/pkg/harvester/list/harvesterhci.io.vmsnapshot.vue
@@ -114,7 +114,7 @@ export default {
},
filteredRows() {
- return this.snapshots.filter((r) => r.spec?.type !== BACKUP_TYPE.BACKUP);
+ return this.snapshots.filter((r) => r.spec?.type === BACKUP_TYPE.SNAPSHOT);
},
},
diff --git a/pkg/harvester/models/__tests__/harvesterhci.io.virtualmachinebackup.test.js b/pkg/harvester/models/__tests__/harvesterhci.io.virtualmachinebackup.test.js
new file mode 100644
index 00000000..a5fe7dd2
--- /dev/null
+++ b/pkg/harvester/models/__tests__/harvesterhci.io.virtualmachinebackup.test.js
@@ -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);
+ });
+});
diff --git a/pkg/harvester/models/__tests__/kubevirt.io.virtualmachine.test.js b/pkg/harvester/models/__tests__/kubevirt.io.virtualmachine.test.js
index e32c1775..d24815d3 100644
--- a/pkg/harvester/models/__tests__/kubevirt.io.virtualmachine.test.js
+++ b/pkg/harvester/models/__tests__/kubevirt.io.virtualmachine.test.js
@@ -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);
diff --git a/pkg/harvester/models/harvester/persistentvolumeclaim.js b/pkg/harvester/models/harvester/persistentvolumeclaim.js
index f56478f5..1351f328 100644
--- a/pkg/harvester/models/harvester/persistentvolumeclaim.js
+++ b/pkg/harvester/models/harvester/persistentvolumeclaim.js
@@ -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';
}
diff --git a/pkg/harvester/models/harvesterhci.io.virtualmachinebackup.js b/pkg/harvester/models/harvesterhci.io.virtualmachinebackup.js
index 7690b09c..c0398a2e 100644
--- a/pkg/harvester/models/harvesterhci.io.virtualmachinebackup.js
+++ b/pkg/harvester/models/harvesterhci.io.virtualmachinebackup.js
@@ -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 || '';
}
diff --git a/pkg/harvester/models/kubevirt.io.virtualmachine.js b/pkg/harvester/models/kubevirt.io.virtualmachine.js
index 64b82503..cdf76cda 100644
--- a/pkg/harvester/models/kubevirt.io.virtualmachine.js
+++ b/pkg/harvester/models/kubevirt.io.virtualmachine.js
@@ -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');
diff --git a/pkg/harvester/utils/setting.js b/pkg/harvester/utils/setting.js
index 67954bfd..4ceaadce 100644
--- a/pkg/harvester/utils/setting.js
+++ b/pkg/harvester/utils/setting.js
@@ -23,3 +23,11 @@ export function isBackupTargetSettingUnavailable(setting = {}) {
return (errorMessage || isEmptyValue) && canUpdate;
}
+
+export function getBackupTarget(setting = {}) {
+ try {
+ return JSON.parse(setting?.value || '{}') || {};
+ } catch (e) {
+ return {};
+ }
+}