From f26211585c6294d516326bb08ead7f46855d64c9 Mon Sep 17 00:00:00 2001 From: Daniel Fajmon Date: Mon, 16 Nov 2026 16:33:06 +0100 Subject: [PATCH 1/2] STOR-2991: Add VolumeGroupSnapshot UI CRUD for VolumeGroupSnapshot/Class/Content: list+details pages, create page w/ PVC label-selector picker, nav/flags. Restoring a group's member VolumeSnapshots to new PVCs is done per-snapshot via the existing VolumeSnapshot restore flow, not from the VGS itself. - create form: exact driver match (not substring) when filtering VolumeGroupSnapshotClass by provisioner; gate submit on StorageClass/VolumeGroupSnapshotClass/PVC watch loaded+error state; disable submit while a create is in progress. - AccessModeSelector: derive the toggle label from the current accessMode instead of a state snapshot taken on mount, so it stays correct once data that arrives after mount (e.g. a source PVC's annotations) changes the auto-picked access mode. - PVCTable empty states use RhStandardAlertIcon/RhStandardBoxIcon instead of the restricted Font Awesome CubesIcon. - PVC-count strings use a numberOf (not count) interpolation var, since their singular/plural text is identical and the shared i18n-structure test rejects identical _one/_other pairs. Co-Authored-By: Claude Sonnet 5 --- .../console-app/console-extensions.json | 111 ++++++ .../console-app/locales/en/console-app.json | 32 ++ frontend/packages/console-app/package.json | 3 + .../volume-group-snapshot-provider.ts | 16 + .../components/access-modes/access-mode.tsx | 8 +- .../_create-volume-group-snapshot.scss | 3 + .../create-volume-group-snapshot.tsx | 323 +++++++++++++++++ .../pvc-resource-viewer.tsx | 180 +++++++++ .../volume-group-snapshot/pvc-table.tsx | 112 ++++++ .../volume-group-snapshot-class-details.tsx | 77 ++++ .../volume-group-snapshot-class.tsx | 175 +++++++++ .../volume-group-snapshot-content-details.tsx | 121 ++++++ .../volume-group-snapshot-content.tsx | 196 ++++++++++ .../volume-group-snapshot-details.tsx | 173 +++++++++ .../volume-group-snapshot.tsx | 343 ++++++++++++++++++ .../console-shared/src/constants/common.ts | 1 + .../console-shared/src/sorts/snapshot.ts | 7 + frontend/public/actions/flags.ts | 15 +- frontend/public/components/app-contents.tsx | 23 ++ frontend/public/components/list-pages.ts | 12 + frontend/public/components/resource-pages.ts | 12 + frontend/public/locales/en/public.json | 6 + frontend/public/models/index.ts | 51 +++ frontend/public/module/k8s/types.ts | 76 ++++ 24 files changed, 2071 insertions(+), 5 deletions(-) create mode 100644 frontend/packages/console-app/src/actions/providers/volume-group-snapshot-provider.ts create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/_create-volume-group-snapshot.scss create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/create-volume-group-snapshot.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/pvc-resource-viewer.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/pvc-table.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class-details.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content-details.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-details.tsx create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot.tsx diff --git a/frontend/packages/console-app/console-extensions.json b/frontend/packages/console-app/console-extensions.json index b891a4ec8f8..315fa49c04e 100644 --- a/frontend/packages/console-app/console-extensions.json +++ b/frontend/packages/console-app/console-extensions.json @@ -214,6 +214,34 @@ "required": ["CAN_LIST_VSC"] } }, + { + "type": "console.page/resource/list", + "properties": { + "model": { + "group": "groupsnapshot.storage.k8s.io", + "version": "v1", + "kind": "VolumeGroupSnapshotContent" + }, + "component": { "$codeRef": "volumeGroupSnapshotContent.default" } + }, + "flags": { + "required": ["CAN_LIST_VGSC"] + } + }, + { + "type": "console.page/resource/details", + "properties": { + "model": { + "group": "groupsnapshot.storage.k8s.io", + "version": "v1", + "kind": "VolumeGroupSnapshotContent" + }, + "component": { "$codeRef": "volumeGroupSnapshotContentDetails.default" } + }, + "flags": { + "required": ["CAN_LIST_VGSC"] + } + }, { "type": "console.tab/horizontalNav", "properties": { @@ -435,6 +463,19 @@ "provider": { "$codeRef": "volumeSnapshotProvider.useVolumeSnapshotActionsProvider" } } }, + { + "type": "console.action/resource-provider", + "properties": { + "model": { + "version": "v1", + "kind": "VolumeGroupSnapshot", + "group": "groupsnapshot.storage.k8s.io" + }, + "provider": { + "$codeRef": "volumeGroupSnapshotProvider.useVolumeGroupSnapshotActionsProvider" + } + } + }, { "type": "console.action/resource-provider", "properties": { @@ -473,6 +514,17 @@ "provider": { "$codeRef": "defaultProvider.useDefaultActionsProvider" } } }, + { + "type": "console.action/resource-provider", + "properties": { + "model": { + "version": "v1", + "kind": "VolumeGroupSnapshotClass", + "group": "groupsnapshot.storage.k8s.io" + }, + "provider": { "$codeRef": "defaultProvider.useDefaultActionsProvider" } + } + }, { "type": "console.action/resource-provider", "properties": { @@ -1407,6 +1459,54 @@ } } }, + { + "type": "console.navigation/resource-ns", + "properties": { + "perspective": "admin", + "section": "storage", + "id": "volumegroupsnapshots", + "insertAfter": "volumesnapshotcontents", + "name": "%console-app~VolumeGroupSnapshots%", + "model": { + "group": "groupsnapshot.storage.k8s.io", + "version": "v1", + "kind": "VolumeGroupSnapshot" + } + } + }, + { + "type": "console.navigation/resource-cluster", + "properties": { + "perspective": "admin", + "section": "storage", + "id": "volumegroupsnapshotclasses", + "insertAfter": "volumegroupsnapshots", + "name": "%console-app~VolumeGroupSnapshotClasses%", + "model": { + "group": "groupsnapshot.storage.k8s.io", + "version": "v1", + "kind": "VolumeGroupSnapshotClass" + } + } + }, + { + "type": "console.navigation/resource-cluster", + "properties": { + "perspective": "admin", + "id": "volumegroupsnapshotcontents", + "section": "storage", + "name": "%console-app~VolumeGroupSnapshotContents%", + "insertAfter": "volumegroupsnapshotclasses", + "model": { + "group": "groupsnapshot.storage.k8s.io", + "kind": "VolumeGroupSnapshotContent", + "version": "v1" + } + }, + "flags": { + "required": ["CAN_LIST_VGSC"] + } + }, { "type": "console.navigation/resource-ns", "properties": { @@ -1460,6 +1560,17 @@ "provider": { "$codeRef": "defaultProvider.useDefaultActionsProvider" } } }, + { + "type": "console.action/resource-provider", + "properties": { + "model": { + "group": "groupsnapshot.storage.k8s.io", + "version": "v1", + "kind": "VolumeGroupSnapshotContent" + }, + "provider": { "$codeRef": "defaultProvider.useDefaultActionsProvider" } + } + }, { "type": "console.action/resource-provider", "properties": { diff --git a/frontend/packages/console-app/locales/en/console-app.json b/frontend/packages/console-app/locales/en/console-app.json index 9198901247e..20c7bb155ae 100644 --- a/frontend/packages/console-app/locales/en/console-app.json +++ b/frontend/packages/console-app/locales/en/console-app.json @@ -15,6 +15,9 @@ "{{index, number}} of {{tasks, number}}": "{{index, number}} of {{tasks, number}}", "{{kind}} {{name}} violates policy {{warning}}": "{{kind}} {{name}} violates policy {{warning}}", "{{minMinutes}}-{{maxMinutes}} min": "{{minMinutes}}-{{maxMinutes}} min", + "{{numberOf}} more PVCs": "{{numberOf}} more PVCs", + "{{numberOf}} PVCs": "{{numberOf}} PVCs", + "{{numberOf}} PVCs are selected to form the volume group for VolumeGroupSnapshots.": "{{numberOf}} PVCs are selected to form the volume group for VolumeGroupSnapshots.", "{{pluginName}} might have violated the Console Content Security Policy. Refer to the browser's console logs for details.": "{{pluginName}} might have violated the Console Content Security Policy. Refer to the browser's console logs for details.", "{{prefix}}: {{remediation}}": "{{prefix}}: {{remediation}}", "{{prefix}}: {{remediation}}; Drain: {{timeout}} timeout": "{{prefix}}: {{remediation}}; Drain: {{timeout}} timeout", @@ -178,6 +181,9 @@ "Create PodDisruptionBudget": "Create PodDisruptionBudget", "Create resources in just a few steps via Git, YAML, or container images.": "Create resources in just a few steps via Git, YAML, or container images.", "Create snapshot": "Create snapshot", + "Create VolumeGroupSnapshot": "Create VolumeGroupSnapshot", + "Create VolumeGroupSnapshotClass": "Create VolumeGroupSnapshotClass", + "Create VolumeGroupSnapshotContent": "Create VolumeGroupSnapshotContent", "Create VolumeSnapshot": "Create VolumeSnapshot", "Create VolumeSnapshotClass": "Create VolumeSnapshotClass", "Create VolumeSnapshotContent": "Create VolumeSnapshotContent", @@ -208,6 +214,7 @@ "Delete {{label}} subject?": "Delete {{label}} subject?", "Delete group {{groupName}}": "Delete group {{groupName}}", "Delete PersistentVolumeClaim": "Delete PersistentVolumeClaim", + "Deleting this VolumeGroupSnapshot will also delete all VolumeSnapshots that belong to this group.": "Deleting this VolumeGroupSnapshot will also delete all VolumeSnapshots that belong to this group.", "Deletion policy": "Deletion policy", "Deny": "Deny", "DeploymentConfigs": "DeploymentConfigs", @@ -267,6 +274,7 @@ "Error": "Error", "Error fetching log filenames: {{message}}": "Error fetching log filenames: {{message}}", "Error fetching logs: {{message}}": "Error fetching logs: {{message}}", + "Error loading PVCs": "Error loading PVCs", "Error occurred": "Error occurred", "Error updating {{nodeName}}": "Error updating {{nodeName}}", "Estimated recovery time": "Estimated recovery time", @@ -299,6 +307,7 @@ "Filter by roles": "Filter by roles", "Filter by status": "Filter by status", "Filter by unit": "Filter by unit", + "Find by name": "Find by name", "Firmware": "Firmware", "Form": "Form", "Framebuffer memory free": "Framebuffer memory free", @@ -332,6 +341,8 @@ "Groups for": "Groups for", "Groups have been updated.": "Groups have been updated.", "Groups help you organize and select resources.": "Groups help you organize and select resources.", + "GroupSnapshot content": "GroupSnapshot content", + "GroupSnapshot handle": "GroupSnapshot handle", "guided tour {{step, number}}": "guided tour {{step, number}}", "HCTL": "HCTL", "Health": "Health", @@ -382,6 +393,7 @@ "Kubelet version": "Kubelet version", "Label": "Label", "Label query for pods whose evictions are managed by the disruption budget. A null selector will match no pods, while an empty ({}) selector will select all pods within the namespace.": "Label query for pods whose evictions are managed by the disruption budget. A null selector will match no pods, while an empty ({}) selector will select all pods within the namespace.", + "Label selector": "Label selector", "Labels": "Labels", "Language": "Language", "Last action": "Last action", @@ -497,6 +509,7 @@ "No persistent volumes found": "No persistent volumes found", "No PodDisruptionBudget": "No PodDisruptionBudget", "No power management": "No power management", + "No PVCs have been identified for the volume group yet": "No PVCs have been identified for the volume group yet", "No quota": "No quota", "No results found": "No results found", "No results match the filter criteria. Remove filters or clear all filters to show results.": "No results match the filter criteria. Remove filters or clear all filters to show results.", @@ -592,6 +605,8 @@ "PVC details": "PVC details", "PVC is not Bound": "PVC is not Bound", "PVC must be Bound to modify VolumeAttributesClass": "PVC must be Bound to modify VolumeAttributesClass", + "PVC name": "PVC name", + "PVCs table": "PVCs table", "Quick create": "Quick create", "Quick starts": "Quick starts", "Quick Starts": "Quick Starts", @@ -675,14 +690,17 @@ "Select GCE type": "Select GCE type", "Select none (0)": "Select none (0)", "Select page ({{pageCount}})": "Select page ({{pageCount}})", + "Select PVCs in the {{namespace}} namespace using label selectors to form a volume group to take VolumeGroupSnapshots.": "Select PVCs in the {{namespace}} namespace using label selectors to form a volume group to take VolumeGroupSnapshots.", "Select Replication type": "Select Replication type", "Select storage provision mode": "Select storage provision mode", "Select the language you want to use for the console.": "Select the language you want to use for the console.", "Select volume snapshot class": "Select volume snapshot class", + "Select VolumeGroupSnapshotClass": "Select VolumeGroupSnapshotClass", "Selected columns will appear in the table.": "Selected columns will appear in the table.", "Selected group is unavailable": "Selected group is unavailable", "Selected machines": "Selected machines", "Selected nodes": "Selected nodes", + "Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.": "Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.", "Selector": "Selector", "Separate multiple group names with commas.": "Separate multiple group names with commas.", "Serial number": "Serial number", @@ -708,6 +726,7 @@ "SNR - Self node remediation": "SNR - Self node remediation", "Software Catalog": "Software Catalog", "Source": "Source", + "Source PVCs": "Source PVCs", "SSD": "SSD", "Start": "Start", "Start {{nextQSDisplayName}} quick start": "Start {{nextQSDisplayName}} quick start", @@ -722,6 +741,7 @@ "Stop impersonating": "Stop impersonating", "Storage": "Storage", "Storage account type": "Storage account type", + "Storage class": "Storage class", "Storage mode": "Storage mode", "Storage pool": "Storage pool", "StorageClass": "StorageClass", @@ -746,6 +766,7 @@ "The specific update of the plugin.": "The specific update of the plugin.", "The state of the plugin.": "The state of the plugin.", "The traditional console appearance.": "The traditional console appearance.", + "There was an error loading the PersistentVolumeClaims. Please try again.": "There was an error loading the PersistentVolumeClaims. Please try again.", "This action is only enabled when the latest revision of the ReplicationController resource is in a failed state.": "This action is only enabled when the latest revision of the ReplicationController resource is in a failed state.", "This count is based on your access permissions and might not include all virtual machines. Contact your administrator for full access.": "This count is based on your access permissions and might not include all virtual machines. Contact your administrator for full access.", "This node does not have an associated BMC configuration.": "This node does not have an associated BMC configuration.", @@ -792,6 +813,7 @@ "Updating cluster to {{version}}": "Updating cluster to {{version}}", "Uptime": "Uptime", "Use the default browser language setting.": "Use the default browser language setting.", + "Use the label selector above to filter and display PVCs that match your criteria. These PVCs will be used to form the volume group.": "Use the label selector above to filter and display PVCs that match your criteria. These PVCs will be used to form the volume group.", "Used capacity": "Used capacity", "User": "User", "User Management": "User Management", @@ -817,6 +839,16 @@ "Volume Snapshot is not Ready": "Volume Snapshot is not Ready", "Volume type": "Volume type", "VolumeAttributesClasses": "VolumeAttributesClasses", + "VolumeGroupSnapshot": "VolumeGroupSnapshot", + "VolumeGroupSnapshot details": "VolumeGroupSnapshot details", + "VolumeGroupSnapshotClass": "VolumeGroupSnapshotClass", + "VolumeGroupSnapshotClass details": "VolumeGroupSnapshotClass details", + "VolumeGroupSnapshotClass with same provisioner as the selected PVCs": "VolumeGroupSnapshotClass with same provisioner as the selected PVCs", + "VolumeGroupSnapshotClasses": "VolumeGroupSnapshotClasses", + "VolumeGroupSnapshotContent": "VolumeGroupSnapshotContent", + "VolumeGroupSnapshotContent details": "VolumeGroupSnapshotContent details", + "VolumeGroupSnapshotContents": "VolumeGroupSnapshotContents", + "VolumeGroupSnapshots": "VolumeGroupSnapshots", "VolumeSnapshot": "VolumeSnapshot", "VolumeSnapshot details": "VolumeSnapshot details", "VolumeSnapshotClass": "VolumeSnapshotClass", diff --git a/frontend/packages/console-app/package.json b/frontend/packages/console-app/package.json index 9e2d2ce008c..acf7529edbd 100644 --- a/frontend/packages/console-app/package.json +++ b/frontend/packages/console-app/package.json @@ -45,6 +45,7 @@ "prometheusProvider": "src/actions/providers/prometheus-provider.ts", "groupProvider": "src/actions/providers/group-provider.ts", "volumeSnapshotProvider": "src/actions/providers/volume-snaphot-provider.ts", + "volumeGroupSnapshotProvider": "src/actions/providers/volume-group-snapshot-provider.ts", "volumeAttributesClassProvider": "src/actions/providers/volumeattributesclass-provider.ts", "vacPlatformSupport": "src/features/vac-platform-support.ts", "canListSecrets": "src/features/can-list-secrets.ts", @@ -91,6 +92,8 @@ "volumeSnapshotPage": "src/components/volume-snapshot/volume-snapshot.tsx", "volumeSnapshotContent": "src/components/volume-snapshot/volume-snapshot-content.tsx", "volumeSnapshotContentDetails": "src/components/volume-snapshot/volume-snapshot-content-details.tsx", + "volumeGroupSnapshotContent": "src/components/volume-group-snapshot/volume-group-snapshot-content.tsx", + "volumeGroupSnapshotContentDetails": "src/components/volume-group-snapshot/volume-group-snapshot-content-details.tsx", "ConsoleOperatorConfig": "src/components/console-operator/ConsoleOperatorConfig.tsx", "ConsolePluginsListPage": "src/components/console-operator/ConsolePluginsTable.tsx", "UserPreferencePage": "src/components/user-preferences/UserPreferencePage.tsx", diff --git a/frontend/packages/console-app/src/actions/providers/volume-group-snapshot-provider.ts b/frontend/packages/console-app/src/actions/providers/volume-group-snapshot-provider.ts new file mode 100644 index 00000000000..49bd83b20d2 --- /dev/null +++ b/frontend/packages/console-app/src/actions/providers/volume-group-snapshot-provider.ts @@ -0,0 +1,16 @@ +import { useTranslation } from 'react-i18next'; +import type { VolumeGroupSnapshotKind } from '@console/internal/module/k8s'; +import { referenceFor } from '@console/internal/module/k8s'; +import { useK8sModel } from '@console/shared/src/hooks/useK8sModel'; +import { useCommonResourceActions } from '../hooks/useCommonResourceActions'; + +export const useVolumeGroupSnapshotActionsProvider = (resource: VolumeGroupSnapshotKind) => { + const { t } = useTranslation('console-app'); + const [kindObj, inFlight] = useK8sModel(referenceFor(resource)); + const deleteMessage = t( + 'Deleting this VolumeGroupSnapshot will also delete all VolumeSnapshots that belong to this group.', + ); + const commonActions = useCommonResourceActions(kindObj, resource, deleteMessage); + + return [commonActions, !inFlight, undefined]; +}; diff --git a/frontend/packages/console-app/src/components/access-modes/access-mode.tsx b/frontend/packages/console-app/src/components/access-modes/access-mode.tsx index 42fac504693..522cd21c4db 100644 --- a/frontend/packages/console-app/src/components/access-modes/access-mode.tsx +++ b/frontend/packages/console-app/src/components/access-modes/access-mode.tsx @@ -77,9 +77,10 @@ export const AccessModeSelector: FC = (props) => { }, [accessMode, onChange]); const [isOpen, setIsOpen] = useState(false); - const [selected, setSelected] = useState( - getAccessModeOptions().find((mode) => mode.value === pvcInitialAccessMode[0])?.title ?? '', - ); + // Derived from accessMode (rather than tracked separately) so the toggle label + // always reflects the real selection, including when accessMode is auto-picked + // above from data that only becomes available after this component first mounts. + const selected = getAccessModeOptions().find((mode) => mode.value === accessMode)?.title ?? ''; const onToggleClick = () => { setIsOpen(!isOpen); @@ -87,7 +88,6 @@ export const AccessModeSelector: FC = (props) => { const onSelect = (_event: undefined, value: { val: string; label: string }) => { setIsOpen(!isOpen); - setSelected(value.label); setAccessMode(value.val); }; const selectOptions = getAccessModeOptions().map((option) => { diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/_create-volume-group-snapshot.scss b/frontend/packages/console-app/src/components/volume-group-snapshot/_create-volume-group-snapshot.scss new file mode 100644 index 00000000000..fb1089d5615 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/_create-volume-group-snapshot.scss @@ -0,0 +1,3 @@ +.co-volume-group-snapshot__body { + display: block; +} diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/create-volume-group-snapshot.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/create-volume-group-snapshot.tsx new file mode 100644 index 00000000000..6437ade634d --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/create-volume-group-snapshot.tsx @@ -0,0 +1,323 @@ +import type { FC, FormEvent } from 'react'; +import { useCallback, useMemo, useState } from 'react'; +import { ActionGroup, Button, Form, FormGroup, TextInput } from '@patternfly/react-core'; +import { useTranslation } from 'react-i18next'; +import { useNavigate, useParams } from 'react-router'; +import { ButtonBar } from '@console/internal/components/utils/button-bar'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { ListDropdown } from '@console/internal/components/utils/list-dropdown'; +import { resourceObjPath } from '@console/internal/components/utils/resource-link'; +import { SelectorInput } from '@console/internal/components/utils/selector-input'; +import { + PersistentVolumeClaimModel, + StorageClassModel, + VolumeGroupSnapshotClassModel, + VolumeGroupSnapshotModel, +} from '@console/internal/models'; +import type { + PersistentVolumeClaimKind, + StorageClassResourceKind, + VolumeGroupSnapshotClassKind, + VolumeGroupSnapshotKind, +} from '@console/internal/module/k8s'; +import { + apiVersionForModel, + k8sCreate, + referenceFor, + referenceForModel, +} from '@console/internal/module/k8s'; +import { DocumentTitle } from '@console/shared/src/components/document-title/DocumentTitle'; +import { PageHeading } from '@console/shared/src/components/heading/PageHeading'; +import PaneBody from '@console/shared/src/components/layout/PaneBody'; +import { LinkTo } from '@console/shared/src/components/links/LinkTo'; +import { usePromiseHandler } from '@console/shared/src/hooks/usePromiseHandler'; +import { getAnnotations, getName } from '@console/shared/src/selectors/common'; +import './_create-volume-group-snapshot.scss'; +import { PVCTable } from './pvc-table'; + +const defaultGroupSnapshotClassAnnotation = 'groupsnapshot.storage.kubernetes.io/is-default-class'; +const isDefaultGroupSnapshotClass = (vgsClass: VolumeGroupSnapshotClassKind) => + getAnnotations(vgsClass, { defaultGroupSnapshotClassAnnotation: 'false' })[ + defaultGroupSnapshotClassAnnotation + ] === 'true'; + +const VolumeGroupSnapshotClassDropdown: FC = (props) => { + const { selectedKey, filter } = props; + const kind = referenceForModel(VolumeGroupSnapshotClassModel); + const resources = [{ kind }]; + const { t } = useTranslation('console-app'); + return ( + + ); +}; + +const CreateGroupSnapshotForm: FC = ({ namespace }) => { + const { t } = useTranslation('console-app'); + const navigate = useNavigate(); + const handleCancel = useCallback(() => navigate(-1), [navigate]); + const [handlePromise, inProgress, errorMessage] = usePromiseHandler(); + + const [groupSnapshotName, setGroupSnapshotName] = useState('group-snapshot'); + const [groupSnapshotClassName, setGroupSnapshotClassName] = useState(''); + const [selectorTags, setSelectorTags] = useState([]); + + const matchLabels = useMemo( + () => SelectorInput.objectify(selectorTags) as { [key: string]: string }, + [selectorTags], + ); + + const pvcWatch = useMemo( + () => ({ + kind: PersistentVolumeClaimModel.kind, + isList: true, + namespace, + selector: selectorTags.length > 0 ? { matchLabels } : undefined, + }), + [namespace, selectorTags, matchLabels], + ); + + const [filteredPVCs, pvcsLoaded, pvcsLoadError] = + useK8sWatchResource(pvcWatch); + + const [storageClasses, storageClassesLoaded, storageClassesLoadError] = useK8sWatchResource< + StorageClassResourceKind[] + >({ + kind: StorageClassModel.kind, + isList: true, + }); + + const getProvisioner = useCallback( + (storageClassName: string): string | undefined => + storageClasses.find((sc) => getName(sc) === storageClassName)?.provisioner, + [storageClasses], + ); + + const provisioners = useMemo( + () => + new Set( + filteredPVCs + .map((pvc) => getProvisioner(pvc.spec?.storageClassName)) + .filter((provisioner): provisioner is string => Boolean(provisioner)), + ), + [filteredPVCs, getProvisioner], + ); + + // True until every matched PVC's StorageClass/provisioner is actually known, so the + // validation below (and the Create button) don't treat a still-loading or failed + // StorageClass watch as "all PVCs share one provisioner". + const hasUnresolvedProvisioner = useMemo( + () => + !storageClassesLoaded || + !!storageClassesLoadError || + filteredPVCs.some((pvc) => !getProvisioner(pvc.spec?.storageClassName)), + [filteredPVCs, getProvisioner, storageClassesLoaded, storageClassesLoadError], + ); + + // Only known when every matched PVC shares the same provisioner; used to filter + // VolumeGroupSnapshotClass options the same way the single-PVC VolumeSnapshot form + // filters VolumeSnapshotClass options by the source PVC's provisioner. + const provisioner = provisioners.size === 1 ? [...provisioners][0] : undefined; + + const validationError = useMemo(() => { + if (!pvcsLoaded || pvcsLoadError || selectorTags.length === 0 || filteredPVCs.length <= 1) { + return undefined; + } + return provisioners.size > 1 + ? t( + 'Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.', + ) + : undefined; + }, [filteredPVCs, pvcsLoaded, pvcsLoadError, provisioners, selectorTags.length, t]); + + const loadErrorMessage = + pvcsLoadError instanceof Error ? pvcsLoadError.message : (pvcsLoadError as string); + const storageClassesLoadErrorMessage = + storageClassesLoadError instanceof Error + ? storageClassesLoadError.message + : (storageClassesLoadError as string); + + const [vgsClasses, vgsClassesLoaded, vgsClassesLoadError] = useK8sWatchResource< + VolumeGroupSnapshotClassKind[] + >({ + groupVersionKind: { + group: VolumeGroupSnapshotClassModel.apiGroup, + kind: VolumeGroupSnapshotClassModel.kind, + version: VolumeGroupSnapshotClassModel.apiVersion, + }, + isList: true, + }); + const vgsClassesLoadErrorMessage = + vgsClassesLoadError instanceof Error + ? vgsClassesLoadError.message + : (vgsClassesLoadError as string); + + const vgsClassFilter = useCallback( + (vgsClass: VolumeGroupSnapshotClassKind) => !provisioner || provisioner === vgsClass.driver, + [provisioner], + ); + + const compatibleVgsClasses = useMemo( + () => vgsClasses.filter(vgsClassFilter), + [vgsClasses, vgsClassFilter], + ); + + // Once the matched PVCs' provisioner is known, fall back to a compatible + // VolumeGroupSnapshotClass (preferring the one marked default) whenever the + // user's explicit selection is empty or no longer compatible, instead of + // storing this derived value in state. + const selectedVgsClassIsCompatible = compatibleVgsClasses.some( + (vgsClass) => getName(vgsClass) === groupSnapshotClassName, + ); + const effectiveGroupSnapshotClassName = + selectedVgsClassIsCompatible || !provisioner + ? groupSnapshotClassName + : getName(compatibleVgsClasses.find(isDefaultGroupSnapshotClass)) || + getName(compatibleVgsClasses[0]) || + ''; + + const create = (event: FormEvent) => { + event.preventDefault(); + if (inProgress || !pvcsLoaded || pvcsLoadError) { + return; + } + const groupSnapshot: VolumeGroupSnapshotKind = { + apiVersion: apiVersionForModel(VolumeGroupSnapshotModel), + kind: VolumeGroupSnapshotModel.kind, + metadata: { + name: groupSnapshotName, + namespace, + }, + spec: { + volumeGroupSnapshotClassName: effectiveGroupSnapshotClassName, + source: { + selector: { matchLabels }, + }, + }, + }; + + handlePromise(k8sCreate(VolumeGroupSnapshotModel, groupSnapshot)) + .then((resource) => { + navigate(resourceObjPath(resource, referenceFor(resource))); + }) + .catch(() => {}); + }; + + const title = t('Create VolumeGroupSnapshot'); + + return ( +
+ {title} + + +
+ + setGroupSnapshotName(value)} + /> + + + + + +

+ {t( + 'Select PVCs in the {{namespace}} namespace using label selectors to form a volume group to take VolumeGroupSnapshots.', + { namespace }, + )} +

+ 0 ? filteredPVCs : []} + selectorTags={selectorTags} + setSelectorTags={setSelectorTags} + loaded={pvcsLoaded} + loadError={pvcsLoadError} + /> +
+ + + + + + +
+
+
+ ); +}; + +export const VolumeGroupSnapshot: FC = () => { + const params = useParams(); + return ; +}; + +type SnapshotClassDropdownProps = { + selectedKey: string; + filter: (vgsClass: VolumeGroupSnapshotClassKind) => boolean; + onChange: (key: string) => void; + id?: string; + dataTest?: string; +}; + +type SnapshotResourceProps = { + namespace: string; +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-resource-viewer.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-resource-viewer.tsx new file mode 100644 index 00000000000..bf6c68fa81e --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-resource-viewer.tsx @@ -0,0 +1,180 @@ +import type { FC } from 'react'; +import { useMemo, useState } from 'react'; +import { + Button, + ButtonVariant, + Modal, + ModalBody, + ModalHeader, + ModalVariant, + Popover, + SearchInput, + Stack, + StackItem, +} from '@patternfly/react-core'; +import { useTranslation } from 'react-i18next'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { PersistentVolumeClaimModel } from '@console/internal/models'; +import { referenceForModel } from '@console/internal/module/k8s'; + +type MorePVCViewerProps = { + limit: number; + pvcNames: string[]; + namespace: string; + isOpen?: boolean; + onClose?: () => void; +}; + +type PVCResourceViewerProps = { + limit: number; + pvcNames: string[]; + asList?: boolean; + namespace: string; +}; + +const PVCResourceViewerBody: FC> = ({ + pvcNames, + namespace, +}) => ( + + {pvcNames.map((pvcName) => ( + + + + ))} + +); + +const MorePVCViewer: FC = ({ pvcNames, namespace, isOpen, onClose }) => { + const { t } = useTranslation('console-app'); + const [searchValue, setSearchValue] = useState(''); + + const filteredPVCs = useMemo( + () => + searchValue + ? pvcNames.filter((pvcName) => pvcName.toLowerCase().includes(searchValue.toLowerCase())) + : pvcNames, + [pvcNames, searchValue], + ); + + const resultsCount = searchValue ? filteredPVCs.length : 0; + + const onChange = (newValue: string) => { + setSearchValue(newValue); + }; + + const onClear = () => { + setSearchValue(''); + }; + + return ( + + + +
+ onChange(value)} + onClear={onClear} + resultsCount={resultsCount} + /> +
+ +
+
+ ); +}; + +export const PVCResourceViewer: FC = ({ + limit, + pvcNames, + asList, + namespace, +}) => { + const { t } = useTranslation('console-app'); + const [isVisible, setIsVisible] = useState(false); + const [isModalOpen, setIsModalOpen] = useState(false); + + const handleModalToggle = () => { + setIsModalOpen((prevIsModalOpen) => !prevIsModalOpen); + setIsVisible(false); + }; + + const onClose = () => { + setIsModalOpen(false); + setIsVisible(false); + }; + + if (asList) { + return ( + <> + + + + + {limit < pvcNames.length && ( + + + + )} + + + + ); + } + + return ( + <> + setIsVisible(true)} + shouldClose={() => setIsVisible(false)} + aria-label="pvc-resource-viewer" + headerContent={
{t('Source PVCs')}
} + bodyContent={ + + } + footerContent={ + limit < pvcNames.length ? ( + + ) : null + } + > + +
+ + + ); +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-table.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-table.tsx new file mode 100644 index 00000000000..e0d521fb482 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/pvc-table.tsx @@ -0,0 +1,112 @@ +import type { FC } from 'react'; +import { EmptyState, EmptyStateBody, FormGroup } from '@patternfly/react-core'; +import { RhStandardAlertIcon, RhStandardBoxIcon } from '@patternfly/react-icons'; +import { Table, Tbody, Td, Th, Thead, Tr } from '@patternfly/react-table'; +import { useTranslation } from 'react-i18next'; +import { ResourceIcon } from '@console/internal/components/utils/resource-icon'; +import { SelectorInput } from '@console/internal/components/utils/selector-input'; +import { PersistentVolumeClaimModel, StorageClassModel } from '@console/internal/models'; +import type { PersistentVolumeClaimKind } from '@console/internal/module/k8s'; + +type PVCTableProps = { + pvcObjs: PersistentVolumeClaimKind[]; + selectorTags: string[]; + setSelectorTags: (tags: string[]) => void; + loaded: boolean; + loadError?: unknown; +}; + +export const PVCTable: FC = ({ + pvcObjs, + selectorTags, + setSelectorTags, + loaded, + loadError, +}) => { + const { t } = useTranslation('console-app'); + + const loadErrorMessage = loadError instanceof Error ? loadError.message : (loadError as string); + + return ( + <> + + + + {loadError ? ( + + + {loadErrorMessage || + t('There was an error loading the PersistentVolumeClaims. Please try again.')} + + + ) : ( + loaded && ( + <> +
+ + + + + + + + + + + + {pvcObjs.length > 0 ? ( + pvcObjs.map((pvc) => ( + + + + + + + + )) + ) : ( + + + + )} + +
{t('PVC name')}{t('Status')}{t('Storage class')}{t('Volume mode')}{t('Requested capacity')}
+ + {pvc.metadata?.name} + {pvc.status?.phase || '-'} + + {pvc.spec?.storageClassName || '-'} + {pvc.spec?.volumeMode || '-'} + {pvc.spec?.resources?.requests?.storage || '-'} +
+ + + {t( + 'Use the label selector above to filter and display PVCs that match your criteria. These PVCs will be used to form the volume group.', + )} + + +
+
+ {pvcObjs.length > 0 && ( +

+ {t( + '{{numberOf}} PVCs are selected to form the volume group for VolumeGroupSnapshots.', + { numberOf: pvcObjs.length }, + )} +

+ )} + + ) + )} + + ); +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class-details.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class-details.tsx new file mode 100644 index 00000000000..ca8d043b5d0 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class-details.tsx @@ -0,0 +1,77 @@ +import type { FC } from 'react'; +import { + DescriptionListDescription, + DescriptionListGroup, + DescriptionListTerm, + Grid, + GridItem, +} from '@patternfly/react-core'; +import { useTranslation } from 'react-i18next'; +import { ResourceEventStream } from '@console/internal/components/events'; +import type { DetailsPageProps } from '@console/internal/components/factory'; +import { DetailsPage } from '@console/internal/components/factory'; +import { ResourceSummary } from '@console/internal/components/utils/details-page'; +import { SectionHeading } from '@console/internal/components/utils/headings'; +import { navFactory } from '@console/internal/components/utils/horizontal-nav'; +import type { VolumeGroupSnapshotClassKind } from '@console/internal/module/k8s'; +import { referenceForModel } from '@console/internal/module/k8s'; +import { ActionServiceProvider } from '@console/shared/src/components/actions/ActionServiceProvider'; +import { ActionMenu } from '@console/shared/src/components/actions/menu/ActionMenu'; +import { ActionMenuVariant } from '@console/shared/src/components/actions/types'; +import PaneBody from '@console/shared/src/components/layout/PaneBody'; + +const { editYaml, events } = navFactory; + +const Details: FC = ({ obj }) => { + const { t } = useTranslation('console-app'); + return ( + + + + + + + {t('Driver')} + {obj?.driver} + + + {t('Deletion policy')} + {obj?.deletionPolicy} + + + + + + ); +}; + +export const VolumeGroupSnapshotClassDetailsPage: FC = (props) => { + const pages = [ + { + href: '', + // t('console-app~Details') + nameKey: 'console-app~Details', + component: Details, + }, + editYaml(), + events(ResourceEventStream), + ]; + const customActionMenu = (kindObj, obj) => { + const resourceKind = referenceForModel(kindObj); + const context = { [resourceKind]: obj }; + return ( + + {({ actions, options, loaded }) => + loaded && ( + + ) + } + + ); + }; + return ; +}; + +type DetailsProps = { + obj: VolumeGroupSnapshotClassKind; +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class.tsx new file mode 100644 index 00000000000..81d235b9d94 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-class.tsx @@ -0,0 +1,175 @@ +import type { FC } from 'react'; +import { useMemo, Suspense } from 'react'; +import type { TFunction } from 'i18next'; +import { useTranslation } from 'react-i18next'; +import { ConsoleDataView } from '@console/app/src/components/data-view/ConsoleDataView'; +import type { + ConsoleDataViewColumn, + GetDataViewRows, +} from '@console/dynamic-plugin-sdk/src/extensions/console-types'; +import { + ListPageBody, + ListPageCreate, + ListPageHeader, +} from '@console/dynamic-plugin-sdk/src/lib-core'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { VolumeGroupSnapshotClassModel } from '@console/internal/models'; +import type { VolumeGroupSnapshotClassKind, Selector } from '@console/internal/module/k8s'; +import { referenceForModel } from '@console/internal/module/k8s'; +import { LoadingBox } from '@console/shared/src/components/loading/LoadingBox'; +import { DASH } from '@console/shared/src/constants/ui'; +import { getAnnotations } from '@console/shared/src/selectors/common'; + +const kind = referenceForModel(VolumeGroupSnapshotClassModel); + +const tableColumnInfo = [{ id: 'name' }, { id: 'driver' }, { id: 'deletionPolicy' }, { id: '' }]; + +const defaultSnapshotClassAnnotation = 'groupsnapshot.storage.kubernetes.io/is-default-class'; + +const isDefaultSnapshotClass = (volumeGroupSnapshotClass: VolumeGroupSnapshotClassKind) => + getAnnotations(volumeGroupSnapshotClass, { defaultSnapshotClassAnnotation: 'false' })[ + defaultSnapshotClassAnnotation + ] === 'true'; + +const getDataViewRowsCreator: (t: TFunction) => GetDataViewRows = + (t) => (data, columns) => + data.map(({ obj }) => { + const name = obj.metadata?.name || ''; + const { deletionPolicy, driver } = obj; + + const rowCells = { + [tableColumnInfo[0].id]: { + cell: ( + + {isDefaultSnapshotClass(obj) && ( + + – {t('console-app~Default')} + + )} + + ), + }, + [tableColumnInfo[1].id]: { + cell: driver, + }, + [tableColumnInfo[2].id]: { + cell: deletionPolicy, + }, + }; + + return columns.map(({ id }) => { + if (id === tableColumnInfo[3].id) return { id }; + const cell = rowCells[id]?.cell || DASH; + return { + id, + cell, + }; + }); + }); + +const useVolumeGroupSnapshotClassColumns = (): { + columns: ConsoleDataViewColumn[]; +} => { + const { t } = useTranslation('console-app'); + + const columns: ConsoleDataViewColumn[] = useMemo( + () => [ + { + type: 'name' as const, + id: tableColumnInfo[0].id, + }, + { + title: t('Driver'), + sort: 'driver', + id: tableColumnInfo[1].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('Deletion policy'), + sort: 'deletionPolicy', + id: tableColumnInfo[2].id, + props: { modifier: 'nowrap' as const }, + }, + { type: 'actions' as const, id: tableColumnInfo[3].id }, + ], + [t], + ); + + return { columns }; +}; + +const VolumeGroupSnapshotClassTable: FC = ({ + data, + loaded, + ...props +}) => { + const { t } = useTranslation('console-app'); + const { columns } = useVolumeGroupSnapshotClassColumns(); + const getDataViewRows = useMemo(() => getDataViewRowsCreator(t), [t]); + + return ( + }> + + {...props} + id={VolumeGroupSnapshotClassModel} + label={VolumeGroupSnapshotClassModel.labelPlural} + data={data} + loaded={loaded} + columns={columns} + getDataViewRows={getDataViewRows} + /> + + ); +}; + +export const VolumeGroupSnapshotClassPage: FC = ({ + canCreate = true, + showTitle = true, + namespace, + selector, +}) => { + const { t } = useTranslation('console-app'); + + const [resources, loaded, loadError] = useK8sWatchResource({ + groupVersionKind: { + group: VolumeGroupSnapshotClassModel.apiGroup, + kind: VolumeGroupSnapshotClassModel.kind, + version: VolumeGroupSnapshotClassModel.apiVersion, + }, + isList: true, + namespaced: true, + namespace, + selector, + }); + + return ( + <> + + {canCreate && ( + + {t('Create VolumeGroupSnapshotClass')} + + )} + + + + + + ); +}; + +type VolumeGroupSnapshotClassPageProps = { + namespace?: string; + canCreate?: boolean; + showTitle?: boolean; + selector?: Selector; +}; + +type VolumeGroupSnapshotClassTableProps = { + data: VolumeGroupSnapshotClassKind[]; + loaded: boolean; + loadError: unknown; +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content-details.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content-details.tsx new file mode 100644 index 00000000000..21b60f8de34 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content-details.tsx @@ -0,0 +1,121 @@ +import type { FC } from 'react'; +import { + DescriptionList, + DescriptionListDescription, + DescriptionListGroup, + DescriptionListTerm, + Grid, + GridItem, +} from '@patternfly/react-core'; +import { useTranslation } from 'react-i18next'; +import { ResourceEventStream } from '@console/internal/components/events'; +import type { DetailsPageProps } from '@console/internal/components/factory'; +import { DetailsPage } from '@console/internal/components/factory'; +import { ResourceSummary } from '@console/internal/components/utils/details-page'; +import { SectionHeading } from '@console/internal/components/utils/headings'; +import { navFactory } from '@console/internal/components/utils/horizontal-nav'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { VolumeGroupSnapshotClassModel, VolumeGroupSnapshotModel } from '@console/internal/models'; +import type { VolumeGroupSnapshotContentKind } from '@console/internal/module/k8s'; +import { referenceForModel } from '@console/internal/module/k8s'; +import PaneBody from '@console/shared/src/components/layout/PaneBody'; +import { Status } from '@console/shared/src/components/status/Status'; +import { groupSnapshotStatus } from '@console/shared/src/sorts/snapshot'; + +const { editYaml, events } = navFactory; + +const Details: FC = ({ obj }) => { + const { t } = useTranslation('console-app'); + const deletionPolicy = obj?.spec?.deletionPolicy || ''; + const driver = obj?.spec?.driver || ''; + const { volumeHandles, groupSnapshotHandles } = obj?.spec?.source || {}; + const { name: snapshotName, namespace: snapshotNamespace } = + obj?.spec?.volumeGroupSnapshotRef || {}; + + return ( + + + + + + + {t('Status')} + + + + + + + + + + {t('VolumeGroupSnapshot')} + + + + + + {t('VolumeGroupSnapshotClass')} + + + + + + {t('Deletion policy')} + {deletionPolicy} + + + {t('Driver')} + {driver} + + {volumeHandles && ( + + {t('Volume handle')} + + {volumeHandles.map((handle) => ( +
{handle}
+ ))} +
+
+ )} + {groupSnapshotHandles && ( + + {t('GroupSnapshot handle')} + + {groupSnapshotHandles.volumeGroupSnapshotHandle} + + + )} +
+
+
+
+ ); +}; + +const VolumeGroupSnapshotContentDetailsPage: FC = (props) => { + const pages = [ + { + href: '', + // t('console-app~Details') + nameKey: 'console-app~Details', + component: Details, + }, + editYaml(), + events(ResourceEventStream), + ]; + return ; +}; + +type DetailsProps = { + obj: VolumeGroupSnapshotContentKind; +}; + +export default VolumeGroupSnapshotContentDetailsPage; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content.tsx new file mode 100644 index 00000000000..bc844f533bd --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-content.tsx @@ -0,0 +1,196 @@ +import type { FC } from 'react'; +import { useMemo, Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ConsoleDataView } from '@console/app/src/components/data-view/ConsoleDataView'; +import type { + ConsoleDataViewColumn, + GetDataViewRows, +} from '@console/dynamic-plugin-sdk/src/extensions/console-types'; +import { + ListPageBody, + ListPageCreate, + ListPageHeader, +} from '@console/dynamic-plugin-sdk/src/lib-core'; +import { sortResourceByValue } from '@console/internal/components/factory/Table/sort'; +import type { PageComponentProps } from '@console/internal/components/utils/horizontal-nav'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { + VolumeGroupSnapshotModel, + VolumeGroupSnapshotClassModel, + VolumeGroupSnapshotContentModel, +} from '@console/internal/models'; +import type { VolumeGroupSnapshotContentKind } from '@console/internal/module/k8s'; +import { referenceForModel } from '@console/internal/module/k8s'; +import { Timestamp } from '@console/shared/src/components/datetime/Timestamp'; +import { LoadingBox } from '@console/shared/src/components/loading/LoadingBox'; +import { Status } from '@console/shared/src/components/status/Status'; +import { DASH } from '@console/shared/src/constants/ui'; +import { groupSnapshotStatus } from '@console/shared/src/sorts/snapshot'; + +const kind = referenceForModel(VolumeGroupSnapshotContentModel); + +const tableColumnInfo = [ + { id: 'name' }, + { id: 'status' }, + { id: 'volumeGroupSnapshot' }, + { id: 'snapshotClass' }, + { id: 'createdAt' }, + { id: '' }, +]; + +const getDataViewRows: GetDataViewRows = (data, columns) => + data.map(({ obj }) => { + const name = obj.metadata?.name || ''; + const creationTimestamp = obj.metadata?.creationTimestamp || ''; + const snapshotName = obj.spec?.volumeGroupSnapshotRef?.name || ''; + const snapshotNamespace = obj.spec?.volumeGroupSnapshotRef?.namespace || ''; + + const rowCells = { + [tableColumnInfo[0].id]: { + cell: , + }, + [tableColumnInfo[1].id]: { + cell: , + }, + [tableColumnInfo[2].id]: { + cell: ( + + ), + }, + [tableColumnInfo[3].id]: { + cell: ( + + ), + }, + [tableColumnInfo[4].id]: { + cell: , + }, + }; + + return columns.map(({ id }) => { + if (id === tableColumnInfo[5].id) return { id }; + const cell = rowCells[id]?.cell || DASH; + return { + id, + cell, + }; + }); + }); + +const useVolumeGroupSnapshotContentColumns = (): { + columns: ConsoleDataViewColumn[]; +} => { + const { t } = useTranslation('console-app'); + + const columns: ConsoleDataViewColumn[] = useMemo( + () => [ + { + type: 'name' as const, + id: tableColumnInfo[0].id, + }, + { + title: t('Status'), + sort: (data, direction) => data.sort(sortResourceByValue(direction, groupSnapshotStatus)), + id: tableColumnInfo[1].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('VolumeGroupSnapshot'), + sort: 'spec.volumeGroupSnapshotRef.name', + id: tableColumnInfo[2].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('SnapshotClass'), + sort: 'spec.volumeGroupSnapshotClassName', + id: tableColumnInfo[3].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('Created at'), + sort: 'metadata.creationTimestamp', + id: tableColumnInfo[4].id, + props: { modifier: 'nowrap' as const }, + }, + { type: 'actions' as const, id: tableColumnInfo[5].id }, + ], + [t], + ); + + return { columns }; +}; + +const VolumeGroupSnapshotContentTable: FC = ({ + data, + loaded, + ...props +}) => { + const { columns } = useVolumeGroupSnapshotContentColumns(); + + return ( + }> + + {...props} + id={VolumeGroupSnapshotContentModel} + label={VolumeGroupSnapshotContentModel.labelPlural} + data={data} + loaded={loaded} + columns={columns} + getDataViewRows={getDataViewRows} + /> + + ); +}; + +const VolumeGroupSnapshotContentPage: FC = ({ + showTitle = true, + canCreate = true, +}) => { + const { t } = useTranslation('console-app'); + + const [resources, loaded, loadError] = useK8sWatchResource({ + groupVersionKind: { + group: VolumeGroupSnapshotContentModel.apiGroup, + kind: VolumeGroupSnapshotContentModel.kind, + version: VolumeGroupSnapshotContentModel.apiVersion, + }, + isList: true, + }); + + return ( + <> + + {canCreate && ( + + {t('Create VolumeGroupSnapshotContent')} + + )} + + + + + + ); +}; + +type VolumeGroupSnapshotContentPageProps = { + canCreate?: boolean; +} & PageComponentProps; + +type VolumeGroupSnapshotContentTableProps = { + data: VolumeGroupSnapshotContentKind[]; + loaded: boolean; + loadError: unknown; +}; + +export default VolumeGroupSnapshotContentPage; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-details.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-details.tsx new file mode 100644 index 00000000000..fd23655e82d --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot-details.tsx @@ -0,0 +1,173 @@ +import type { FC } from 'react'; +import { useMemo } from 'react'; +import { + DescriptionList, + DescriptionListDescription, + DescriptionListGroup, + DescriptionListTerm, + Grid, + GridItem, +} from '@patternfly/react-core'; +import { useTranslation } from 'react-i18next'; +import { ResourceEventStream } from '@console/internal/components/events'; +import type { DetailsPageProps } from '@console/internal/components/factory'; +import { DetailsPage } from '@console/internal/components/factory'; +import { ResourceSummary } from '@console/internal/components/utils/details-page'; +import { SectionHeading } from '@console/internal/components/utils/headings'; +import { navFactory } from '@console/internal/components/utils/horizontal-nav'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { + VolumeGroupSnapshotClassModel, + VolumeGroupSnapshotContentModel, + VolumeSnapshotModel, +} from '@console/internal/models'; +import type { VolumeGroupSnapshotKind, VolumeSnapshotKind } from '@console/internal/module/k8s'; +import { referenceFor, referenceForModel } from '@console/internal/module/k8s'; +import { ActionServiceProvider } from '@console/shared/src/components/actions/ActionServiceProvider'; +import { ActionMenu } from '@console/shared/src/components/actions/menu/ActionMenu'; +import { ActionMenuVariant } from '@console/shared/src/components/actions/types'; +import PaneBody from '@console/shared/src/components/layout/PaneBody'; +import { Status } from '@console/shared/src/components/status/Status'; +import { FLAGS } from '@console/shared/src/constants/common'; +import { useFlag } from '@console/shared/src/hooks/useFlag'; +import { groupSnapshotStatus } from '@console/shared/src/sorts/snapshot'; +import { PVCResourceViewer } from './pvc-resource-viewer'; + +const { editYaml, events } = navFactory; + +const Details: FC = ({ obj }) => { + const { t } = useTranslation('console-app'); + const name = obj?.metadata?.name || ''; + const namespace = obj?.metadata?.namespace || ''; + + const snapshotContent = obj?.status?.boundVolumeGroupSnapshotContentName; + const snapshotClass = obj?.spec?.volumeGroupSnapshotClassName; + + const canListVGSC = useFlag(FLAGS.CAN_LIST_VGSC); + + const [volumeSnapshots, loaded, loadError] = useK8sWatchResource({ + groupVersionKind: { + group: VolumeSnapshotModel.apiGroup, + kind: VolumeSnapshotModel.kind, + version: VolumeSnapshotModel.apiVersion, + }, + isList: true, + namespaced: true, + namespace, + }); + + // Derive group membership from the actual bound VolumeSnapshots (via ownerReferences) + // instead of re-evaluating spec.source.selector client-side, so this reflects what the + // backend actually snapshotted rather than what the selector was intended to match. + const pvcNames = useMemo( + () => + loaded && !loadError + ? volumeSnapshots + .filter((vs) => + vs?.metadata?.ownerReferences?.some( + (ref) => ref.kind === 'VolumeGroupSnapshot' && ref.name === name, + ), + ) + .map((vs) => vs?.spec?.source?.persistentVolumeClaimName) + .filter(Boolean) + : [], + [volumeSnapshots, loaded, loadError, name], + ); + + return ( + + + + + + + {t('Status')} + + + + + + + + + + {t('Source')} + + {loaded && !loadError && ( + + )} + + + {canListVGSC && ( + + {t('VolumeGroupSnapshotContent')} + + {snapshotContent ? ( + + ) : ( + '-' + )} + + + )} + + {t('VolumeGroupSnapshotClass')} + + {snapshotClass ? ( + + ) : ( + '-' + )} + + + + + + + ); +}; + +export const VolumeGroupSnapshotDetailsPage: FC = (props) => { + const pages = [ + { + href: '', + // t('console-app~Details') + nameKey: 'console-app~Details', + component: Details, + }, + editYaml(), + events(ResourceEventStream), + ]; + const customActionMenu = (_, obj: VolumeGroupSnapshotKind) => { + const resourceKind = referenceFor(obj); + const context = { [resourceKind]: obj }; + return ( + + {({ actions, options, loaded }) => + loaded && ( + + ) + } + + ); + }; + return ( + + ); +}; + +type DetailsProps = { + obj: VolumeGroupSnapshotKind; +}; diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot.tsx new file mode 100644 index 00000000000..e8e4b411675 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/volume-group-snapshot.tsx @@ -0,0 +1,343 @@ +import type { FC } from 'react'; +import { useMemo, useCallback, Suspense } from 'react'; +import { DataViewCheckboxFilter } from '@patternfly/react-data-view'; +import type { DataViewFilterOption } from '@patternfly/react-data-view/dist/esm/DataViewFilters'; +import { useTranslation } from 'react-i18next'; +import { ConsoleDataView } from '@console/app/src/components/data-view/ConsoleDataView'; +import type { + ConsoleDataViewColumn, + ResourceFilters, + GetDataViewRows, +} from '@console/dynamic-plugin-sdk/src/extensions/console-types'; +import { + ListPageBody, + ListPageHeader, + ListPageCreateLink, +} from '@console/dynamic-plugin-sdk/src/lib-core'; +import { sortResourceByValue } from '@console/internal/components/factory/Table/sort'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { ResourceLink } from '@console/internal/components/utils/resource-link'; +import { + NamespaceModel, + VolumeGroupSnapshotModel, + VolumeGroupSnapshotClassModel, + VolumeGroupSnapshotContentModel, + VolumeSnapshotModel, +} from '@console/internal/models'; +import type { + VolumeGroupSnapshotKind, + VolumeSnapshotKind, + Selector, +} from '@console/internal/module/k8s'; +import { referenceForModel } from '@console/internal/module/k8s'; +import { Timestamp } from '@console/shared/src/components/datetime/Timestamp'; +import { LoadingBox } from '@console/shared/src/components/loading/LoadingBox'; +import { Status } from '@console/shared/src/components/status/Status'; +import { FLAGS } from '@console/shared/src/constants/common'; +import { DASH } from '@console/shared/src/constants/ui'; +import { useFlag } from '@console/shared/src/hooks/useFlag'; +import { groupSnapshotStatus } from '@console/shared/src/sorts/snapshot'; +import { PVCResourceViewer } from './pvc-resource-viewer'; + +const kind = referenceForModel(VolumeGroupSnapshotModel); + +const tableColumnInfo = [ + { id: 'name' }, + { id: 'namespace' }, + { id: 'status' }, + { id: 'source' }, + { id: 'snapshotContent' }, + { id: 'snapshotClass' }, + { id: 'createdAt' }, + { id: '' }, +]; + +const GroupSnapshotSource: FC<{ name: string; namespace: string }> = ({ name, namespace }) => { + const [volumeSnapshots, loaded, loadError] = useK8sWatchResource({ + groupVersionKind: { + group: VolumeSnapshotModel.apiGroup, + kind: VolumeSnapshotModel.kind, + version: VolumeSnapshotModel.apiVersion, + }, + isList: true, + namespaced: true, + namespace, + }); + + // Derive group membership from the actual bound VolumeSnapshots (via ownerReferences) + // instead of re-evaluating spec.source.selector client-side, so this reflects what the + // backend actually snapshotted rather than what the selector was intended to match. + const pvcNames = useMemo( + () => + loaded && !loadError + ? volumeSnapshots + .filter((vs) => + vs?.metadata?.ownerReferences?.some( + (ref) => ref.kind === 'VolumeGroupSnapshot' && ref.name === name, + ), + ) + .map((vs) => vs?.spec?.source?.persistentVolumeClaimName) + .filter(Boolean) + : [], + [volumeSnapshots, loaded, loadError, name], + ); + + if (!loaded || loadError) { + return <>{DASH}; + } + + return ; +}; + +const getDataViewRows: GetDataViewRows = ( + data, + columns, +) => + data.map(({ obj, rowData: { hideSnapshotContentColumn } }) => { + const name = obj.metadata?.name || ''; + const namespace = obj.metadata?.namespace || ''; + const creationTimestamp = obj.metadata?.creationTimestamp || ''; + const snapshotContent = obj.status?.boundVolumeGroupSnapshotContentName; + const snapshotClass = obj.spec?.volumeGroupSnapshotClassName; + + const rowCells = { + [tableColumnInfo[0].id]: { + cell: , + }, + [tableColumnInfo[1].id]: { + cell: , + }, + [tableColumnInfo[2].id]: { + cell: , + }, + [tableColumnInfo[3].id]: { + cell: , + }, + [tableColumnInfo[4].id]: { + cell: snapshotContent ? ( + + ) : ( + DASH + ), + disabled: hideSnapshotContentColumn, + }, + [tableColumnInfo[5].id]: { + cell: snapshotClass ? ( + + ) : ( + DASH + ), + }, + [tableColumnInfo[6].id]: { + cell: , + }, + }; + + return columns + .filter(({ id }) => !rowCells[id]?.disabled) + .map(({ id }) => { + if (id === tableColumnInfo[7].id) return { id }; + const cell = rowCells[id]?.cell || DASH; + return { + id, + cell, + }; + }); + }); + +const useVolumeGroupSnapshotColumns = ( + rowData: VolumeGroupSnapshotRowData, +): { columns: ConsoleDataViewColumn[] } => { + const { t } = useTranslation('console-app'); + + const columns: ConsoleDataViewColumn[] = useMemo( + () => + [ + { + type: 'name' as const, + id: tableColumnInfo[0].id, + }, + { + type: 'namespace' as const, + id: tableColumnInfo[1].id, + }, + { + title: t('Status'), + sort: (data, direction) => data.sort(sortResourceByValue(direction, groupSnapshotStatus)), + id: tableColumnInfo[2].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('Source'), + id: tableColumnInfo[3].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('GroupSnapshot content'), + sort: 'status.boundVolumeGroupSnapshotContentName', + id: tableColumnInfo[4].id, + props: { modifier: 'nowrap' as const }, + disabled: rowData.hideSnapshotContentColumn, + }, + { + title: t('VolumeGroupSnapshotClass'), + sort: 'spec.volumeGroupSnapshotClassName', + id: tableColumnInfo[5].id, + props: { modifier: 'nowrap' as const }, + }, + { + title: t('Created at'), + sort: 'metadata.creationTimestamp', + id: tableColumnInfo[6].id, + props: { modifier: 'nowrap' as const }, + }, + { type: 'actions' as const, id: tableColumnInfo[7].id }, + ].filter((c) => !c.disabled), + [t, rowData.hideSnapshotContentColumn], + ); + + return { columns }; +}; + +const VolumeGroupSnapshotTable: FC = ({ + data, + loaded, + ...props +}) => { + const { t } = useTranslation('console-app'); + const canListVGSC = useFlag(FLAGS.CAN_LIST_VGSC); + + const customRowData: VolumeGroupSnapshotRowData = { + hideSnapshotContentColumn: !canListVGSC, + }; + + const { columns } = useVolumeGroupSnapshotColumns(customRowData); + + const snapshotStatusFilterOptions = useMemo( + () => [ + { + value: 'Ready', + label: t('Ready'), + }, + { + value: 'Pending', + label: t('Pending'), + }, + { + value: 'Error', + label: t('Error'), + }, + ], + [t], + ); + + const initialFilters = useMemo(() => ({ status: [] }), []); + + const additionalFilterNodes = useMemo( + () => [ + , + ], + [t, snapshotStatusFilterOptions], + ); + + const matchesAdditionalFilters = useCallback( + (resource: VolumeGroupSnapshotKind, filters: VolumeGroupSnapshotFilters) => { + if (filters.status.length > 0) { + const status = groupSnapshotStatus(resource); + if (!filters.status.includes(status)) { + return false; + } + } + + return true; + }, + [], + ); + + return ( + }> + + {...props} + id={VolumeGroupSnapshotModel} + label={VolumeGroupSnapshotModel.labelPlural} + data={data} + loaded={loaded} + columns={columns} + getDataViewRows={getDataViewRows} + customRowData={customRowData} + initialFilters={initialFilters} + additionalFilterNodes={additionalFilterNodes} + matchesAdditionalFilters={matchesAdditionalFilters} + /> + + ); +}; + +export const VolumeGroupSnapshotPage: FC = ({ + canCreate = true, + showTitle = true, + namespace, + selector, +}) => { + const { t } = useTranslation('console-app'); + + const createPath = `/k8s/ns/${namespace || 'default'}/${VolumeGroupSnapshotModel.plural}/~new/form`; + + const [resources, loaded, loadError] = useK8sWatchResource({ + groupVersionKind: { + group: VolumeGroupSnapshotModel.apiGroup, + kind: VolumeGroupSnapshotModel.kind, + version: VolumeGroupSnapshotModel.apiVersion, + }, + isList: true, + namespaced: true, + namespace, + selector, + }); + + return ( + <> + + {canCreate && ( + {t('Create VolumeGroupSnapshot')} + )} + + + + + + ); +}; + +type VolumeGroupSnapshotFilters = ResourceFilters & { + status: string[]; +}; + +type VolumeGroupSnapshotPageProps = { + namespace?: string; + canCreate?: boolean; + showTitle?: boolean; + selector?: Selector; +}; + +type VolumeGroupSnapshotTableProps = { + data: VolumeGroupSnapshotKind[]; + loaded: boolean; + loadError: unknown; +}; + +type VolumeGroupSnapshotRowData = { + hideSnapshotContentColumn?: boolean; +}; diff --git a/frontend/packages/console-shared/src/constants/common.ts b/frontend/packages/console-shared/src/constants/common.ts index 9d3a30072f2..76408915400 100644 --- a/frontend/packages/console-shared/src/constants/common.ts +++ b/frontend/packages/console-shared/src/constants/common.ts @@ -73,6 +73,7 @@ export enum FLAGS { CAN_LIST_PACKAGE_MANIFEST = 'CAN_LIST_PACKAGE_MANIFEST', CAN_CREATE_PROJECT = 'CAN_CREATE_PROJECT', CAN_LIST_VSC = 'CAN_LIST_VSC', + CAN_LIST_VGSC = 'CAN_LIST_VGSC', CLUSTER_AUTOSCALER = 'CLUSTER_AUTOSCALER', SHOW_OPENSHIFT_START_GUIDE = 'SHOW_OPENSHIFT_START_GUIDE', CLUSTER_API = 'CLUSTER_API', diff --git a/frontend/packages/console-shared/src/sorts/snapshot.ts b/frontend/packages/console-shared/src/sorts/snapshot.ts index 78b70d8bbe5..ce322059579 100644 --- a/frontend/packages/console-shared/src/sorts/snapshot.ts +++ b/frontend/packages/console-shared/src/sorts/snapshot.ts @@ -1,5 +1,6 @@ import { convertToBaseValue } from '@console/internal/components/utils/units'; import type { + VolumeGroupSnapshotStatus, VolumeSnapshotContentKind, VolumeSnapshotKind, VolumeSnapshotStatus, @@ -11,6 +12,12 @@ export const snapshotStatus = ({ status }: { status?: VolumeSnapshotStatus }): s return readyToUse ? 'Ready' : isError ? 'Error' : 'Pending'; }; +export const groupSnapshotStatus = ({ status }: { status?: VolumeGroupSnapshotStatus }): string => { + const readyToUse = status?.readyToUse; + const isError = !!status?.error?.message; + return readyToUse ? 'Ready' : isError ? 'Error' : 'Pending'; +}; + export const snapshotSize = (snapshot: VolumeSnapshotKind): number => { const size = snapshot?.status?.restoreSize; return size ? convertToBaseValue(size) : 0; diff --git a/frontend/public/actions/flags.ts b/frontend/public/actions/flags.ts index 181e60e9376..7d341302f5a 100644 --- a/frontend/public/actions/flags.ts +++ b/frontend/public/actions/flags.ts @@ -8,7 +8,12 @@ import { k8sBasePath } from '@console/dynamic-plugin-sdk/src/utils/k8s/k8s'; import type { K8sModel } from '@console/internal/module/k8s'; import { FLAGS } from '@console/shared/src/constants/common'; import { coFetchJSON } from '@console/shared/src/utils/console-fetch'; -import { GroupModel, UserModel, VolumeSnapshotContentModel } from '../models'; +import { + GroupModel, + UserModel, + VolumeGroupSnapshotContentModel, + VolumeSnapshotContentModel, +} from '../models'; export enum ActionType { SetFlag = 'setFlag', @@ -140,6 +145,14 @@ export const ssarChecks = [ verb: 'list', }, }, + { + flag: FLAGS.CAN_LIST_VGSC, + resourceAttributes: { + group: VolumeGroupSnapshotContentModel.apiGroup, + resource: VolumeGroupSnapshotContentModel.plural, + verb: 'list', + }, + }, ]; export const clearSSARFlags = () => diff --git a/frontend/public/components/app-contents.tsx b/frontend/public/components/app-contents.tsx index 4cd10ac1d79..d91fc7e96a1 100644 --- a/frontend/public/components/app-contents.tsx +++ b/frontend/public/components/app-contents.tsx @@ -19,6 +19,7 @@ import { AlertmanagerModel, CronJobModel, HorizontalPodAutoscalerModel, + VolumeGroupSnapshotModel, VolumeSnapshotModel, } from '../models'; import { referenceForModel } from '../module/k8s'; @@ -500,6 +501,28 @@ const AppContents: FC = () => { } /> + + import( + '@console/app/src/components/volume-group-snapshot/create-volume-group-snapshot' /* webpackChunkName: "create-volume-group-snapshot" */ + ).then((m) => m.VolumeGroupSnapshot) + } + /> + } + /> + + } + /> + = new Map() import( '@console/app/src/components/volume-snapshot/volume-snapshot-class' /* webpackChunkName: "volume-snapshot-class" */ ).then((m) => m.VolumeSnapshotClassPage), + ) + .set(referenceForModel(VolumeGroupSnapshotModel), () => + import( + '@console/app/src/components/volume-group-snapshot/volume-group-snapshot' /* webpackChunkName: "volume-group-snapshot" */ + ).then((m) => m.VolumeGroupSnapshotPage), + ) + .set(referenceForModel(VolumeGroupSnapshotClassModel), () => + import( + '@console/app/src/components/volume-group-snapshot/volume-group-snapshot-class' /* webpackChunkName: "volume-group-snapshot-class" */ + ).then((m) => m.VolumeGroupSnapshotClassPage), ); export const getResourceListPages = (pluginPages: ResourceListPage[] = []) => { diff --git a/frontend/public/components/resource-pages.ts b/frontend/public/components/resource-pages.ts index 64b86855f83..6c8bb072e69 100644 --- a/frontend/public/components/resource-pages.ts +++ b/frontend/public/components/resource-pages.ts @@ -45,6 +45,8 @@ import { VolumeAttributesClassModel, TemplateInstanceModel, UserModel, + VolumeGroupSnapshotModel, + VolumeGroupSnapshotClassModel, VolumeSnapshotModel, VolumeSnapshotClassModel, ClusterRoleBindingModel, @@ -283,6 +285,16 @@ const baseDetailsPages: Map = new Map() import( '@console/app/src/components/volume-snapshot/volume-snapshot-class-details' /* webpackChunkName: "volume-snapshot-class-details" */ ).then((m) => m.VolumeSnapshotClassDetailsPage), + ) + .set(referenceForModel(VolumeGroupSnapshotModel), () => + import( + '@console/app/src/components/volume-group-snapshot/volume-group-snapshot-details' /* webpackChunkName: "volume-group-snapshot-details" */ + ).then((m) => m.VolumeGroupSnapshotDetailsPage), + ) + .set(referenceForModel(VolumeGroupSnapshotClassModel), () => + import( + '@console/app/src/components/volume-group-snapshot/volume-group-snapshot-class-details' /* webpackChunkName: "volume-group-snapshot-class-details" */ + ).then((m) => m.VolumeGroupSnapshotClassDetailsPage), ); export const getResourceDetailsPages = (pluginPages: ResourceDetailsPage[] = []) => { diff --git a/frontend/public/locales/en/public.json b/frontend/public/locales/en/public.json index 671d68c23a3..099abc1bff6 100644 --- a/frontend/public/locales/en/public.json +++ b/frontend/public/locales/en/public.json @@ -1764,6 +1764,12 @@ "VolumeAttributesClass modification failed. Your volume settings could not be updated. Please try again.": "VolumeAttributesClass modification failed. Your volume settings could not be updated. Please try again.", "VolumeAttributesClass modification in progress": "VolumeAttributesClass modification in progress", "VolumeAttributesClasses": "VolumeAttributesClasses", + "VolumeGroupSnapshot": "VolumeGroupSnapshot", + "VolumeGroupSnapshotClass": "VolumeGroupSnapshotClass", + "VolumeGroupSnapshotClasses": "VolumeGroupSnapshotClasses", + "VolumeGroupSnapshotContent": "VolumeGroupSnapshotContent", + "VolumeGroupSnapshotContents": "VolumeGroupSnapshotContents", + "VolumeGroupSnapshots": "VolumeGroupSnapshots", "Volumes": "Volumes", "Volumes allow data to be shared as files with the pod": "Volumes allow data to be shared as files with the pod", "VolumeSnapshot": "VolumeSnapshot", diff --git a/frontend/public/models/index.ts b/frontend/public/models/index.ts index 44d72c88391..32faa5f49e3 100644 --- a/frontend/public/models/index.ts +++ b/frontend/public/models/index.ts @@ -1217,6 +1217,57 @@ export const VolumeSnapshotContentModel: K8sKind = { crd: true, }; +export const VolumeGroupSnapshotModel: K8sKind = { + label: 'VolumeGroupSnapshot', + // t('public~VolumeGroupSnapshot') + labelKey: 'public~VolumeGroupSnapshot', + apiVersion: 'v1', + apiGroup: 'groupsnapshot.storage.k8s.io', + plural: 'volumegroupsnapshots', + abbr: 'VGS', + namespaced: true, + kind: 'VolumeGroupSnapshot', + id: 'volumegroupsnapshot', + labelPlural: 'VolumeGroupSnapshots', + // t('public~VolumeGroupSnapshots') + labelPluralKey: 'public~VolumeGroupSnapshots', + crd: true, +}; + +export const VolumeGroupSnapshotClassModel: K8sKind = { + label: 'VolumeGroupSnapshotClass', + // t('public~VolumeGroupSnapshotClass') + labelKey: 'public~VolumeGroupSnapshotClass', + apiVersion: 'v1', + apiGroup: 'groupsnapshot.storage.k8s.io', + plural: 'volumegroupsnapshotclasses', + abbr: 'VGSC', + namespaced: false, + kind: 'VolumeGroupSnapshotClass', + id: 'volumegroupsnapshotclass', + labelPlural: 'VolumeGroupSnapshotClasses', + // t('public~VolumeGroupSnapshotClasses') + labelPluralKey: 'public~VolumeGroupSnapshotClasses', + crd: true, +}; + +export const VolumeGroupSnapshotContentModel: K8sKind = { + label: 'VolumeGroupSnapshotContent', + // t('public~VolumeGroupSnapshotContent') + labelKey: 'public~VolumeGroupSnapshotContent', + apiVersion: 'v1', + apiGroup: 'groupsnapshot.storage.k8s.io', + plural: 'volumegroupsnapshotcontents', + abbr: 'VGSC', + namespaced: false, + kind: 'VolumeGroupSnapshotContent', + id: 'volumegroupsnapshotcontent', + labelPlural: 'VolumeGroupSnapshotContents', + // t('public~VolumeGroupSnapshotContents') + labelPluralKey: 'public~VolumeGroupSnapshotContents', + crd: true, +}; + export const ConsolePluginModel: K8sKind = { label: 'ConsolePlugin', // t('public~ConsolePlugin') diff --git a/frontend/public/module/k8s/types.ts b/frontend/public/module/k8s/types.ts index c96f6e1844a..fa1d9d0a3d7 100644 --- a/frontend/public/module/k8s/types.ts +++ b/frontend/public/module/k8s/types.ts @@ -1067,6 +1067,82 @@ export type VolumeSnapshotClassKind = K8sResourceCommon & { driver: string; }; +type VolumeGroupSnapshotLabelSelector = { + matchLabels?: { + [key: string]: string; + }; + matchExpressions?: { + key: string; + operator: string; + values?: string[]; + }[]; +}; + +export type VolumeGroupSnapshotStatus = { + boundVolumeGroupSnapshotContentName?: string; + readyToUse?: boolean; + creationTime?: string; + error?: { + message?: string; + time?: string; + }; +}; + +export type VolumeGroupSnapshotKind = K8sResourceCommon & { + spec: { + volumeGroupSnapshotClassName?: string; + source: { + selector?: VolumeGroupSnapshotLabelSelector; + volumeGroupSnapshotContentName?: string; + }; + }; + status?: VolumeGroupSnapshotStatus; +}; + +type VolumeSnapshotHandlePair = { + volumeHandle: string; + snapshotHandle: string; +}; + +type VolumeGroupSnapshotContentStatus = { + readyToUse?: boolean; + creationTime?: string; + volumeGroupSnapshotHandle?: string; + volumeSnapshotHandlePairList?: VolumeSnapshotHandlePair[]; + error?: { + message?: string; + time?: string; + }; +}; + +export type VolumeGroupSnapshotContentKind = K8sResourceCommon & { + spec: { + deletionPolicy: 'Delete' | 'Retain'; + driver: string; + volumeGroupSnapshotClassName?: string; + volumeGroupSnapshotRef: { + name: string; + namespace: string; + }; + source: { + volumeHandles?: string[]; + groupSnapshotHandles?: { + volumeGroupSnapshotHandle: string; + volumeSnapshotHandles: string[]; + }; + }; + }; + status?: VolumeGroupSnapshotContentStatus; +}; + +export type VolumeGroupSnapshotClassKind = K8sResourceCommon & { + deletionPolicy: 'Delete' | 'Retain'; + driver: string; + parameters?: { + [key: string]: string; + }; +}; + export type PersistentVolumeClaimKind = K8sResourceCommon & { spec: { accessModes: string[]; From 0de60e8465546e30e51fe1bdcfa44bb2190248c8 Mon Sep 17 00:00:00 2001 From: Daniel Fajmon Date: Mon, 16 Nov 2026 16:33:33 +0100 Subject: [PATCH 2/2] STOR-2991: Add test coverage for VolumeGroupSnapshot No tests existed for VGS (unit or e2e). Add both. - Unit: create-form provisioner filtering/fallback (including an exact-vs-substring driver match regression case), mixed-provisioner validation, submit-disabled states (including a stale-cached-PVCs- plus-watch-error case), matchLabels-not-matchExpressions payload. - E2E: create/list/delete via label selector + mixed-provisioner validation blocks submit. Discovers a StorageClass whose provisioner matches an existing VolumeGroupSnapshotClass's driver (one with deletionPolicy Delete, so repeated runs don't leak cluster-scoped content) instead of assuming one works, since group-snapshot support isn't implied by the CRDs or by platform; the API-available check also confirms the CRD actually serves v1, and both discovery helpers propagate real API errors instead of treating them as "unsupported cluster". Mixed-provisioner fixture uses two throwaway StorageClasses so it doesn't depend on any real class, and skips if the groupsnapshot.storage.k8s.io CRDs aren't installed. - Update the featureReducer default-state test for the new CAN_LIST_VGSC flag. Co-Authored-By: Claude Sonnet 5 --- frontend/e2e/mocks/storage.ts | 196 +++++++++++++ .../storage/volume-group-snapshot.spec.ts | 172 ++++++++++++ .../create-volume-group-snapshot.spec.tsx | 259 ++++++++++++++++++ .../reducers/__tests__/features.spec.tsx | 1 + 4 files changed, 628 insertions(+) create mode 100644 frontend/e2e/tests/console/storage/volume-group-snapshot.spec.ts create mode 100644 frontend/packages/console-app/src/components/volume-group-snapshot/__tests__/create-volume-group-snapshot.spec.tsx diff --git a/frontend/e2e/mocks/storage.ts b/frontend/e2e/mocks/storage.ts index a369d65fb59..a66a56d5871 100644 --- a/frontend/e2e/mocks/storage.ts +++ b/frontend/e2e/mocks/storage.ts @@ -1,3 +1,5 @@ +import { isNotFound } from '../clients/kubernetes-client'; + export const testerDeployment = { apiVersion: 'apps/v1', kind: 'Deployment', @@ -257,6 +259,105 @@ export const getVACFixtures = (suffix: string) => { }; }; +// --- VolumeGroupSnapshot fixtures --- + +export const getVGSFixtures = (suffix: string, groupSnapshotStorageClassName: string) => { + const names = { + TEST_PVC_A: `vgs-testpvc-a-${suffix}`, + TEST_PVC_B: `vgs-testpvc-b-${suffix}`, + TEST_PVC_MIXED_A: `vgs-mixed-pvc-a-${suffix}`, + TEST_PVC_MIXED_B: `vgs-mixed-pvc-b-${suffix}`, + TEST_FAKE_STORAGECLASS_A: `vgs-fake-sc-a-${suffix}`, + TEST_FAKE_STORAGECLASS_B: `vgs-fake-sc-b-${suffix}`, + TEST_DEPLOYMENT: `vgs-tester-deployment-${suffix}`, + }; + + const makePVC = (name: string, storageClassName: string, labels: Record) => ({ + apiVersion: 'v1', + kind: 'PersistentVolumeClaim', + metadata: { name, labels }, + spec: { + storageClassName, + accessModes: ['ReadWriteOnce'], + resources: { requests: { storage: '1Gi' } }, + }, + }); + + return { + ...names, + // Two PVCs on the same StorageClass/provisioner, for the happy-path group snapshot. + // The caller discovers groupSnapshotStorageClassName from an existing + // VolumeGroupSnapshotClass on the cluster (see findGroupSnapshotCapableStorageClass), + // since not every StorageClass's CSI driver actually implements group snapshots. + PVC_SAME_PROVISIONER_A: makePVC(names.TEST_PVC_A, groupSnapshotStorageClassName, { + 'vgs-test': 'true', + }), + PVC_SAME_PROVISIONER_B: makePVC(names.TEST_PVC_B, groupSnapshotStorageClassName, { + 'vgs-test': 'true', + }), + // Two PVCs on two throwaway StorageClasses with distinct fake provisioners, so the + // create form's mixed-provisioner validation is exercised without depending on any + // real StorageClass existing on the cluster. Neither needs to be Bound: the + // validation only inspects the matched PVCs' declared StorageClass/provisioner. + PVC_MIXED_FAKE_PROVISIONER_A: makePVC(names.TEST_PVC_MIXED_A, names.TEST_FAKE_STORAGECLASS_A, { + 'vgs-mixed-test': 'true', + }), + PVC_MIXED_FAKE_PROVISIONER_B: makePVC(names.TEST_PVC_MIXED_B, names.TEST_FAKE_STORAGECLASS_B, { + 'vgs-mixed-test': 'true', + }), + FAKE_STORAGE_CLASS_A: { + apiVersion: 'storage.k8s.io/v1', + kind: 'StorageClass', + metadata: { name: names.TEST_FAKE_STORAGECLASS_A }, + provisioner: 'csi.fake-a.example.com', + }, + FAKE_STORAGE_CLASS_B: { + apiVersion: 'storage.k8s.io/v1', + kind: 'StorageClass', + metadata: { name: names.TEST_FAKE_STORAGECLASS_B }, + provisioner: 'csi.fake-b.example.com', + }, + getDeployment: (namespace: string, pvcNames: string[]) => ({ + apiVersion: 'apps/v1', + kind: 'Deployment', + metadata: { name: names.TEST_DEPLOYMENT, namespace }, + spec: { + replicas: 1, + selector: { matchLabels: { app: names.TEST_DEPLOYMENT } }, + template: { + metadata: { labels: { app: names.TEST_DEPLOYMENT } }, + spec: { + securityContext: { + runAsNonRoot: true, + seccompProfile: { type: 'RuntimeDefault' }, + }, + containers: [ + { + name: 'busybox', + image: 'busybox', + imagePullPolicy: 'IfNotPresent', + securityContext: { + allowPrivilegeEscalation: false, + capabilities: { drop: ['ALL'] }, + }, + command: ['sh', '-c', 'echo Container is Running ; sleep 3600'], + volumeMounts: pvcNames.map((pvcName, i) => ({ + name: `vol-${i}`, + mountPath: `/data-${i}`, + })), + }, + ], + volumes: pvcNames.map((pvcName, i) => ({ + name: `vol-${i}`, + persistentVolumeClaim: { claimName: pvcName }, + })), + }, + }, + }, + }), + }; +}; + export async function isAwsPlatform( k8sClient: import('../clients/kubernetes-client').default, ): Promise { @@ -268,3 +369,98 @@ export async function isAwsPlatform( )) as any; return infra?.status?.platformStatus?.type === 'AWS'; } + +/** + * Whether the groupsnapshot.storage.k8s.io v1 CRDs are installed. Unlike + * findGroupSnapshotCapableStorageClass, this doesn't require a working CSI + * driver/snapshot-controller - just that the API itself is served, which is + * all UI-only tests (e.g. form validation) that never create a real + * VolumeGroupSnapshot need. + */ +export async function isGroupSnapshotApiAvailable( + k8sClient: import('../clients/kubernetes-client').default, +): Promise { + let crd: { spec?: { versions?: { name: string; served: boolean }[] } } | null; + try { + crd = (await k8sClient.getClusterCustomResource( + 'apiextensions.k8s.io', + 'v1', + 'customresourcedefinitions', + 'volumegroupsnapshotclasses.groupsnapshot.storage.k8s.io', + )) as { spec?: { versions?: { name: string; served: boolean }[] } }; + } catch (err) { + // Only a genuine 404 means the CRD isn't installed. Any other failure (permissions, + // 503, etc.) shouldn't be silently treated as "unsupported cluster" - that masks a + // real problem behind a skipped test instead of a failure. + if (isNotFound(err)) { + return false; + } + throw err; + } + return !!crd?.spec?.versions?.some((version) => version.name === 'v1' && version.served); +} + +/** + * Like k8sClient.listClusterCustomResources, but propagates failures instead of treating + * every error (permissions, 503, etc.) as "no items". A genuine 404 (the resource type + * itself doesn't exist) still returns an empty list, since that's a real "not installed" + * signal. + */ +async function listClusterCustomResourcesStrict( + k8sClient: import('../clients/kubernetes-client').default, + group: string, + version: string, + plural: string, +): Promise { + try { + const response = await k8sClient.customObjectsApi.listClusterCustomObject({ + group, + plural, + version, + }); + return (response as any)?.items || []; + } catch (err) { + if (isNotFound(err)) { + return []; + } + throw err; + } +} + +/** + * Finds a StorageClass whose provisioner matches the driver of an existing + * VolumeGroupSnapshotClass. Group-snapshot support depends on the CSI driver/ + * snapshot-controller sidecar having the CSIVolumeGroupSnapshot feature gate + * enabled, which isn't implied by the CRDs being installed or by any particular + * platform, so this discovers a combination the cluster has actually been + * configured with rather than assuming one. + */ +export async function findGroupSnapshotCapableStorageClass( + k8sClient: import('../clients/kubernetes-client').default, +): Promise<{ storageClassName: string; vgsClassName: string } | null> { + const vgsClasses = (await listClusterCustomResourcesStrict( + k8sClient, + 'groupsnapshot.storage.k8s.io', + 'v1', + 'volumegroupsnapshotclasses', + )) as { metadata: { name: string }; driver: string; deletionPolicy: string }[]; + if (vgsClasses.length === 0) { + return null; + } + const storageClasses = (await listClusterCustomResourcesStrict( + k8sClient, + 'storage.k8s.io', + 'v1', + 'storageclasses', + )) as { metadata: { name: string }; provisioner: string }[]; + // Require Delete so the member VolumeSnapshots/content this test creates don't outlive + // namespace deletion (Retain would leak cluster-scoped VolumeGroupSnapshotContent and + // backend snapshot storage across test runs). + for (const vgsClass of vgsClasses.filter((c) => c.deletionPolicy === 'Delete')) { + const storageClass = storageClasses.find((sc) => sc.provisioner === vgsClass.driver); + if (storageClass) { + return { storageClassName: storageClass.metadata.name, vgsClassName: vgsClass.metadata.name }; + } + } + return null; +} diff --git a/frontend/e2e/tests/console/storage/volume-group-snapshot.spec.ts b/frontend/e2e/tests/console/storage/volume-group-snapshot.spec.ts new file mode 100644 index 00000000000..61680a0f96d --- /dev/null +++ b/frontend/e2e/tests/console/storage/volume-group-snapshot.spec.ts @@ -0,0 +1,172 @@ +import { test, expect } from '../../../fixtures'; +import { ListPage } from '../../../pages/list-page'; +import { ModalPage } from '../../../pages/modal-page'; +import { + findGroupSnapshotCapableStorageClass, + getVGSFixtures, + isGroupSnapshotApiAvailable, +} from '../../../mocks/storage'; + +const VALIDATION_ERROR = + 'Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.'; + +test.describe('VolumeGroupSnapshot Tests', { tag: ['@admin', '@storage'] }, () => { + test('creates, lists, and deletes a VolumeGroupSnapshot from a label selector', async ({ + page, + k8sClient, + cleanup, + }) => { + // Group-snapshot support depends on a CSI driver/snapshot-controller with the + // CSIVolumeGroupSnapshot feature gate enabled, which isn't implied by the CRDs being + // installed or by any particular platform. Discover a StorageClass/VolumeGroupSnapshotClass + // pairing the cluster has actually been configured with, and skip otherwise. + const capable = await findGroupSnapshotCapableStorageClass(k8sClient); + test.skip( + !capable, + 'No StorageClass with a provisioner matching an existing VolumeGroupSnapshotClass was found', + ); + const { storageClassName, vgsClassName } = capable!; + + const ns = `test-vgs-${Date.now()}`; + const fixtures = getVGSFixtures(`${Date.now()}`, storageClassName); + const { + TEST_PVC_A, + TEST_PVC_B, + PVC_SAME_PROVISIONER_A, + PVC_SAME_PROVISIONER_B, + getDeployment, + } = fixtures; + const vgsName = 'vgs-group-snapshot'; + const listPage = new ListPage(page); + const modal = new ModalPage(page); + + await test.step('Set up namespace and PVCs', async () => { + await k8sClient.createNamespace(ns); + cleanup.trackNamespace(ns); + await k8sClient.createPVC(ns, { + ...PVC_SAME_PROVISIONER_A, + metadata: { ...PVC_SAME_PROVISIONER_A.metadata, namespace: ns }, + } as any); + await k8sClient.createPVC(ns, { + ...PVC_SAME_PROVISIONER_B, + metadata: { ...PVC_SAME_PROVISIONER_B.metadata, namespace: ns }, + } as any); + await k8sClient.createDeployment(ns, getDeployment(ns, [TEST_PVC_A, TEST_PVC_B]) as any); + }); + + await test.step('Wait for both PVCs to be Bound', async () => { + for (const pvcName of [TEST_PVC_A, TEST_PVC_B]) { + await page.goto(`/k8s/ns/${ns}/persistentvolumeclaims`); + await listPage.waitForRows(); + await listPage.filterByName(pvcName); + const pvcRow = listPage.getCell(pvcName).locator('xpath=ancestor::tr'); + await expect(pvcRow.locator('[data-test="status-text"]')).toContainText('Bound', { + timeout: 120_000, + }); + } + }); + + await test.step('Create VolumeGroupSnapshot from a label selector', async () => { + await page.goto(`/k8s/ns/${ns}/groupsnapshot.storage.k8s.io~v1~VolumeGroupSnapshot`); + await listPage.clickCreateButton(); + await page.getByTestId('snapshot-name').fill(vgsName); + await page.getByTestId('tags-input').fill('vgs-test=true'); + await page.getByTestId('tags-input').press('Enter'); + await page.getByTestId('snapshot-class-dropdown').click(); + await page.getByRole('option', { name: vgsClassName }).click(); + await page.locator('#save-changes').click(); + }); + + await test.step('Verify VolumeGroupSnapshot details show the source PVCs', async () => { + await expect(page).toHaveURL( + new RegExp( + `groupsnapshot\\.storage\\.k8s\\.io~v1~VolumeGroupSnapshot/${vgsName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, + ), + ); + await expect(page.getByTestId('page-heading')).toContainText(vgsName); + await expect( + page.getByTestId('resource-summary').locator('[data-test="status-text"]'), + ).toContainText('Ready', { timeout: 120_000 }); + await expect(page.getByTestId(TEST_PVC_A)).toBeVisible(); + await expect(page.getByTestId(TEST_PVC_B)).toBeVisible(); + }); + + await test.step('Verify VolumeGroupSnapshot in list', async () => { + await page.goto(`/k8s/ns/${ns}/groupsnapshot.storage.k8s.io~v1~VolumeGroupSnapshot`); + await listPage.waitForRows(); + await expect(listPage.getCell(vgsName)).toBeVisible({ timeout: 30_000 }); + }); + + await test.step('Delete VolumeGroupSnapshot', async () => { + await listPage.clickKebabAction(vgsName, 'Delete VolumeGroupSnapshot'); + await modal.waitForOpen(); + await expect(modal.getSubmitButton()).toBeEnabled({ timeout: 10_000 }); + await modal.submit(); + await modal.waitForClosed(); + await expect(listPage.getCell(vgsName)).not.toBeAttached({ timeout: 90_000 }); + }); + }); + + test('blocks VolumeGroupSnapshot creation when matched PVCs have different provisioners', async ({ + page, + k8sClient, + cleanup, + }) => { + // The create form watches VolumeGroupSnapshotClass; if the CRDs aren't installed that + // watch errors and the error takes priority over the mismatch message this test checks + // for. This test otherwise doesn't need a working snapshot-capable driver - just the API. + test.skip( + !(await isGroupSnapshotApiAvailable(k8sClient)), + 'groupsnapshot.storage.k8s.io v1 CRDs are not installed on this cluster', + ); + + const ns = `test-vgs-mixed-${Date.now()}`; + // This test only needs PVCs that declare different provisioners; it never creates a + // VolumeGroupSnapshot, so it doesn't depend on any real StorageClass/platform - both + // PVCs use throwaway StorageClasses with distinct fake provisioners. + const fixtures = getVGSFixtures(`${Date.now()}`, 'unused'); + const { + PVC_MIXED_FAKE_PROVISIONER_A, + PVC_MIXED_FAKE_PROVISIONER_B, + FAKE_STORAGE_CLASS_A, + FAKE_STORAGE_CLASS_B, + } = fixtures; + + await test.step('Set up namespace and mismatched-provisioner PVCs', async () => { + await k8sClient.createNamespace(ns); + cleanup.trackNamespace(ns); + for (const fakeStorageClass of [FAKE_STORAGE_CLASS_A, FAKE_STORAGE_CLASS_B]) { + await k8sClient.createClusterCustomResource( + 'storage.k8s.io', + 'v1', + 'storageclasses', + fakeStorageClass as any, + ); + cleanup.trackClusterCustomResource( + fakeStorageClass.metadata.name, + 'storage.k8s.io', + 'v1', + 'storageclasses', + ); + } + await k8sClient.createPVC(ns, { + ...PVC_MIXED_FAKE_PROVISIONER_A, + metadata: { ...PVC_MIXED_FAKE_PROVISIONER_A.metadata, namespace: ns }, + } as any); + await k8sClient.createPVC(ns, { + ...PVC_MIXED_FAKE_PROVISIONER_B, + metadata: { ...PVC_MIXED_FAKE_PROVISIONER_B.metadata, namespace: ns }, + } as any); + }); + + await test.step('Select both PVCs via a label selector and verify validation blocks submit', async () => { + await page.goto(`/k8s/ns/${ns}/volumegroupsnapshots/~new/form`); + await page.getByTestId('snapshot-name').fill('vgs-mixed-provisioner-test'); + await page.getByTestId('tags-input').fill('vgs-mixed-test=true'); + await page.getByTestId('tags-input').press('Enter'); + + await expect(page.getByText(VALIDATION_ERROR)).toBeVisible({ timeout: 30_000 }); + await expect(page.locator('#save-changes')).toBeDisabled(); + }); + }); +}); diff --git a/frontend/packages/console-app/src/components/volume-group-snapshot/__tests__/create-volume-group-snapshot.spec.tsx b/frontend/packages/console-app/src/components/volume-group-snapshot/__tests__/create-volume-group-snapshot.spec.tsx new file mode 100644 index 00000000000..69695edf609 --- /dev/null +++ b/frontend/packages/console-app/src/components/volume-group-snapshot/__tests__/create-volume-group-snapshot.spec.tsx @@ -0,0 +1,259 @@ +import type { ReactNode } from 'react'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { useK8sWatchResource } from '@console/internal/components/utils/k8s-watch-hook'; +import { StorageClassModel, VolumeGroupSnapshotClassModel } from '@console/internal/models'; +import { k8sCreate } from '@console/internal/module/k8s'; +import type { + PersistentVolumeClaimKind, + StorageClassResourceKind, + VolumeGroupSnapshotClassKind, + VolumeGroupSnapshotKind, +} from '@console/internal/module/k8s'; +import { VolumeGroupSnapshot } from '../create-volume-group-snapshot'; + +jest.mock('react-router', () => ({ + ...jest.requireActual('react-router'), + useNavigate: jest.fn(), + useParams: jest.fn(), +})); + +jest.mock('@console/internal/components/utils/k8s-watch-hook', () => ({ + useK8sWatchResource: jest.fn(), +})); + +jest.mock('@console/internal/module/k8s', () => ({ + k8sCreate: jest.fn(), + apiVersionForModel: jest.fn(() => 'groupsnapshot.storage.k8s.io/v1'), + referenceForModel: jest.fn(() => 'groupsnapshot.storage.k8s.io~v1~VolumeGroupSnapshot'), + referenceFor: jest.fn(() => 'groupsnapshot.storage.k8s.io~v1~VolumeGroupSnapshot'), +})); + +jest.mock('@console/shared/src/components/heading/PageHeading', () => ({ + PageHeading: ({ title }: { title: string }) => title, +})); + +jest.mock('@console/internal/components/utils/resource-link', () => ({ + resourceObjPath: jest.fn( + () => '/k8s/ns/test-ns/groupsnapshot.storage.k8s.io~v1~VolumeGroupSnapshot/group-snapshot', + ), +})); + +jest.mock('@console/internal/components/utils/button-bar', () => ({ + ButtonBar: ({ children, errorMessage }: { children: ReactNode; errorMessage?: ReactNode }) => ( + <> + {errorMessage} + {children} + + ), +})); + +jest.mock('@console/internal/components/utils/list-dropdown', () => ({ + ListDropdown: ({ + selectedKey, + onChange, + }: { + selectedKey: string; + onChange: (key: string) => void; + }) => ( +
+ {selectedKey} + + +
+ ), +})); + +jest.mock('../pvc-table', () => ({ + PVCTable: ({ setSelectorTags }: { setSelectorTags: (tags: string[]) => void }) => ( + + ), +})); + +const useK8sWatchResourceMock = useK8sWatchResource as jest.Mock; +const useNavigateMock = jest.requireMock('react-router').useNavigate as jest.Mock; +const useParamsMock = jest.requireMock('react-router').useParams as jest.Mock; +const k8sCreateMock = k8sCreate as jest.Mock; + +const pvc = (name: string, storageClassName: string): PersistentVolumeClaimKind => + ({ + metadata: { uid: name, name }, + spec: { storageClassName }, + }) as PersistentVolumeClaimKind; + +const storageClass = (name: string, provisioner: string): StorageClassResourceKind => + ({ metadata: { name }, provisioner }) as StorageClassResourceKind; + +const vgsClass = ( + name: string, + driver: string, + isDefault?: boolean, +): VolumeGroupSnapshotClassKind => + ({ + metadata: { + name, + annotations: isDefault + ? { 'groupsnapshot.storage.kubernetes.io/is-default-class': 'true' } + : {}, + }, + driver, + }) as VolumeGroupSnapshotClassKind; + +const storageClasses = [ + storageClass('sc-a', 'driver.example.com'), + storageClass('sc-b', 'driver.example.com'), + storageClass('sc-c', 'other-driver.example.com'), + // Provisioner deliberately contains 'driver.example.com' as a substring, to catch a + // vgsClassFilter that uses String.includes instead of exact equality. + storageClass('sc-d', 'csi.driver.example.com'), +]; + +const vgsClasses = [ + vgsClass('compatible-class-a', 'driver.example.com'), + vgsClass('compatible-class-b', 'driver.example.com', true), + vgsClass('incompatible-class', 'other-driver.example.com'), +]; + +const singleProvisionerPVCs = [pvc('pvc-1', 'sc-a'), pvc('pvc-2', 'sc-b')]; +const mixedProvisionerPVCs = [pvc('pvc-1', 'sc-a'), pvc('pvc-2', 'sc-c')]; +const substringProvisionerPVCs = [pvc('pvc-1', 'sc-d')]; + +const setup = (pvcs: PersistentVolumeClaimKind[], pvcsLoadError?: unknown) => { + useK8sWatchResourceMock.mockImplementation( + (resource: { kind?: string; groupVersionKind?: { kind: string } }) => { + if (resource?.kind === StorageClassModel.kind) { + return [storageClasses, true, undefined]; + } + if (resource?.groupVersionKind?.kind === VolumeGroupSnapshotClassModel.kind) { + return [vgsClasses, true, undefined]; + } + return [pvcs, true, pvcsLoadError]; + }, + ); + render(); +}; + +describe('CreateGroupSnapshotForm', () => { + beforeEach(() => { + jest.clearAllMocks(); + useParamsMock.mockReturnValue({ ns: 'test-ns' }); + useNavigateMock.mockReturnValue(jest.fn()); + }); + + it('should select the default-flagged VolumeGroupSnapshotClass compatible with the matched PVCs provisioner', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + + expect(screen.getByTestId('selected-vgsc')).toHaveTextContent('compatible-class-b'); + }); + + it('should keep an explicit compatible class selection instead of reverting to the default', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + await user.click(screen.getByRole('button', { name: 'choose compatible-class-a' })); + + expect(screen.getByTestId('selected-vgsc')).toHaveTextContent('compatible-class-a'); + }); + + it('should fall back to a compatible class when the user picks one with a different provisioner', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + await user.click(screen.getByRole('button', { name: 'choose incompatible-class' })); + + expect(screen.getByTestId('selected-vgsc')).toHaveTextContent('compatible-class-b'); + }); + + it('should not offer a class whose driver is only a substring of the matched provisioner', async () => { + const user = userEvent.setup(); + setup(substringProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + + expect(screen.getByTestId('selected-vgsc')).toBeEmptyDOMElement(); + }); + + it('should show a validation error and disable Create when matched PVCs have different provisioners', async () => { + const user = userEvent.setup(); + setup(mixedProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + + expect( + screen.getByText( + 'Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.', + ), + ).toBeVisible(); + expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled(); + }); + + it('should not show a validation error when no PVCs have been selected yet', () => { + setup(mixedProvisionerPVCs); + + expect( + screen.queryByText( + 'Selected PVCs have different storage provisioners. All PVCs must have StorageClasses with the same provisioner.', + ), + ).not.toBeInTheDocument(); + }); + + it('should disable Create when the name field is cleared even though PVCs and class are valid', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + await user.clear(screen.getByLabelText(/Name/)); + + expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled(); + }); + + it('should enable Create once a name, class, and single-provisioner PVCs are set', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs); + + expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled(); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + + expect(screen.getByRole('button', { name: 'Create' })).toBeEnabled(); + }); + + it('should disable Create when the PVC watch errors, even with otherwise-valid stale cached PVCs', async () => { + const user = userEvent.setup(); + setup(singleProvisionerPVCs, new Error('watch failed')); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + + expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled(); + }); + + it('should create the VolumeGroupSnapshot with a matchLabels selector, never matchExpressions', async () => { + jest.spyOn(console, 'error').mockImplementation(() => {}); + const user = userEvent.setup(); + k8sCreateMock.mockResolvedValue({ + metadata: { name: 'group-snapshot', namespace: 'test-ns' }, + } as VolumeGroupSnapshotKind); + setup(singleProvisionerPVCs); + + await user.click(screen.getByRole('button', { name: 'select PVCs' })); + await user.click(screen.getByRole('button', { name: 'Create' })); + + expect(k8sCreateMock).toHaveBeenCalledTimes(1); + const [, submittedResource] = k8sCreateMock.mock.calls[0]; + expect(submittedResource.spec.source.selector).toStrictEqual({ + matchLabels: { 'vgs-select': 'true' }, + }); + expect(submittedResource.spec.source.selector.matchExpressions).toBeUndefined(); + }); +}); diff --git a/frontend/public/reducers/__tests__/features.spec.tsx b/frontend/public/reducers/__tests__/features.spec.tsx index f624cf4bfc5..b2bbc9744a7 100644 --- a/frontend/public/reducers/__tests__/features.spec.tsx +++ b/frontend/public/reducers/__tests__/features.spec.tsx @@ -29,6 +29,7 @@ describe('featureReducer', () => { CAN_LIST_PACKAGE_MANIFEST: undefined, CAN_CREATE_PROJECT: undefined, CAN_LIST_VSC: undefined, + CAN_LIST_VGSC: undefined, CLUSTER_AUTOSCALER: undefined, SHOW_OPENSHIFT_START_GUIDE: undefined, CLUSTER_API: undefined,