Files
cozystack/internal/controller/workload_controller_test.go
Aleksei Sviridkin 4225be12cc feat(gpu): bind, move and release GPU claims in the leader
The binder is the only writer of a claim's placement, so budget and
capacity checks that admission already ran cannot be raced past by two
replicas. Every event collapses into one pass over all GPU objects,
which serializes the decisions without per-object locks, and claims
are read past the cache so a unit booked in the last pass is never
booked again from a stale view.

A VM starts through its launcher pod, which the pod webhook holds at a
scheduling gate. The pass creates the VMI's template claims, gathers
the whole set onto one node that every class of the set tolerates and
has room on, then pins the pod there and removes the gate in one
update, since the API server lets a pod's node affinity change only
while the pod is gated. A set that cannot be placed keeps its pod
gated with a condition on its claims and a Warning event on the VMI,
once per change of reason, so the VM waits for capacity instead of
being refused into KubeVirt's backoff. The set goes only to a node the
pod's own node selector and required affinity accept and, when the VMI
has a volume bound to a node's PersistentVolume, that volume reaches.
Gated pods go before moves and new orders.

A pin cannot be undone, so a pinned pod its node refuses for lack of
resources is deleted and the node is skipped for that set for ten
minutes, or until its allocatable, taints or readiness change. The
template claims of the set go with its failed VMI, so the controller
also keeps the rejection in memory for the VM's next VMI. Only a VMI
whose pod is already pinned is deleted to free a claim whose node
cannot keep it; a VMI whose pod is gated has its set gathered instead.

The full pass also moves held sets off nodes that cannot keep them,
rebinds Lost sets before new orders, and binds new orders onto the
fullest node with room. Finalizers and usage records run with the
feature disabled too, so turning GPU off never hangs a namespace or
class deletion. Each usage record is owned by its claim and sits under
no WorkloadMonitor, so no tenant label can add or drop one, and
garbage collection removes it with the claim. Without a monitor label
the Workload controller would take such a record for an orphan, so it
now leaves a record owned by a GPUClaim to that owner.

The claims one VM names move, go Lost and are rebound as a set. Every
pass restores that invariant before it places anything, gathering a
set left partly Lost, by a write that failed half way or by a VMI that
ended next to held members, onto one node or sending all of it to
Lost, so each later step only ever changes whole sets.

A Lost claim already counts against its tenant's budgets, so the pod
of its still running VMI is not counted again under a raw GPU key; for
node capacity it is, since the claim itself holds no units. A pod is a
VMI's launcher only when the VMI lists it in status.activePods,
because whoever creates a pod sets its owner reference. The KubeVirt
watches start once KubeVirt serves its kinds, whose CRDs a fresh
install adds after this controller starts.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
2026-10-26 11:22:36 +03:00

158 lines
5.3 KiB
Go

package controller
import (
"context"
"testing"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
func TestUnprefixedMonitoredObjectReturnsNil(t *testing.T) {
w := &cozyv1alpha1.Workload{}
w.Name = "unprefixed-name"
obj := getMonitoredObject(w)
if obj != nil {
t.Errorf(`getMonitoredObject(&Workload{Name: "%s"}) == %v, want nil`, w.Name, obj)
}
}
func TestPodMonitoredObject(t *testing.T) {
w := &cozyv1alpha1.Workload{}
w.Name = "pod-mypod"
obj := getMonitoredObject(w)
if pod, ok := obj.(*corev1.Pod); !ok || pod.Name != "mypod" {
t.Errorf(`getMonitoredObject(&Workload{Name: "%s"}) == %v, want &Pod{Name: "mypod"}`, w.Name, obj)
}
}
func TestWorkloadReconciler_DeletesOnMissingMonitor(t *testing.T) {
scheme := runtime.NewScheme()
_ = cozyv1alpha1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)
// Workload with a non-existent monitor
w := &cozyv1alpha1.Workload{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-foo",
Namespace: "default",
Labels: map[string]string{
"workloads.cozystack.io/monitor": "missing-monitor",
},
},
}
fakeClient := fake.NewClientBuilder().
WithScheme(scheme).
WithObjects(w).
Build()
reconciler := &WorkloadReconciler{Client: fakeClient}
req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "pod-foo", Namespace: "default"}}
if _, err := reconciler.Reconcile(context.TODO(), req); err != nil {
t.Fatalf("Reconcile returned error: %v", err)
}
// Expect workload to be deleted
err := fakeClient.Get(context.TODO(), req.NamespacedName, &cozyv1alpha1.Workload{})
if !apierrors.IsNotFound(err) {
t.Errorf("expected workload to be deleted, got: %v", err)
}
}
func TestWorkloadReconciler_KeepsWhenAllExist(t *testing.T) {
scheme := runtime.NewScheme()
_ = cozyv1alpha1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)
// Create a monitor and its backing Pod
monitor := &cozyv1alpha1.WorkloadMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: "mon",
Namespace: "default",
},
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "default",
},
}
w := &cozyv1alpha1.Workload{
ObjectMeta: metav1.ObjectMeta{
Name: "pod-foo",
Namespace: "default",
Labels: map[string]string{
"workloads.cozystack.io/monitor": "mon",
},
},
}
fakeClient := fake.NewClientBuilder().
WithScheme(scheme).
WithObjects(monitor, pod, w).
Build()
reconciler := &WorkloadReconciler{Client: fakeClient}
req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "pod-foo", Namespace: "default"}}
if _, err := reconciler.Reconcile(context.TODO(), req); err != nil {
t.Fatalf("Reconcile returned error: %v", err)
}
// Expect workload to remain
err := fakeClient.Get(context.TODO(), req.NamespacedName, &cozyv1alpha1.Workload{})
if err != nil {
t.Errorf("expected workload to persist, got error: %v", err)
}
}
// A GPU usage record carries no monitor label: its GPUClaim owns it. The
// Workload controller leaves such a record to its owner, and still deletes
// one without a monitor label and without that owner.
func TestWorkloadReconciler_LeavesARecordOwnedByAGPUClaim(t *testing.T) {
scheme := runtime.NewScheme()
_ = cozyv1alpha1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)
record := func(owners ...metav1.OwnerReference) *cozyv1alpha1.Workload {
return &cozyv1alpha1.Workload{
ObjectMeta: metav1.ObjectMeta{Name: "gpu-train-0", Namespace: "default", OwnerReferences: owners},
Status: cozyv1alpha1.WorkloadStatus{Kind: "gpu-claim"},
}
}
claim := metav1.OwnerReference{APIVersion: "gpu.cozystack.io/v1alpha1", Kind: "GPUClaim", Name: "train-0", UID: "uid-train-0"}
req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "gpu-train-0", Namespace: "default"}}
kept := fake.NewClientBuilder().WithScheme(scheme).WithObjects(record(claim)).Build()
if _, err := (&WorkloadReconciler{Client: kept}).Reconcile(context.TODO(), req); err != nil {
t.Fatalf("Reconcile: %v", err)
}
if err := kept.Get(context.TODO(), req.NamespacedName, &cozyv1alpha1.Workload{}); err != nil {
t.Errorf("a record owned by a GPUClaim was deleted: %v", err)
}
for name, owner := range map[string]metav1.OwnerReference{
"no owner": {},
"another kind": {APIVersion: "gpu.cozystack.io/v1alpha1", Kind: "GPUClass", Name: "l40s", UID: "uid-l40s"},
"a GPUClaim of another group": {APIVersion: "example.com/v1", Kind: "GPUClaim", Name: "train-0", UID: "uid-train-0"},
} {
var owners []metav1.OwnerReference
if owner.Kind != "" {
owners = append(owners, owner)
}
orphaned := fake.NewClientBuilder().WithScheme(scheme).WithObjects(record(owners...)).Build()
if _, err := (&WorkloadReconciler{Client: orphaned}).Reconcile(context.TODO(), req); err != nil {
t.Fatalf("%s: Reconcile: %v", name, err)
}
if err := orphaned.Get(context.TODO(), req.NamespacedName, &cozyv1alpha1.Workload{}); !apierrors.IsNotFound(err) {
t.Errorf("%s: a record without a monitor label or a GPUClaim owner was kept: %v", name, err)
}
}
}