diff --git a/api/v1alpha1/gpuclass_types.go b/api/v1alpha1/gpuclass_types.go index 71ef78974..30aa71efa 100644 --- a/api/v1alpha1/gpuclass_types.go +++ b/api/v1alpha1/gpuclass_types.go @@ -101,7 +101,6 @@ type GPUClassToleration struct { TolerationSeconds *int64 `json:"tolerationSeconds,omitempty"` } -// Toleration returns t as a pod toleration. func (t GPUClassToleration) Toleration() corev1.Toleration { return corev1.Toleration{Key: t.Key, Operator: t.Operator, Value: t.Value, Effect: t.Effect, TolerationSeconds: t.TolerationSeconds} } diff --git a/internal/gpu/consts.go b/internal/gpu/consts.go new file mode 100644 index 000000000..ea726d883 --- /dev/null +++ b/internal/gpu/consts.go @@ -0,0 +1,64 @@ +/* +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 gpu + +const ( + // LabelGPUReference, valued LabelValueTrue, marks a VMI template with + // class entries; KubeVirt copies it to the VMI and its virt-launcher + // pod. The webhooks select on it, so only such VMIs and pods can be + // blocked by their outage. + LabelGPUReference = "cozystack.io/gpu-reference" + // AnnotationGPUs holds the class entries of a VMI template as a JSON + // list of {"className", "count"}. + AnnotationGPUs = "cozystack.io/gpus" + // VMIGPUNamePrefix starts the name of every gpus entry the VMI webhook + // writes, so a reinvocation recognises its own entries. + VMIGPUNamePrefix = "gpu-" + + // LabelNamespaceVGPU is the effective vGPU entitlement the tenant chart + // writes on every tenant namespace. Only LabelValueTrue entitles. + LabelNamespaceVGPU = "namespace.cozystack.io/vgpu" + LabelValueTrue = "true" + + // QuotaKeyDomain is the domain of every GPU budget key in a tenant's + // resourceQuotas, after DRA's .deviceclass.resource.k8s.io/devices. + QuotaKeyDomain = "gpuclass.cozystack.io" + // QuotaKeyTotal is the budget over every class; a class's own key is + // model.ClassQuotaKey. + QuotaKeyTotal = QuotaKeyDomain + "/devices" + + // LicenseSecretNamespace holds the hoster's license Secrets that + // GPUClass.spec.license.secretName names. + LicenseSecretNamespace = "cozy-system" + // LabelGPUClass names the class of a license copy. The controller + // touches only Secrets carrying it. + LabelGPUClass = "cozystack.io/gpuclass" + // LicenseTokenKey is the token key of the hoster's Secret and of each + // copy; LicenseGriddConfKey is the copy's gridd.conf with the class's + // FeatureType. + LicenseTokenKey = "client_configuration_token.tok" + LicenseGriddConfKey = "gridd.conf" + // LicenseVolumeLabel is the volume label of the license disk a VMI of + // a licensed vGPU class gets; guest images find the disk by it. + LicenseVolumeLabel = "GPULICENSE" +) + +// LicenseSecretName is the name of a class's license copy in an entitled +// namespace. +func LicenseSecretName(class string) string { + return "gpuclass-" + class + "-license" +} diff --git a/internal/gpu/consts_test.go b/internal/gpu/consts_test.go new file mode 100644 index 000000000..58fe2a1de --- /dev/null +++ b/internal/gpu/consts_test.go @@ -0,0 +1,25 @@ +/* +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 gpu + +import "testing" + +func TestLicenseSecretName(t *testing.T) { + if got := LicenseSecretName("l40s-24c"); got != "gpuclass-l40s-24c-license" { + t.Errorf("LicenseSecretName = %q", got) + } +} diff --git a/internal/gpu/model/class.go b/internal/gpu/model/class.go new file mode 100644 index 000000000..a733f06ba --- /dev/null +++ b/internal/gpu/model/class.go @@ -0,0 +1,132 @@ +/* +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 model + +import ( + "slices" + "strings" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" +) + +// Class is the part of a GPUClass that capacity and admission read. +type Class struct { + Name string + UID types.UID + Created metav1.Time + Mode cozyv1alpha1.GPUMode + ResourceName corev1.ResourceName + OwnedResourceName corev1.ResourceName + Tolerations []corev1.Toleration +} + +func ClassFrom(c *cozyv1alpha1.GPUClass) Class { + out := Class{Name: c.Name, UID: c.UID, Created: c.CreationTimestamp, Mode: c.Spec.Mode, OwnedResourceName: corev1.ResourceName(c.Status.OwnedResourceName)} + for _, t := range c.Spec.Tolerations { + out.Tolerations = append(out.Tolerations, t.Toleration()) + } + if dp := c.Spec.Source.DevicePlugin; dp != nil { + out.ResourceName = corev1.ResourceName(dp.ResourceName) + } + return out +} + +// EffectiveMaxCount returns how many GPUs of the class one VM may take, +// and false when nothing beyond one node's GPUs limits it. +func EffectiveMaxCount(spec *cozyv1alpha1.GPUClassSpec) (int32, bool) { + if spec.MaxCount != nil { + return *spec.MaxCount, true + } + if spec.Mode == cozyv1alpha1.GPUModeVGPU { + return 1, true + } + return 0, false +} + +// ResourceNameCandidates selects an existing owner, or a creation-time/name +// candidate for an unreserved name. A reservation survives a changed request; +// duplicates block that name even when their holders request other names. +// Candidates are not offered until their ownership is acknowledged. +func ResourceNameCandidates(classes []Class) map[corev1.ResourceName]types.UID { + reserved := map[corev1.ResourceName][]Class{} + requested := map[corev1.ResourceName][]Class{} + for _, c := range classes { + if c.OwnedResourceName != "" { + reserved[c.OwnedResourceName] = append(reserved[c.OwnedResourceName], c) + } + if c.ResourceName != "" { + requested[c.ResourceName] = append(requested[c.ResourceName], c) + } + } + out := map[corev1.ResourceName]types.UID{} + for name, owners := range reserved { + if len(owners) == 1 && owners[0].UID != "" { + out[name] = owners[0].UID + } + } + for name, group := range requested { + if _, held := reserved[name]; held { + continue + } + slices.SortFunc(group, func(a, b Class) int { + if c := a.Created.Compare(b.Created.Time); c != 0 { + return c + } + return strings.Compare(a.Name, b.Name) + }) + if group[0].UID != "" { + out[name] = group[0].UID + } + } + return out +} + +// ConfirmedResourceNames returns exact requested names uniquely acknowledged +// by their current object UIDs in this snapshot. It is not a transaction with +// future status writes or a capacity reservation. +func ConfirmedResourceNames(classes []Class) map[types.UID]corev1.ResourceName { + candidates := ResourceNameCandidates(classes) + out := map[types.UID]corev1.ResourceName{} + for _, c := range classes { + if c.UID != "" && c.ResourceName != "" && c.ResourceName == c.OwnedResourceName && candidates[c.ResourceName] == c.UID { + out[c.UID] = c.ResourceName + } + } + return out +} + +// Conflicts returns classes whose requested name is reserved or selected for +// another UID, or has ambiguous ownership. A nonconflicting candidate may still +// be pending acknowledgement; admission must use ConfirmedResourceNames too. +func Conflicts(classes []Class) sets.Set[string] { + candidates := ResourceNameCandidates(classes) + out := sets.New[string]() + for _, c := range classes { + if c.ResourceName == "" { + continue + } + if owner, ok := candidates[c.ResourceName]; !ok || owner != c.UID { + out.Insert(c.Name) + } + } + return out +} diff --git a/internal/gpu/model/class_test.go b/internal/gpu/model/class_test.go new file mode 100644 index 000000000..10ba6f447 --- /dev/null +++ b/internal/gpu/model/class_test.go @@ -0,0 +1,266 @@ +/* +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 model + +import ( + "reflect" + "slices" + "testing" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/utils/ptr" + + cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" +) + +const ( + h100Name = corev1.ResourceName("nvidia.com/GH100_H100") + l40sName = corev1.ResourceName("nvidia.com/NVIDIA_L40S-24C") +) + +func TestEffectiveMaxCount(t *testing.T) { + tests := []struct { + name string + spec cozyv1alpha1.GPUClassSpec + want int32 + wantLimit bool + }{ + {"vgpu unset defaults to 1", cozyv1alpha1.GPUClassSpec{Mode: cozyv1alpha1.GPUModeVGPU}, 1, true}, + {"vgpu set", cozyv1alpha1.GPUClassSpec{Mode: cozyv1alpha1.GPUModeVGPU, MaxCount: ptr.To[int32](2)}, 2, true}, + {"passthrough unset is no limit", cozyv1alpha1.GPUClassSpec{Mode: cozyv1alpha1.GPUModePassthrough}, 0, false}, + {"passthrough set", cozyv1alpha1.GPUClassSpec{Mode: cozyv1alpha1.GPUModePassthrough, MaxCount: ptr.To[int32](4)}, 4, true}, + } + for _, tc := range tests { + got, limited := EffectiveMaxCount(&tc.spec) + if got != tc.want || limited != tc.wantLimit { + t.Errorf("%s: EffectiveMaxCount = (%d, %v), want (%d, %v)", tc.name, got, limited, tc.want, tc.wantLimit) + } + } +} + +func TestClassFrom(t *testing.T) { + seconds := int64(300) + class := &cozyv1alpha1.GPUClass{ + ObjectMeta: metav1.ObjectMeta{Name: "h100", UID: "h100-uid", CreationTimestamp: metav1.Unix(1000, 0)}, + Status: cozyv1alpha1.GPUClassStatus{OwnedResourceName: string(h100Name)}, + Spec: cozyv1alpha1.GPUClassSpec{ + Mode: cozyv1alpha1.GPUModePassthrough, + Tolerations: []cozyv1alpha1.GPUClassToleration{ + {Key: dedicatedTaint, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}, + {Key: "example.com/maintenance", Operator: corev1.TolerationOpEqual, Value: "planned", Effect: corev1.TaintEffectNoExecute, TolerationSeconds: &seconds}, + }, + Source: cozyv1alpha1.GPUClassSource{DevicePlugin: &cozyv1alpha1.DevicePluginSource{ResourceName: string(h100Name)}}, + }, + } + want := Class{Name: "h100", UID: "h100-uid", Created: metav1.Unix(1000, 0), Mode: cozyv1alpha1.GPUModePassthrough, ResourceName: h100Name, OwnedResourceName: h100Name, Tolerations: append(slices.Clone(tolerateDedicated), + corev1.Toleration{Key: "example.com/maintenance", Operator: corev1.TolerationOpEqual, Value: "planned", Effect: corev1.TaintEffectNoExecute, TolerationSeconds: &seconds})} + if got := ClassFrom(class); !reflect.DeepEqual(got, want) { + t.Errorf("ClassFrom = %+v, want %+v", got, want) + } +} + +func TestConflicts(t *testing.T) { + older, newer := metav1.Unix(1000, 0), metav1.Unix(2000, 0) + tests := []struct { + name string + classes []Class + want []string + }{ + {name: "distinct names", classes: []Class{{Name: "h100", ResourceName: h100Name}, {Name: "l40s-24c", ResourceName: l40sName}}}, + { + name: "the newer class conflicts", + classes: []Class{{Name: "h100", Created: older, ResourceName: h100Name}, {Name: "h100-alt", Created: newer, ResourceName: h100Name}, {Name: "l40s-24c", Created: newer, ResourceName: l40sName}}, + want: []string{"h100-alt"}, + }, + { + name: "the newer class conflicts whatever the list order", + classes: []Class{{Name: "h100-alt", Created: newer, ResourceName: h100Name}, {Name: "h100", Created: older, ResourceName: h100Name}}, + want: []string{"h100-alt"}, + }, + { + name: "creation time decides before the name", + classes: []Class{{Name: "a", Created: newer, ResourceName: h100Name}, {Name: "z", Created: older, ResourceName: h100Name}}, + want: []string{"a"}, + }, + { + name: "the name breaks a tie in creation time", + classes: []Class{{Name: "b", Created: older, ResourceName: h100Name}, {Name: "a", Created: older, ResourceName: h100Name}}, + want: []string{"b"}, + }, + { + name: "three classes on one name", + classes: []Class{{Name: "c", Created: newer, ResourceName: h100Name}, {Name: "a", Created: older, ResourceName: h100Name}, {Name: "b", Created: newer, ResourceName: h100Name}}, + want: []string{"b", "c"}, + }, + {name: "classes without a resource name do not conflict", classes: []Class{{Name: "a"}, {Name: "b"}}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + for i := range tc.classes { + tc.classes[i].UID = types.UID(tc.classes[i].Name) + } + if got := Conflicts(tc.classes); !got.Equal(sets.New(tc.want...)) { + t.Errorf("Conflicts = %v, want %v", sets.List(got), tc.want) + } + }) + } +} + +func nameClass(name string, created int64, requested, owned corev1.ResourceName) Class { + return Class{Name: name, UID: types.UID(name + "-uid"), Created: metav1.Unix(created, 0), ResourceName: requested, OwnedResourceName: owned} +} + +func TestResourceNameIncumbent(t *testing.T) { + owner := nameClass("owner", 2000, h100Name, h100Name) + contender := nameClass("older-edited", 1000, h100Name, l40sName) + for _, classes := range [][]Class{{owner, contender}, {contender, owner}} { + if got := Conflicts(classes); !got.Equal(sets.New(contender.Name)) { + t.Errorf("Conflicts = %v, want only %s", sets.List(got), contender.Name) + } + } +} + +func TestResourceNameReservationSurvivesUnrelatedStatus(t *testing.T) { + owner := &cozyv1alpha1.GPUClass{ + ObjectMeta: metav1.ObjectMeta{Name: "owner", UID: "owner-uid", CreationTimestamp: metav1.Unix(2000, 0), Generation: 1}, + Spec: cozyv1alpha1.GPUClassSpec{ + Mode: cozyv1alpha1.GPUModeVGPU, + Source: cozyv1alpha1.GPUClassSource{DevicePlugin: &cozyv1alpha1.DevicePluginSource{ResourceName: string(h100Name)}}, + }, + Status: cozyv1alpha1.GPUClassStatus{OwnedResourceName: string(h100Name)}, + } + contender := nameClass("older-edited", 1000, h100Name, l40sName) + for _, ready := range []metav1.ConditionStatus{metav1.ConditionFalse, metav1.ConditionUnknown, metav1.ConditionTrue} { + updated := owner.DeepCopy() + updated.Generation++ + updated.Spec.License = &cozyv1alpha1.GPUClassLicense{SecretName: "updated-license"} + updated.Status.Conditions = []metav1.Condition{ + {Type: "Ready", Status: ready, ObservedGeneration: owner.Generation}, + {Type: cozyv1alpha1.GPUClassResourceNameConflict, Status: metav1.ConditionTrue, ObservedGeneration: owner.Generation}, + } + classes := []Class{contender, ClassFrom(updated)} + if got := Conflicts(classes); !got.Equal(sets.New(contender.Name)) { + t.Errorf("Ready=%s: conflicts = %v", ready, sets.List(got)) + } + if got := ConfirmedResourceNames(classes); got[updated.UID] != h100Name || len(got) != 1 { + t.Errorf("Ready=%s: confirmed = %v", ready, got) + } + } +} + +func TestResourceNameAcknowledgement(t *testing.T) { + a := nameClass("a", 1000, h100Name, "") + b := nameClass("b", 2000, h100Name, "") + for _, classes := range [][]Class{{a, b}, {b, a}} { + if got := ResourceNameCandidates(classes); got[h100Name] != a.UID { + t.Errorf("candidates = %v, want %s", got, a.UID) + } + if got := ConfirmedResourceNames(classes); len(got) != 0 { + t.Errorf("unacknowledged classes offered: %v", got) + } + } + a.OwnedResourceName = h100Name + if got := ConfirmedResourceNames([]Class{b, a}); got[a.UID] != h100Name || len(got) != 1 { + t.Errorf("confirmed = %v, want acknowledged owner", got) + } +} + +func TestResourceNameTransition(t *testing.T) { + a := nameClass("a", 1000, l40sName, h100Name) + b := nameClass("b", 2000, h100Name, "") + classes := []Class{a, b} + if got := ResourceNameCandidates(classes); got[h100Name] != a.UID || got[l40sName] != a.UID { + t.Fatalf("pending rename candidates = %v", got) + } + if got := ConfirmedResourceNames(classes); len(got) != 0 { + t.Errorf("old reservation offers a new name: %v", got) + } + a.ResourceName = h100Name + if got := ConfirmedResourceNames([]Class{b, a}); got[a.UID] != h100Name { + t.Errorf("unacknowledged ABA lost the retained name: %v", got) + } + a.ResourceName, a.OwnedResourceName = l40sName, l40sName + b.OwnedResourceName = h100Name + a.ResourceName = h100Name + classes = []Class{a, b} + if got := Conflicts(classes); !got.Equal(sets.New(a.Name)) { + t.Errorf("acknowledged ABA conflicts = %v, want returning class", got) + } + if got := ConfirmedResourceNames(classes); got[b.UID] != h100Name || len(got) != 1 { + t.Errorf("acknowledged ABA confirmed = %v", got) + } +} + +func TestResourceNameDuplicateReservations(t *testing.T) { + a := nameClass("a", 1000, h100Name, h100Name) + b := nameClass("b", 2000, l40sName, h100Name) + for _, classes := range [][]Class{{a, b}, {b, a}} { + if got := ResourceNameCandidates(classes); got[h100Name] != "" { + t.Errorf("ambiguous name acquired a candidate: %v", got) + } + if got := ConfirmedResourceNames(classes); len(got) != 0 { + t.Errorf("ambiguous reservation offered: %v", got) + } + if got := Conflicts(classes); !got.Has(a.Name) { + t.Errorf("duplicate old-name reservation did not block its requester: %v", got) + } + } +} + +func TestResourceNameAmbiguitySurvivesConditionUpdates(t *testing.T) { + var objects []*cozyv1alpha1.GPUClass + for i, name := range []string{"older", "newer"} { + objects = append(objects, &cozyv1alpha1.GPUClass{ + ObjectMeta: metav1.ObjectMeta{Name: name, UID: types.UID(name), CreationTimestamp: metav1.Unix(int64(1000+i), 0)}, + Spec: cozyv1alpha1.GPUClassSpec{Source: cozyv1alpha1.GPUClassSource{ + DevicePlugin: &cozyv1alpha1.DevicePluginSource{ResourceName: string(h100Name)}, + }}, + Status: cozyv1alpha1.GPUClassStatus{OwnedResourceName: string(h100Name)}, + }) + } + for pass := range 3 { + classes := []Class{ClassFrom(objects[pass%2]), ClassFrom(objects[(pass+1)%2])} + if got := Conflicts(classes); !got.Equal(sets.New("older", "newer")) { + t.Errorf("pass %d: conflicts = %v", pass, got) + } + if got := ConfirmedResourceNames(classes); len(got) != 0 { + t.Errorf("pass %d: ambiguous name offered: %v", pass, got) + } + for _, obj := range objects { + obj.Status.Conditions = []metav1.Condition{{Type: cozyv1alpha1.GPUClassResourceNameConflict, Status: metav1.ConditionTrue, ObservedGeneration: obj.Generation}} + } + } +} + +func TestResourceNameIdentity(t *testing.T) { + old := nameClass("a", 1000, h100Name, h100Name) + recreated := nameClass("a", 3000, h100Name, "") + recreated.UID = "new-uid" + b := nameClass("b", 2000, h100Name, h100Name) + got := ConfirmedResourceNames([]Class{recreated, b}) + if got[old.UID] != "" || got[recreated.UID] != "" || got[b.UID] != h100Name { + t.Errorf("recreated identity inherited ownership: %v", got) + } + missingUID := nameClass("invalid", 1000, h100Name, h100Name) + missingUID.UID = "" + if got := ConfirmedResourceNames([]Class{missingUID}); len(got) != 0 { + t.Errorf("missing identity confirmed: %v", got) + } +} diff --git a/internal/gpu/model/kubevirt.go b/internal/gpu/model/kubevirt.go new file mode 100644 index 000000000..3e396ef02 --- /dev/null +++ b/internal/gpu/model/kubevirt.go @@ -0,0 +1,52 @@ +/* +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 model + +import ( + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/sets" +) + +// The KubeVirt CR the platform renders permittedHostDevices into. +const ( + KubeVirtNamespace = "cozy-kubevirt" + KubeVirtName = "kubevirt" +) + +// PermittedResourceNames returns the resource names of the KubeVirt CR's +// PCI and mediated permittedHostDevices lists, where GPUs are declared, or +// nil when the table is unset: KubeVirt checks GPU entries against it only +// when it is non-nil (renderresources.go validatePermittedHostDevices in +// v1.9.0). +func PermittedResourceNames(kv *unstructured.Unstructured) sets.Set[string] { + table, ok, _ := unstructured.NestedMap(kv.Object, "spec", "configuration", "permittedHostDevices") + if !ok || table == nil { + return nil + } + out := sets.New[string]() + for _, list := range []string{"pciHostDevices", "mediatedDevices"} { + entries, _, _ := unstructured.NestedSlice(table, list) + for _, e := range entries { + if m, ok := e.(map[string]any); ok { + if name, ok := m["resourceName"].(string); ok { + out.Insert(name) + } + } + } + } + return out +} diff --git a/internal/gpu/model/kubevirt_test.go b/internal/gpu/model/kubevirt_test.go new file mode 100644 index 000000000..6694060d6 --- /dev/null +++ b/internal/gpu/model/kubevirt_test.go @@ -0,0 +1,50 @@ +/* +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 model + +import ( + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/sets" +) + +func TestPermittedResourceNames(t *testing.T) { + kv := &unstructured.Unstructured{Object: map[string]any{}} + if PermittedResourceNames(kv) != nil { + t.Fatal("an unset table permits everything") + } + _ = unstructured.SetNestedField(kv.Object, map[string]any{}, "spec", "configuration", "permittedHostDevices") + if got := PermittedResourceNames(kv); got == nil || got.Len() != 0 { + t.Fatalf("an empty table permits nothing, got %v", got) + } + _ = unstructured.SetNestedField(kv.Object, map[string]any{ + "pciHostDevices": []any{ + map[string]any{"pciVendorSelector": "10de:26B9", "resourceName": "nvidia.com/L40S"}, + map[string]any{"pciVendorSelector": "15B3:101E", "resourceName": "nvidia.com/hostdev"}, + }, + "mediatedDevices": []any{ + map[string]any{"mdevNameSelector": "GRID A100-40C", "resourceName": "nvidia.com/GRID_A100-40C"}, + }, + "usbHostDevices": []any{map[string]any{"resourceName": "kubevirt.io/usb"}}, + }, "spec", "configuration", "permittedHostDevices") + + want := sets.New("nvidia.com/L40S", "nvidia.com/hostdev", "nvidia.com/GRID_A100-40C") + if got := PermittedResourceNames(kv); !got.Equal(want) { + t.Fatalf("permitted = %v, want %v", sets.List(got), sets.List(want)) + } +} diff --git a/internal/gpu/model/node.go b/internal/gpu/model/node.go new file mode 100644 index 000000000..c5f059fb8 --- /dev/null +++ b/internal/gpu/model/node.go @@ -0,0 +1,126 @@ +/* +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 model + +import ( + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" +) + +// Cordoned reports whether the node is cordoned. Only spec.unschedulable +// counts: a taint, such as the one Fence Agents Remediation sets, is not a +// cordon and goes through UntoleratedTaint instead. +func Cordoned(n *corev1.Node) bool { + return n.Spec.Unschedulable +} + +// Ready reports whether the node's Ready condition is True. +func Ready(n *corev1.Node) bool { + for _, c := range n.Status.Conditions { + if c.Type == corev1.NodeReady { + return c.Status == corev1.ConditionTrue + } + } + return false +} + +// mirrorsCordonOrReadiness reports whether the taint is one Kubernetes +// sets for a cordon or a node that is not Ready, which Cordoned and Ready +// already decide: the cordon taint as NoSchedule, the readiness taints with +// either effect. The node lifecycle controller removes these forms from a +// schedulable Ready node, a hand-applied one included, so seeing one there +// is a passing state. It never sets the cordon taint as NoExecute, so that +// one counts like any other taint. +func mirrorsCordonOrReadiness(t *corev1.Taint) bool { + switch t.Key { + case corev1.TaintNodeUnschedulable: + return t.Effect == corev1.TaintEffectNoSchedule + case corev1.TaintNodeNotReady, corev1.TaintNodeUnreachable: + return true + } + return false +} + +// UntoleratedTaint returns the first NoSchedule or NoExecute taint of the +// node that class c does not tolerate indefinitely, or nil, skipping the +// taints that mirror a cordon or readiness. Gt and Lt tolerations never match: where +// their feature gate is off the scheduler does not honour them, and a +// unit is better left out of free than counted in vain. +func UntoleratedTaint(n *corev1.Node, c Class) *corev1.Taint { + return untoleratedTaint(n.Spec.Taints, c.Tolerations) +} + +func untoleratedTaint(taints []corev1.Taint, tolerations []corev1.Toleration) *corev1.Taint { + for i := range taints { + taint := &taints[i] + if taint.Effect != corev1.TaintEffectNoSchedule && taint.Effect != corev1.TaintEffectNoExecute { + continue + } + if mirrorsCordonOrReadiness(taint) { + continue + } + tolerated := false + for j := range tolerations { + if taint.Effect == corev1.TaintEffectNoExecute && tolerations[j].TolerationSeconds != nil { + continue + } + if tolerations[j].ToleratesTaint(logr.Discard(), taint, false) { + tolerated = true + break + } + } + if !tolerated { + return taint + } + } + return nil +} + +// Node is the part of a Node that capacity reads. +type Node struct { + Name string + Allocatable map[corev1.ResourceName]int64 + // Usable is false for a cordoned or not Ready node, which adds nothing + // to any class whatever its taints. + Usable bool + Taints []corev1.Taint +} + +func NodeFrom(n *corev1.Node) Node { + alloc := make(map[corev1.ResourceName]int64, len(n.Status.Allocatable)) + for k, v := range n.Status.Allocatable { + alloc[k] = v.Value() + } + return Node{Name: n.Name, Allocatable: alloc, Usable: !Cordoned(n) && Ready(n), Taints: n.Spec.Taints} +} + +// FreeOnNode returns the free units of class c on node n: its allocatable +// count of the class's resource name minus what the pods scheduled there +// request of it, never below zero. A cordoned or not Ready node, or one +// with a taint the class does not tolerate, has none. +func FreeOnNode(c Class, n Node, pods []Pod) int64 { + if !n.Usable || untoleratedTaint(n.Taints, c.Tolerations) != nil { + return 0 + } + free := n.Allocatable[c.ResourceName] + for _, p := range pods { + if p.NodeName == n.Name { + free -= p.Units[c.ResourceName] + } + } + return max(free, 0) +} diff --git a/internal/gpu/model/node_test.go b/internal/gpu/model/node_test.go new file mode 100644 index 000000000..87acd3f96 --- /dev/null +++ b/internal/gpu/model/node_test.go @@ -0,0 +1,246 @@ +/* +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 model + +import ( + "reflect" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" +) + +func readyNode(mutate func(*corev1.Node)) *corev1.Node { + n := &corev1.Node{Status: corev1.NodeStatus{Conditions: []corev1.NodeCondition{{Type: corev1.NodeReady, Status: corev1.ConditionTrue}}}} + n.Name = "gpu-node-3" + if mutate != nil { + mutate(n) + } + return n +} + +func withTaint(key string, effect corev1.TaintEffect) func(*corev1.Node) { + return func(n *corev1.Node) { + n.Spec.Taints = append(n.Spec.Taints, corev1.Taint{Key: key, Effect: effect}) + } +} + +const ( + farTaint = "medik8s.io/fence-agents-remediation" + dedicatedTaint = "nvidia.com/gpu" +) + +var tolerateDedicated = []corev1.Toleration{{Key: dedicatedTaint, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}} + +func TestCordoned(t *testing.T) { + tests := []struct { + name string + node *corev1.Node + want bool + }{ + {"unschedulable", readyNode(func(n *corev1.Node) { n.Spec.Unschedulable = true }), true}, + {"schedulable", readyNode(nil), false}, + {"Fence Agents Remediation taint alone", readyNode(withTaint(farTaint, corev1.TaintEffectNoSchedule)), false}, + {"unschedulable taint without the field", readyNode(withTaint(corev1.TaintNodeUnschedulable, corev1.TaintEffectNoSchedule)), false}, + } + for _, tc := range tests { + if got := Cordoned(tc.node); got != tc.want { + t.Errorf("%s: Cordoned = %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestReady(t *testing.T) { + tests := []struct { + name string + node *corev1.Node + want bool + }{ + {"ready", readyNode(nil), true}, + {"not ready", readyNode(func(n *corev1.Node) { n.Status.Conditions[0].Status = corev1.ConditionFalse }), false}, + {"unknown", readyNode(func(n *corev1.Node) { n.Status.Conditions[0].Status = corev1.ConditionUnknown }), false}, + {"no condition", readyNode(func(n *corev1.Node) { n.Status.Conditions = nil }), false}, + } + for _, tc := range tests { + if got := Ready(tc.node); got != tc.want { + t.Errorf("%s: Ready = %v, want %v", tc.name, got, tc.want) + } + } +} + +func TestUntoleratedTaint(t *testing.T) { + tolerateFAR := []corev1.Toleration{{Key: farTaint, Operator: corev1.TolerationOpExists}} + tests := []struct { + name string + node *corev1.Node + tolerations []corev1.Toleration + want string + }{ + {name: "untainted", node: readyNode(nil)}, + {name: "untolerated NoSchedule", node: readyNode(withTaint(farTaint, corev1.TaintEffectNoSchedule)), want: farTaint}, + {name: "untolerated NoExecute", node: readyNode(withTaint("example.com/maintenance", corev1.TaintEffectNoExecute)), want: "example.com/maintenance"}, + {name: "tolerated NoSchedule", node: readyNode(withTaint(farTaint, corev1.TaintEffectNoSchedule)), tolerations: tolerateFAR}, + {name: "PreferNoSchedule does not count", node: readyNode(withTaint("example.com/soft", corev1.TaintEffectPreferNoSchedule))}, + // These taints mirror cordon and readiness, which the field and the + // condition already decide. + {name: "node.kubernetes.io/unschedulable", node: readyNode(withTaint(corev1.TaintNodeUnschedulable, corev1.TaintEffectNoSchedule))}, + // Kubernetes sets the cordon taint only as NoSchedule, so a NoExecute + // one is a hoster's taint like any other. + {name: "node.kubernetes.io/unschedulable as NoExecute", node: readyNode(withTaint(corev1.TaintNodeUnschedulable, corev1.TaintEffectNoExecute)), want: corev1.TaintNodeUnschedulable}, + {name: "node.kubernetes.io/not-ready", node: readyNode(withTaint(corev1.TaintNodeNotReady, corev1.TaintEffectNoExecute))}, + {name: "node.kubernetes.io/unreachable", node: readyNode(withTaint(corev1.TaintNodeUnreachable, corev1.TaintEffectNoExecute))}, + {name: "node.kubernetes.io/not-ready as NoSchedule", node: readyNode(withTaint(corev1.TaintNodeNotReady, corev1.TaintEffectNoSchedule))}, + {name: "node.kubernetes.io/unreachable as NoSchedule", node: readyNode(withTaint(corev1.TaintNodeUnreachable, corev1.TaintEffectNoSchedule))}, + // Pressure, network and out-of-service taints have no field or + // condition here that decides them, so they count like any other. + {name: "disk-pressure", node: readyNode(withTaint(corev1.TaintNodeDiskPressure, corev1.TaintEffectNoSchedule)), want: corev1.TaintNodeDiskPressure}, + {name: "network-unavailable", node: readyNode(withTaint(corev1.TaintNodeNetworkUnavailable, corev1.TaintEffectNoSchedule)), want: corev1.TaintNodeNetworkUnavailable}, + {name: "out-of-service", node: readyNode(withTaint(corev1.TaintNodeOutOfService, corev1.TaintEffectNoExecute)), want: corev1.TaintNodeOutOfService}, + { + name: "Gt toleration does not count", + node: readyNode(func(n *corev1.Node) { + n.Spec.Taints = []corev1.Taint{{Key: "example.com/gpu-gen", Value: "5", Effect: corev1.TaintEffectNoSchedule}} + }), + tolerations: []corev1.Toleration{{Key: "example.com/gpu-gen", Operator: corev1.TolerationOpGt, Value: "3", Effect: corev1.TaintEffectNoSchedule}}, + want: "example.com/gpu-gen", + }, + {name: "toleration of another effect", node: readyNode(withTaint(farTaint, corev1.TaintEffectNoExecute)), tolerations: []corev1.Toleration{{Key: farTaint, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoSchedule}}, want: farTaint}, + { + name: "first untolerated taint after a tolerated one", + node: readyNode(func(n *corev1.Node) { + withTaint(dedicatedTaint, corev1.TaintEffectNoSchedule)(n) + withTaint(farTaint, corev1.TaintEffectNoSchedule)(n) + }), + tolerations: tolerateDedicated, + want: farTaint, + }, + } + for _, tc := range tests { + got := UntoleratedTaint(tc.node, Class{Name: "h100", Tolerations: tc.tolerations}) + var key string + if got != nil { + key = got.Key + } + if key != tc.want { + t.Errorf("%s: UntoleratedTaint = %q, want %q", tc.name, key, tc.want) + } + } +} + +func TestEnduringToleration(t *testing.T) { + finite, zero, negative := int64(300), int64(0), int64(-1) + for _, tc := range []struct { + name string + seconds *int64 + }{ + {"finite", &finite}, {"zero", &zero}, {"negative", &negative}, {"enduring", nil}, + } { + for _, effect := range []corev1.TaintEffect{corev1.TaintEffectNoExecute, corev1.TaintEffectNoSchedule} { + t.Run(tc.name+"/"+string(effect), func(t *testing.T) { + taint := corev1.Taint{Key: dedicatedTaint, Effect: effect} + toleration := corev1.Toleration{Key: dedicatedTaint, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoExecute, TolerationSeconds: tc.seconds} + c := Class{ResourceName: h100Name, Tolerations: []corev1.Toleration{toleration}} + n := Node{Name: "gpu-node-3", Usable: true, Allocatable: map[corev1.ResourceName]int64{h100Name: 4}, Taints: []corev1.Taint{taint}} + want := int64(0) + if effect == corev1.TaintEffectNoExecute && tc.seconds == nil { + want = 4 + } + if got := FreeOnNode(c, n, nil); got != want { + t.Errorf("FreeOnNode = %d, want %d", got, want) + } + node := readyNode(withTaint(dedicatedTaint, effect)) + if got := UntoleratedTaint(node, c); (got == nil) != (want > 0) { + t.Errorf("UntoleratedTaint = %v, want tolerated %v", got, want > 0) + } + }) + } + } + for _, effect := range []corev1.TaintEffect{corev1.TaintEffectNoExecute, corev1.TaintEffectNoSchedule} { + for _, finiteFirst := range []bool{true, false} { + finiteToleration := corev1.Toleration{Key: dedicatedTaint, Operator: corev1.TolerationOpExists, Effect: corev1.TaintEffectNoExecute, TolerationSeconds: &finite} + enduring := corev1.Toleration{Key: dedicatedTaint, Operator: corev1.TolerationOpExists} + tolerations := []corev1.Toleration{finiteToleration, enduring} + if !finiteFirst { + tolerations[0], tolerations[1] = tolerations[1], tolerations[0] + } + n := Node{Usable: true, Allocatable: map[corev1.ResourceName]int64{h100Name: 4}, Taints: []corev1.Taint{{Key: dedicatedTaint, Effect: effect}}} + if got := FreeOnNode(Class{ResourceName: h100Name, Tolerations: tolerations}, n, nil); got != 4 { + t.Errorf("finiteFirst=%v effect=%s: FreeOnNode = %d, want 4", finiteFirst, effect, got) + } + } + } +} + +func TestNodeFrom(t *testing.T) { + n := readyNode(func(n *corev1.Node) { + n.Status.Allocatable = corev1.ResourceList{h100Name: resource.MustParse("8")} + n.Spec.Taints = []corev1.Taint{{Key: dedicatedTaint, Effect: corev1.TaintEffectNoSchedule}} + }) + got := NodeFrom(n) + if got.Name != "gpu-node-3" || got.Allocatable[h100Name] != 8 || !got.Usable || !reflect.DeepEqual(got.Taints, n.Spec.Taints) { + t.Errorf("NodeFrom = %+v", got) + } + for name, mutate := range map[string]func(*corev1.Node){ + "cordoned": func(n *corev1.Node) { n.Spec.Unschedulable = true }, + "not ready": func(n *corev1.Node) { n.Status.Conditions[0].Status = corev1.ConditionFalse }, + } { + if NodeFrom(readyNode(mutate)).Usable { + t.Errorf("NodeFrom of a %s node is usable", name) + } + } +} + +func TestFreeOnNode(t *testing.T) { + h100 := Class{Name: "h100", ResourceName: h100Name, Tolerations: tolerateDedicated} + node := func(mutate func(*corev1.Node)) Node { + return NodeFrom(readyNode(func(n *corev1.Node) { + n.Status.Allocatable = corev1.ResourceList{h100Name: resource.MustParse("4"), l40sName: resource.MustParse("16")} + if mutate != nil { + mutate(n) + } + })) + } + pod := func(nodeName string, units int64) Pod { + return Pod{Namespace: "tenant-acme", NodeName: nodeName, Units: map[corev1.ResourceName]int64{h100Name: units}} + } + tests := []struct { + name string + class Class + node Node + pods []Pod + want int64 + }{ + {name: "allocatable when nothing runs", class: h100, node: node(nil), want: 4}, + {name: "minus pod requests on the node", class: h100, node: node(nil), pods: []Pod{pod("gpu-node-3", 1), pod("gpu-node-3", 2)}, want: 1}, + {name: "pods on other nodes do not count", class: h100, node: node(nil), pods: []Pod{pod("gpu-node-4", 3)}, want: 4}, + {name: "unscheduled pods do not count", class: h100, node: node(nil), pods: []Pod{pod("", 3)}, want: 4}, + {name: "other resource names do not count", class: h100, node: node(nil), pods: []Pod{{NodeName: "gpu-node-3", Units: map[corev1.ResourceName]int64{l40sName: 8}}}, want: 4}, + {name: "never below zero", class: h100, node: node(nil), pods: []Pod{pod("gpu-node-3", 6)}, want: 0}, + {name: "cordoned", class: h100, node: node(func(n *corev1.Node) { n.Spec.Unschedulable = true }), want: 0}, + {name: "not ready", class: h100, node: node(func(n *corev1.Node) { n.Status.Conditions[0].Status = corev1.ConditionFalse }), want: 0}, + {name: "untolerated taint", class: h100, node: node(withTaint(farTaint, corev1.TaintEffectNoSchedule)), want: 0}, + {name: "tolerated taint", class: h100, node: node(withTaint(dedicatedTaint, corev1.TaintEffectNoSchedule)), want: 4}, + {name: "taint mirroring readiness", class: h100, node: node(withTaint(corev1.TaintNodeNotReady, corev1.TaintEffectNoExecute)), want: 4}, + {name: "node that does not advertise the name", class: Class{Name: "a100", ResourceName: "nvidia.com/GA100_A100"}, node: node(nil), want: 0}, + {name: "class without a resource name", class: Class{Name: "x"}, node: node(nil), want: 0}, + } + for _, tc := range tests { + if got := FreeOnNode(tc.class, tc.node, tc.pods); got != tc.want { + t.Errorf("%s: FreeOnNode = %d, want %d", tc.name, got, tc.want) + } + } +} diff --git a/internal/gpu/model/pod.go b/internal/gpu/model/pod.go new file mode 100644 index 000000000..552aca0d3 --- /dev/null +++ b/internal/gpu/model/pod.go @@ -0,0 +1,84 @@ +/* +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 model + +import ( + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/sets" +) + +// Pod is the GPU units a pod requests. +type Pod struct { + Namespace string + // NodeName is empty for a pod not yet scheduled, which takes no unit + // of any node. + NodeName string + Units map[corev1.ResourceName]int64 +} + +// PodFrom returns the units p requests of each name in gpuNames, and +// false when it requests none or is finished. +func PodFrom(p *corev1.Pod, gpuNames sets.Set[corev1.ResourceName]) (Pod, bool) { + if p.Status.Phase == corev1.PodSucceeded || p.Status.Phase == corev1.PodFailed { + return Pod{}, false + } + units := map[corev1.ResourceName]int64{} + for name := range gpuNames { + if u := podUnits(p, name); u > 0 { + units[name] = u + } + } + if len(units) == 0 { + return Pod{}, false + } + return Pod{Namespace: p.Namespace, NodeName: p.Spec.NodeName, Units: units}, true +} + +// podUnits is the pod's effective request of name, as the scheduler +// computes it: sidecars (init containers that always restart) run beside +// the later init containers and the main ones, and the pod overhead comes +// on top. +func podUnits(p *corev1.Pod, name corev1.ResourceName) int64 { + var sum, sidecars, initPeak int64 + for i := range p.Spec.Containers { + sum += containerUnits(&p.Spec.Containers[i], name) + } + for i := range p.Spec.InitContainers { + c := &p.Spec.InitContainers[i] + u := containerUnits(c, name) + if c.RestartPolicy != nil && *c.RestartPolicy == corev1.ContainerRestartPolicyAlways { + sidecars += u + initPeak = max(initPeak, sidecars) + continue + } + initPeak = max(initPeak, sidecars+u) + } + return max(sum+sidecars, initPeak) + p.Spec.Overhead.Name(name, resource.DecimalSI).Value() +} + +// containerUnits reads the limit first: an extended resource may be given +// as a limit alone, and when both are set they are equal. +func containerUnits(c *corev1.Container, name corev1.ResourceName) int64 { + if q, ok := c.Resources.Limits[name]; ok { + return q.Value() + } + if q, ok := c.Resources.Requests[name]; ok { + return q.Value() + } + return 0 +} diff --git a/internal/gpu/model/pod_test.go b/internal/gpu/model/pod_test.go new file mode 100644 index 000000000..f0615f33b --- /dev/null +++ b/internal/gpu/model/pod_test.go @@ -0,0 +1,153 @@ +/* +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 model + +import ( + "reflect" + "testing" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + "k8s.io/apimachinery/pkg/util/sets" +) + +func gpuContainer(limits, requests corev1.ResourceList) corev1.Container { + return corev1.Container{Resources: corev1.ResourceRequirements{Limits: limits, Requests: requests}} +} + +func sidecar(limits corev1.ResourceList) corev1.Container { + c := gpuContainer(limits, nil) + always := corev1.ContainerRestartPolicyAlways + c.RestartPolicy = &always + return c +} + +func TestPodFrom(t *testing.T) { + names := sets.New(h100Name, l40sName) + one := resource.MustParse("1") + two := resource.MustParse("2") + tests := []struct { + name string + pod corev1.Pod + want map[corev1.ResourceName]int64 + wantOK bool + }{ + { + name: "limits", + pod: corev1.Pod{Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: two}, nil)}}}, + want: map[corev1.ResourceName]int64{h100Name: 2}, + wantOK: true, + }, + { + name: "requests only", + pod: corev1.Pod{Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(nil, corev1.ResourceList{h100Name: one})}}}, + want: map[corev1.ResourceName]int64{h100Name: 1}, + wantOK: true, + }, + { + name: "two names in two containers", + pod: corev1.Pod{Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: two}, nil), gpuContainer(corev1.ResourceList{l40sName: one}, nil)}}}, + want: map[corev1.ResourceName]int64{h100Name: 2, l40sName: 1}, + wantOK: true, + }, + { + name: "name outside the set ignored", + pod: corev1.Pod{Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(corev1.ResourceList{"nvidia.com/hostdev": one}, nil)}}}, + wantOK: false, + }, + { + name: "init container larger than the sum", + pod: corev1.Pod{Spec: corev1.PodSpec{ + InitContainers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: two}, nil)}, + Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: one}, nil)}, + }}, + want: map[corev1.ResourceName]int64{h100Name: 2}, + wantOK: true, + }, + { + name: "sidecar adds to the main containers", + pod: corev1.Pod{Spec: corev1.PodSpec{ + InitContainers: []corev1.Container{sidecar(corev1.ResourceList{h100Name: one})}, + Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: one}, nil)}, + }}, + want: map[corev1.ResourceName]int64{h100Name: 2}, + wantOK: true, + }, + { + name: "init container runs beside an earlier sidecar", + pod: corev1.Pod{Spec: corev1.PodSpec{ + InitContainers: []corev1.Container{ + sidecar(corev1.ResourceList{h100Name: one}), + gpuContainer(corev1.ResourceList{h100Name: two}, nil), + }, + Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: one}, nil)}, + }}, + want: map[corev1.ResourceName]int64{h100Name: 3}, + wantOK: true, + }, + { + name: "init container before a sidecar does not run beside it", + pod: corev1.Pod{Spec: corev1.PodSpec{ + InitContainers: []corev1.Container{ + gpuContainer(corev1.ResourceList{h100Name: two}, nil), + sidecar(corev1.ResourceList{h100Name: one}), + }, + Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: one}, nil)}, + }}, + want: map[corev1.ResourceName]int64{h100Name: 2}, + wantOK: true, + }, + { + // The scheduler adds a RuntimeClass overhead to the pod's request. + name: "overhead adds to the request", + pod: corev1.Pod{Spec: corev1.PodSpec{ + Overhead: corev1.ResourceList{h100Name: one}, + Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: one}, nil)}, + }}, + want: map[corev1.ResourceName]int64{h100Name: 2}, + wantOK: true, + }, + { + name: "succeeded pod requests nothing", + pod: corev1.Pod{ + Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: two}, nil)}}, + Status: corev1.PodStatus{Phase: corev1.PodSucceeded}, + }, + wantOK: false, + }, + { + name: "failed pod requests nothing", + pod: corev1.Pod{ + Spec: corev1.PodSpec{Containers: []corev1.Container{gpuContainer(corev1.ResourceList{h100Name: two}, nil)}}, + Status: corev1.PodStatus{Phase: corev1.PodFailed}, + }, + wantOK: false, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + tc.pod.Namespace, tc.pod.Spec.NodeName = "tenant-acme", "n1" + got, ok := PodFrom(&tc.pod, names) + if ok != tc.wantOK { + t.Fatalf("ok = %v, want %v", ok, tc.wantOK) + } + if ok && (!reflect.DeepEqual(got.Units, tc.want) || got.Namespace != "tenant-acme" || got.NodeName != "n1") { + t.Errorf("PodFrom = %+v, want units %v", got, tc.want) + } + }) + } +} diff --git a/internal/gpu/model/quota.go b/internal/gpu/model/quota.go new file mode 100644 index 000000000..8c9e3f0a7 --- /dev/null +++ b/internal/gpu/model/quota.go @@ -0,0 +1,59 @@ +/* +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 model + +import ( + "strings" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/util/validation" + + "github.com/cozystack/cozystack/internal/gpu" +) + +// QuotaKey is a parsed GPU budget key. +type QuotaKey struct { + // Class is the class the key limits; empty when Total is set. + Class string + Total bool +} + +// ParseQuotaKey parses a resourceQuotas key of the form +// .gpuclass.cozystack.io/devices or gpuclass.cozystack.io/devices. +func ParseQuotaKey(key corev1.ResourceName) (QuotaKey, bool) { + if key == gpu.QuotaKeyTotal { + return QuotaKey{Total: true}, true + } + class, ok := strings.CutSuffix(string(key), "."+gpu.QuotaKeyTotal) + if !ok || len(validation.IsDNS1123Label(class)) > 0 { + return QuotaKey{}, false + } + return QuotaKey{Class: class}, true +} + +// ClassQuotaKey is the budget key of one class. +func ClassQuotaKey(class string) corev1.ResourceName { + return corev1.ResourceName(class + "." + gpu.QuotaKeyTotal) +} + +// IsGPUQuotaKey reports whether key is in the GPU budget domain, +// well-formed or not. Such keys are not resource names a pod requests, so +// they stay out of the namespace ResourceQuota. +func IsGPUQuotaKey(key corev1.ResourceName) bool { + domain, _, _ := strings.Cut(string(key), "/") + return domain == gpu.QuotaKeyDomain || strings.HasSuffix(domain, "."+gpu.QuotaKeyDomain) +} diff --git a/internal/gpu/model/quota_test.go b/internal/gpu/model/quota_test.go new file mode 100644 index 000000000..bde7d0638 --- /dev/null +++ b/internal/gpu/model/quota_test.go @@ -0,0 +1,86 @@ +/* +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 model + +import ( + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" +) + +func TestParseQuotaKey(t *testing.T) { + tests := []struct { + key corev1.ResourceName + wantClass string + wantTotal bool + wantOK bool + }{ + {key: "l40s-24c.gpuclass.cozystack.io/devices", wantClass: "l40s-24c", wantOK: true}, + {key: "total.gpuclass.cozystack.io/devices", wantClass: "total", wantOK: true}, + {key: "gpuclass.cozystack.io/devices", wantTotal: true, wantOK: true}, + {key: ".gpuclass.cozystack.io/devices"}, + {key: "a.b.gpuclass.cozystack.io/devices"}, + {key: "H100.gpuclass.cozystack.io/devices"}, + {key: corev1.ResourceName(strings.Repeat("a", 64) + ".gpuclass.cozystack.io/devices")}, + {key: "h100.gpuclass.cozystack.io/units"}, + {key: "h100.gpuclass.cozystack.io/devices/x"}, + {key: "gpuclass.cozystack.io/"}, + {key: "xgpuclass.cozystack.io/devices"}, + {key: "requests.h100.gpuclass.cozystack.io/devices"}, + {key: "nvidia.com/GH100_H100"}, + {key: "cpu"}, + } + for _, tc := range tests { + t.Run(string(tc.key), func(t *testing.T) { + k, ok := ParseQuotaKey(tc.key) + if ok != tc.wantOK || k.Class != tc.wantClass || k.Total != tc.wantTotal { + t.Errorf("ParseQuotaKey = (%+v, %v), want ({Class:%s Total:%v}, %v)", k, ok, tc.wantClass, tc.wantTotal, tc.wantOK) + } + }) + } +} + +func TestClassQuotaKey(t *testing.T) { + if got := ClassQuotaKey("h100"); got != "h100.gpuclass.cozystack.io/devices" { + t.Errorf("ClassQuotaKey = %s", got) + } + k, ok := ParseQuotaKey(ClassQuotaKey("h100")) + if !ok || k.Class != "h100" || k.Total { + t.Errorf("round trip gave (%+v, %v)", k, ok) + } +} + +// Every key in the budget domain is a GPU key, well-formed or not, so a +// mistyped budget never renders into a ResourceQuota as a pod resource. +func TestIsGPUQuotaKey(t *testing.T) { + for key, want := range map[corev1.ResourceName]bool{ + "h100.gpuclass.cozystack.io/devices": true, + "gpuclass.cozystack.io/devices": true, + "gpuclass.cozystack.io/": true, + "a.b.gpuclass.cozystack.io/units": true, + "xgpuclass.cozystack.io/devices": false, + "gpuclass.cozystack.io.example/x": false, + "nvidia.com/GH100_H100": false, + "cpu": false, + "requests.cpu": false, + } { + if got := IsGPUQuotaKey(key); got != want { + t.Errorf("IsGPUQuotaKey(%s) = %v, want %v", key, got, want) + } + } +} diff --git a/internal/gpu/model/tenant.go b/internal/gpu/model/tenant.go new file mode 100644 index 000000000..17762cf83 --- /dev/null +++ b/internal/gpu/model/tenant.go @@ -0,0 +1,26 @@ +/* +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 model + +import "github.com/cozystack/cozystack/internal/gpu" + +// Entitled reports whether a tenant namespace's labels grant vGPU. The +// tenant chart writes the effective value, parent included, so the label +// alone decides. +func Entitled(namespaceLabels map[string]string) bool { + return namespaceLabels[gpu.LabelNamespaceVGPU] == gpu.LabelValueTrue +} diff --git a/internal/gpu/model/tenant_test.go b/internal/gpu/model/tenant_test.go new file mode 100644 index 000000000..6b50737bd --- /dev/null +++ b/internal/gpu/model/tenant_test.go @@ -0,0 +1,38 @@ +/* +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 model + +import "testing" + +func TestEntitled(t *testing.T) { + tests := []struct { + name string + labels map[string]string + want bool + }{ + {"label true", map[string]string{"namespace.cozystack.io/vgpu": "true"}, true}, + {"label false", map[string]string{"namespace.cozystack.io/vgpu": "false"}, false}, + {"label True is not true", map[string]string{"namespace.cozystack.io/vgpu": "True"}, false}, + {"no label", map[string]string{"other": "true"}, false}, + {"nil labels", nil, false}, + } + for _, tc := range tests { + if got := Entitled(tc.labels); got != tc.want { + t.Errorf("%s: Entitled = %v, want %v", tc.name, got, tc.want) + } + } +}