diff --git a/Makefile b/Makefile index 764775058..6c877b571 100644 --- a/Makefile +++ b/Makefile @@ -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/ 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 := diff --git a/cmd/check-consumption/main.go b/cmd/check-consumption/main.go new file mode 100644 index 000000000..8a1df2d8b --- /dev/null +++ b/cmd/check-consumption/main.go @@ -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) + } +} diff --git a/cmd/check-consumption/main_test.go b/cmd/check-consumption/main_test.go new file mode 100644 index 000000000..b43de3ae6 --- /dev/null +++ b/cmd/check-consumption/main_test.go @@ -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) + } + }) + } +} diff --git a/hack/check-rd-consumption.sh b/hack/check-rd-consumption.sh new file mode 100755 index 000000000..c9379770a --- /dev/null +++ b/hack/check-rd-consumption.sh @@ -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-.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" diff --git a/hack/check-rd-consumption_test.bats b/hack/check-rd-consumption_test.bats new file mode 100644 index 000000000..eff7aebc7 --- /dev/null +++ b/hack/check-rd-consumption_test.bats @@ -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' +}