feat(virtual-machine): group a VM's claims for Velero volume group snapshots (#5240)

<!-- Thank you for making a contribution! Here are some tips for you:
- Use Conventional Commits for the PR title: `type(scope): description`
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
- Scopes are not an exhaustive list — pick the most specific scope for
the change and extend the list when a genuinely new area appears.
Examples:
- System components: dashboard, platform, operator, cilium, kube-ovn,
linstor, fluxcd, cluster-api
- Managed apps: postgres, mariadb, redis, kafka, clickhouse,
virtual-machine, kubernetes
- Development and maintenance: api, hack, tests, ci, docs, maintenance
- Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or
add a `BREAKING CHANGE:` footer
- If it's a work in progress, consider creating this PR as a draft.
- Don't hesistate to ask for opinion and review in the community chats,
even if it's still a draft.
- Add the label `kind/backport` if it's a bugfix that needs to be
backported to a previous version.
-->

## What this PR does

An application-consistent Velero backup of a VM freezes the guest,
snapshots its PVCs one after another, then thaws it. Windows holds a VSS
freeze for 10 seconds at most, and on LINSTOR each CSI snapshot takes
about 4 seconds. So a Windows VM with three volumes (system disk, data
disk and the `persistent-state-for-*` claim KubeVirt keeps for TPM/EFI
state) overruns the window: `virt-freezer --unfreeze` fails with
`VSS_E_HOLD_WRITES_TIMEOUT` and the backup is only crash-consistent.
Velero 1.18 snapshots the PVCs that share a `velero.io/volume-group`
value as one VolumeGroupSnapshot, which linstor-csi takes as a single
atomic snapshot.

This adds a `post-install,post-upgrade` hook to `vm-instance` that
labels every claim of the VM with `velero.io/volume-group:
<VirtualMachine name>`. That covers the `vm-disk-<name>` claim of each
disk in `disks`, and the claims KubeVirt labels `persistent-state-for:
<VirtualMachine name>`. The hook also removes the label from claims
still carrying this VM's group once they no longer belong to it (a
detached disk, or a group that can no longer form). A claim grouped
under another VM is left alone.

A `vm-disk-<name>` claim belongs to the `vm-disk` release and outlives
the VM, and the hook leaves out a claim grouped under another VM's name,
so a disk reattached to a replacement VM would otherwise keep its old
group for good. A `pre-delete` hook therefore removes this VM's group
from every claim still carrying it when the release is uninstalled. Helm
runs uninstall hooks from the stored manifest, so that hook is rendered
unconditionally, and it selects the claims at run time with `-l
velero.io/volume-group=<VM>` rather than from a render-time list that
would be stale by then. Its Role needs `list` on the namespace's claims
for that; the removal is the same JSON `test`+`remove` patch, so a claim
another VM grouped in the meantime keeps its group.

Why a hook and not a label in the charts' own manifests:

- CDI copies DataVolume labels to the PVC only when it creates it
(`newPersistentVolumeClaim` in
`pkg/controller/datavolume/controller-base.go`, v1.66.1), so a label
added to an existing VMDisk's DataVolume never reaches its claim.
- A VMDisk is created, and its PVC with it, before any VMInstance names
it, so `vm-disk` cannot know the VM at that point; the disk-to-VM
mapping only exists in `vm-instance` values. `vm-disk` is therefore
unchanged.
- KubeVirt creates the persistent-state PVC with a fixed label set
(`createPVC` in `pkg/storage/backend-storage/backend-storage.go`,
v1.9.0); nothing on the VM or VMI spec adds labels to it.

Velero 1.18.1 has no fallback for a labelled claim it cannot group
(`getVolumeSnapshotReference` in
`pkg/backup/actions/csi/pvc_action.go`). Any of these fails the claim's
backup: an unbound member, two CSI drivers in the group, or anything
other than exactly one VolumeGroupSnapshotClass labelled
`velero.io/csi-volumegroupsnapshot-class: "true"` for the driver. The
hook therefore forms the group only when all of these hold, and removes
the label otherwise:

- the claims are bound and use a single CSI driver;
- at least two of them exist;
- `groupsnapshot.storage.k8s.io/v1beta2` is served;
- exactly one default class serves that driver.

On a cluster without group snapshot support the hook does not render.
That is every cluster on current `main`, which runs snapshot-controller
v8.0.1 with v1alpha1 CRDs. A companion change upgrades
snapshot-controller to v8.7.0, enables the `CSIVolumeGroupSnapshot` gate
on linstor-csi and adds a default VolumeGroupSnapshotClass. This PR does
nothing until something like it lands.

The hook is gated on render-time lookups like `vm-update-hook.yaml`, so
a converged VM renders no Job, and its Role is limited by
`resourceNames` to the claims it patches. Existing VMs are picked up on
their next Helm upgrade, which a Cozystack upgrade that bumps the chart
triggers.

Known limit: the hook labels only the claims the render saw. A
persistent-state claim created after it stays unlabelled until the next
upgrade. That happens on the first boot of a new VM, and on every live
migration, where KubeVirt creates a new RWO claim. Such a claim is
snapshotted on its own, next to one group snapshot of the disks: two
snapshot operations, which still fit the freeze window, as two-volume
VMs show today. Closing that gap needs something that sees every PVC
creation. The lineage webhook is a candidate: it already mutates PVCs on
create and walks the owner graph to the VMInstance. That is left for a
follow-up.

`tests/instancetype_resources_test.yaml` rendered every template, and
the fake client of helm-unittest refuses a list lookup for a kind it
does not register. That suite is therefore scoped to `vm.yaml` and
`vm-update-hook.yaml`, the two templates it covers.
`tests/volume_group_hook_test.yaml` covers labelling, convergence, label
removal, the Job's security context and each gate: API not served, no
default class, two default classes, two drivers, an unbound claim, a
single claim. Each gate was checked to fail its test when removed.

`tests/volume_group_release_hook_test.yaml` pins the uninstall hook's
manifest, and `hack/vm-volume-group-release-hook.bats` runs its script
against a fake kubectl: every claim the VM grouped is released, a
detached disk included, another VM's claim is untouched, a claim
regrouped or deleted between the list and the patch does not fail the
uninstall, and a failed list or a patch that leaves the label in place
does. `tests/volume_group_hook_test.yaml` also covers a differently
named VM grouping the released disks.


### Screenshots

<!-- REQUIRED for UI changes: attach screenshots or screen recordings
demonstrating
the visual impact of your changes. PRs with UI changes without
screenshots will not be merged. -->

### Downstream repositories

<!--
Cozystack is upstream for repositories that are NOT kept in sync with it
automatically, and nothing in CI compares the two sides, so a change
here can break them silently.

Which change forces what, and which file to touch, is the trigger map in
docs/agents/contributing.md under "Downstream Repositories". Walk it
before you tick anything.

IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM
TO FILL IN:

1. Walk the trigger map against the actual diff of this PR, file by
file. Do not decide from the PR title or from your memory of what you
changed.
2. For every repository you tick, open the follow-up PR there and link
it on the same line. A ticked box with no link claims work that does not
exist, which is worse than an empty box. Search that repository for an
open PR or issue covering it first, and link that instead of filing a
duplicate.
3. When the follow-up is out of scope, or needs a decision that is not
yours to make, open an issue in that repository instead, link that, and
say so in the PR body. Do not push a speculative PR into another
repository just to fill a line here.
4. Do not tick "No downstream repository is affected" to make the
checklist go away. If you are unsure, leave every box empty and say so
in the PR body, so a human decides.
-->

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

<!--  Write a release note:
- Explain what has changed internally and for users.
- Start with the same `type(scope):` prefix as in the PR title
- Follow the guidelines at
https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md.
-->

```release-note
feat(virtual-machine): label every PVC of a VMInstance with velero.io/volume-group, so Velero snapshots them as one VolumeGroupSnapshot when the cluster serves groupsnapshot v1beta2 with a default VolumeGroupSnapshotClass for their CSI driver.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* VM disk and persistent-state volumes can now be grouped for snapshots
when the storage provider and snapshot configuration support it.
* Volume grouping is updated automatically as claims change; ineligible
volumes are excluded, and claims assigned to another VM are left
unchanged.
* Grouping is applied only when multiple bound volumes share a supported
storage driver and a matching default snapshot class is available.
* Volumes no longer eligible for the VM’s group are ungrouped, and
missing volumes are safely skipped.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Aleksei Sviridkin authored and GitHub committed 2026-11-23 13:26:04 +03:00
commit afa3dfa224
6 files changed
+1121

No files matched your search

+241
View File
@@ -0,0 +1,241 @@
#!/usr/bin/env bats
# Behavioural tests for the pre-delete hook that releases a VM's Velero volume
# group, packages/apps/vm-instance/templates/volume-group-release-hook.yaml.
#
# A vm-disk-<name> claim belongs to the vm-disk release and outlives the VM.
# Every VM leaves out a claim grouped under another VM's name, so a label left
# behind by a deleted VM keeps the disk out of any replacement VM's group for
# good. The script is extracted from the rendered chart and RUN against a fake
# kubectl holding claim labels on disk, because what matters is the labels it
# leaves and its exit code; the helm-unittest suite in
# packages/apps/vm-instance/tests/ matches the source text instead.
#
# Run from the repo root through `make bats-unit-tests`. Each @test builds and
# removes its fixture inline, and there is no EXIT trap: see
# docs/agents/e2e-testing.md.
load test_helper
VM_CHART=packages/apps/vm-instance
# render_release_hook <release> <out>
# The chart's vm.yaml looks up the default instance type and profile, which a
# render with no cluster cannot find, so the VM is given explicit resources.
render_release_hook() {
release=$1 out=$2
helm template "$release" "$VM_CHART" --namespace tenant-test \
--set instanceType= --set instanceProfile= \
--set resources.cpu=1 --set resources.sockets=1 --set resources.memory=1Gi \
--set-json '_cluster={"scheduling":{}}' \
--show-only templates/volume-group-release-hook.yaml 2>/dev/null \
| yq eval 'select(.kind == "Job") | .spec.template.spec.containers[0].args[0]' - > "$out"
[ -s "$out" ] || return 1
}
# write_fake_kubectl <dir>
# Each file in $CLAIMS is a claim; its content is the value of its
# velero.io/volume-group label, an empty file a claim without one. The fake
# serves the three calls the hook makes:
# * a label-selector list of the claims carrying a value, or a failure when
# $FAIL_LIST is set;
# * a JSON test+remove patch, which fails with the API server's Invalid
# answer when the value differs, as a JSON patch test does, and NotFound
# when the claim is gone. $BEFORE_PATCH runs first, to model another writer
# between the list and the patch; $FAIL_PATCH names a claim whose patch
# fails for a reason unrelated to its label;
# * a read of one claim's label.
write_fake_kubectl() {
cat > "$1/kubectl" <<'KEOF'
#!/bin/sh
echo "$*" >> "$KLOG"
verb=$1 target=$2
case "$verb:$target" in
get:persistentvolumeclaims)
if [ -n "${FAIL_LIST:-}" ]; then
echo "error: the server could not list persistentvolumeclaims" >&2
exit 1
fi
want=${6#*=}
for f in "$CLAIMS"/*; do
[ -e "$f" ] || continue
if [ "$(cat "$f")" = "$want" ]; then echo "persistentvolumeclaim/${f##*/}"; fi
done
exit 0
;;
esac
name=${target#persistentvolumeclaim/}
if [ "$verb" = patch ] && [ -n "${BEFORE_PATCH:-}" ]; then
sh -c "$BEFORE_PATCH"
fi
if [ ! -e "$CLAIMS/$name" ]; then
echo "Error from server (NotFound): persistentvolumeclaims \"$name\" not found" >&2
exit 1
fi
case "$verb" in
get)
cat "$CLAIMS/$name"
;;
patch)
if [ "$name" = "${FAIL_PATCH:-}" ]; then
echo "Error from server (InternalError): etcdserver: request timed out" >&2
exit 1
fi
expected=$(printf '%s' "$7" | sed -n 's/.*"value":"\([^"]*\)".*/\1/p')
if [ "$(cat "$CLAIMS/$name")" != "$expected" ]; then
echo "The request is invalid: the server rejected our request due to an error in our request" >&2
exit 1
fi
: > "$CLAIMS/$name"
;;
*)
echo "fake kubectl: unexpected call $*" >&2
exit 64
;;
esac
KEOF
chmod 0755 "$1/kubectl"
}
@test "a render that produces no script fails instead of passing as a no-op" {
tmp=$(mktemp -d)
if VM_CHART="$tmp/no-such-chart" render_release_hook vm-instance-old "$tmp/hook.sh"; then
echo "FAIL: render_release_hook reported success with no chart to render"
false
fi
rm -rf "$tmp"
}
@test "uninstall releases every claim the VM grouped, and a differently named VM can group them again" {
# vm-disk-old-data was detached before the uninstall, with no upgrade since,
# so no render-time list of the VM's disks would still name it.
tmp=$(mktemp -d)
write_fake_kubectl "$tmp"
render_release_hook vm-instance-old "$tmp/hook.sh"
export KLOG="$tmp/calls" CLAIMS="$tmp/claims"
mkdir "$CLAIMS"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-old-system"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-old-data"
printf 'vm-instance-old' > "$CLAIMS/persistent-state-for-vm-instance-old-abcde"
printf 'vm-instance-other' > "$CLAIMS/vm-disk-other"
: > "$CLAIMS/vm-disk-loose"
rc=0
PATH="$tmp:$PATH" sh -e "$tmp/hook.sh" > "$tmp/out" 2> "$tmp/err" || rc=$?
if [ "$rc" -ne 0 ]; then
echo "FAIL: hook exited $rc when every patch succeeded"
cat "$tmp/out" "$tmp/err"
false
fi
for claim in vm-disk-old-system vm-disk-old-data persistent-state-for-vm-instance-old-abcde; do
if [ -s "$CLAIMS/$claim" ]; then
echo "FAIL: $claim still carries the group $(cat "$CLAIMS/$claim")"
false
fi
done
if [ "$(cat "$CLAIMS/vm-disk-other")" != vm-instance-other ]; then
echo "FAIL: another VM's group was removed"
cat "$tmp/calls"
false
fi
if grep -q 'vm-disk-other\|vm-disk-loose' "$tmp/calls"; then
echo "FAIL: the hook touched a claim this VM never grouped"
cat "$tmp/calls"
false
fi
# The post-install hook of a replacement VM groups a claim whose label is
# absent or empty and leaves out one grouped under another name; the
# helm-unittest suite pins that side.
rm -rf "$tmp"
}
@test "a claim another VM grouped between the list and the patch keeps that group" {
tmp=$(mktemp -d)
write_fake_kubectl "$tmp"
render_release_hook vm-instance-old "$tmp/hook.sh"
export KLOG="$tmp/calls" CLAIMS="$tmp/claims"
mkdir "$CLAIMS"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-a"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-b"
export BEFORE_PATCH="printf vm-instance-new > '$CLAIMS/vm-disk-a'"
rc=0
PATH="$tmp:$PATH" sh -e "$tmp/hook.sh" > "$tmp/out" 2> "$tmp/err" || rc=$?
if [ "$rc" -ne 0 ]; then
echo "FAIL: hook exited $rc for a claim that is no longer this VM's"
cat "$tmp/out" "$tmp/err"
false
fi
if [ "$(cat "$CLAIMS/vm-disk-a")" != vm-instance-new ]; then
echo "FAIL: the newer group was removed"
false
fi
rm -rf "$tmp"
}
@test "a claim deleted between the list and the patch does not fail the uninstall" {
tmp=$(mktemp -d)
write_fake_kubectl "$tmp"
render_release_hook vm-instance-old "$tmp/hook.sh"
export KLOG="$tmp/calls" CLAIMS="$tmp/claims"
mkdir "$CLAIMS"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-a"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-b"
export BEFORE_PATCH="rm -f '$CLAIMS/vm-disk-a'"
rc=0
PATH="$tmp:$PATH" sh -e "$tmp/hook.sh" > "$tmp/out" 2> "$tmp/err" || rc=$?
if [ "$rc" -ne 0 ]; then
echo "FAIL: hook exited $rc for a claim that no longer exists"
cat "$tmp/out" "$tmp/err"
false
fi
if [ -s "$CLAIMS/vm-disk-b" ]; then
echo "FAIL: the claim after the deleted one kept its group"
false
fi
rm -rf "$tmp"
}
@test "a claim that still carries the group after a failed patch fails the uninstall" {
# Succeeding here would leave a label no release ever removes.
tmp=$(mktemp -d)
write_fake_kubectl "$tmp"
render_release_hook vm-instance-old "$tmp/hook.sh"
export KLOG="$tmp/calls" CLAIMS="$tmp/claims"
mkdir "$CLAIMS"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-a"
export FAIL_PATCH=vm-disk-a
rc=0
PATH="$tmp:$PATH" sh -e "$tmp/hook.sh" > "$tmp/out" 2> "$tmp/err" || rc=$?
if [ "$rc" -eq 0 ]; then
echo "FAIL: hook exited 0 with the group still on vm-disk-a"
cat "$tmp/out" "$tmp/err"
false
fi
if ! grep -q 'request timed out' "$tmp/err"; then
echo "FAIL: the patch error was not reported"
cat "$tmp/err"
false
fi
rm -rf "$tmp"
}
@test "a failed list fails the uninstall instead of releasing nothing" {
tmp=$(mktemp -d)
write_fake_kubectl "$tmp"
render_release_hook vm-instance-old "$tmp/hook.sh"
export KLOG="$tmp/calls" CLAIMS="$tmp/claims"
mkdir "$CLAIMS"
printf 'vm-instance-old' > "$CLAIMS/vm-disk-a"
export FAIL_LIST=1
rc=0
PATH="$tmp:$PATH" sh -e "$tmp/hook.sh" > "$tmp/out" 2> "$tmp/err" || rc=$?
if [ "$rc" -eq 0 ]; then
echo "FAIL: hook exited 0 although the claims could not be listed"
cat "$tmp/out" "$tmp/err"
false
fi
rm -rf "$tmp"
}