mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-01 12:46:14 +09:00
feat(gpu): compute GPUClass free capacity from node allocatable
A tenant picking a GPU class needs to know whether a VM of it is likely to start, and a hoster needs to see a class that can never serve a VM before a tenant's start is refused. With no GPUNode and no binder in step 1, both figures come from the Node and Pod objects alone: free units are a node's allocatable count of the class's resource name minus what its pods request, over nodes that are Ready, not cordoned and carry no taint the class does not tolerate. One pass covers every class, because a class's ResourceNameConflict depends on the other classes that name the same resource. The pass reads classes uncached and records the acknowledged name in status.ownedResourceName in the same resourceVersion-checked update that releases the previous one, so a lagging cache cannot decide ownership. Among classes asking for a name no class holds, the oldest gets it; after that the holder keeps it whatever the age of a class created later. Turning GPU features off clears the computed status but keeps the acknowledged name. The KubeVirt CR is read on each pass and on a one-minute recheck instead of watched, so the controller needs no KubeVirt kinds served to start. The class status is readable by every authenticated user, so the inventory and load behind it, the allocatable and requested totals per class, go to metrics instead. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
4 files changed
+832
No files matched your search
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/runtime"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/fake"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
||||
|
||||
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
||||
)
|
||||
|
||||
const (
|
||||
rnL40S = "nvidia.com/NVIDIA_L40S-24C"
|
||||
rnH100 = "nvidia.com/GH100_H100"
|
||||
)
|
||||
|
||||
var epoch = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
func testScheme(t *testing.T) *runtime.Scheme {
|
||||
t.Helper()
|
||||
s := runtime.NewScheme()
|
||||
if err := clientgoscheme.AddToScheme(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cozyv1alpha1.AddToScheme(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func newClient(t *testing.T, funcs *interceptor.Funcs, objs ...client.Object) client.WithWatch {
|
||||
t.Helper()
|
||||
b := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(objs...).
|
||||
WithStatusSubresource(&cozyv1alpha1.GPUClass{})
|
||||
if funcs != nil {
|
||||
b = b.WithInterceptorFuncs(*funcs)
|
||||
}
|
||||
return b.Build()
|
||||
}
|
||||
|
||||
// gpuClass is created age minutes after epoch, so tests order classes by age.
|
||||
func gpuClass(name, resourceName string, age int, mutate ...func(*cozyv1alpha1.GPUClass)) *cozyv1alpha1.GPUClass {
|
||||
c := &cozyv1alpha1.GPUClass{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: name, UID: types.UID(name + "-uid"), Generation: 1, CreationTimestamp: metav1.NewTime(epoch.Add(time.Duration(age) * time.Minute))},
|
||||
Spec: cozyv1alpha1.GPUClassSpec{
|
||||
Vendor: "nvidia", Model: "L40S", Mode: cozyv1alpha1.GPUModePassthrough,
|
||||
Source: cozyv1alpha1.GPUClassSource{DevicePlugin: &cozyv1alpha1.DevicePluginSource{ResourceName: resourceName}},
|
||||
},
|
||||
}
|
||||
for _, m := range mutate {
|
||||
m(c)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func gpuNode(name string, alloc map[string]int64, mutate ...func(*corev1.Node)) *corev1.Node {
|
||||
n := &corev1.Node{
|
||||
ObjectMeta: metav1.ObjectMeta{Name: name},
|
||||
Status: corev1.NodeStatus{
|
||||
Allocatable: corev1.ResourceList{},
|
||||
Conditions: []corev1.NodeCondition{{Type: corev1.NodeReady, Status: corev1.ConditionTrue}},
|
||||
},
|
||||
}
|
||||
for rn, v := range alloc {
|
||||
n.Status.Allocatable[corev1.ResourceName(rn)] = *resource.NewQuantity(v, resource.DecimalSI)
|
||||
}
|
||||
for _, m := range mutate {
|
||||
m(n)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func gpuPod(name, node, resourceName string, units int64, mutate ...func(*corev1.Pod)) *corev1.Pod {
|
||||
q := *resource.NewQuantity(units, resource.DecimalSI)
|
||||
p := &corev1.Pod{
|
||||
ObjectMeta: metav1.ObjectMeta{Namespace: "tenant-a", Name: name},
|
||||
Spec: corev1.PodSpec{NodeName: node, Containers: []corev1.Container{{
|
||||
Name: "compute",
|
||||
Resources: corev1.ResourceRequirements{Limits: corev1.ResourceList{corev1.ResourceName(resourceName): q}},
|
||||
}}},
|
||||
Status: corev1.PodStatus{Phase: corev1.PodRunning},
|
||||
}
|
||||
for _, m := range mutate {
|
||||
m(p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func getClass(t *testing.T, c client.Client, name string) *cozyv1alpha1.GPUClass {
|
||||
t.Helper()
|
||||
out := &cozyv1alpha1.GPUClass{}
|
||||
if err := c.Get(context.Background(), types.NamespacedName{Name: name}, out); err != nil {
|
||||
t.Fatalf("get GPUClass %s: %v", name, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"sigs.k8s.io/controller-runtime/pkg/metrics"
|
||||
)
|
||||
|
||||
// The class's inventory and load, which the GPUClass status, readable by
|
||||
// every authenticated user, must not show.
|
||||
var (
|
||||
classCapacity = prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "cozystack_gpu_class_capacity_units",
|
||||
Help: "Allocatable units of the GPU class's resource name summed over every node, free or not.",
|
||||
}, []string{"class"})
|
||||
classUsed = prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Name: "cozystack_gpu_class_used_units",
|
||||
Help: "Units of the GPU class's resource name that scheduled, unfinished pods request, summed over every node.",
|
||||
}, []string{"class"})
|
||||
)
|
||||
|
||||
func init() {
|
||||
metrics.Registry.MustRegister(classCapacity, classUsed)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
"k8s.io/apimachinery/pkg/api/equality"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/apimachinery/pkg/types"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/utils/ptr"
|
||||
ctrl "sigs.k8s.io/controller-runtime"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/event"
|
||||
"sigs.k8s.io/controller-runtime/pkg/predicate"
|
||||
|
||||
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
||||
"github.com/cozystack/cozystack/internal/gpu/model"
|
||||
)
|
||||
|
||||
const (
|
||||
reasonSharedResourceName = "SharedResourceName"
|
||||
reasonUniqueResourceName = "UniqueResourceName"
|
||||
reasonNotInPermittedDevice = "NotInPermittedHostDevices"
|
||||
reasonPermitted = "Permitted"
|
||||
|
||||
// permittedRecheck bounds how long a change to the KubeVirt
|
||||
// permittedHostDevices table takes to reach ResourceNameNotPermitted:
|
||||
// the table is read on every pass and not watched.
|
||||
permittedRecheck = time.Minute
|
||||
)
|
||||
|
||||
var kubeVirtGVK = schema.GroupVersionKind{Group: "kubevirt.io", Version: "v1", Kind: "KubeVirt"}
|
||||
|
||||
// StatusReconciler writes ownedResourceName, free, maxFreePerNode,
|
||||
// ResourceNameConflict and ResourceNameNotPermitted on every GPUClass in one
|
||||
// pass, since name ownership depends on the other classes. It is the only
|
||||
// writer of ownedResourceName; leader election keeps it single in steady
|
||||
// state but does not fence an overlapping old leader, whose duplicate
|
||||
// acknowledgements the next pass keeps as a conflict. The status is readable
|
||||
// by every authenticated user, so it names no node.
|
||||
type StatusReconciler struct {
|
||||
Client client.Client
|
||||
// Reader is uncached: the classes and the KubeVirt CR are read on each
|
||||
// pass, so ownership is not decided from a lagging cache and the
|
||||
// controller holds no KubeVirt watch.
|
||||
Reader client.Reader
|
||||
}
|
||||
|
||||
func (r *StatusReconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result, error) {
|
||||
permitted, err := r.permittedResourceNames(ctx)
|
||||
if err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
// Name ownership is decided from an uncached read; each update is
|
||||
// checked against the resourceVersion of that read.
|
||||
var classList cozyv1alpha1.GPUClassList
|
||||
if err := r.Reader.List(ctx, &classList); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
var nodeList corev1.NodeList
|
||||
if err := r.Client.List(ctx, &nodeList); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
var podList corev1.PodList
|
||||
if err := r.Client.List(ctx, &podList); err != nil {
|
||||
return ctrl.Result{}, err
|
||||
}
|
||||
|
||||
classes := make([]model.Class, len(classList.Items))
|
||||
names := sets.New[corev1.ResourceName]()
|
||||
for i := range classList.Items {
|
||||
classes[i] = model.ClassFrom(&classList.Items[i])
|
||||
names.Insert(classes[i].ResourceName)
|
||||
}
|
||||
nodes := make([]model.Node, len(nodeList.Items))
|
||||
for i := range nodeList.Items {
|
||||
nodes[i] = model.NodeFrom(&nodeList.Items[i])
|
||||
}
|
||||
var pods []model.Pod
|
||||
for i := range podList.Items {
|
||||
if p, ok := model.PodFrom(&podList.Items[i], names); ok {
|
||||
pods = append(pods, p)
|
||||
}
|
||||
}
|
||||
// A candidate acquires its requested name in the same status update
|
||||
// that releases the name it held before.
|
||||
candidates := model.ResourceNameCandidates(classes)
|
||||
for i := range classes {
|
||||
if rn := classes[i].ResourceName; rn != "" && candidates[rn] == classes[i].UID {
|
||||
classes[i].OwnedResourceName = rn
|
||||
}
|
||||
}
|
||||
conflicts := model.Conflicts(classes)
|
||||
holder := map[types.UID]string{}
|
||||
for _, c := range classes {
|
||||
holder[c.UID] = c.Name
|
||||
}
|
||||
|
||||
classCapacity.Reset()
|
||||
classUsed.Reset()
|
||||
var errs []error
|
||||
for i := range classList.Items {
|
||||
obj, c := &classList.Items[i], classes[i]
|
||||
var free, maxFree, capacity int64
|
||||
for _, n := range nodes {
|
||||
f := model.FreeOnNode(c, n, pods)
|
||||
free += f
|
||||
maxFree = max(maxFree, f)
|
||||
capacity += n.Allocatable[c.ResourceName]
|
||||
}
|
||||
var used int64
|
||||
for _, p := range pods {
|
||||
if p.NodeName != "" {
|
||||
used += p.Units[c.ResourceName]
|
||||
}
|
||||
}
|
||||
classCapacity.WithLabelValues(c.Name).Set(float64(capacity))
|
||||
classUsed.WithLabelValues(c.Name).Set(float64(used))
|
||||
|
||||
before := obj.Status.DeepCopy()
|
||||
obj.Status.Free = ptr.To(int32(free))
|
||||
obj.Status.MaxFreePerNode = ptr.To(int32(maxFree))
|
||||
obj.Status.OwnedResourceName = string(c.OwnedResourceName)
|
||||
conflict := metav1.Condition{Type: cozyv1alpha1.GPUClassResourceNameConflict, Status: metav1.ConditionFalse,
|
||||
Reason: reasonUniqueResourceName, ObservedGeneration: obj.Generation}
|
||||
if conflicts.Has(c.Name) {
|
||||
conflict.Status, conflict.Reason = metav1.ConditionTrue, reasonSharedResourceName
|
||||
if owner, ok := candidates[c.ResourceName]; ok {
|
||||
conflict.Message = fmt.Sprintf("resource name %s belongs to GPUClass %s; this class is not offered", c.ResourceName, holder[owner])
|
||||
} else {
|
||||
conflict.Message = fmt.Sprintf("more than one GPUClass holds resource name %s; none of them is offered until one releases it", c.ResourceName)
|
||||
}
|
||||
}
|
||||
notPermitted := metav1.Condition{Type: cozyv1alpha1.GPUClassResourceNameNotPermitted, Status: metav1.ConditionFalse,
|
||||
Reason: reasonPermitted, ObservedGeneration: obj.Generation}
|
||||
if permitted != nil && !permitted.Has(string(c.ResourceName)) {
|
||||
notPermitted.Status, notPermitted.Reason = metav1.ConditionTrue, reasonNotInPermittedDevice
|
||||
notPermitted.Message = fmt.Sprintf("resource name %s is not in the KubeVirt permittedHostDevices table, so no VM of this class can start", c.ResourceName)
|
||||
}
|
||||
meta.SetStatusCondition(&obj.Status.Conditions, conflict)
|
||||
meta.SetStatusCondition(&obj.Status.Conditions, notPermitted)
|
||||
if equality.Semantic.DeepEqual(before, &obj.Status) {
|
||||
continue
|
||||
}
|
||||
errs = append(errs, client.IgnoreNotFound(r.Client.Status().Update(ctx, obj)))
|
||||
}
|
||||
return ctrl.Result{RequeueAfter: permittedRecheck}, errors.Join(errs...)
|
||||
}
|
||||
|
||||
// permittedResourceNames returns nil, which KubeVirt reads as no table,
|
||||
// where KubeVirt or its CR is absent.
|
||||
func (r *StatusReconciler) permittedResourceNames(ctx context.Context) (sets.Set[string], error) {
|
||||
kv := &unstructured.Unstructured{}
|
||||
kv.SetGroupVersionKind(kubeVirtGVK)
|
||||
err := r.Reader.Get(ctx, client.ObjectKey{Namespace: model.KubeVirtNamespace, Name: model.KubeVirtName}, kv)
|
||||
if apierrors.IsNotFound(err) || meta.IsNoMatchError(err) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read the KubeVirt CR: %w", err)
|
||||
}
|
||||
return model.PermittedResourceNames(kv), nil
|
||||
}
|
||||
|
||||
// nodeCapacityChanged drops node updates that cannot change free units,
|
||||
// such as the kubelet's heartbeats.
|
||||
var nodeCapacityChanged = predicate.Funcs{UpdateFunc: func(e event.UpdateEvent) bool {
|
||||
o, ok1 := e.ObjectOld.(*corev1.Node)
|
||||
n, ok2 := e.ObjectNew.(*corev1.Node)
|
||||
if !ok1 || !ok2 {
|
||||
return true
|
||||
}
|
||||
return o.Spec.Unschedulable != n.Spec.Unschedulable ||
|
||||
!equality.Semantic.DeepEqual(o.Spec.Taints, n.Spec.Taints) ||
|
||||
!equality.Semantic.DeepEqual(o.Status.Allocatable, n.Status.Allocatable) ||
|
||||
model.Ready(o) != model.Ready(n)
|
||||
}}
|
||||
|
||||
// requestsExtendedResource keeps the events of pods that can change GPU
|
||||
// usage without resolving the class resource names on every pod event.
|
||||
func requestsExtendedResource(o client.Object) bool {
|
||||
p, ok := o.(*corev1.Pod)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for _, cs := range [][]corev1.Container{p.Spec.Containers, p.Spec.InitContainers} {
|
||||
for i := range cs {
|
||||
for _, rl := range []corev1.ResourceList{cs[i].Resources.Limits, cs[i].Resources.Requests} {
|
||||
for name := range rl {
|
||||
if strings.Contains(string(name), "/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
/*
|
||||
Copyright 2026 The Cozystack Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
||||
"k8s.io/apimachinery/pkg/api/meta"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||
"k8s.io/utils/ptr"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client"
|
||||
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
|
||||
"sigs.k8s.io/controller-runtime/pkg/event"
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile"
|
||||
|
||||
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
||||
"github.com/cozystack/cozystack/internal/gpu/model"
|
||||
)
|
||||
|
||||
func kubeVirt(permitted ...string) *unstructured.Unstructured {
|
||||
kv := &unstructured.Unstructured{}
|
||||
kv.SetGroupVersionKind(kubeVirtGVK)
|
||||
kv.SetNamespace(model.KubeVirtNamespace)
|
||||
kv.SetName(model.KubeVirtName)
|
||||
if permitted != nil {
|
||||
var devs []any
|
||||
for _, rn := range permitted {
|
||||
devs = append(devs, map[string]any{"resourceName": rn})
|
||||
}
|
||||
_ = unstructured.SetNestedSlice(kv.Object, devs, "spec", "configuration", "permittedHostDevices", "pciHostDevices")
|
||||
}
|
||||
return kv
|
||||
}
|
||||
|
||||
// kubeVirtReader serves kv, or err when set, for the KubeVirt CR and
|
||||
// delegates everything else.
|
||||
func kubeVirtReader(c client.Client, kv *unstructured.Unstructured, err error) client.Reader {
|
||||
return interceptor.NewClient(c.(client.WithWatch), interceptor.Funcs{
|
||||
Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
u, ok := obj.(*unstructured.Unstructured)
|
||||
if !ok || u.GroupVersionKind() != kubeVirtGVK {
|
||||
return cl.Get(ctx, key, obj, opts...)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if kv == nil {
|
||||
return apierrors.NewNotFound(schema.GroupResource{Group: "kubevirt.io", Resource: "kubevirts"}, key.Name)
|
||||
}
|
||||
kv.DeepCopyInto(u)
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func runStatus(t *testing.T, c client.Client, reader client.Reader) reconcile.Result {
|
||||
t.Helper()
|
||||
r := &StatusReconciler{Client: c, Reader: reader}
|
||||
res, err := r.Reconcile(context.Background(), reconcile.Request{})
|
||||
if err != nil {
|
||||
t.Fatalf("Reconcile: %v", err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func cordoned(n *corev1.Node) { n.Spec.Unschedulable = true }
|
||||
func notReady(n *corev1.Node) { n.Status.Conditions[0].Status = corev1.ConditionFalse }
|
||||
func tainted(key string) func(*corev1.Node) {
|
||||
return func(n *corev1.Node) {
|
||||
n.Spec.Taints = append(n.Spec.Taints, corev1.Taint{Key: key, Effect: corev1.TaintEffectNoSchedule})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusFreeAndMaxFreePerNode(t *testing.T) {
|
||||
class := gpuClass("l40s", rnL40S, 0, func(c *cozyv1alpha1.GPUClass) {
|
||||
c.Spec.Tolerations = []cozyv1alpha1.GPUClassToleration{{Key: "dedicated", Operator: "Exists"}}
|
||||
})
|
||||
c := newClient(t, nil, class,
|
||||
gpuNode("busy", map[string]int64{rnL40S: 4}),
|
||||
gpuNode("idle", map[string]int64{rnL40S: 2}),
|
||||
gpuNode("cordoned", map[string]int64{rnL40S: 8}, cordoned),
|
||||
gpuNode("not-ready", map[string]int64{rnL40S: 8}, notReady),
|
||||
gpuNode("tainted", map[string]int64{rnL40S: 8}, tainted("maintenance")),
|
||||
gpuNode("dedicated", map[string]int64{rnL40S: 1}, tainted("dedicated")),
|
||||
gpuNode("overcommitted", map[string]int64{rnL40S: 1}),
|
||||
gpuNode("cpu-only", nil),
|
||||
gpuPod("vm-1", "busy", rnL40S, 1),
|
||||
gpuPod("done", "idle", rnL40S, 2, func(p *corev1.Pod) { p.Status.Phase = corev1.PodSucceeded }),
|
||||
gpuPod("pending", "", rnL40S, 2),
|
||||
gpuPod("other-name", "idle", rnH100, 2),
|
||||
gpuPod("vm-2", "overcommitted", rnL40S, 3),
|
||||
)
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
|
||||
got := getClass(t, c, "l40s").Status
|
||||
if got.Free == nil || *got.Free != 6 {
|
||||
t.Errorf("free = %v, want 6 (busy 3, idle 2, dedicated 1)", ptr.Deref(got.Free, -1))
|
||||
}
|
||||
if got.MaxFreePerNode == nil || *got.MaxFreePerNode != 3 {
|
||||
t.Errorf("maxFreePerNode = %v, want 3", ptr.Deref(got.MaxFreePerNode, -1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusNoNodesIsZeroNotAbsent(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("l40s", rnL40S, 0))
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
got := getClass(t, c, "l40s").Status
|
||||
if got.Free == nil || *got.Free != 0 || got.MaxFreePerNode == nil || *got.MaxFreePerNode != 0 {
|
||||
t.Errorf("free/maxFreePerNode = %v/%v, want 0/0", got.Free, got.MaxFreePerNode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusResourceNameConflict(t *testing.T) {
|
||||
c := newClient(t, nil,
|
||||
gpuClass("younger", rnL40S, 5),
|
||||
gpuClass("older", rnL40S, 1),
|
||||
gpuClass("other", rnH100, 9),
|
||||
)
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
|
||||
cond := meta.FindStatusCondition(getClass(t, c, "younger").Status.Conditions, cozyv1alpha1.GPUClassResourceNameConflict)
|
||||
if cond == nil || cond.Status != metav1.ConditionTrue {
|
||||
t.Fatalf("younger: ResourceNameConflict = %+v, want True", cond)
|
||||
}
|
||||
if !strings.Contains(cond.Message, "GPUClass older") || !strings.Contains(cond.Message, rnL40S) {
|
||||
t.Errorf("younger: message %q should name the class that keeps %s", cond.Message, rnL40S)
|
||||
}
|
||||
if cond.ObservedGeneration != 1 {
|
||||
t.Errorf("observedGeneration = %d, want 1", cond.ObservedGeneration)
|
||||
}
|
||||
for _, name := range []string{"older", "other"} {
|
||||
cond := meta.FindStatusCondition(getClass(t, c, name).Status.Conditions, cozyv1alpha1.GPUClassResourceNameConflict)
|
||||
if cond == nil || cond.Status != metav1.ConditionFalse {
|
||||
t.Errorf("%s: ResourceNameConflict = %+v, want False", name, cond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func owned(name string) func(*cozyv1alpha1.GPUClass) {
|
||||
return func(c *cozyv1alpha1.GPUClass) { c.Status.OwnedResourceName = name }
|
||||
}
|
||||
|
||||
func conflictStatus(t *testing.T, c client.Client, name string) metav1.ConditionStatus {
|
||||
t.Helper()
|
||||
cond := meta.FindStatusCondition(getClass(t, c, name).Status.Conditions, cozyv1alpha1.GPUClassResourceNameConflict)
|
||||
if cond == nil {
|
||||
return ""
|
||||
}
|
||||
return cond.Status
|
||||
}
|
||||
|
||||
func TestStatusAcknowledgesResourceNames(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("younger", rnL40S, 5), gpuClass("older", rnL40S, 1), gpuClass("other", rnH100, 9))
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
for name, want := range map[string]string{"older": rnL40S, "other": rnH100, "younger": ""} {
|
||||
if got := getClass(t, c, name).Status.OwnedResourceName; got != want {
|
||||
t.Errorf("%s: ownedResourceName = %q, want %q", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusKeepsTheIncumbentName(t *testing.T) {
|
||||
c := newClient(t, nil,
|
||||
gpuClass("incumbent", rnL40S, 5, owned(rnL40S)),
|
||||
gpuClass("older-edited", rnL40S, 1, owned(rnH100)),
|
||||
)
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if got := getClass(t, c, "incumbent").Status.OwnedResourceName; got != rnL40S {
|
||||
t.Errorf("incumbent ownedResourceName = %q, want %s", got, rnL40S)
|
||||
}
|
||||
if got := getClass(t, c, "older-edited").Status.OwnedResourceName; got != rnH100 {
|
||||
t.Errorf("an unacknowledged rename released the old name: %q", got)
|
||||
}
|
||||
if conflictStatus(t, c, "incumbent") != metav1.ConditionFalse || conflictStatus(t, c, "older-edited") != metav1.ConditionTrue {
|
||||
t.Errorf("conflicts: incumbent %s, older-edited %s", conflictStatus(t, c, "incumbent"), conflictStatus(t, c, "older-edited"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusMovesAnAcknowledgedName(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("a", rnH100, 1, owned(rnL40S)), gpuClass("b", rnL40S, 2))
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if got := getClass(t, c, "a").Status.OwnedResourceName; got != rnH100 {
|
||||
t.Fatalf("a ownedResourceName = %q, want the free requested name", got)
|
||||
}
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if got := getClass(t, c, "b").Status.OwnedResourceName; got != rnL40S {
|
||||
t.Errorf("b ownedResourceName = %q after a released the name", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusKeepsAmbiguousOwnership(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("a", rnL40S, 1, owned(rnL40S)), gpuClass("b", rnL40S, 2, owned(rnL40S)))
|
||||
for range 2 {
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
for _, name := range []string{"a", "b"} {
|
||||
got := getClass(t, c, name)
|
||||
if got.Status.OwnedResourceName != rnL40S || conflictStatus(t, c, name) != metav1.ConditionTrue {
|
||||
t.Errorf("%s: owned %q conflict %s, want both acknowledgements kept and refused", name, got.Status.OwnedResourceName, conflictStatus(t, c, name))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// staleClassReader serves GPUClass lists from an earlier snapshot, as a
|
||||
// writer that read before a later spec change would.
|
||||
func staleClassReader(c client.Client, stale *cozyv1alpha1.GPUClassList) client.Reader {
|
||||
return interceptor.NewClient(c.(client.WithWatch), interceptor.Funcs{
|
||||
List: func(ctx context.Context, cl client.WithWatch, list client.ObjectList, opts ...client.ListOption) error {
|
||||
if l, ok := list.(*cozyv1alpha1.GPUClassList); ok {
|
||||
stale.DeepCopyInto(l)
|
||||
return nil
|
||||
}
|
||||
return cl.List(ctx, list, opts...)
|
||||
},
|
||||
Get: func(ctx context.Context, cl client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
|
||||
if u, ok := obj.(*unstructured.Unstructured); ok && u.GroupVersionKind() == kubeVirtGVK {
|
||||
return apierrors.NewNotFound(schema.GroupResource{Group: "kubevirt.io", Resource: "kubevirts"}, key.Name)
|
||||
}
|
||||
return cl.Get(ctx, key, obj, opts...)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestStatusDelayedWriterCannotElectAWinner(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("older", rnH100, 1), gpuClass("newer", rnL40S, 2))
|
||||
stale := &cozyv1alpha1.GPUClassList{}
|
||||
if err := c.List(context.Background(), stale); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
edited := getClass(t, c, "older")
|
||||
edited.Spec.Source.DevicePlugin.ResourceName = rnL40S
|
||||
if err := c.Update(context.Background(), edited); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// An overlapping writer that read after the edit acknowledges the
|
||||
// older class; its CAS touches no other object.
|
||||
current := getClass(t, c, "older")
|
||||
current.Status.OwnedResourceName = rnL40S
|
||||
if err := c.Status().Update(context.Background(), current); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delayed := &StatusReconciler{Client: c, Reader: staleClassReader(c, stale)}
|
||||
_, err := delayed.Reconcile(context.Background(), reconcile.Request{})
|
||||
if !apierrors.IsConflict(err) {
|
||||
t.Errorf("delayed writer error = %v, want a conflict on the class it read before the change", err)
|
||||
}
|
||||
for _, name := range []string{"older", "newer"} {
|
||||
if got := getClass(t, c, name).Status.OwnedResourceName; got != rnL40S {
|
||||
t.Fatalf("%s: ownedResourceName = %q, want both per-object writes to have landed", name, got)
|
||||
}
|
||||
}
|
||||
for range 2 {
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
var classes []model.Class
|
||||
for _, name := range []string{"older", "newer"} {
|
||||
got := getClass(t, c, name)
|
||||
if got.Status.OwnedResourceName != rnL40S || conflictStatus(t, c, name) != metav1.ConditionTrue {
|
||||
t.Errorf("%s: owned %q conflict %s, want ambiguity kept", name, got.Status.OwnedResourceName, conflictStatus(t, c, name))
|
||||
}
|
||||
classes = append(classes, model.ClassFrom(got))
|
||||
}
|
||||
if confirmed := model.ConfirmedResourceNames(classes); len(confirmed) != 0 {
|
||||
t.Errorf("ambiguous name confirmed for %v", confirmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusResourceNameNotPermitted(t *testing.T) {
|
||||
noMatch := &meta.NoKindMatchError{GroupKind: kubeVirtGVK.GroupKind()}
|
||||
tests := []struct {
|
||||
name string
|
||||
kv *unstructured.Unstructured
|
||||
err error
|
||||
want metav1.ConditionStatus
|
||||
}{
|
||||
{"table leaves the name out", kubeVirt(rnH100), nil, metav1.ConditionTrue},
|
||||
{"table lists the name", kubeVirt(rnL40S, rnH100), nil, metav1.ConditionFalse},
|
||||
{"table unset", kubeVirt(), nil, metav1.ConditionFalse},
|
||||
{"no KubeVirt CR", nil, nil, metav1.ConditionFalse},
|
||||
{"KubeVirt not installed", nil, noMatch, metav1.ConditionFalse},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("l40s", rnL40S, 0))
|
||||
runStatus(t, c, kubeVirtReader(c, tc.kv, tc.err))
|
||||
cond := meta.FindStatusCondition(getClass(t, c, "l40s").Status.Conditions, cozyv1alpha1.GPUClassResourceNameNotPermitted)
|
||||
if cond == nil || cond.Status != tc.want {
|
||||
t.Fatalf("ResourceNameNotPermitted = %+v, want %s", cond, tc.want)
|
||||
}
|
||||
if tc.want == metav1.ConditionTrue && !strings.Contains(cond.Message, rnL40S) {
|
||||
t.Errorf("message %q should name %s", cond.Message, rnL40S)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusKubeVirtReadErrorWritesNothing(t *testing.T) {
|
||||
c := newClient(t, nil, gpuClass("l40s", rnL40S, 0))
|
||||
r := &StatusReconciler{Client: c, Reader: kubeVirtReader(c, nil, errors.New("connection refused"))}
|
||||
if _, err := r.Reconcile(context.Background(), reconcile.Request{}); err == nil {
|
||||
t.Fatal("Reconcile succeeded on a failed KubeVirt read")
|
||||
}
|
||||
if got := getClass(t, c, "l40s").Status; got.Free != nil || len(got.Conditions) != 0 {
|
||||
t.Errorf("status written from an unknown table: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusKeepsOtherConditionsAndTransitionTimes(t *testing.T) {
|
||||
old := metav1.NewTime(epoch)
|
||||
class := gpuClass("l40s", rnL40S, 0, func(c *cozyv1alpha1.GPUClass) {
|
||||
c.Status.Conditions = []metav1.Condition{
|
||||
{Type: cozyv1alpha1.GPUClassLicenseSecretMissing, Status: metav1.ConditionTrue, Reason: "SecretNotFound", LastTransitionTime: old},
|
||||
{Type: cozyv1alpha1.GPUClassResourceNameConflict, Status: metav1.ConditionFalse, Reason: reasonUniqueResourceName, LastTransitionTime: old},
|
||||
}
|
||||
})
|
||||
c := newClient(t, nil, class)
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
|
||||
conds := getClass(t, c, "l40s").Status.Conditions
|
||||
if lic := meta.FindStatusCondition(conds, cozyv1alpha1.GPUClassLicenseSecretMissing); lic == nil || lic.Status != metav1.ConditionTrue {
|
||||
t.Errorf("LicenseSecretMissing = %+v, want it left True", lic)
|
||||
}
|
||||
if cond := meta.FindStatusCondition(conds, cozyv1alpha1.GPUClassResourceNameConflict); cond == nil || !cond.LastTransitionTime.Equal(&old) {
|
||||
t.Errorf("ResourceNameConflict = %+v, want lastTransitionTime kept at %v", cond, old)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusSecondPassWritesNothing(t *testing.T) {
|
||||
updates := 0
|
||||
c := newClient(t, &interceptor.Funcs{
|
||||
SubResourceUpdate: func(ctx context.Context, cl client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error {
|
||||
updates++
|
||||
return cl.SubResource(sub).Update(ctx, obj, opts...)
|
||||
},
|
||||
}, gpuClass("l40s", rnL40S, 0), gpuNode("n1", map[string]int64{rnL40S: 2}))
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if updates != 1 {
|
||||
t.Errorf("status updates = %d, want 1", updates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusRequeuesForTheKubeVirtTable(t *testing.T) {
|
||||
c := newClient(t, nil)
|
||||
if res := runStatus(t, c, kubeVirtReader(c, nil, nil)); res.RequeueAfter <= 0 {
|
||||
t.Errorf("RequeueAfter = %v, want a recheck of the unwatched KubeVirt table", res.RequeueAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCapacityMetrics(t *testing.T) {
|
||||
c := newClient(t, nil,
|
||||
gpuClass("l40s", rnL40S, 0),
|
||||
gpuNode("n1", map[string]int64{rnL40S: 4}),
|
||||
gpuNode("n2", map[string]int64{rnL40S: 2}, cordoned),
|
||||
gpuPod("vm-1", "n1", rnL40S, 1),
|
||||
gpuPod("vm-2", "n2", rnL40S, 2),
|
||||
gpuPod("pending", "", rnL40S, 4),
|
||||
gpuPod("done", "n1", rnL40S, 3, func(p *corev1.Pod) { p.Status.Phase = corev1.PodFailed }),
|
||||
gpuPod("other", "n1", rnH100, 5),
|
||||
)
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if got := testutil.ToFloat64(classCapacity.WithLabelValues("l40s")); got != 6 {
|
||||
t.Errorf("capacity = %v, want 6: allocatable on every node, used or not", got)
|
||||
}
|
||||
if got := testutil.ToFloat64(classUsed.WithLabelValues("l40s")); got != 3 {
|
||||
t.Errorf("used = %v, want 3: scheduled, unfinished pods on every node", got)
|
||||
}
|
||||
if got := getClass(t, c, "l40s").Status; got.Free == nil || *got.Free != 3 {
|
||||
t.Errorf("free = %v, want 3", got.Free)
|
||||
}
|
||||
|
||||
if err := c.Delete(context.Background(), getClass(t, c, "l40s")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runStatus(t, c, kubeVirtReader(c, nil, nil))
|
||||
if n := testutil.CollectAndCount(classCapacity) + testutil.CollectAndCount(classUsed); n != 0 {
|
||||
t.Errorf("metric series after the class went = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeCapacityChanged(t *testing.T) {
|
||||
base := gpuNode("n1", map[string]int64{rnL40S: 4})
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*corev1.Node)
|
||||
want bool
|
||||
}{
|
||||
{"heartbeat only", func(n *corev1.Node) { n.Status.Conditions[0].LastHeartbeatTime = metav1.Now() }, false},
|
||||
{"label only", func(n *corev1.Node) { n.Labels = map[string]string{"x": "y"} }, false},
|
||||
{"cordon", cordoned, true},
|
||||
{"readiness", notReady, true},
|
||||
{"taint", tainted("maintenance"), true},
|
||||
{"allocatable", func(n *corev1.Node) { delete(n.Status.Allocatable, rnL40S) }, true},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
n := base.DeepCopy()
|
||||
tc.mutate(n)
|
||||
if got := nodeCapacityChanged.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: n}); got != tc.want {
|
||||
t.Errorf("%s: nodeCapacityChanged = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestsExtendedResource(t *testing.T) {
|
||||
kvm := gpuPod("launcher", "n1", "devices.kubevirt.io/kvm", 1)
|
||||
tests := []struct {
|
||||
name string
|
||||
pod *corev1.Pod
|
||||
want bool
|
||||
}{
|
||||
{"GPU limit", gpuPod("vm", "n1", rnL40S, 1), true},
|
||||
{"GPU in an init container", gpuPod("init", "n1", rnL40S, 1, func(p *corev1.Pod) {
|
||||
p.Spec.InitContainers = p.Spec.Containers
|
||||
p.Spec.Containers = nil
|
||||
}), true},
|
||||
{"GPU request without a limit", gpuPod("req", "n1", "cpu", 1, func(p *corev1.Pod) {
|
||||
p.Spec.Containers[0].Resources = corev1.ResourceRequirements{Requests: corev1.ResourceList{rnL40S: p.Spec.Containers[0].Resources.Limits["cpu"]}}
|
||||
}), true},
|
||||
{"a class may name a devices.kubevirt.io resource", kvm, true},
|
||||
{"CPU only", gpuPod("web", "n1", "cpu", 1), false},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
if got := requestsExtendedResource(tc.pod); got != tc.want {
|
||||
t.Errorf("%s: requestsExtendedResource = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user