mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 12:16:03 +09:00
The evaluator and classifier tests read the kinds' schemas from packages/system/<kind>-rd/cozyrds/<kind>.yaml and the instance type catalog from the kubevirt-instancetypes templates. That ties unit tests of CEL semantics, quantity arithmetic and classification to how the charts lay out their sources, so a chart change unrelated to the evaluator could fail them. Give them schemas cut down to the keys the declarations read and instance types in the shapes the classifier has to tell apart. The expected figures are unchanged. The exact product past int64, pinned until now only through the shipped vm-instance declaration, gets a case of its own. The shipped-catalog reader moves next to its last user, the shipped-declaration test. Assisted-by: LLM Signed-off-by: Aleksei Sviridkin <f@lex.la>
663 lines
24 KiB
Go
663 lines
24 KiB
Go
/*
|
|
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 (
|
|
"errors"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
|
|
"k8s.io/apimachinery/pkg/api/resource"
|
|
|
|
"github.com/cozystack/cozystack/pkg/apis/apps/defaulting"
|
|
)
|
|
|
|
// The declarations below are test fixtures in the shape a kind would carry
|
|
// 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{{
|
|
Name: "count",
|
|
// The autoscaler writes the Cluster's scale subresource, never the
|
|
// application, so the ceiling is what has to be reserved.
|
|
Expression: `values.autoscaling.enabled && values.autoscaling.maxReplicas > values.replicas
|
|
? values.autoscaling.maxReplicas : values.replicas`,
|
|
}},
|
|
Resources: map[string]string{
|
|
// cozy-lib fills a preset per key, so each key is overridden on its own.
|
|
"cpu": `(has(values.resources.cpu) ? quantity(values.resources.cpu) : preset(values.resourcesPreset).cpu).mul(count)`,
|
|
"memory": `(has(values.resources.memory) ? quantity(values.resources.memory) : preset(values.resourcesPreset).memory).mul(count)`,
|
|
"storage": `quantity(values.size).mul(count)`,
|
|
},
|
|
}
|
|
|
|
var vmInstanceDecl = &Declaration{
|
|
Let: []Binding{
|
|
// vm-instance treats resources as all-or-nothing, and cpu is per socket.
|
|
{Name: "sized", Expression: `has(values.resources.cpu) && has(values.resources.sockets) && has(values.resources.memory)`},
|
|
{Name: "it", Expression: `instanceType(values.instanceType)`},
|
|
},
|
|
Resources: map[string]string{
|
|
"cpu": `sized ? int(values.resources.cpu) * int(values.resources.sockets) : it.cpu`,
|
|
"dedicated-cpu": `sized ? 0 : it['dedicated-cpu']`,
|
|
"memory": `sized ? quantity(values.resources.memory) : it.memory`,
|
|
"hugepages-2Mi": `sized ? 0 : it['hugepages-2Mi']`,
|
|
"hugepages-1Gi": `sized ? 0 : it['hugepages-1Gi']`,
|
|
"overcommitted-memory": `sized ? 0 : it['overcommitted-memory']`,
|
|
"services.loadbalancers": `values.external ? 1 : 0`,
|
|
},
|
|
}
|
|
|
|
var kubernetesNodesDecl = &Declaration{
|
|
Let: []Binding{{Name: "it", Expression: `instanceType(values.instanceType)`}},
|
|
Resources: map[string]string{
|
|
"cpu": `it.cpu.mul(values.maxReplicas)`,
|
|
"memory": `it.memory.mul(values.maxReplicas)`,
|
|
},
|
|
}
|
|
|
|
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()
|
|
s, err := defaulting.BuildSchema(fixtureSchemas[kind])
|
|
if err != nil || s == nil {
|
|
t.Fatalf("%s schema: %v", kind, err)
|
|
}
|
|
return s
|
|
}
|
|
|
|
func testEnvironment(t *testing.T) Environment {
|
|
t.Helper()
|
|
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")},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return env
|
|
}
|
|
|
|
func mustCompile(t *testing.T, decl *Declaration, kind string) *Evaluator {
|
|
t.Helper()
|
|
ev, err := Compile(decl, fixtureSchema(t, kind))
|
|
if err != nil {
|
|
t.Fatalf("compile %s: %v", kind, err)
|
|
}
|
|
return ev
|
|
}
|
|
|
|
func rl(kv ...string) ResourceList {
|
|
out := ResourceList{}
|
|
for i := 0; i < len(kv); i += 2 {
|
|
out[kv[i]] = resource.MustParse(kv[i+1])
|
|
}
|
|
return out
|
|
}
|
|
|
|
func TestEvaluateKinds(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
postgres := mustCompile(t, postgresDecl, "postgres")
|
|
vm := mustCompile(t, vmInstanceDecl, "vm-instance")
|
|
|
|
cases := []struct {
|
|
name string
|
|
ev *Evaluator
|
|
values string
|
|
want ResourceList
|
|
}{
|
|
{
|
|
// Two replicas of t1.micro with 10Gi each, all from schema defaults.
|
|
name: "postgres defaults", ev: postgres, values: `{}`,
|
|
want: rl("cpu", "1", "memory", "512Mi", "storage", "20Gi"),
|
|
},
|
|
{
|
|
// The per-key fill: cpu from resources, memory from the preset.
|
|
name: "postgres partial resources on a preset", ev: postgres,
|
|
values: `{"replicas": 1, "resourcesPreset": "t1.nano", "resources": {"cpu": "1"}}`,
|
|
want: rl("cpu", "1", "memory", "128Mi", "storage", "10Gi"),
|
|
},
|
|
{
|
|
name: "postgres integer cpu", ev: postgres,
|
|
values: `{"replicas": 1, "resources": {"cpu": 2, "memory": "1Gi"}}`,
|
|
want: rl("cpu", "2", "memory", "1Gi", "storage", "10Gi"),
|
|
},
|
|
{
|
|
name: "postgres autoscaling reserves the ceiling", ev: postgres,
|
|
values: `{"autoscaling": {"enabled": true}}`,
|
|
want: rl("cpu", "3", "memory", "1536Mi", "storage", "60Gi"),
|
|
},
|
|
{
|
|
name: "postgres autoscaling off reserves replicas", ev: postgres,
|
|
values: `{"autoscaling": {"enabled": false, "maxReplicas": 6}}`,
|
|
want: rl("cpu", "1", "memory", "512Mi", "storage", "20Gi"),
|
|
},
|
|
{
|
|
name: "vm-instance default instance type", ev: vm, values: `{}`,
|
|
want: rl("cpu", "1", "memory", "4Gi"),
|
|
},
|
|
{
|
|
name: "vm-instance dedicated type pins the emulator core", ev: vm,
|
|
values: `{"instanceType": "cx1.2xlarge"}`,
|
|
want: rl("dedicated-cpu", "9", "hugepages-2Mi", "16Gi"),
|
|
},
|
|
{
|
|
name: "vm-instance overcommitted type", ev: vm,
|
|
values: `{"instanceType": "o1.large"}`,
|
|
want: rl("cpu", "2", "overcommitted-memory", "8Gi"),
|
|
},
|
|
{
|
|
// cpu is cores per socket.
|
|
name: "vm-instance complete resources block", ev: vm,
|
|
values: `{"instanceType": "u1.small", "resources": {"cpu": 4, "sockets": 2, "memory": "8Gi"}}`,
|
|
want: rl("cpu", "8", "memory", "8Gi"),
|
|
},
|
|
{
|
|
// Without sockets the chart sizes the VM from its instance type.
|
|
name: "vm-instance cpu without sockets", ev: vm,
|
|
values: `{"instanceType": "u1.small", "resources": {"cpu": 4, "memory": "8Gi"}}`,
|
|
want: rl("cpu", "1", "memory", "2Gi"),
|
|
},
|
|
{
|
|
name: "vm-instance external", ev: vm,
|
|
values: `{"instanceType": "u1.small", "external": true}`,
|
|
want: rl("cpu", "1", "memory", "2Gi", "services.loadbalancers", "1"),
|
|
},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
got, err := tc.ev.EvaluateJSON([]byte(tc.values), env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, tc.name, got, tc.want)
|
|
})
|
|
}
|
|
}
|
|
|
|
// A release a platform chart renders, such as ComputePlane's default md0
|
|
// pool, carries only the keys the chart wrote. It has to reserve exactly what
|
|
// the same pool with its defaults written out reserves.
|
|
func TestEvaluateDefaultsStoredValues(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
ev := mustCompile(t, kubernetesNodesDecl, "kubernetes-nodes")
|
|
|
|
sparse, err := ev.EvaluateJSON([]byte(`{"roles": ["ingress-nginx"], "minReplicas": 0}`), env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
explicit, err := ev.EvaluateJSON([]byte(`{"roles": ["ingress-nginx"], "minReplicas": 0, "maxReplicas": 10, "instanceType": "u1.medium"}`), env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, "sparse vs explicit", sparse, explicit)
|
|
assertList(t, "sparse", sparse, rl("cpu", "10", "memory", "40Gi"))
|
|
}
|
|
|
|
func TestEvaluateFailsClosed(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
postgres := mustCompile(t, postgresDecl, "postgres")
|
|
vm := mustCompile(t, vmInstanceDecl, "vm-instance")
|
|
|
|
if _, err := vm.EvaluateJSON([]byte(`{"instanceType": "u9.imaginary"}`), env); err == nil {
|
|
t.Error("unknown instance type: expected an error")
|
|
} else if !errors.Is(err, ErrNotFound) {
|
|
t.Errorf("unknown instance type: expected ErrNotFound, got %v", err)
|
|
}
|
|
if _, err := postgres.EvaluateJSON([]byte(`{"resourcesPreset": "t9.huge"}`), env); !errors.Is(err, ErrNotFound) {
|
|
t.Errorf("unknown preset: expected ErrNotFound, got %v", err)
|
|
}
|
|
if _, err := postgres.EvaluateJSON([]byte(`{"replicas": "two"}`), env); err == nil {
|
|
t.Error("wrong value type: expected an error")
|
|
}
|
|
if _, err := postgres.EvaluateJSON([]byte(`{"size": "lots"}`), env); err == nil {
|
|
t.Error("unparseable quantity: expected an error")
|
|
}
|
|
if _, err := postgres.EvaluateJSON([]byte(`[1, 2]`), env); err == nil {
|
|
t.Error("non-object values: expected an error")
|
|
}
|
|
if _, err := postgres.EvaluateJSON([]byte(`{}`), nil); err == nil {
|
|
t.Error("no environment: expected an error")
|
|
}
|
|
|
|
unguarded, err := Compile(&Declaration{Resources: map[string]string{"cpu": `quantity(values.notInTheSchema)`}}, fixtureSchema(t, "postgres"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := unguarded.EvaluateJSON([]byte(`{}`), env); err == nil {
|
|
t.Error("unguarded absent key: expected an error, not a zero")
|
|
}
|
|
|
|
negative, err := Compile(&Declaration{Resources: map[string]string{"cpu": `-1`}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := negative.EvaluateJSON(nil, env); err == nil {
|
|
t.Error("negative reservation: expected an error")
|
|
}
|
|
|
|
// A negative double too small to survive rounding to millis is still
|
|
// negative.
|
|
tiny, err := Compile(&Declaration{Resources: map[string]string{"cpu": `-0.0001`}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := tiny.EvaluateJSON(nil, env); err == nil {
|
|
t.Error("small negative reservation: expected an error, not a zero")
|
|
}
|
|
|
|
// A double past the range of an int64 in millis must not be clamped into
|
|
// a smaller figure.
|
|
for _, expr := range []string{`1e100`, `1e308`, `9.3e15`} {
|
|
huge, err := Compile(&Declaration{Resources: map[string]string{"cpu": expr}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got, err := huge.EvaluateJSON(nil, env); err == nil {
|
|
t.Errorf("%s: expected an error, got %v", expr, got)
|
|
}
|
|
}
|
|
finite, err := Compile(&Declaration{Resources: map[string]string{"cpu": `1e3`, "memory": `0.25`}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := finite.EvaluateJSON(nil, env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, "finite doubles", got, rl("cpu", "1k", "memory", "250m"))
|
|
}
|
|
|
|
func TestEvaluateRejectsValuesOfTheWrongType(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
// Defaulting replaces a value whose type does not match the schema with
|
|
// the schema's own default, so the type is checked before it runs:
|
|
// otherwise this guard would read an erased resources object and
|
|
// reserve its fallback.
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{
|
|
"cpu": `has(values.resources.cpu) ? values.resources.cpu : 1`,
|
|
}}, fixtureSchema(t, "postgres"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, raw := range []string{
|
|
`{"resources": "invalid"}`,
|
|
`{"resources": [1]}`,
|
|
`{"resources": true}`,
|
|
`{"resources": {"cpu": true}}`,
|
|
`{"replicas": 2.5}`,
|
|
`{"replicas": "2"}`,
|
|
`{"external": "yes"}`,
|
|
`{"postgresql": {"sharedPreloadLibraries": "pg_prewarm"}}`,
|
|
`{"users": {"app": "admin"}}`,
|
|
} {
|
|
if got, err := ev.EvaluateJSON([]byte(raw), env); err == nil {
|
|
t.Errorf("%s: expected an error, got %v", raw, got)
|
|
}
|
|
}
|
|
for raw, want := range map[string]ResourceList{
|
|
`{}`: rl("cpu", "1"),
|
|
`{"resources": {}}`: rl("cpu", "1"),
|
|
`{"resources": {"cpu": 2}}`: rl("cpu", "2"),
|
|
`{"resources": {"cpu": "500m"}}`: rl("cpu", "500m"),
|
|
`{"resources": null, "replicas": 3}`: rl("cpu", "1"),
|
|
`{"users": {"app": {"replication": true}}}`: rl("cpu", "1"),
|
|
} {
|
|
got, err := ev.EvaluateJSON([]byte(raw), env)
|
|
if err != nil {
|
|
t.Errorf("%s: %v", raw, err)
|
|
continue
|
|
}
|
|
assertList(t, raw, got, want)
|
|
}
|
|
}
|
|
|
|
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`}}, fixtureSchema(t, "postgres"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, raw := range []string{`{"replicas": 2}`, `{"replicas": 2.0}`, `{"replicas": 2e0}`, `{"replicas": 0.2e1}`} {
|
|
got, err := ev.EvaluateJSON([]byte(raw), env)
|
|
if err != nil {
|
|
t.Errorf("%s: %v", raw, err)
|
|
continue
|
|
}
|
|
assertList(t, raw, got, rl("cpu", "2"))
|
|
}
|
|
for _, raw := range []string{`{"replicas": 2.5}`, `{"replicas": 25e-1}`} {
|
|
if got, err := ev.EvaluateJSON([]byte(raw), env); err == nil {
|
|
t.Errorf("%s: expected an error, got %v", raw, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestEvaluateChecksUntypedSchemasByShape(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
// BuildSchema does not require a structural schema to be typed, and
|
|
// defaulting treats an untyped node with properties as an object and one
|
|
// with items as an array, so the type check must as well.
|
|
s, err := defaulting.BuildSchema(`{"type":"object","properties":{
|
|
"resources":{"properties":{"cpu":{"type":"integer"}}},
|
|
"disks":{"items":{"type":"string"}},
|
|
"labels":{"additionalProperties":{"type":"string"}}}}`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{
|
|
"cpu": `has(values.resources) && has(values.resources.cpu) ? values.resources.cpu : 1`,
|
|
}}, s)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, raw := range []string{`{"resources": "invalid"}`, `{"resources": {"cpu": "2"}}`, `{"disks": "a"}`, `{"disks": [1]}`, `{"labels": "a"}`, `{"labels": {"a": 1}}`} {
|
|
if got, err := ev.EvaluateJSON([]byte(raw), env); err == nil {
|
|
t.Errorf("%s: expected an error, got %v", raw, got)
|
|
}
|
|
}
|
|
for raw, want := range map[string]ResourceList{
|
|
`{"resources": {"cpu": 2}}`: rl("cpu", "2"),
|
|
`{"disks": ["a"]}`: rl("cpu", "1"),
|
|
`{"labels": {"a": "b"}}`: rl("cpu", "1"),
|
|
} {
|
|
got, err := ev.EvaluateJSON([]byte(raw), env)
|
|
if err != nil {
|
|
t.Errorf("%s: %v", raw, err)
|
|
continue
|
|
}
|
|
assertList(t, raw, got, want)
|
|
}
|
|
}
|
|
|
|
func TestCompile(t *testing.T) {
|
|
if _, err := Compile(nil, nil); !errors.Is(err, ErrNoDeclaration) {
|
|
t.Errorf("nil declaration: got %v, want ErrNoDeclaration", err)
|
|
}
|
|
if _, err := Compile(&Declaration{}, nil); !errors.Is(err, ErrNoDeclaration) {
|
|
t.Errorf("empty declaration: got %v, want ErrNoDeclaration", err)
|
|
}
|
|
|
|
exempt, err := Compile(&Declaration{Exempt: true}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := exempt.EvaluateJSON([]byte(`{"anything": 1}`), nil)
|
|
if err != nil || len(got) != 0 || !exempt.Exempt() {
|
|
t.Errorf("exempt: got %v, %v", got, err)
|
|
}
|
|
|
|
invalid := map[string]*Declaration{
|
|
"exempt with resources": {Exempt: true, Resources: map[string]string{"cpu": "1"}},
|
|
"syntax error": {Resources: map[string]string{"cpu": "values.("}},
|
|
"undeclared variable": {Resources: map[string]string{"cpu": "count"}},
|
|
"empty key": {Resources: map[string]string{"": "1"}},
|
|
"bad let name": {Let: []Binding{{Name: "a-b", Expression: "1"}}, Resources: map[string]string{"cpu": "1"}},
|
|
"let shadows values": {Let: []Binding{{Name: "values", Expression: "1"}}, Resources: map[string]string{"cpu": "1"}},
|
|
"duplicate let": {Let: []Binding{{Name: "a", Expression: "1"}, {Name: "a", Expression: "2"}}, Resources: map[string]string{"cpu": "a"}},
|
|
}
|
|
for name, decl := range invalid {
|
|
if _, err := Compile(decl, nil); err == nil {
|
|
t.Errorf("%s: expected a compile error", name)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The Kubernetes quantity library returns a pointer from add and sub, where
|
|
// quantity() and mul return a value; a declaration summing several components
|
|
// mixes both.
|
|
func TestEvaluateQuantityArithmetic(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
cases := map[string]struct {
|
|
expr string
|
|
want string
|
|
}{
|
|
"add": {`quantity('1').add(quantity('500m'))`, "1500m"},
|
|
"add an int": {`quantity('1').add(2)`, "3"},
|
|
"sub": {`quantity('2Gi').sub(quantity('512Mi'))`, "1536Mi"},
|
|
"mul after add": {`preset('t1.micro').cpu.add(preset('t1.nano').cpu).mul(2)`, "1500m"},
|
|
"add after mul": {`quantity('1Gi').mul(2).add(quantity('1Gi'))`, "3Gi"},
|
|
}
|
|
for name, tc := range cases {
|
|
t.Run(name, func(t *testing.T) {
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{"x": tc.expr}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := ev.Evaluate(map[string]any{}, env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, name, got, rl("x", tc.want))
|
|
})
|
|
}
|
|
}
|
|
|
|
// A fractional binary quantity is stored at a scale whose coefficient leaves
|
|
// int64 well before its value does, which is where resource.Quantity.Mul
|
|
// reports an inexact int64 for a product it still holds exactly.
|
|
func TestEvaluateMulKeepsExactProducts(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
cases := map[string]struct {
|
|
expr string
|
|
want string
|
|
}{
|
|
"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) {
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{"x": tc.expr}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := ev.Evaluate(map[string]any{}, env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, name, got, rl("x", tc.want))
|
|
})
|
|
}
|
|
}
|
|
|
|
// A declaration states a spec its chart refuses to render with fail(), so
|
|
// that the refusal carries the declaration's own reason.
|
|
func TestEvaluateFail(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
// Keys evaluate in sorted order, so cpu succeeds before memory fails.
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{
|
|
"cpu": `quantity('1')`,
|
|
"memory": `has(values.memory) ? quantity(values.memory) : fail('memory is required')`,
|
|
}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := ev.Evaluate(map[string]any{}, env)
|
|
if err == nil || !strings.Contains(err.Error(), "memory is required") {
|
|
t.Errorf("got %v, want an error carrying the declared reason", err)
|
|
}
|
|
if got != nil {
|
|
t.Errorf("a failed evaluation returned a partial reservation %v", got)
|
|
}
|
|
got, err = ev.Evaluate(map[string]any{"memory": "1Gi"}, env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, "branch not taken", got, rl("cpu", "1", "memory", "1Gi"))
|
|
}
|
|
|
|
// A null is absent to Helm, which deletes the key it nulls, so it must be
|
|
// absent to an expression too, including where the schema has no default to
|
|
// put in its place.
|
|
func TestEvaluateTreatsNullAsAbsent(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
ev, err := Compile(&Declaration{Resources: map[string]string{
|
|
"cpu": `has(values.r.cpu) ? 1 : 2`,
|
|
}}, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
got, err := ev.Evaluate(map[string]any{"r": map[string]any{"cpu": nil}}, env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, "null", got, rl("cpu", "2"))
|
|
}
|
|
|
|
// Helm deletes a nulled key from the chart's defaults as well, so a null must
|
|
// not be replaced by the schema default either.
|
|
func TestEvaluateNullOverridesDefault(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
ev := mustCompile(t, &Declaration{Resources: map[string]string{
|
|
"cpu": `has(values.instanceType) ? 1 : 2`,
|
|
}}, "vm-instance")
|
|
for name, tc := range map[string]struct {
|
|
values string
|
|
want string
|
|
}{
|
|
"omitted takes the default": {`{}`, "1"},
|
|
"null deletes the default": {`{"instanceType": null}`, "2"},
|
|
"nested null": {`{"resources": null}`, "1"},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
got, err := ev.EvaluateJSON([]byte(tc.values), env)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
assertList(t, name, got, rl("cpu", tc.want))
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestEvaluateIsConcurrencySafe(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
vm := mustCompile(t, vmInstanceDecl, "vm-instance")
|
|
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))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for range 8 {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
got, err := vm.EvaluateJSON([]byte(`{"instanceType": "`+it+`"}`), env)
|
|
if err != nil {
|
|
t.Error(err)
|
|
return
|
|
}
|
|
assertList(t, it, got, want)
|
|
}()
|
|
}
|
|
}
|
|
wg.Wait()
|
|
}
|
|
|
|
func findInstancetype(t *testing.T, catalog []map[string]any, name string) map[string]any {
|
|
t.Helper()
|
|
for _, obj := range catalog {
|
|
if obj["metadata"].(map[string]any)["name"] == name {
|
|
return obj
|
|
}
|
|
}
|
|
t.Fatalf("%s is not a fixture instance type", name)
|
|
return nil
|
|
}
|
|
|
|
func TestAggregate(t *testing.T) {
|
|
env := testEnvironment(t)
|
|
evaluators := map[string]*Evaluator{
|
|
"VMInstance": mustCompile(t, vmInstanceDecl, "vm-instance"),
|
|
"Postgres": mustCompile(t, postgresDecl, "postgres"),
|
|
}
|
|
lookup := func(kind, group string) (*Evaluator, error) {
|
|
if group != "apps.cozystack.io" {
|
|
return nil, errors.New("unknown group")
|
|
}
|
|
if ev, ok := evaluators[kind]; ok {
|
|
return ev, nil
|
|
}
|
|
return nil, ErrNoDeclaration
|
|
}
|
|
apps := []Application{
|
|
{Namespace: "tenant-a", Name: "vm1", Kind: "VMInstance", Group: "apps.cozystack.io", Values: []byte(`{"instanceType": "u1.small"}`)},
|
|
{Namespace: "tenant-a", Name: "vm2", Kind: "VMInstance", Group: "apps.cozystack.io", Values: []byte(`{"instanceType": "u1.small", "external": true}`)},
|
|
{Namespace: "tenant-a", Name: "db", Kind: "Postgres", Group: "apps.cozystack.io", Values: []byte(`{}`)},
|
|
{Namespace: "tenant-b", Name: "vm3", Kind: "VMInstance", Group: "apps.cozystack.io", Values: []byte(`{"instanceType": "u1.small"}`)},
|
|
{Namespace: "tenant-b", Name: "broken", Kind: "VMInstance", Group: "apps.cozystack.io", Values: []byte(`{"instanceType": "gone"}`)},
|
|
{Namespace: "tenant-b", Name: "undeclared", Kind: "Redis", Group: "apps.cozystack.io", Values: []byte(`{}`)},
|
|
}
|
|
sums, failures := Aggregate(apps, lookup, env)
|
|
assertList(t, "tenant-a", sums["tenant-a"], rl("cpu", "3", "memory", "4608Mi", "storage", "20Gi", "services.loadbalancers", "1"))
|
|
assertList(t, "tenant-b", sums["tenant-b"], rl("cpu", "1", "memory", "2Gi"))
|
|
if len(failures) != 2 {
|
|
t.Fatalf("expected 2 failures, got %v", failures)
|
|
}
|
|
if failures[0].Application.Name != "broken" || !errors.Is(failures[0].Err, ErrNotFound) {
|
|
t.Errorf("first failure: %v", failures[0])
|
|
}
|
|
if failures[1].Application.Name != "undeclared" || !errors.Is(failures[1].Err, ErrNoDeclaration) {
|
|
t.Errorf("second failure: %v", failures[1])
|
|
}
|
|
}
|
|
|
|
func TestResourceListArithmetic(t *testing.T) {
|
|
a := rl("cpu", "2", "memory", "4Gi")
|
|
b := a.DeepCopy()
|
|
b.Add(rl("cpu", "1", "storage", "10Gi"))
|
|
assertList(t, "copy unaffected", a, rl("cpu", "2", "memory", "4Gi"))
|
|
assertList(t, "add", b, rl("cpu", "3", "memory", "4Gi", "storage", "10Gi"))
|
|
b.Sub(rl("cpu", "4", "services.loadbalancers", "1"))
|
|
assertList(t, "sub", b, rl("cpu", "-1", "memory", "4Gi", "storage", "10Gi", "services.loadbalancers", "-1"))
|
|
if keys := b.Keys(); len(keys) != 4 || keys[0] != "cpu" || keys[3] != "storage" {
|
|
t.Errorf("keys not sorted: %v", keys)
|
|
}
|
|
}
|