feat(api): check GPU budgets when a VM or a worker pool is written

GPU budgets are not pod resources, so ResourceQuota cannot enforce them.
Until the pool-wide admission gate is available, the API server needs
to check declared class reservations to avoid accepting applications
that exceed a tenant's budget. Reusing its inputs and pool arithmetic
keeps the eventual switch from changing admission decisions.

Tenant quota allocation must account for those reservations because
ResourceQuota usage cannot report them. Ordinary-resource accounting
must retain GPU-only descendants in the parent's pool, matching the
tenant chart and runtime controller. Unsupported keys in the GPU budget
domain must not create an unenforced promise when the chart omits them.

Assisted-by: LLM
Signed-off-by: Aleksei Sviridkin <f@lex.la>
This commit is contained in:
Aleksei Sviridkin committed 2026-11-28 07:18:08 +03:00
1 parent 3a1bb156b9
commit 2d8af2bfe8
8 files changed
+857 -32

No files matched your search

@@ -340,7 +340,7 @@ func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
// ownedNamespace maps a tenant HelmRelease (name "<prefix><app>" in namespace
// hrNamespace) to the namespace that tenant owns. It mirrors
// REST.computeTenantNamespace in the aggregated apiserver.
// computeTenantNamespace in the aggregated apiserver.
func ownedNamespace(hrNamespace, appName string) string {
switch {
case hrNamespace == rootTenantNamespace && appName == "root":
+8
View File
@@ -118,6 +118,14 @@ The `resourceQuotas` parameter allows you to limit resources available to the te
- `secrets` - Maximum number of Secrets
- `persistentvolumeclaims` - Maximum number of PVCs
**GPU budgets** (checked when a VM or a worker pool is written, never rendered into the namespace ResourceQuota):
- `<class>.gpuclass.cozystack.io/devices` - GPUs of one GPUClass, each vGPU counting as one
- `gpuclass.cozystack.io/devices` - GPUs of every class together
A `VMInstance` reserves the `count` of each class entry and a `KubernetesNodes` pool reserves `count` times `maxReplicas`, stopped VMs included. A tenant with only GPU budgets gets no ResourceQuota and no default LimitRange.
GPU budgets are checked against the application's tenant pool, not recursively against every ancestor's GPU budget.
**Example:**
```yaml
resourceQuotas:
+287
View File
@@ -0,0 +1,287 @@
/*
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 application
import (
"context"
"encoding/json"
"fmt"
"math"
"slices"
"sort"
"strings"
"sync"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/cozystack/cozystack/internal/gpu"
"github.com/cozystack/cozystack/internal/gpu/model"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/apis/apps/validation"
)
const (
vmInstanceKind = "VMInstance"
kubernetesNodesKind = "KubernetesNodes"
)
// tenantReleasePrefix is the name prefix of a Tenant's HelmRelease and namespace.
const tenantReleasePrefix = "tenant-"
// specSchemas maps an application kind to its spec schema. NewREST fills
// it, so a check served by one kind can default the stored values of
// another, the way the chart reads them.
var specSchemas sync.Map
type gpuEntry struct {
ClassName string `json:"className"`
Count *int64 `json:"count"`
}
type gpuValues struct {
GPUs []gpuEntry `json:"gpus"`
MaxReplicas *int64 `json:"maxReplicas"`
}
// gpuDemand returns the GPU budget units an application's values reserve,
// by budget key: every class entry reserves its count under its class key
// and under the all-class key, times maxReplicas for a worker pool. Raw
// name entries reserve nothing.
func gpuDemand(kind string, raw []byte) (map[string]int64, error) {
if kind != vmInstanceKind && kind != kubernetesNodesKind {
return nil, nil
}
values := map[string]any{}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &values); err != nil {
return nil, fmt.Errorf("decode %s values: %w", kind, err)
}
}
if s, ok := specSchemas.Load(kind); ok {
if err := defaultLikeKubernetes(&values, s.(*structuralschema.Structural)); err != nil {
return nil, fmt.Errorf("default %s values: %w", kind, err)
}
}
defaulted, err := json.Marshal(values)
if err != nil {
return nil, err
}
var v gpuValues
if err := json.Unmarshal(defaulted, &v); err != nil {
return nil, fmt.Errorf("decode %s gpus: %w", kind, err)
}
classEntries := slices.ContainsFunc(v.GPUs, func(e gpuEntry) bool { return e.ClassName != "" })
replicas := int64(1)
if kind == kubernetesNodesKind && classEntries {
if v.MaxReplicas == nil {
return nil, fmt.Errorf("decode %s values: no maxReplicas", kind)
}
replicas = *v.MaxReplicas
if replicas < 0 {
return nil, fmt.Errorf("decode %s values: maxReplicas %d is negative", kind, replicas)
}
}
demand := map[string]int64{}
for _, e := range v.GPUs {
if e.ClassName == "" {
continue
}
count := int64(1)
if e.Count != nil {
count = *e.Count
}
if count < 1 {
return nil, fmt.Errorf("decode %s gpus: class %s has count %d, below 1", kind, e.ClassName, count)
}
if replicas > 0 && count > math.MaxInt64/replicas {
return nil, fmt.Errorf("decode %s gpus: class %s reserves more than %d units", kind, e.ClassName, int64(math.MaxInt64))
}
units := count * replicas
for _, k := range []string{string(model.ClassQuotaKey(e.ClassName)), gpu.QuotaKeyTotal} {
if units > math.MaxInt64-demand[k] {
return nil, fmt.Errorf("decode %s gpus: more than %d units under %s", kind, int64(math.MaxInt64), k)
}
demand[k] += units
}
}
return demand, nil
}
// tenantQuotas returns the declared resourceQuotas of every tenant, keyed
// by the namespace the tenant owns.
func (r *REST) tenantQuotas(ctx context.Context) (map[string]map[string]resource.Quantity, error) {
releases := &helmv2.HelmReleaseList{}
selector := labels.SelectorFromSet(labels.Set{
ApplicationKindLabel: validation.TenantKind,
ApplicationGroupLabel: appsv1alpha1.GroupName,
})
if err := r.c.List(ctx, releases, &client.ListOptions{LabelSelector: selector}); err != nil {
return nil, err
}
out := make(map[string]map[string]resource.Quantity, len(releases.Items))
for i := range releases.Items {
hr := &releases.Items[i]
ns := computeTenantNamespace(hr.Namespace, strings.TrimPrefix(hr.Name, tenantReleasePrefix))
quotas, err := declaredQuotasFromHelmRelease(hr)
if err != nil {
klog.Warningf("skipping tenant %s/%s with unparseable quotas while checking GPU budgets: %v", hr.Namespace, hr.Name, err)
quotas = nil
}
out[ns] = quotas
}
return out, nil
}
func boundedTenants(quotas map[string]map[string]resource.Quantity) map[string]bool {
bounded := make(map[string]bool, len(quotas))
for ns, q := range quotas {
if len(q) > 0 {
bounded[ns] = true
}
}
return bounded
}
// gpuPoolUsage sums the GPU budget the class entries in the pool rooted at
// root reserve: the root's namespace plus every namespace whose nearest
// bounded ancestor is root, minus excludeNS. A release of the kind and name
// in skip is left out, so an update does not count against itself.
func (r *REST) gpuPoolUsage(ctx context.Context, root, excludeNS string, bounded map[string]bool, skip client.ObjectKey) (map[string]int64, error) {
used := map[string]int64{}
for _, kind := range []string{vmInstanceKind, kubernetesNodesKind} {
releases := &helmv2.HelmReleaseList{}
selector := labels.SelectorFromSet(labels.Set{
ApplicationKindLabel: kind,
ApplicationGroupLabel: appsv1alpha1.GroupName,
})
if err := r.c.List(ctx, releases, &client.ListOptions{LabelSelector: selector}); err != nil {
return nil, err
}
for i := range releases.Items {
hr := &releases.Items[i]
if hr.Namespace == excludeNS || client.ObjectKeyFromObject(hr) == skip || r.poolRootOf(hr.Namespace, bounded) != root {
continue
}
var raw []byte
if hr.Spec.Values != nil {
raw = hr.Spec.Values.Raw
}
demand, err := gpuDemand(kind, raw)
if err != nil {
klog.Warningf("skipping %s %s/%s with unreadable gpus while checking GPU budgets: %v", kind, hr.Namespace, hr.Name, err)
continue
}
for k, v := range demand {
used[k] = min(used[k], math.MaxInt64-v) + v
}
}
}
return used, nil
}
// validateGPUBudget refuses a VMInstance or KubernetesNodes write whose
// class entries would take its pool over a declared GPU budget. It applies
// the tenant pool arithmetic to the declared resourceQuotas and the
// declared class entries, the inputs the pool-wide admission gate of the
// design reads. On an update only growth is checked, so shrinking and
// unchanged entries always pass.
func (r *REST) validateGPUBudget(ctx context.Context, app, old *appsv1alpha1.Application) field.ErrorList {
fldPath := field.NewPath("spec", "gpus")
demand, err := gpuDemand(r.kindName, specRaw(app))
if err != nil {
return field.ErrorList{field.Invalid(fldPath, "", err.Error())}
}
var previous map[string]int64
if old != nil {
// The stored values passed this check before, so a read failure
// counts them as reserving nothing and checks the full new demand.
previous, _ = gpuDemand(r.kindName, specRaw(old))
}
var grown []string
for k, v := range demand {
if v > previous[k] {
grown = append(grown, k)
}
}
if len(grown) == 0 {
return nil
}
sort.Strings(grown)
quotas, err := r.tenantQuotas(ctx)
if err != nil {
return field.ErrorList{field.InternalError(fldPath, err)}
}
bounded := boundedTenants(quotas)
root := r.poolRootOf(app.Namespace, bounded)
if root == "" {
return nil
}
budget := quotas[root]
carved := map[string]resource.Quantity{}
for ns, q := range quotas {
if r.poolRootOf(r.parentNamespaceOf(ns), bounded) == root {
addQuotas(carved, q)
}
}
used, err := r.gpuPoolUsage(ctx, root, "", bounded, client.ObjectKey{Namespace: app.Namespace, Name: r.releaseConfig.Prefix + app.Name})
if err != nil {
return field.ErrorList{field.InternalError(fldPath, err)}
}
var errs field.ErrorList
for _, k := range grown {
limit, ok := budget[k]
if !ok {
continue
}
reserved := carved[k].DeepCopy()
reserved.Add(*resource.NewQuantity(used[k], resource.DecimalSI))
total := reserved.DeepCopy()
total.Add(*resource.NewQuantity(demand[k], resource.DecimalSI))
if total.Cmp(limit) > 0 {
errs = append(errs, field.Forbidden(fldPath, fmt.Sprintf(
"GPU budget %q of tenant pool %s is %s and %s is already reserved; this application needs %d",
k, root, limit.String(), reserved.String(), demand[k])))
}
}
return errs
}
// parentPoolGPUUsage is the GPU counterpart of parentPoolUsage for the
// tenant declaration gate.
func (r *REST) parentPoolGPUUsage(ctx context.Context, parentNS, excludeNS string) (map[string]int64, error) {
quotas, err := r.tenantQuotas(ctx)
if err != nil {
return nil, err
}
return r.gpuPoolUsage(ctx, parentNS, excludeNS, boundedTenants(quotas), client.ObjectKey{})
}
func specRaw(app *appsv1alpha1.Application) []byte {
if app == nil || app.Spec == nil {
return nil
}
return app.Spec.Raw
}
@@ -0,0 +1,424 @@
/*
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 application
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"testing"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apiserver/pkg/endpoints/request"
"sigs.k8s.io/controller-runtime/pkg/client"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
)
const (
h100Key = "h100.gpuclass.cozystack.io/devices"
l40sKey = "l40s-24c.gpuclass.cozystack.io/devices"
totalKey = "gpuclass.cozystack.io/devices"
)
// The defaults the kubernetes-nodes and vm-instance charts declare for the
// fields the budget reads.
const (
kubernetesNodesTestSchema = `{"type":"object","properties":{"maxReplicas":{"type":"integer","default":10},"gpus":{"type":"array","default":[],"items":{"type":"object","properties":{"className":{"type":"string"},"count":{"type":"integer"},"name":{"type":"string"}}}}}}`
vmInstanceTestSchema = `{"type":"object","properties":{"gpus":{"type":"array","default":[],"items":{"type":"object","properties":{"className":{"type":"string"},"count":{"type":"integer"},"name":{"type":"string"}}}}}}`
)
func registerTestSchemas(t *testing.T) {
t.Helper()
for kind, raw := range map[string]string{kubernetesNodesKind: kubernetesNodesTestSchema, vmInstanceKind: vmInstanceTestSchema} {
s, err := buildSpecSchema(raw)
if err != nil {
t.Fatalf("build %s schema: %v", kind, err)
}
specSchemas.Store(kind, s)
}
}
func TestGPUDemand(t *testing.T) {
registerTestSchemas(t)
tests := []struct {
name string
kind string
values string
want map[string]int64
}{
{
name: "vm-instance class entries",
kind: vmInstanceKind,
values: `{"gpus":[{"className":"h100","count":2},{"className":"l40s-24c"}]}`,
want: map[string]int64{h100Key: 2, l40sKey: 1, totalKey: 3},
},
{
name: "two entries of one class add up",
kind: vmInstanceKind,
values: `{"gpus":[{"className":"h100","count":2},{"className":"h100","count":1}]}`,
want: map[string]int64{h100Key: 3, totalKey: 3},
},
{
name: "raw name entries reserve no budget",
kind: vmInstanceKind,
values: `{"gpus":[{"name":"nvidia.com/GH100_H100"}]}`,
want: map[string]int64{},
},
{name: "no gpus", kind: vmInstanceKind, values: `{}`, want: map[string]int64{}},
{
name: "kubernetes-nodes pool times maxReplicas",
kind: kubernetesNodesKind,
values: `{"maxReplicas":3,"gpus":[{"className":"h100","count":2}]}`,
want: map[string]int64{h100Key: 6, totalKey: 6},
},
{
name: "kubernetes-nodes maxReplicas from the chart default",
kind: kubernetesNodesKind,
values: `{"gpus":[{"className":"h100"}]}`,
want: map[string]int64{h100Key: 10, totalKey: 10},
},
{name: "other kinds reserve nothing", kind: "Postgres", values: `{"gpus":[{"className":"h100","count":2}]}`},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, err := gpuDemand(tc.kind, []byte(tc.values))
if err != nil {
t.Fatal(err)
}
if len(got) != len(tc.want) || (len(tc.want) > 0 && !reflect.DeepEqual(got, tc.want)) {
t.Errorf("gpuDemand = %v, want %v", got, tc.want)
}
})
}
}
// Without the chart default a worker pool's size is unknown, and reading it
// as zero would let any pool through.
func TestGPUDemandRefusesAPoolWithoutMaxReplicas(t *testing.T) {
registerTestSchemas(t)
s, _ := specSchemas.LoadAndDelete(kubernetesNodesKind)
t.Cleanup(func() { specSchemas.Store(kubernetesNodesKind, s) })
if _, err := gpuDemand(kubernetesNodesKind, []byte(`{"gpus":[{"className":"h100"}]}`)); err == nil {
t.Error("a pool without maxReplicas read as reserving nothing")
}
// A pool without class entries reserves nothing whatever its size.
if got, err := gpuDemand(kubernetesNodesKind, []byte(`{"gpus":[{"name":"nvidia.com/GH100_H100"}]}`)); err != nil || len(got) != 0 {
t.Errorf("pool without class entries = %v, %v; want no demand and no error", got, err)
}
}
func TestNewRESTRegistersTheSpecSchema(t *testing.T) {
NewREST(nil, nil, nil, &config.Resource{Application: config.ApplicationConfig{Kind: "GPUBudgetTestKind", Plural: "gpubudgettestkinds", OpenAPISchema: vmInstanceTestSchema}})
t.Cleanup(func() { specSchemas.Delete("GPUBudgetTestKind") })
if _, ok := specSchemas.Load("GPUBudgetTestKind"); !ok {
t.Error("NewREST did not register the kind's spec schema")
}
}
// A count below one would offset another entry of the same class, and an
// overflow would wrap to a negative demand; either would slip past the
// budget.
func TestGPUDemandRefusesUnusableValues(t *testing.T) {
registerTestSchemas(t)
for name, tc := range map[string]struct{ kind, values string }{
"count that is not a number": {vmInstanceKind, `{"gpus":[{"className":"h100","count":"two"}]}`},
"zero count": {vmInstanceKind, `{"gpus":[{"className":"h100","count":0}]}`},
"negative count": {vmInstanceKind, `{"gpus":[{"className":"h100","count":5},{"className":"h100","count":-4}]}`},
"negative maxReplicas": {kubernetesNodesKind, `{"maxReplicas":-1,"gpus":[{"className":"h100"}]}`},
"count times maxReplicas overflows": {kubernetesNodesKind, `{"maxReplicas":4,"gpus":[{"className":"h100","count":4611686018427387904}]}`},
"sum overflows": {vmInstanceKind, `{"gpus":[{"className":"h100","count":4611686018427387904},{"className":"h100","count":4611686018427387904}]}`},
} {
t.Run(name, func(t *testing.T) {
if got, err := gpuDemand(tc.kind, []byte(tc.values)); err == nil {
t.Errorf("read as demand %v", got)
}
})
}
}
func appHelmRelease(t *testing.T, kind, prefix, name, namespace, values string) *helmv2.HelmRelease {
t.Helper()
return &helmv2.HelmRelease{
ObjectMeta: metav1.ObjectMeta{
Name: prefix + name,
Namespace: namespace,
Labels: map[string]string{
ApplicationKindLabel: kind,
ApplicationGroupLabel: appsv1alpha1.GroupName,
ApplicationNameLabel: name,
},
},
Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(values)}},
}
}
func vmRelease(t *testing.T, name, namespace, values string) *helmv2.HelmRelease {
return appHelmRelease(t, vmInstanceKind, "vm-instance-", name, namespace, values)
}
func nodesRelease(t *testing.T, name, namespace, values string) *helmv2.HelmRelease {
return appHelmRelease(t, kubernetesNodesKind, "kubernetes-nodes-", name, namespace, values)
}
func newAppREST(t *testing.T, kind, prefix, plural string, objects ...client.Object) *REST {
t.Helper()
r := newTenantREST(t, objects...)
r.kindName = kind
r.gvk = schema.GroupVersionKind{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Kind: kind}
r.gvr = schema.GroupVersionResource{Group: appsv1alpha1.GroupName, Version: "v1alpha1", Resource: plural}
r.releaseConfig = config.ReleaseConfig{Prefix: prefix}
return r
}
func vmApplication(name, namespace, values string) *appsv1alpha1.Application {
return &appsv1alpha1.Application{
TypeMeta: metav1.TypeMeta{APIVersion: "apps.cozystack.io/v1alpha1", Kind: vmInstanceKind},
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
Spec: &apiextv1.JSON{Raw: []byte(values)},
}
}
func expectGPUErrs(t *testing.T, errs field.ErrorList, want string) {
t.Helper()
if want == "" {
if len(errs) > 0 {
t.Fatalf("refused: %v", errs)
}
return
}
if len(errs) == 0 {
t.Fatalf("admitted, want a refusal with %q", want)
}
if !strings.Contains(errs.ToAggregate().Error(), want) {
t.Errorf("refused for another reason, want %q: %v", want, errs)
}
}
func TestValidateGPUBudget(t *testing.T) {
registerTestSchemas(t)
root := tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "4", totalKey: "6"})
twoH100 := `{"gpus":[{"className":"h100","count":2}]}`
tests := []struct {
name string
objects []client.Object
app *appsv1alpha1.Application
old *appsv1alpha1.Application
want string
}{
{
name: "fits the class budget",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", twoH100)},
app: vmApplication("b", "tenant-root", twoH100),
},
{
name: "over the class budget names pool, key, limit and reservation",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", twoH100)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":3}]}`),
want: `GPU budget "h100.gpuclass.cozystack.io/devices" of tenant pool tenant-root is 4 and 2 is already reserved; this application needs 3`,
},
{
name: "over the all-class budget",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", `{"gpus":[{"className":"l40s-24c","count":5}]}`)},
app: vmApplication("b", "tenant-root", twoH100),
want: `GPU budget "gpuclass.cozystack.io/devices" of tenant pool tenant-root is 6 and 5 is already reserved`,
},
{
name: "an unbounded child tenant's VMs count in the parent pool",
objects: []client.Object{root, tenantHelmRelease(t, "acme", "tenant-root", nil), vmRelease(t, "a", "tenant-acme", `{"gpus":[{"className":"h100","count":3}]}`)},
app: vmApplication("b", "tenant-root", twoH100),
want: "4 and 3 is already reserved",
},
{
name: "a write in an unbounded child is checked against the parent pool",
objects: []client.Object{root, tenantHelmRelease(t, "acme", "tenant-root", nil), vmRelease(t, "a", "tenant-root", `{"gpus":[{"className":"h100","count":3}]}`)},
app: vmApplication("b", "tenant-acme", twoH100),
want: "of tenant pool tenant-root is 4",
},
{
name: "a bounded child tenant's declared budget is carved out",
objects: []client.Object{root, tenantHelmRelease(t, "acme", "tenant-root", map[string]string{h100Key: "3"})},
app: vmApplication("b", "tenant-root", twoH100),
want: "4 and 3 is already reserved",
},
{
name: "a bounded child tenant's usage is charged once, as its carve-out",
objects: []client.Object{
tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "10"}),
tenantHelmRelease(t, "acme", "tenant-root", map[string]string{h100Key: "2"}),
vmRelease(t, "a", "tenant-acme", twoH100),
},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":8}]}`),
},
{
name: "a write in a bounded child is checked against its own pool",
objects: []client.Object{root, tenantHelmRelease(t, "acme", "tenant-root", map[string]string{h100Key: "1"})},
app: vmApplication("b", "tenant-acme", twoH100),
want: "of tenant pool tenant-acme is 1",
},
{
name: "an ancestor's budget is not carved out of a child pool",
objects: []client.Object{root, tenantHelmRelease(t, "acme", "tenant-root", map[string]string{h100Key: "3"})},
app: vmApplication("b", "tenant-acme", twoH100),
},
{
name: "a namespace outside the tenant tree is not limited",
objects: []client.Object{root},
app: vmApplication("b", "default", `{"gpus":[{"className":"h100","count":9}]}`),
},
{
name: "a key the pool does not declare is not limited",
objects: []client.Object{tenantHelmRelease(t, "root", "tenant-root", map[string]string{l40sKey: "1"})},
app: vmApplication("b", "tenant-root", twoH100),
},
{
name: "no bounded tenant at all",
objects: []client.Object{tenantHelmRelease(t, "root", "tenant-root", nil)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":9}]}`),
},
{
name: "kubernetes-nodes pools reserve count times maxReplicas",
objects: []client.Object{root, nodesRelease(t, "workers", "tenant-root", `{"maxReplicas":2,"gpus":[{"className":"h100","count":1}]}`)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":3}]}`),
want: "4 and 2 is already reserved",
},
{
name: "update excludes the application's own release",
objects: []client.Object{root, vmRelease(t, "b", "tenant-root", twoH100), vmRelease(t, "a", "tenant-root", twoH100)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":2}]}`),
old: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":1}]}`),
},
{
name: "growing over the budget on update",
objects: []client.Object{root, vmRelease(t, "b", "tenant-root", twoH100), vmRelease(t, "a", "tenant-root", twoH100)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":3}]}`),
old: vmApplication("b", "tenant-root", twoH100),
want: "4 and 2 is already reserved; this application needs 3",
},
{
name: "shrinking passes in a pool already over its budget",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", `{"gpus":[{"className":"h100","count":5}]}`)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":1}]}`),
old: vmApplication("b", "tenant-root", twoH100),
},
{
name: "an unchanged entry passes in a pool already over its budget",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", `{"gpus":[{"className":"h100","count":5}]}`)},
app: vmApplication("b", "tenant-root", twoH100),
old: vmApplication("b", "tenant-root", twoH100),
},
{
name: "a fractional budget is not rounded up",
objects: []client.Object{tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "1500m"})},
app: vmApplication("b", "tenant-root", twoH100),
want: `of tenant pool tenant-root is 1500m and 0 is already reserved; this application needs 2`,
},
{
name: "a release with unreadable values is skipped",
objects: []client.Object{root, vmRelease(t, "a", "tenant-root", `{"gpus":[{"className":"h100","count":"x"}]}`)},
app: vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":4}]}`),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
r := newAppREST(t, vmInstanceKind, "vm-instance-", "vminstances", tc.objects...)
errs := r.validateGPUBudget(context.Background(), tc.app, tc.old)
expectGPUErrs(t, errs, tc.want)
})
}
}
func TestValidateGPUBudgetRefusesUnreadableValues(t *testing.T) {
registerTestSchemas(t)
r := newAppREST(t, vmInstanceKind, "vm-instance-", "vminstances", tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "4"}))
errs := r.validateGPUBudget(context.Background(), vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":"x"}]}`), nil)
expectGPUErrs(t, errs, "spec.gpus")
}
func TestValidateGPUBudgetIgnoresOtherKinds(t *testing.T) {
registerTestSchemas(t)
r := newAppREST(t, "Postgres", "postgres-", "postgreses", tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "0"}))
expectGPUErrs(t, r.validateGPUBudget(context.Background(), vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":2}]}`), nil), "")
}
// A key in the GPU budget domain that names no class budget would be kept
// out of the ResourceQuota and checked by nothing.
func TestValidateTenantResourceQuotasRefusesMalformedGPUKeys(t *testing.T) {
r := newTenantREST(t, tenantHelmRelease(t, "foo", "tenant-root", nil))
for _, key := range []string{"h100.gpuclass.cozystack.io/units", "a.b.gpuclass.cozystack.io/devices", "gpuclass.cozystack.io/total"} {
t.Run(key, func(t *testing.T) {
expectGPUErrs(t, r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{key: "1"})), "not a GPU budget key")
})
}
expectGPUErrs(t, r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{h100Key: "1", totalKey: "2", "xgpuclass.cozystack.io/devices": "1"})), "")
}
// A child tenant's GPU budget is carved out of what its parent's pool has
// left after the class entries already declared there.
func TestValidateTenantResourceQuotasCountsGPUClassEntries(t *testing.T) {
registerTestSchemas(t)
parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{h100Key: "4"})
vm := vmRelease(t, "a", "tenant-foo", `{"gpus":[{"className":"h100","count":3}]}`)
r := newTenantREST(t, parent, vm)
expectGPUErrs(t, r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{h100Key: "2"})), "3 currently in use by the parent pool")
expectGPUErrs(t, r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{h100Key: "1"})), "")
// The child's own namespace is excluded, as for every other key.
own := vmRelease(t, "b", "tenant-foo-bar", `{"gpus":[{"className":"h100","count":3}]}`)
r = newTenantREST(t, parent, own)
expectGPUErrs(t, r.validateTenantResourceQuotas(context.Background(), childApplication(t, "bar", "tenant-foo", map[string]string{h100Key: "4"})), "")
}
func newVMInstanceREST(t *testing.T, objects ...client.Object) *REST {
t.Helper()
r := newKubernetesWarnREST(t, objects...)
r.kindName = vmInstanceKind
r.gvk.Kind = vmInstanceKind
r.gvr.Resource = "vminstances"
r.releaseConfig = config.ReleaseConfig{Prefix: "vm-instance-"}
return r
}
func TestCreateAndUpdateCheckTheGPUBudget(t *testing.T) {
registerTestSchemas(t)
root := tenantHelmRelease(t, "root", "tenant-root", map[string]string{h100Key: "1"})
over := vmApplication("b", "tenant-root", `{"gpus":[{"className":"h100","count":2}]}`)
ctx := request.WithNamespace(context.Background(), "tenant-root")
sentinel := errors.New("past the GPU budget check")
r := newVMInstanceREST(t, root)
createValidation := func(context.Context, runtime.Object) error { return sentinel }
if _, err := r.Create(ctx, over.DeepCopy(), createValidation, &metav1.CreateOptions{}); errors.Is(err, sentinel) || !strings.Contains(fmt.Sprint(err), "GPU budget") {
t.Fatalf("Create = %v, want a GPU budget refusal", err)
}
existing := vmRelease(t, "b", "tenant-root", `{"gpus":[{"className":"h100","count":1}]}`)
r = newVMInstanceREST(t, root, existing)
updateValidation := func(context.Context, runtime.Object, runtime.Object) error { return nil }
_, _, err := r.Update(ctx, "b", newDefaultUpdatedObjectInfo(over.DeepCopy()), nil, updateValidation, false, &metav1.UpdateOptions{})
if !strings.Contains(fmt.Sprint(err), "GPU budget") {
t.Fatalf("Update = %v, want a GPU budget refusal", err)
}
}
+31 -9
View File
@@ -32,6 +32,7 @@ import (
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/cozystack/cozystack/internal/gpu/model"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/apis/apps/validation"
)
@@ -82,7 +83,7 @@ func declaredQuotasFromHelmRelease(hr *helmv2.HelmRelease) (map[string]resource.
// parentTenantHelmReleaseRef maps the namespace owned by a tenant to the
// name/namespace of that tenant's own HelmRelease. It is the inverse of
// REST.computeTenantNamespace: a tenant created as Application "<name>" in
// computeTenantNamespace: a tenant created as Application "<name>" in
// namespace C owns the workload namespace computeTenantNamespace(C, name), so
// given the owned namespace we recover (release name, release namespace).
//
@@ -193,6 +194,15 @@ func (r *REST) validateTenantResourceQuotas(ctx context.Context, app *appsv1alph
if err != nil {
return append(allErrs, field.Invalid(fldPath, "", err.Error()))
}
for _, res := range sortedQuotaKeys(childQuota) {
if _, ok := model.ParseQuotaKey(corev1.ResourceName(res)); model.IsGPUQuotaKey(corev1.ResourceName(res)) && !ok {
allErrs = append(allErrs, field.Invalid(fldPath.Key(res), res,
"is in the GPU budget domain but is not a GPU budget key; use <class>.gpuclass.cozystack.io/devices or gpuclass.cozystack.io/devices"))
}
}
if len(allErrs) > 0 {
return allErrs
}
if len(childQuota) == 0 {
// Unbounded child: shares the parent pool, allowed at declaration time.
return allErrs
@@ -220,11 +230,17 @@ func (r *REST) validateTenantResourceQuotas(ctx context.Context, app *appsv1alph
// best-effort (a snapshot; concurrent writes can briefly overshoot and
// already-running pods are never evicted) — the tenant-quota controller is
// the runtime backstop.
childNamespace := r.computeTenantNamespace(app.Namespace, app.Name)
childNamespace := computeTenantNamespace(app.Namespace, app.Name)
poolUsed, err := r.parentPoolUsage(ctx, app.Namespace, childNamespace)
if err != nil {
return append(allErrs, field.InternalError(fldPath, err))
}
// GPU budget keys never reach a ResourceQuota, so their pool usage is
// what the pool's class entries reserve.
gpuUsed, err := r.parentPoolGPUUsage(ctx, app.Namespace, childNamespace)
if err != nil {
return append(allErrs, field.InternalError(fldPath, err))
}
for _, res := range sortedQuotaKeys(parentQuota) {
want, requested := childQuota[res]
@@ -234,6 +250,9 @@ func (r *REST) validateTenantResourceQuotas(ctx context.Context, app *appsv1alph
parentLimit := parentQuota[res]
allocated := siblings[res] // zero value when no sibling bounds this resource
used := poolUsed[usageKey(res)]
if model.IsGPUQuotaKey(corev1.ResourceName(res)) {
used = *resource.NewQuantity(gpuUsed[res], resource.DecimalSI)
}
remaining := parentLimit.DeepCopy()
remaining.Sub(allocated)
remaining.Sub(used)
@@ -326,7 +345,7 @@ func usageKey(raw string) string {
// hierarchy is encoded in the namespace name, so the parent is recovered by
// stripping the trailing "-<name>" segment.
func (r *REST) parentNamespaceOf(ns string) string {
if ns == rootTenantNamespace || !strings.HasPrefix(ns, r.releaseConfig.Prefix) {
if ns == rootTenantNamespace || !strings.HasPrefix(ns, tenantReleasePrefix) {
return ""
}
segments := strings.Split(ns, "-")
@@ -355,9 +374,9 @@ func (r *REST) poolRootOf(ns string, bounded map[string]bool) string {
// created/updated). Usage is read from each member's ResourceQuota.status.used,
// taking a per-resource max within a namespace to avoid double-counting the
// chart-rendered and controller-allocated quotas, and is keyed in the rendered
// quota key space (see usageKey). Boundedness is decided by declared
// resourceQuotas so the result does not depend on whether Flux has rendered a
// freshly-created tenant's quota yet.
// quota key space (see usageKey). Only non-GPU declarations form these
// pools: the tenant chart omits GPU budgets from ResourceQuota. Using declared
// values avoids depending on whether Flux has rendered a new tenant yet.
func (r *REST) parentPoolUsage(ctx context.Context, parentNS, excludeNS string) (map[string]resource.Quantity, error) {
releases := &helmv2.HelmReleaseList{}
selector := labels.SelectorFromSet(labels.Set{
@@ -373,15 +392,18 @@ func (r *REST) parentPoolUsage(ctx context.Context, parentNS, excludeNS string)
for i := range releases.Items {
hr := &releases.Items[i]
name := strings.TrimPrefix(hr.Name, r.releaseConfig.Prefix)
ns := r.computeTenantNamespace(hr.Namespace, name)
ns := computeTenantNamespace(hr.Namespace, name)
owned = append(owned, ns)
quotas, err := declaredQuotasFromHelmRelease(hr)
if err != nil {
klog.Warningf("skipping tenant %s/%s with unparseable quotas while summing pool usage: %v", hr.Namespace, hr.Name, err)
continue
}
if len(quotas) > 0 {
bounded[ns] = true
for key := range quotas {
if !model.IsGPUQuotaKey(corev1.ResourceName(key)) {
bounded[ns] = true
break
}
}
}
@@ -371,6 +371,92 @@ func TestValidateTenantResourceQuotas_PoolUsage(t *testing.T) {
})
}
func TestGPUOnlyTenantSharesOrdinaryResourcePool(t *testing.T) {
for _, tc := range []struct {
key, usedKey, budget, used, remaining string
}{
{"cpu", "limits.cpu", "10", "8", "2"},
{"memory", "limits.memory", "10Gi", "8Gi", "2Gi"},
{"ephemeral-storage", "limits.ephemeral-storage", "10Gi", "8Gi", "2Gi"},
} {
t.Run(tc.key, func(t *testing.T) {
for _, gpuQuotas := range []map[string]string{nil, {totalKey: "2"}, {h100Key: "2"}} {
parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{tc.key: tc.budget})
child := tenantHelmRelease(t, "c", "tenant-foo", gpuQuotas)
used := usageQuota(t, "tenant-foo-c", "tenant-quota-allocated", map[string]string{tc.usedKey: tc.used})
r := newTenantREST(t, parent, child, used)
for _, request := range []struct {
amount string
denied bool
}{{tc.budget, true}, {tc.remaining, false}} {
app := childApplication(t, "sibling", "tenant-foo", map[string]string{tc.key: request.amount})
errs := r.validateTenantResourceQuotas(context.Background(), app)
if (len(errs) > 0) != request.denied {
t.Errorf("GPU quotas %v, sibling %s=%s: errors %v, want denied=%v", gpuQuotas, tc.key, request.amount, errs, request.denied)
}
}
}
})
}
}
func TestGPUOnlyTenantPoolUsage(t *testing.T) {
for _, usedKey := range []string{"limits.cpu", "limits.memory", "limits.ephemeral-storage", "requests.example.com/device", "requests.hugepages-2Mi", "requests.storage", "pods"} {
t.Run(usedKey, func(t *testing.T) {
parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{"cpu": "10"})
child := tenantHelmRelease(t, "c", "tenant-foo", map[string]string{totalKey: "2"})
grandchild := tenantHelmRelease(t, "d", "tenant-foo-c", nil)
childUsed := usageQuota(t, "tenant-foo-c", "tenant-quota-allocated", map[string]string{usedKey: "5"})
grandchildUsed := usageQuota(t, "tenant-foo-c-d", "tenant-quota-allocated", map[string]string{usedKey: "3"})
r := newTenantREST(t, parent, child, grandchild, childUsed, grandchildUsed)
used, err := r.parentPoolUsage(context.Background(), "tenant-foo", "tenant-foo-sibling")
if err != nil {
t.Fatal(err)
}
got := used[usedKey]
if got.Cmp(resource.MustParse("8")) != 0 {
t.Errorf("parent pool %s usage = %s, want 8", usedKey, got.String())
}
})
}
}
func TestOrdinaryResourceDeclarationKeepsSeparatePool(t *testing.T) {
for name, quotas := range map[string]map[string]string{
"ordinary": {"cpu": "4"},
"mixed": {"cpu": "4", totalKey: "2"},
} {
t.Run(name, func(t *testing.T) {
parent := tenantHelmRelease(t, "foo", "tenant-root", map[string]string{"cpu": "10"})
child := tenantHelmRelease(t, "c", "tenant-foo", quotas)
used := usageQuota(t, "tenant-foo-c", "tenant-quota", map[string]string{"limits.cpu": "4"})
r := newTenantREST(t, parent, child, used)
app := childApplication(t, "sibling", "tenant-foo", map[string]string{"cpu": "6"})
if errs := r.validateTenantResourceQuotas(context.Background(), app); len(errs) > 0 {
t.Errorf("child usage counted in addition to its declared reservation: %v", errs)
}
})
}
}
func TestComputeTenantNamespace(t *testing.T) {
for _, tc := range []struct {
parent, name, want string
}{
{"tenant-root", "root", "tenant-root"},
{"tenant-root", "foo", "tenant-foo"},
{"tenant-foo", "root", "tenant-foo-root"},
{"tenant-foo", "bar", "tenant-foo-bar"},
{"tenant-foo-bar", "baz", "tenant-foo-bar-baz"},
} {
t.Run(tc.want, func(t *testing.T) {
if got := computeTenantNamespace(tc.parent, tc.name); got != tc.want {
t.Errorf("computeTenantNamespace(%q, %q) = %q, want %q", tc.parent, tc.name, got, tc.want)
}
})
}
}
func TestParentTenantHelmReleaseRef(t *testing.T) {
tests := []struct {
owned string
+18 -20
View File
@@ -126,6 +126,9 @@ func NewREST(c client.Client, w client.WithWatch, defaultsReader client.Reader,
if err != nil {
klog.Errorf("Failed to build spec schema: %v", err)
}
if specSchema != nil {
specSchemas.Store(config.Application.Kind, specSchema)
}
nameSchema, nameSchemaErr := resolveNameSchema(config)
if nameSchemaErr != nil {
@@ -237,6 +240,10 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
r.warnRemovedKubernetesFields(ctx, app)
r.warnRemovedUserPasswords(ctx, app)
if gErrs := r.validateGPUBudget(ctx, app, nil); len(gErrs) > 0 {
return nil, apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, gErrs)
}
// Run the genericapiserver-supplied validating admission chain
// (validating webhooks + ValidatingAdmissionPolicies) before
// persisting anything. Mutating webhooks already ran upstream in
@@ -600,6 +607,9 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
return nil, false, apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, qErrs)
}
}
if gErrs := r.validateGPUBudget(ctx, app, oldObj.(*appsv1alpha1.Application)); len(gErrs) > 0 {
return nil, false, apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, gErrs)
}
r.warnLegacyPresets(app)
r.warnRemovedKubernetesFields(ctx, app)
@@ -1213,7 +1223,7 @@ func (r *REST) Watch(ctx context.Context, options *metainternalversion.ListOptio
// Filter out WM events whose child namespace does not
// correspond to the Tenant in our watched namespace, since
// the cluster-wide WM watch delivers events for all tenants.
if r.computeTenantNamespace(namespace, wmAppName) != wm.Namespace {
if computeTenantNamespace(namespace, wmAppName) != wm.Namespace {
continue
}
if !fieldFilter.MatchesNamespace(hrNS) {
@@ -1698,7 +1708,7 @@ func (r *REST) validateTenantNamespaceLength(currentNamespace, tenantName string
fldPath := field.NewPath("metadata").Child("name")
allErrs := field.ErrorList{}
computed := r.computeTenantNamespace(currentNamespace, tenantName)
computed := computeTenantNamespace(currentNamespace, tenantName)
if len(computed) > maxNamespaceName {
allErrs = append(allErrs, field.Invalid(fldPath, tenantName,
fmt.Sprintf("computed tenant namespace %q would be %d characters, which exceeds the %d-character Kubernetes namespace limit; shorten the tenant name or reduce ancestor nesting depth",
@@ -1764,7 +1774,7 @@ func (r *REST) convertHelmReleaseToApplication(ctx context.Context, hr *helmv2.H
// not in the same namespace as the owning HelmRelease — look there instead.
workloadsNS := hr.Namespace
if r.kindName == "Tenant" {
workloadsNS = r.computeTenantNamespace(hr.Namespace, app.Name)
workloadsNS = computeTenantNamespace(hr.Namespace, app.Name)
}
ws, wsErr := r.getWorkloadsOperational(ctx, workloadsNS, app.Name, freshMonitor)
// Derive a stable LastTransitionTime: use the owning HelmRelease's own
@@ -1840,7 +1850,7 @@ func (r *REST) convertHelmReleaseToApplication(ctx context.Context, hr *helmv2.H
// Add namespace field for Tenant applications
if r.kindName == validation.TenantKind {
app.Status.Namespace = r.computeTenantNamespace(hr.Namespace, app.Name)
app.Status.Namespace = computeTenantNamespace(hr.Namespace, app.Name)
externalIPsCount, err := r.countTenantExternalIPs(ctx, app.Status.Namespace)
if err != nil {
klog.Warningf("Failed to count external IPs for tenant %s/%s: %v", hr.Namespace, app.Name, err)
@@ -2207,23 +2217,11 @@ func conditionStatus(conditions []metav1.Condition, conditionType, absent string
return absent
}
// computeTenantNamespace computes the namespace for a Tenant application based on the specified logic
func (r *REST) computeTenantNamespace(currentNamespace, tenantName string) string {
hrName := r.releaseConfig.Prefix + tenantName
switch {
case currentNamespace == "tenant-root" && hrName == "tenant-root":
// 1) root tenant inside root namespace
return "tenant-root"
case currentNamespace == "tenant-root":
// 2) any other tenant in root namespace
return fmt.Sprintf("tenant-%s", tenantName)
default:
// 3) tenant in a dedicated namespace
return fmt.Sprintf("%s-%s", currentNamespace, tenantName)
func computeTenantNamespace(currentNamespace, tenantName string) string {
if currentNamespace == rootTenantNamespace {
return tenantReleasePrefix + tenantName
}
return currentNamespace + "-" + tenantName
}
func (r *REST) countTenantExternalIPs(ctx context.Context, namespace string) (int32, error) {
@@ -410,7 +410,7 @@ func TestValidateTenantNamespaceLength(t *testing.T) {
errs := r.validateTenantNamespaceLength(tt.currentNamespace, tt.tenantName)
if tt.wantError && len(errs) == 0 {
computed := r.computeTenantNamespace(tt.currentNamespace, tt.tenantName)
computed := computeTenantNamespace(tt.currentNamespace, tt.tenantName)
t.Errorf("expected error for parent=%q name=%q (computed=%q, len=%d), got none",
tt.currentNamespace, tt.tenantName, computed, len(computed))
return
@@ -425,7 +425,7 @@ func TestValidateTenantNamespaceLength(t *testing.T) {
// computed namespace string and its actual length so a
// regression in the message format is caught.
if tt.wantError {
computed := r.computeTenantNamespace(tt.currentNamespace, tt.tenantName)
computed := computeTenantNamespace(tt.currentNamespace, tt.tenantName)
msg := errs.ToAggregate().Error()
if !strings.Contains(msg, computed) {
t.Errorf("error message must contain computed namespace %q, got: %s", computed, msg)