test(reservation): check shipped consumption declarations on the rendered charts (#5411)

## What this PR does

The shipped-declaration test in `pkg/reservation` enforced a file layout
that no requirement asks for, and a correct open PR went red because of
it. The test came with #5349. It read
`packages/system/*-rd/cozyrds/*.yaml` as raw files and failed when two
files carried the same `metadata.name`. An `-rd` chart may keep one
definition per variant under one name and render only one of them. #4508
does this for the VPC cozyplane variant and has been red since #5349
merged. The same test also parsed cozy-lib's preset template with a
regexp, pinned about seventy figures the shipped declarations compute,
and required the IaaS kinds to declare consumption while nothing reads
the declarations yet.

The first commit moves the evaluator and classifier tests to fixtures.
They used to read schemas from the `cozyrds/` files and instance types
from the kubevirt-instancetypes templates. The expected figures stay the
same, and the exact product past int64 gets its own case.

The second commit checks the shipped declarations where the charts live.
`hack/check-rd-consumption.sh` renders each `-rd` chart with
`values.yaml`, and once more for each `values-<variant>.yaml` next to
it, together with the kubevirt-instancetypes chart.
`cmd/check-consumption` reads that stream and knows nothing about
charts. It fails when a declaration does not compile or does not
evaluate on its kind's defaults, and when a rendered instance type does
not classify. Presets come from a cozy-lib template helper and nothing
renders them, so an evaluation that reaches `preset()` stops there and
is reported as compiled. Only that lookup is tolerated, an unknown
instance type still fails. The check is a new `rd-consumption-check`
target under `make unit-tests`, which the Unit & controller tests job
runs.

The third commit deletes `pkg/reservation/shipped_test.go`. Open PRs
that add tests to that file (#5401, #5397) will need to move them.

I checked it against #4508 merged onto this branch, with no changes to
#4508: the Go tests and the new check pass, and the VPC cozyplane
variant is rendered on its own; it declares no consumption, so the check
has nothing to evaluate there. A broken shipped declaration fails the
check.

Comparing a declaration with the requests and limits its chart actually
renders is left for #5416.

### Screenshots

Not a UI change.

### Downstream repositories

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

### Release note

```release-note
test(reservation): shipped consumption declarations are checked on the rendered -rd charts instead of their source files, so an -rd chart can ship one definition per variant under the same name.
```


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **Tests**
- Automated checks now validate resource consumption declarations across
system application charts and their value variants, reporting chart
rendering or validation failures.
- Unit tests now cover additional resource classification and
calculation cases, including products that exceed the supported integer
range.
- **Chores**
- The new validation check is included in the standard unit test
workflows.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Timofei Larkin authored and GitHub committed 2026-11-25 14:58:56 +04:00
commit f91ffd8fa7
9 files changed
+394 -727

No files matched your search

+6 -3
View File
@@ -1,4 +1,4 @@
.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check migrations-target-check test test-controllers test-controllers-envtest test-backport-batch preflight
.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check rd-consumption-check migrations-target-check test test-controllers test-controllers-envtest test-backport-batch preflight
include hack/common-envs.mk
@@ -120,7 +120,7 @@ test:
make -C packages/core/testing apply
make -C packages/core/testing e2e
unit-tests: helm-unit-tests bats-unit-tests bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check test-check-readiness migrations-target-check
unit-tests: helm-unit-tests bats-unit-tests bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check rd-consumption-check test-check-readiness migrations-target-check
helm-unit-tests:
hack/helm-unit-tests.sh
@@ -132,6 +132,9 @@ helm-unit-tests:
rd-presets-check:
hack/check-rd-presets.sh
rd-consumption-check:
hack/check-rd-consumption.sh
# Catch the off-by-one where migrations/<N> is added but
# migrations.targetVersion in packages/core/platform/values.yaml is not
# bumped to >= N+1. run-migrations.sh loops `seq $$CURRENT $$((TARGET-1))`,
@@ -292,7 +295,7 @@ bats-posix-compat-tests:
# Every prerequisite of unit-tests is listed so it is guarded when run on its
# own too; hack/unit-lane-no-cluster.bats fails when one is missing.
NO_CLUSTER_TARGETS := unit-tests test-controllers helm-unit-tests bats-unit-tests \
bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check \
bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check rd-consumption-check \
test-check-readiness test-backport-batch migrations-target-check
$(NO_CLUSTER_TARGETS): export KUBECONFIG := /dev/null
$(NO_CLUSTER_TARGETS): export KUBERNETES_SERVICE_HOST :=
+109
View File
@@ -0,0 +1,109 @@
/*
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.
*/
// Command check-consumption reads rendered manifests on stdin and checks that
// every consumption declaration on an ApplicationDefinition compiles against
// its kind's schema and evaluates on the kind's defaults, resolving instance
// types against the VirtualMachineClusterInstancetypes in the same stream.
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
"github.com/cozystack/cozystack/pkg/apis/apps/defaulting"
"github.com/cozystack/cozystack/pkg/reservation"
)
// errPresetsNotRendered ends an evaluation at a preset lookup: cozy-lib's
// preset table is a template helper, not an object a chart renders.
var errPresetsNotRendered = errors.New("presets are not rendered")
type renderedEnvironment struct{ *reservation.StaticEnvironment }
func (renderedEnvironment) Preset(name string) (reservation.ResourceList, error) {
return nil, fmt.Errorf("preset %q: %w", name, errPresetsNotRendered)
}
func check(in io.Reader, out io.Writer) error {
var defs []*cozyv1alpha1.ApplicationDefinition
var instancetypes []map[string]any
dec := utilyaml.NewYAMLOrJSONDecoder(in, 4096)
for {
var obj map[string]any
if err := dec.Decode(&obj); err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
switch obj["kind"] {
case "VirtualMachineClusterInstancetype":
instancetypes = append(instancetypes, obj)
case "ApplicationDefinition":
raw, err := json.Marshal(obj)
if err != nil {
return err
}
def := &cozyv1alpha1.ApplicationDefinition{}
if err := json.Unmarshal(raw, def); err != nil {
return err
}
defs = append(defs, def)
}
}
static, err := reservation.NewStaticEnvironment(instancetypes, nil)
if err != nil {
return err
}
env := renderedEnvironment{static}
var errs []error
for _, def := range defs {
if def.Spec.Consumption == nil {
continue
}
schema, err := defaulting.BuildSchema(def.Spec.Application.OpenAPISchema)
if err == nil {
var ev *reservation.Evaluator
if ev, err = reservation.Compile(def.Spec.Consumption, schema); err == nil {
_, err = ev.EvaluateJSON([]byte(`{}`), env)
}
}
switch {
case errors.Is(err, errPresetsNotRendered):
fmt.Fprintf(out, "%s: compiled; evaluation on defaults stopped at a preset lookup\n", def.Name)
case err != nil:
errs = append(errs, fmt.Errorf("%s: %w", def.Name, err))
default:
fmt.Fprintf(out, "%s: ok\n", def.Name)
}
}
return errors.Join(errs...)
}
func main() {
if err := check(os.Stdin, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
+111
View File
@@ -0,0 +1,111 @@
/*
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 main
import (
"bytes"
"strings"
"testing"
)
const instancetypeDoc = `
apiVersion: instancetype.kubevirt.io/v1beta1
kind: VirtualMachineClusterInstancetype
metadata:
name: u1.small
spec:
cpu:
guest: 1
memory:
guest: 2Gi
`
func definition(name, consumption string) string {
return `
apiVersion: cozystack.io/v1alpha1
kind: ApplicationDefinition
metadata:
name: ` + name + `
spec:
application:
kind: X
openAPISchema: '{"type":"object","properties":{"instanceType":{"type":"string","default":"u1.small"},"preset":{"type":"string","default":"t1.micro"}}}'
` + consumption
}
func stream(docs ...string) string {
return "---" + strings.Join(docs, "---")
}
func TestCheck(t *testing.T) {
for name, tc := range map[string]struct {
in string
// fail is a substring the error must carry; empty means no error.
fail string
// out is a substring the report must carry, absent one it must not.
out, absent string
}{
"evaluates on the rendered instance types": {
in: stream(instancetypeDoc, definition("vm", " consumption:\n resources:\n cpu: instanceType(values.instanceType).cpu\n")),
},
"a definition without a declaration is not checked": {
in: stream(definition("plain", "")),
absent: "plain",
},
"a schema that does not build": {
in: stream(strings.Replace(definition("bad-schema", " consumption:\n resources:\n cpu: \"1\"\n"), `'{"type"`, `'{"type":`, 1)),
fail: "bad-schema",
},
"a stream that is not YAML": {
in: "kind: [\n",
fail: "yaml",
},
"a declaration that does not compile": {
in: stream(definition("broken", " consumption:\n resources:\n cpu: nosuchfunction(values.instanceType)\n")),
fail: "broken",
},
"an instance type the stream does not render": {
in: stream(definition("vm", " consumption:\n resources:\n cpu: instanceType(values.instanceType).cpu\n")),
fail: "u1.small",
},
"an instance type the classifier rejects": {
in: stream("\nkind: VirtualMachineClusterInstancetype\nmetadata:\n name: bad\nspec:\n cpu:\n guest: 1\n"),
fail: "bad",
},
"presets are not rendered, so a preset lookup ends the evaluation": {
in: stream(definition("db", " consumption:\n resources:\n cpu: preset(values.preset).cpu\n")),
out: "db: compiled; evaluation on defaults stopped at a preset lookup",
},
} {
t.Run(name, func(t *testing.T) {
var out bytes.Buffer
err := check(strings.NewReader(tc.in), &out)
switch {
case tc.fail == "" && err != nil:
t.Fatalf("unexpected error: %v", err)
case tc.fail != "" && (err == nil || !strings.Contains(err.Error(), tc.fail)):
t.Fatalf("got %v, want an error carrying %q", err, tc.fail)
}
if !strings.Contains(out.String(), tc.out) {
t.Fatalf("report %q does not carry %q", out.String(), tc.out)
}
if tc.absent != "" && strings.Contains(out.String(), tc.absent) {
t.Fatalf("report %q carries %q", out.String(), tc.absent)
}
})
}
}
+1 -1
View File
@@ -26,7 +26,6 @@ require (
github.com/spf13/pflag v1.0.10
github.com/vmware-tanzu/velero v1.18.4
go.uber.org/zap v1.28.0
go.yaml.in/yaml/v3 v3.0.5
gomodules.xyz/jsonpatch/v2 v2.5.0
k8s.io/api v0.37.1
k8s.io/apiextensions-apiserver v0.37.1
@@ -131,6 +130,7 @@ require (
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/exp v0.0.0-20261009195045-ca0d7ba23607 // indirect
golang.org/x/mod v0.42.0 // indirect
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Render every packages/system/*-rd chart the way each of its variants is
# installed, values.yaml alone and with each values-<variant>.yaml beside it,
# and check the consumption declarations the rendered ApplicationDefinitions
# carry. Instance types resolve against the rendered kubevirt-instancetypes.
set -euo pipefail
shopt -s nullglob
cd "$(dirname "$0")/.."
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
go build -o "$work/check-consumption" ./cmd/check-consumption
helm template instancetypes packages/system/kubevirt-instancetypes >"$work/instancetypes.yaml"
fail=0
for chart in packages/system/*-rd; do
for values in "" "$chart"/values-*.yaml; do
args=(template rd "$chart")
label=$chart
if [ -n "$values" ]; then
args+=(--values "$values")
label="$chart with $(basename "$values")"
fi
if ! helm "${args[@]}" >"$work/rendered.yaml"; then
echo "FAIL: $label does not render" >&2
fail=1
continue
fi
if ! cat "$work/instancetypes.yaml" "$work/rendered.yaml" | "$work/check-consumption"; then
echo "FAIL: $label" >&2
fail=1
fi
done
done
exit "$fail"
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bats
load test_helper
REPO_ROOT="$(cd "$(dirname "${BATS_TEST_FILENAME:-$0}")/.." && pwd)"
# The script is copied into a scratch tree with go and helm stubbed: helm
# renders a chart's render.yaml followed by the values file it was given, and
# the checker built by go fails on a stream containing BROKEN.
setup() {
strict_setup
dir=$(mktemp -d)
mkdir -p "$dir/hack" "$dir/bin" "$dir/packages/system/foo-rd" "$dir/packages/system/kubevirt-instancetypes"
cp "$REPO_ROOT/hack/check-rd-consumption.sh" "$dir/hack/"
echo 'kind: ApplicationDefinition' > "$dir/packages/system/foo-rd/render.yaml"
cat > "$dir/bin/go" <<'STUB'
#!/bin/sh
printf '#!/bin/sh\n! grep -q BROKEN\n' > "$3"
chmod +x "$3"
STUB
cat > "$dir/bin/helm" <<'STUB'
#!/bin/sh
echo "$*" >> "$HELM_LOG"
[ "$3" = packages/system/kubevirt-instancetypes ] && exit 0
[ -e "$3/unrenderable" ] && exit 1
cat "$3/render.yaml"
[ "${4:-}" = --values ] && cat "$5"
exit 0
STUB
chmod +x "$dir/bin/go" "$dir/bin/helm"
export HELM_LOG="$dir/helm.log"
}
teardown() {
rm -rf "$dir"
}
run_check() {
rc=0
out=$(PATH="$dir/bin:$PATH" "$dir/hack/check-rd-consumption.sh" 2>&1) || rc=$?
printf '%s\n' "$out"
}
@test "a chart without variants renders once and passes" {
run_check
[ "$rc" -eq 0 ]
[ "$(grep -c 'packages/system/foo-rd' "$HELM_LOG")" -eq 1 ]
}
@test "a declaration broken only in a variant fails, naming the variant" {
echo 'BROKEN' > "$dir/packages/system/foo-rd/values-bar.yaml"
run_check
[ "$rc" -ne 0 ]
printf '%s\n' "$out" | grep -Fx 'FAIL: packages/system/foo-rd with values-bar.yaml'
if printf '%s\n' "$out" | grep -Fx 'FAIL: packages/system/foo-rd'; then
return 1
fi
}
@test "a chart that does not render fails" {
touch "$dir/packages/system/foo-rd/unrenderable"
run_check
[ "$rc" -ne 0 ]
printf '%s\n' "$out" | grep -Fx 'FAIL: packages/system/foo-rd does not render'
}
+37 -28
View File
@@ -18,22 +18,19 @@ package reservation
import (
"errors"
"os"
"strings"
"sync"
"testing"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
"k8s.io/apimachinery/pkg/api/resource"
"sigs.k8s.io/yaml"
"github.com/cozystack/cozystack/pkg/apis/apps/defaulting"
)
// The declarations below are test fixtures in the shape a kind would carry
// on its ApplicationDefinition. They are evaluated against the kinds' real
// shipped schemas so that defaulting is exercised with the defaults tenants
// actually get.
// on its ApplicationDefinition, evaluated against schemas cut down from the
// kinds' to the keys the declarations and the type checks read.
var postgresDecl = &Declaration{
Let: []Binding{{
@@ -76,23 +73,34 @@ var kubernetesNodesDecl = &Declaration{
},
}
func shippedSchema(t *testing.T, kind string) *structuralschema.Structural {
const quantitySchema = `{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true}`
var fixtureSchemas = map[string]string{
"postgres": `{"type":"object","properties":{
"replicas":{"type":"integer","default":2},
"resources":{"type":"object","default":{},"properties":{"cpu":` + quantitySchema + `,"memory":` + quantitySchema + `}},
"resourcesPreset":{"type":"string","default":"t1.micro"},
"size":{"anyOf":[{"type":"integer"},{"type":"string"}],"x-kubernetes-int-or-string":true,"default":"10Gi"},
"external":{"type":"boolean","default":false},
"postgresql":{"type":"object","default":{},"properties":{"sharedPreloadLibraries":{"type":"array","items":{"type":"string"}}}},
"autoscaling":{"type":"object","default":{},"properties":{
"enabled":{"type":"boolean","default":false},
"maxReplicas":{"type":"integer","default":6}}},
"users":{"type":"object","default":{},"additionalProperties":{"type":"object","properties":{"replication":{"type":"boolean"}}}}}}`,
"vm-instance": `{"type":"object","properties":{
"external":{"type":"boolean","default":false},
"instanceType":{"type":"string","default":"u1.medium"},
"resources":{"type":"object","default":{},"properties":{"cpu":` + quantitySchema + `,"memory":` + quantitySchema + `,"sockets":` + quantitySchema + `}}}}`,
"kubernetes-nodes": `{"type":"object","properties":{
"minReplicas":{"type":"integer","default":0},
"maxReplicas":{"type":"integer","default":10},
"instanceType":{"type":"string","default":"u1.medium"},
"roles":{"type":"array","default":[],"items":{"type":"string"}}}}`,
}
func fixtureSchema(t *testing.T, kind string) *structuralschema.Structural {
t.Helper()
raw, err := os.ReadFile("../../packages/system/" + kind + "-rd/cozyrds/" + kind + ".yaml")
if err != nil {
t.Fatal(err)
}
var def struct {
Spec struct {
Application struct {
OpenAPISchema string `json:"openAPISchema"`
} `json:"application"`
} `json:"spec"`
}
if err := yaml.Unmarshal(raw, &def); err != nil {
t.Fatal(err)
}
s, err := defaulting.BuildSchema(def.Spec.Application.OpenAPISchema)
s, err := defaulting.BuildSchema(fixtureSchemas[kind])
if err != nil || s == nil {
t.Fatalf("%s schema: %v", kind, err)
}
@@ -101,7 +109,7 @@ func shippedSchema(t *testing.T, kind string) *structuralschema.Structural {
func testEnvironment(t *testing.T) Environment {
t.Helper()
env, err := NewStaticEnvironment(shippedInstancetypes(t), map[string]ResourceList{
env, err := NewStaticEnvironment(fixtureInstancetypes, map[string]ResourceList{
"t1.nano": {"cpu": resource.MustParse("250m"), "memory": resource.MustParse("128Mi"), "ephemeral-storage": resource.MustParse("2Gi")},
"t1.micro": {"cpu": resource.MustParse("500m"), "memory": resource.MustParse("256Mi"), "ephemeral-storage": resource.MustParse("2Gi")},
})
@@ -113,7 +121,7 @@ func testEnvironment(t *testing.T) Environment {
func mustCompile(t *testing.T, decl *Declaration, kind string) *Evaluator {
t.Helper()
ev, err := Compile(decl, shippedSchema(t, kind))
ev, err := Compile(decl, fixtureSchema(t, kind))
if err != nil {
t.Fatalf("compile %s: %v", kind, err)
}
@@ -253,7 +261,7 @@ func TestEvaluateFailsClosed(t *testing.T) {
t.Error("no environment: expected an error")
}
unguarded, err := Compile(&Declaration{Resources: map[string]string{"cpu": `quantity(values.notInTheSchema)`}}, shippedSchema(t, "postgres"))
unguarded, err := Compile(&Declaration{Resources: map[string]string{"cpu": `quantity(values.notInTheSchema)`}}, fixtureSchema(t, "postgres"))
if err != nil {
t.Fatal(err)
}
@@ -309,7 +317,7 @@ func TestEvaluateRejectsValuesOfTheWrongType(t *testing.T) {
// reserve its fallback.
ev, err := Compile(&Declaration{Resources: map[string]string{
"cpu": `has(values.resources.cpu) ? values.resources.cpu : 1`,
}}, shippedSchema(t, "postgres"))
}}, fixtureSchema(t, "postgres"))
if err != nil {
t.Fatal(err)
}
@@ -349,7 +357,7 @@ func TestEvaluateAcceptsIntegralSpellings(t *testing.T) {
env := testEnvironment(t)
// The Kubernetes schema validator accepts an integral number however it
// is spelled, so the evaluator must too.
ev, err := Compile(&Declaration{Resources: map[string]string{"cpu": `values.replicas`}}, shippedSchema(t, "postgres"))
ev, err := Compile(&Declaration{Resources: map[string]string{"cpu": `values.replicas`}}, fixtureSchema(t, "postgres"))
if err != nil {
t.Fatal(err)
}
@@ -480,6 +488,7 @@ func TestEvaluateMulKeepsExactProducts(t *testing.T) {
"fractional Gi": {`quantity('20.5Gi').mul(3)`, "62976Mi"},
"fractional Ti": {`quantity('1.5Ti').mul(3)`, "4608Gi"},
"after a sum": {`quantity('8.5Gi').add(quantity('1Gi')).mul(2)`, "19Gi"},
"past int64": {`quantity('4294967295').mul(4294967295)`, "18446744065119617025"},
}
for name, tc := range cases {
t.Run(name, func(t *testing.T) {
@@ -568,7 +577,7 @@ func TestEvaluateNullOverridesDefault(t *testing.T) {
func TestEvaluateIsConcurrencySafe(t *testing.T) {
env := testEnvironment(t)
vm := mustCompile(t, vmInstanceDecl, "vm-instance")
catalog := shippedInstancetypes(t)
catalog := fixtureInstancetypes
var wg sync.WaitGroup
for _, it := range []string{"u1.small", "cx1.2xlarge", "o1.large", "u1.medium"} {
want, err := ClassifyInstancetype(findInstancetype(t, catalog, it))
@@ -598,7 +607,7 @@ func findInstancetype(t *testing.T, catalog []map[string]any, name string) map[s
return obj
}
}
t.Fatalf("%s is not shipped", name)
t.Fatalf("%s is not a fixture instance type", name)
return nil
}
+29 -121
View File
@@ -17,141 +17,49 @@ limitations under the License.
package reservation
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
"testing"
"k8s.io/apimachinery/pkg/api/resource"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
)
// shippedInstancetypes decodes every VirtualMachineClusterInstancetype the
// platform ships, so that the classification is pinned against the real
// catalog rather than against hand-written fixtures.
func shippedInstancetypes(t *testing.T) []map[string]any {
t.Helper()
files, err := filepath.Glob("../../packages/system/kubevirt-instancetypes/templates/*.yaml")
if err != nil || len(files) == 0 {
t.Fatalf("no instance type templates found: %v", err)
}
var out []map[string]any
for _, f := range files {
fh, err := os.Open(f)
if err != nil {
t.Fatal(err)
}
dec := utilyaml.NewYAMLOrJSONDecoder(fh, 4096)
for {
var obj map[string]any
if err := dec.Decode(&obj); err != nil {
if errors.Is(err, io.EOF) {
break
}
t.Fatalf("%s: %v", f, err)
}
if obj["kind"] == "VirtualMachineClusterInstancetype" {
out = append(out, obj)
}
}
if err := fh.Close(); err != nil {
t.Fatalf("%s: %v", f, err)
}
}
return out
// fixtureInstancetypes are VirtualMachineClusterInstancetypes in the shapes
// the classifier has to tell apart, cut down to the fields it reads.
var fixtureInstancetypes = []map[string]any{
instancetype("u1.small", map[string]any{"guest": int64(1)}, map[string]any{"guest": "2Gi"}),
instancetype("u1.medium", map[string]any{"guest": int64(1)}, map[string]any{"guest": "4Gi"}),
instancetype("o1.large", map[string]any{"guest": int64(2)}, map[string]any{"guest": "8Gi", "overcommitPercent": int64(50)}),
instancetype("m1.large", map[string]any{"guest": int64(2)}, map[string]any{"guest": "16Gi", "hugepages": map[string]any{"pageSize": "2Mi"}}),
instancetype("m1.large1gi", map[string]any{"guest": int64(2)}, map[string]any{"guest": "16Gi", "hugepages": map[string]any{"pageSize": "1Gi"}}),
instancetype("d1.large", map[string]any{"guest": int64(2), "dedicatedCPUPlacement": true, "isolateEmulatorThread": true}, map[string]any{"guest": "8Gi"}),
instancetype("cx1.2xlarge", map[string]any{"guest": int64(8), "dedicatedCPUPlacement": true, "isolateEmulatorThread": true}, map[string]any{"guest": "16Gi", "hugepages": map[string]any{"pageSize": "2Mi"}}),
}
func TestClassifyShippedInstancetypes(t *testing.T) {
// The expected class per series is written from what each series is,
// not derived from the spec, so a name-based rule and a spec-based rule
// disagreeing shows up here. m1 is shared CPU with hugepages, n1 a
// dedicated series with hugepages, o1 overcommits memory.
type class struct{ cpu, memory string }
want := map[string]class{
"u1": {KeyCPU, KeyMemory},
"gn1": {KeyCPU, KeyMemory},
"m1": {KeyCPU, "hugepages"},
"o1": {KeyCPU, KeyOvercommittedMemory},
"d1": {KeyDedicatedCPU, KeyMemory},
"cx1": {KeyDedicatedCPU, "hugepages"},
"n1": {KeyDedicatedCPU, "hugepages"},
"rt1": {KeyDedicatedCPU, "hugepages"},
func instancetype(name string, cpu, memory map[string]any) map[string]any {
return map[string]any{
"kind": "VirtualMachineClusterInstancetype",
"metadata": map[string]any{"name": name},
"spec": map[string]any{"cpu": cpu, "memory": memory},
}
}
types := shippedInstancetypes(t)
if len(types) < 60 {
t.Fatalf("expected the full shipped catalog, decoded only %d instance types", len(types))
func TestClassifyInstancetypes(t *testing.T) {
want := map[string]ResourceList{
"u1.small": {KeyCPU: resource.MustParse("1"), KeyMemory: resource.MustParse("2Gi")},
"u1.medium": {KeyCPU: resource.MustParse("1"), KeyMemory: resource.MustParse("4Gi")},
"o1.large": {KeyCPU: resource.MustParse("2"), KeyOvercommittedMemory: resource.MustParse("8Gi")},
"m1.large": {KeyCPU: resource.MustParse("2"), KeyHugepagesPrefix + "2Mi": resource.MustParse("16Gi")},
"m1.large1gi": {KeyCPU: resource.MustParse("2"), KeyHugepagesPrefix + "1Gi": resource.MustParse("16Gi")},
// The isolated emulator thread takes a core nobody else can be given.
"d1.large": {KeyDedicatedCPU: resource.MustParse("3"), KeyMemory: resource.MustParse("8Gi")},
"cx1.2xlarge": {KeyDedicatedCPU: resource.MustParse("9"), KeyHugepagesPrefix + "2Mi": resource.MustParse("16Gi")},
}
seen := map[string]bool{}
for _, obj := range types {
for _, obj := range fixtureInstancetypes {
name := obj["metadata"].(map[string]any)["name"].(string)
series := strings.SplitN(name, ".", 2)[0]
seen[series] = true
w, ok := want[series]
if !ok {
t.Errorf("%s: series %q has no expected class; add it to this table", name, series)
continue
}
rl, err := ClassifyInstancetype(obj)
if err != nil {
t.Errorf("%s: %v", name, err)
continue
}
if len(rl) != 2 {
t.Errorf("%s: expected one CPU class and one memory class, got %v", name, rl)
}
if _, ok := rl[w.cpu]; !ok {
t.Errorf("%s: expected CPU class %q, got %v", name, w.cpu, rl)
}
if w.memory == "hugepages" {
found := false
for k := range rl {
found = found || strings.HasPrefix(k, KeyHugepagesPrefix)
}
if !found {
t.Errorf("%s: expected a hugepages class, got %v", name, rl)
}
} else if _, ok := rl[w.memory]; !ok {
t.Errorf("%s: expected memory class %q, got %v", name, w.memory, rl)
}
}
for series := range want {
if !seen[series] {
t.Errorf("series %q is no longer shipped; drop it from this table", series)
}
}
}
func TestClassifyShippedFigures(t *testing.T) {
byName := map[string]map[string]any{}
for _, obj := range shippedInstancetypes(t) {
byName[obj["metadata"].(map[string]any)["name"].(string)] = obj
}
cases := []struct {
name string
want ResourceList
}{
// The KubeVirt u1.small is 2Gi; the cozy-lib preset of the same name
// is 4Gi. The two catalogs share names, not figures.
{"u1.small", ResourceList{KeyCPU: resource.MustParse("1"), KeyMemory: resource.MustParse("2Gi")}},
// Eight guest vCPUs on nine pinned cores: the isolated emulator
// thread takes a core nobody else can be given.
{"cx1.2xlarge", ResourceList{KeyDedicatedCPU: resource.MustParse("9"), KeyHugepagesPrefix + "2Mi": resource.MustParse("16Gi")}},
{"d1.large", ResourceList{KeyDedicatedCPU: resource.MustParse("3"), KeyMemory: resource.MustParse("8Gi")}},
{"m1.large", ResourceList{KeyCPU: resource.MustParse("2"), KeyHugepagesPrefix + "2Mi": resource.MustParse("16Gi")}},
}
for _, tc := range cases {
obj, ok := byName[tc.name]
if !ok {
t.Fatalf("%s is not shipped", tc.name)
}
got, err := ClassifyInstancetype(obj)
if err != nil {
t.Fatalf("%s: %v", tc.name, err)
t.Fatalf("%s: %v", name, err)
}
assertList(t, tc.name, got, tc.want)
assertList(t, name, got, want[name])
}
}
-574
View File
@@ -1,574 +0,0 @@
/*
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 reservation
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
yamlv3 "go.yaml.in/yaml/v3"
"k8s.io/apimachinery/pkg/api/resource"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
"github.com/cozystack/cozystack/pkg/apis/apps/defaulting"
)
// The kinds whose consumption has to be declared: the IaaS kinds carry the
// virtualization overhead the reservation exists to keep out of the tenant
// contract.
var declaredKinds = []string{"vm-instance", "vm-disk", "kubernetes", "kubernetes-nodes"}
func shippedDefinitions(t *testing.T) map[string]*cozyv1alpha1.ApplicationDefinition {
t.Helper()
files, err := filepath.Glob("../../packages/system/*-rd/cozyrds/*.yaml")
if err != nil {
t.Fatal(err)
}
if len(files) == 0 {
t.Fatal("no ApplicationDefinition found under packages/system/*-rd/cozyrds")
}
out := make(map[string]*cozyv1alpha1.ApplicationDefinition, len(files))
from := make(map[string]string, len(files))
for _, f := range files {
raw, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
doc, err := singleDocument(raw)
if err != nil {
t.Fatalf("%s: %v", f, err)
}
def := &cozyv1alpha1.ApplicationDefinition{}
// Strict, so that a misspelled field in a hand-written declaration
// fails here instead of being pruned by the API server.
if err := yaml.UnmarshalStrict(doc, def); err != nil {
t.Fatalf("%s: %v", f, err)
}
// A later file would replace an earlier one of the same name, and the
// earlier declaration would then never be compiled.
if prev, ok := from[def.Name]; ok {
t.Fatalf("ApplicationDefinition %q is declared in both %s and %s", def.Name, prev, f)
}
from[def.Name] = f
out[def.Name] = def
}
return out
}
// singleDocument returns the one YAML document raw holds, as written, so that
// a strict decode of it still catches duplicate keys. Helm renders every
// document of the file, while a strict decode reads only the first, so a
// second one would go unchecked. Line endings are normalized first, as YAML
// itself reads them, and a document holding only comments counts as none.
func singleDocument(raw []byte) ([]byte, error) {
normalized := strings.ReplaceAll(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\r", "\n")
reader := utilyaml.NewYAMLReader(bufio.NewReader(strings.NewReader(normalized)))
var found []byte
for {
doc, err := reader.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
var node yamlv3.Node
if err := yamlv3.Unmarshal(doc, &node); err != nil {
return nil, err
}
if len(node.Content) == 0 || (node.Content[0].Kind == yamlv3.ScalarNode && node.Content[0].Tag == "!!null") {
continue
}
if found != nil {
return nil, fmt.Errorf("holds more than one YAML document, expected one")
}
found = doc
}
if found == nil {
return nil, fmt.Errorf("holds no YAML document")
}
return found, nil
}
// The document returned must be the one that holds the definition, or the
// strict decode reads an empty one and checks nothing.
func TestSingleDocumentReturnsTheDefinition(t *testing.T) {
def := "kind: ApplicationDefinition\nmetadata:\n name: x\n"
for name, raw := range map[string]string{
"empty documents first": "---\n# empty\n---\n" + def,
"CR line endings": strings.ReplaceAll("---\n# empty\n---\n"+def, "\n", "\r"),
"CRLF line endings": strings.ReplaceAll("# head\n---\n"+def, "\n", "\r\n"),
"trailing empty document": def + "---\n# empty\n",
} {
t.Run(name, func(t *testing.T) {
doc, err := singleDocument([]byte(raw))
if err != nil {
t.Fatal(err)
}
got := &cozyv1alpha1.ApplicationDefinition{}
if err := yaml.UnmarshalStrict(doc, got); err != nil {
t.Fatal(err)
}
if got.Name != "x" {
t.Fatalf("decoded name %q from %q", got.Name, doc)
}
})
}
// Strict decoding still sees the document as written.
if doc, err := singleDocument([]byte("---\n# empty\n---\nkind: A\nkind: B\n")); err != nil {
t.Fatal(err)
} else if err := yaml.UnmarshalStrict(doc, &cozyv1alpha1.ApplicationDefinition{}); err == nil {
t.Fatal("a duplicate key in the returned document must fail the strict decode")
}
}
func TestSingleDocument(t *testing.T) {
def := "kind: ApplicationDefinition\nmetadata:\n name: x\n"
for name, tc := range map[string]struct {
raw string
ok bool
}{
"bare": {def, true},
"leading marker": {"---\n" + def, true},
"comment before the marker": {"# owned by the chart\n---\n" + def, true},
"trailing empty document": {def + "---\n", true},
"trailing comment-only document": {def + "---\n# nothing here\n", true},
"second document": {def + "---\n" + def, false},
"empty": {"# nothing\n", false},
"second document, CR line endings": {strings.ReplaceAll(def+"---\n"+def, "\n", "\r"), false},
"single document, CR line endings": {strings.ReplaceAll(def, "\n", "\r"), true},
} {
t.Run(name, func(t *testing.T) {
if _, err := singleDocument([]byte(tc.raw)); (err == nil) != tc.ok {
t.Fatalf("got %v, want ok=%v", err, tc.ok)
}
})
}
}
// presetRow matches one row of the dict literals in _resourcepresets.tpl;
// its fields are then read by key, so that their order does not matter.
var (
presetRow = regexp.MustCompile(`"([a-z0-9.]+)"\s+\(dict ([^)]*)\)`)
presetField = func(key string) *regexp.Regexp { return regexp.MustCompile(`"` + key + `"\s+"([^"]+)"`) }
presetCPU = presetField("cpu")
presetMem = presetField("memory")
)
// shippedPresets reads the preset table the charts render from, so that a
// declaration is evaluated against the figures a tenant actually gets.
func shippedPresets(t *testing.T) map[string]ResourceList {
t.Helper()
raw, err := os.ReadFile("../../packages/library/cozy-lib/templates/_resourcepresets.tpl")
if err != nil {
t.Fatal(err)
}
out := map[string]ResourceList{}
for _, m := range presetRow.FindAllStringSubmatch(string(raw), -1) {
cpu, mem := presetCPU.FindStringSubmatch(m[2]), presetMem.FindStringSubmatch(m[2])
if cpu == nil || mem == nil {
t.Fatalf("preset %q: no cpu or memory in %q", m[1], m[2])
}
out[m[1]] = ResourceList{"cpu": resource.MustParse(cpu[1]), "memory": resource.MustParse(mem[1])}
}
// Five series of eight sizes and seven legacy aliases. A table whose
// layout drifts from the pattern above must fail here, not shrink.
if len(out) != 47 {
t.Fatalf("parsed %d presets from _resourcepresets.tpl, expected 47", len(out))
}
return out
}
func shippedEnvironment(t *testing.T) Environment {
t.Helper()
env, err := NewStaticEnvironment(shippedInstancetypes(t), shippedPresets(t))
if err != nil {
t.Fatal(err)
}
return env
}
func compileShipped(t *testing.T, defs map[string]*cozyv1alpha1.ApplicationDefinition, kind string) *Evaluator {
t.Helper()
def, ok := defs[kind]
if !ok {
t.Fatalf("no ApplicationDefinition named %q", kind)
}
schema, err := defaulting.BuildSchema(def.Spec.Application.OpenAPISchema)
if err != nil {
t.Fatalf("%s schema: %v", def.Name, err)
}
ev, err := Compile(def.Spec.Consumption, schema)
if err != nil {
t.Fatalf("compile %s: %v", def.Name, err)
}
return ev
}
// Every declaration that ships has to compile against its kind's schema and
// evaluate on the kind's defaults, so a broken one fails here rather than on
// the first order of that kind.
func TestShippedDeclarationsCompile(t *testing.T) {
env := shippedEnvironment(t)
defs := shippedDefinitions(t)
for _, kind := range declaredKinds {
def, ok := defs[kind]
if !ok {
t.Fatalf("no ApplicationDefinition named %q", kind)
}
if def.Spec.Consumption == nil {
t.Errorf("%s: declares neither its consumption nor an exemption", kind)
}
}
for name, def := range defs {
if def.Spec.Consumption == nil {
continue
}
t.Run(name, func(t *testing.T) {
if _, err := compileShipped(t, defs, name).EvaluateJSON([]byte(`{}`), env); err != nil {
t.Fatalf("evaluate defaults: %v", err)
}
})
}
}
func TestShippedDeclarations(t *testing.T) {
env := shippedEnvironment(t)
defs := shippedDefinitions(t)
cases := []struct {
kind, name, values string
want ResourceList
}{
{
kind: "vm-instance", name: "defaults",
values: `{}`,
want: rl("cpu", "1", "memory", "4Gi"),
},
{
kind: "vm-instance", name: "dedicated type pins the emulator core",
values: `{"instanceType": "cx1.2xlarge"}`,
want: rl("dedicated-cpu", "9", "hugepages-2Mi", "16Gi"),
},
{
kind: "vm-instance", name: "1Gi hugepages type",
values: `{"instanceType": "m1.large1gi"}`,
want: rl("cpu", "2", "hugepages-1Gi", "16Gi"),
},
{
kind: "vm-instance", name: "overcommitted type",
values: `{"instanceType": "o1.large"}`,
want: rl("cpu", "2", "overcommitted-memory", "8Gi"),
},
{
// cpu is cores per socket, and a complete block replaces the
// instance type.
kind: "vm-instance", name: "complete resources block",
values: `{"instanceType": "cx1.2xlarge", "resources": {"cpu": 4, "sockets": 2, "memory": "8Gi"}}`,
want: rl("cpu", "8", "memory", "8Gi"),
},
{
kind: "vm-instance", name: "complete resources block as strings",
values: `{"resources": {"cpu": "4", "sockets": "2", "memory": "8Gi"}}`,
want: rl("cpu", "8", "memory", "8Gi"),
},
{
// No instance type to resolve: the block alone sizes the VM.
kind: "vm-instance", name: "complete resources block without an instance type",
values: `{"instanceType": "", "resources": {"cpu": 2, "sockets": 1, "memory": "2Gi"}}`,
want: rl("cpu", "2", "memory", "2Gi"),
},
{
// The chart decodes cpu and sockets as YAML, so any spelling of a
// whole number sizes the VM.
kind: "vm-instance", name: "whole numbers spelled as decimals and exponents",
values: `{"resources": {"cpu": "2.0", "sockets": "1e1", "memory": "8Gi"}}`,
want: rl("cpu", "20", "memory", "8Gi"),
},
{
kind: "vm-instance", name: "explicit plus sign",
values: `{"resources": {"cpu": "+2", "sockets": 1, "memory": "1Gi"}}`,
want: rl("cpu", "2", "memory", "1Gi"),
},
{
kind: "vm-instance", name: "memory at the 1M floor",
values: `{"resources": {"cpu": 1, "sockets": 1, "memory": "1M"}}`,
want: rl("cpu", "1", "memory", "1M"),
},
{
// cpu without sockets emits no topology, so the instance type
// still sizes the VM.
kind: "vm-instance", name: "cpu alone leaves the instance type in charge",
values: `{"instanceType": "u1.small", "resources": {"cpu": 4}}`,
want: rl("cpu", "1", "memory", "2Gi"),
},
{
kind: "vm-instance", name: "null cpu and sockets are absent",
values: `{"instanceType": "u1.small", "resources": {"cpu": null, "sockets": null}}`,
want: rl("cpu", "1", "memory", "2Gi"),
},
{
// Helm deletes a nulled key, chart default included, so only the
// resources block can size this VM.
kind: "vm-instance", name: "null instance type beside complete resources",
values: `{"instanceType": null, "resources": {"cpu": 2, "sockets": 1, "memory": "1Gi"}}`,
want: rl("cpu", "2", "memory", "1Gi"),
},
{
kind: "vm-instance", name: "external",
values: `{"instanceType": "u1.small", "external": true}`,
want: rl("cpu", "1", "memory", "2Gi", "services.loadbalancers", "1"),
},
{
kind: "vm-disk", name: "defaults",
values: `{}`,
want: rl("storage", "5Gi"),
},
{
kind: "vm-disk", name: "declared size",
values: `{"storage": "100Gi"}`,
want: rl("storage", "100Gi"),
},
{
kind: "vm-disk", name: "size in bytes",
values: `{"storage": 10737418240}`,
want: rl("storage", "10Gi"),
},
{
// Two replicas of c1.medium plus three t1.micro, all defaults.
kind: "kubernetes", name: "defaults",
values: `{}`,
want: rl("cpu", "7", "memory", "5632Mi"),
},
{
// cozy-lib fills the preset per key: cpu from resources, memory
// from c1.medium.
kind: "kubernetes", name: "partial override on a preset",
values: `{"controlPlane": {"replicas": 1, "apiServer": {"resources": {"cpu": "4"}}}}`,
want: rl("cpu", "5500m", "memory", "2816Mi"),
},
{
kind: "kubernetes", name: "every component sized",
values: `{"controlPlane": {"replicas": 3,
"apiServer": {"resourcesPreset": "u1.small"},
"controllerManager": {"resourcesPreset": "t1.small"},
"scheduler": {"resources": {"cpu": 1, "memory": "1Gi"}},
"konnectivity": {"server": {"resourcesPreset": "t1.nano"}}}}`,
want: rl("cpu", "9750m", "memory", "17280Mi"),
},
{
// The apiserver Service is published so that Proxmox workers can
// reach it.
kind: "kubernetes", name: "proxmox publishes the apiserver",
values: `{"substrate": "proxmox", "controlPlane": {"replicas": 1}}`,
want: rl("cpu", "3500m", "memory", "2816Mi", "services.loadbalancers", "1"),
},
{
// The tenant cluster's cloud-controller-manager realizes the
// controller's Service as a LoadBalancer in the tenant namespace.
kind: "kubernetes", name: "ingress exposed by a load balancer",
values: `{"controlPlane": {"replicas": 1}, "addons": {"ingressNginx": {"enabled": true, "exposeMethod": "LoadBalancer"}}}`,
want: rl("cpu", "3500m", "memory", "2816Mi", "services.loadbalancers", "1"),
},
{
kind: "kubernetes", name: "proxied ingress publishes nothing",
values: `{"controlPlane": {"replicas": 1}, "addons": {"ingressNginx": {"enabled": true, "exposeMethod": "Proxied"}}}`,
want: rl("cpu", "3500m", "memory", "2816Mi"),
},
{
// No cloud-controller-manager runs for a Proxmox cluster, so only
// the apiserver Service is published.
kind: "kubernetes", name: "proxmox ingress load balancer is not realized here",
values: `{"substrate": "proxmox", "controlPlane": {"replicas": 1}, "addons": {"ingressNginx": {"enabled": true, "exposeMethod": "LoadBalancer"}}}`,
want: rl("cpu", "3500m", "memory", "2816Mi", "services.loadbalancers", "1"),
},
{
kind: "kubernetes", name: "legacy preset alias",
values: `{"controlPlane": {"replicas": 1, "apiServer": {"resourcesPreset": "medium"}}}`,
want: rl("cpu", "2500m", "memory", "1792Mi"),
},
{
// A pool created with defaults reserves its ceiling.
kind: "kubernetes-nodes", name: "defaults",
values: `{}`,
want: rl("cpu", "10", "memory", "40Gi", "storage", "200Gi"),
},
{
kind: "kubernetes-nodes", name: "sized by resources",
values: `{"maxReplicas": 3, "instanceType": "cx1.2xlarge", "resources": {"cpu": 2, "memory": "4Gi"}, "diskSize": "30Gi"}`,
want: rl("cpu", "6", "memory", "12Gi", "storage", "90Gi"),
},
{
// An unquoted zero is unset to the chart, which then sizes the
// worker from its instance type.
kind: "kubernetes-nodes", name: "zero resources leave the instance type in charge",
values: `{"maxReplicas": 1, "instanceType": "u1.small", "resources": {"cpu": 0, "memory": 0}}`,
want: rl("cpu", "1", "memory", "2Gi", "storage", "20Gi"),
},
{
kind: "kubernetes-nodes", name: "dedicated instance type",
values: `{"maxReplicas": 2, "instanceType": "cx1.2xlarge"}`,
want: rl("dedicated-cpu", "18", "hugepages-2Mi", "32Gi", "storage", "40Gi"),
},
{
// CAPI seeds the MachineDeployment from the floor, which nothing
// keeps at or below the ceiling.
kind: "kubernetes-nodes", name: "a floor above the ceiling is reserved",
values: `{"minReplicas": 2, "maxReplicas": 1}`,
want: rl("cpu", "2", "memory", "8Gi", "storage", "40Gi"),
},
{
// Proxmox rounds a fractional core up and runs off-cluster.
kind: "kubernetes-nodes", name: "proxmox accepts millicores",
values: `{"substrate": "proxmox", "resources": {"cpu": "500m", "memory": "4Gi"}}`,
want: rl(),
},
{
kind: "kubernetes-nodes", name: "a pool that cannot grow reserves nothing",
values: `{"maxReplicas": 0}`,
want: rl(),
},
{
// The chart falls back to 20Gi for an empty disk size, as Helm's
// default does for any empty value.
kind: "kubernetes-nodes", name: "zero disk size takes the chart's fallback",
values: `{"maxReplicas": 3, "diskSize": 0}`,
want: rl("cpu", "3", "memory", "12Gi", "storage", "60Gi"),
},
{
kind: "kubernetes-nodes", name: "null disk size takes the chart's fallback",
values: `{"maxReplicas": 3, "diskSize": null}`,
want: rl("cpu", "3", "memory", "12Gi", "storage", "60Gi"),
},
{
kind: "kubernetes-nodes", name: "empty disk size takes the chart's fallback",
values: `{"maxReplicas": 3, "diskSize": ""}`,
want: rl("cpu", "3", "memory", "12Gi", "storage", "60Gi"),
},
{
// The chart ignores diskSize on Proxmox, so a value only the
// schema admits must not fail the reservation.
kind: "kubernetes-nodes", name: "proxmox ignores an unparseable disk size",
values: `{"substrate": "proxmox", "diskSize": "1e1.5", "resources": {"cpu": 4, "memory": "8Gi"}}`,
want: rl(),
},
{
// Proxmox workers run on an external hypervisor and their disks
// are cloned there.
kind: "kubernetes-nodes", name: "proxmox runs outside the cluster",
values: `{"substrate": "proxmox", "maxReplicas": 5, "resources": {"cpu": 4, "memory": "8Gi"}}`,
want: rl(),
},
}
evaluators := map[string]*Evaluator{}
for _, tc := range cases {
t.Run(tc.kind+"/"+tc.name, func(t *testing.T) {
ev, ok := evaluators[tc.kind]
if !ok {
ev = compileShipped(t, defs, tc.kind)
evaluators[tc.kind] = ev
}
got, err := ev.EvaluateJSON([]byte(tc.values), env)
if err != nil {
t.Fatal(err)
}
assertList(t, tc.name, got, tc.want)
})
}
}
// The largest topology the chart renders is past int64 as a vCPU count, so
// the product has to be exact rather than overflow.
func TestShippedVMInstanceLargestTopology(t *testing.T) {
env := shippedEnvironment(t)
defs := shippedDefinitions(t)
got, err := compileShipped(t, defs, "vm-instance").EvaluateJSON([]byte(`{"resources": {"cpu": 4294967295, "sockets": 4294967295, "memory": "1Gi"}}`), env)
if err != nil {
t.Fatal(err)
}
cpu := got["cpu"]
if s := cpu.AsDec().String(); s != "18446744065119617025" {
t.Errorf("cpu = %s, want 18446744065119617025", s)
}
}
// A figure the declaration cannot resolve is an error, never a smaller one.
func TestShippedDeclarationsFailClosed(t *testing.T) {
env := shippedEnvironment(t)
defs := shippedDefinitions(t)
cases := []struct {
kind, name, values string
notFound bool
// reason, when set, must appear in the error, for a case that more
// than one rule would refuse.
reason string
}{
{kind: "vm-instance", name: "unknown instance type", values: `{"instanceType": "u9.huge"}`, notFound: true},
{kind: "vm-instance", name: "no sizing at all", values: `{"instanceType": ""}`, notFound: true},
{kind: "vm-instance", name: "millicore cpu", values: `{"resources": {"cpu": "500m", "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "fractional cpu", values: `{"resources": {"cpu": "1.5", "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "zero cpu", values: `{"resources": {"cpu": 0, "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "zero sockets", values: `{"resources": {"cpu": 2, "sockets": "0", "memory": "1Gi"}}`},
{kind: "vm-instance", name: "negative cpu", values: `{"resources": {"cpu": -2, "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "cpu above uint32", values: `{"resources": {"cpu": 4294967296, "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "leading-zero cpu", values: `{"resources": {"cpu": "010", "sockets": 1, "memory": "1Gi"}}`},
{kind: "vm-instance", name: "invalid cpu beside an instance type", values: `{"instanceType": "u1.small", "resources": {"cpu": "500m"}}`},
{kind: "vm-instance", name: "memory beside an instance type", values: `{"instanceType": "u1.medium", "resources": {"memory": "8Gi"}}`},
{kind: "vm-instance", name: "cpu and memory without sockets", values: `{"instanceType": "u1.small", "resources": {"cpu": 4, "memory": "8Gi"}}`},
{kind: "vm-instance", name: "cpu and sockets without memory", values: `{"instanceType": "u1.small", "resources": {"cpu": 2, "sockets": 1}}`},
{kind: "vm-instance", name: "zero memory", values: `{"resources": {"cpu": 2, "sockets": 1, "memory": 0}}`},
{kind: "vm-instance", name: "memory below 1M", values: `{"resources": {"cpu": 2, "sockets": 1, "memory": "999k"}}`},
{kind: "vm-instance", name: "memory below 1M beside an instance type", values: `{"instanceType": "u1.small", "resources": {"memory": "512k"}}`, reason: "resources.memory at least 1M"},
{kind: "vm-instance", name: "null instance type without resources", values: `{"instanceType": null}`},
{kind: "vm-disk", name: "unparseable size", values: `{"storage": "lots"}`},
{kind: "kubernetes", name: "unknown preset", values: `{"controlPlane": {"apiServer": {"resourcesPreset": "x9.huge"}}}`, notFound: true},
{kind: "kubernetes-nodes", name: "unknown instance type", values: `{"instanceType": "u9.huge"}`, notFound: true},
{kind: "kubernetes-nodes", name: "unparseable disk", values: `{"diskSize": "1e1.5"}`},
{kind: "kubernetes-nodes", name: "cpu without memory", values: `{"maxReplicas": 3, "resources": {"cpu": 2}}`},
{kind: "kubernetes-nodes", name: "millicore cpu on kubevirt", values: `{"maxReplicas": 3, "resources": {"cpu": "500m", "memory": "4Gi"}}`},
{kind: "kubernetes-nodes", name: "quoted zero cpu on kubevirt", values: `{"maxReplicas": 3, "resources": {"cpu": "0", "memory": "4Gi"}}`},
{kind: "kubernetes-nodes", name: "fractional cpu on kubevirt", values: `{"maxReplicas": 3, "resources": {"cpu": "1.5", "memory": "4Gi"}}`},
{kind: "kubernetes-nodes", name: "quoted zero memory without cpu", values: `{"maxReplicas": 3, "resources": {"memory": "0"}}`, reason: "cpu and memory together"},
{kind: "kubernetes-nodes", name: "proxmox without resources", values: `{"substrate": "proxmox"}`, reason: "substrate proxmox requires"},
{kind: "kubernetes-nodes", name: "proxmox with only cpu", values: `{"substrate": "proxmox", "resources": {"cpu": 4}}`, reason: "substrate proxmox requires"},
{kind: "kubernetes-nodes", name: "memory without cpu", values: `{"maxReplicas": 3, "resources": {"cpu": 0, "memory": "4Gi"}}`},
}
for _, tc := range cases {
t.Run(tc.kind+"/"+tc.name, func(t *testing.T) {
_, err := compileShipped(t, defs, tc.kind).EvaluateJSON([]byte(tc.values), env)
if err == nil {
t.Fatal("expected an error")
}
if tc.notFound && !errors.Is(err, ErrNotFound) {
t.Fatalf("expected ErrNotFound, got %v", err)
}
if tc.reason != "" && !strings.Contains(err.Error(), tc.reason) {
t.Fatalf("expected an error carrying %q, got %v", tc.reason, err)
}
})
}
}