mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-01 20:56:02 +09:00
feat(api, kubernetes, virtual-machine): declare tenant quota reservations on ApplicationDefinitions (#5349)
<!-- Thank you for making a contribution! Here are some tips for you: - Use Conventional Commits for the PR title: `type(scope): description` - Types: feat, fix, security (a fix that comes through a security advisory), docs, style, refactor, perf, test, build, ci, chore - Scopes are not an exhaustive list — pick the most specific scope for the change and extend the list when a genuinely new area appears. Examples: - System components: dashboard, platform, operator, cilium, kube-ovn, linstor, fluxcd, cluster-api - Managed apps: postgres, mariadb, redis, kafka, clickhouse, virtual-machine, kubernetes - Development and maintenance: api, hack, tests, ci, docs, maintenance - Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or add a `BREAKING CHANGE:` footer - If it's a work in progress, consider creating this PR as a draft. - Don't hesistate to ask for opinion and review in the community chats, even if it's still a draft. - Fixes merged to `main` reach the release lines the backport batch runs for automatically, so do not open backport PRs by hand: https://github.com/cozystack/cozystack/blob/main/docs/release/backports.md --> ## What this PR does Second phase of the accepted [tenant quotas as reservation limits](https://github.com/cozystack/community/pull/48) design, after the evaluator in #4983. An `ApplicationDefinition` can now declare what an application of its kind reserves from its tenant's budget, as CEL over its defaulted values, and the four IaaS kinds (`vm-instance`, `vm-disk`, `kubernetes`, `kubernetes-nodes`) declare theirs. Nothing reads the declarations yet: the usage oracle and the generalized admission gate are the next phase, behind a flag. - `fix(api)`: the evaluator could not sum quantities. The Kubernetes CEL library returns a pointer from `add` and `sub`, which the evaluator did not recognize, so any declaration summing components failed. Found while writing the `kubernetes` declaration, which sums four control-plane components. - `fix(api)`: the evaluator refused exact products. `resource.Quantity.Mul` returns false once the product leaves an int64 coefficient, not when it is wrong, so any fractional binary size above about 8.5Gi (`20.5Gi × 3`) failed as an overflow. - `fix(api)`: a null value stayed present wherever the schema had no default to replace it, so `has()` saw a key Helm deletes, and evaluation failed on a spec the chart renders. - `feat(api)`: `spec.consumption` on `ApplicationDefinition` (`exempt`, ordered `let` bindings, `resources` per quota key), owned as a whole so that a binding and the expressions reading it are replaced together. The evaluator's `Declaration` is now an alias of the API type. The CRD rejects an exempt declaration that still carries expressions and a non-exempt one that names no resource. - `refactor(extra)`: ComputePlane's default `md0` pool now writes its ceiling, instance type and disk size into its release instead of relying on the pool chart's schema defaults, so the release alone says what the pool can reserve. The rendered pool does not change. - `feat(api, kubernetes, virtual-machine)`: the four declarations, each following its chart's own precedence, plus a test that evaluates the shipped declarations against the shipped instance types and preset table, with the failures that must stay errors. Validated locally: `go test ./pkg/reservation/` with each commit built and tested on its own, `helm unittest` on computeplane and the touched `-rd` charts, the four definitions plus three invalid ones validated against the generated CRD schema and its CEL rules, and `make generate` in the touched packages left the tree unchanged (with `cozyvalues-gen` v1.7.0, the version CI pins). Decisions worth a reviewer's look: - **Proxmox worker pools reserve nothing.** Their VMs and disks run on the external hypervisor, so they draw nothing from this cluster's capacity. The `kubernetes` kind reserves one `services.loadbalancers` on Proxmox, for its published apiserver Service, and one on KubeVirt when the ingress addon is exposed by a load balancer, which the tenant cluster's cloud controller realizes in the tenant namespace. - **GPUs are not declared.** Their quota key is the device name (`nvidia.com/<model>`), and `resources` keys are fixed strings. Expressing them needs either a dynamic-key form in the declaration or a class key for GPUs; I would rather settle that in its own change than guess here. Until then the namespace `ResourceQuota` keeps bounding them. - **A spec the chart refuses to render is refused, not estimated.** A partial `resources` block on a VM or a worker pool, a non-whole core count or a memory below 1M fails the evaluation with the declaration's reason, through a `fail(reason)` function the evaluator now offers, so the gate in the next phase can answer with the same reason the render would give. Two decisions left for the next phase, both about what values alone cannot see: - A `vm-disk` whose `storage` is lowered keeps its larger volume, because the chart only ever grows it, while its declaration reads the lowered value. The admission gate has to refuse a storage decrease on Update before it relies on this declaration. - A worker pool's rollout runs one surge worker and its disk next to the old ones (`maxUnavailable: 0` by default), which `maxReplicas` does not cover. Whether that overlap counts against the tenant's budget or is platform margin decides whether a tenant at its ceiling can roll a pool at all. Refs: cozystack/community#48 ### Screenshots <!-- REQUIRED for UI changes: attach screenshots or screen recordings demonstrating the visual impact of your changes. PRs with UI changes without screenshots will not be merged. --> ### Downstream repositories I walked the trigger map against the diff. Two repositories are affected, and each has a follow-up issue: - `cozystack/website`: the map lists "Change `ApplicationDefinition` semantics". This adds a field nothing reads yet; documenting it seems more useful once the gate in the next phase gives it an effect. - `cozystack/external-apps-example`: the map lists changes to the `ApplicationDefinition` CRD. The field is optional, so nothing breaks there now, but the next phase refuses orders of a kind that declares neither its consumption nor an exemption, so out-of-tree catalogs will need a declaration before that phase is switched on. - [ ] No downstream repository is affected by this change - [x] [cozystack/website](https://github.com/cozystack/website) - follow-up: cozystack/website#820 - [ ] [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: - [x] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: cozystack/external-apps-example#6 - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note <!-- Write a release note: - Explain what has changed internally and for users. - Start with the same `type(scope):` prefix as in the PR title - Follow the guidelines at https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md. --> ```release-note feat(api, kubernetes, virtual-machine): ApplicationDefinitions can declare the tenant quota reservation of their kind, and the VM, disk, Kubernetes and worker pool kinds declare theirs. Nothing enforces the declarations yet. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Application definitions can declare resource consumption for CPU, memory, storage, and load balancers, with reservations based on configured sizing and substrate choices. * Kubernetes worker-pool reservations reflect replica counts, resource overrides, instance types, and disk size; control-plane reservations reflect component sizing and replica counts. * VM instance and disk definitions report resource and storage consumption. * Default compute clusters now specify a node-pool limit of 10, an instance type, and a disk size. * **Validation** * Invalid or incomplete resource sizing and consumption declarations now produce errors, including mismatched CPU and memory settings. Consumption declarations also enforce limits on resource entries and bindings. * **Bug Fixes** * Null values are treated as absent when calculating reservations, and quantity calculations support larger and fractional results. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
14 files changed
+1109
-26
No files matched your search
@@ -61,6 +61,68 @@ type ApplicationDefinitionSpec struct {
|
||||
|
||||
// Dashboard configuration for this resource
|
||||
Dashboard *ApplicationDefinitionDashboard `json:"dashboard,omitempty"`
|
||||
|
||||
// Consumption declares what an application of this kind reserves from
|
||||
// its tenant's quota budget, computed from its values. Unset means the
|
||||
// kind has not declared it, which is not the same as consuming nothing:
|
||||
// a kind that consumes nothing sets exempt.
|
||||
// +optional
|
||||
Consumption *ApplicationDefinitionConsumption `json:"consumption,omitempty"`
|
||||
}
|
||||
|
||||
// ApplicationDefinitionConsumption is how an application's reservation is
|
||||
// computed from its values, as CEL over the values defaulted against the
|
||||
// kind's openAPISchema.
|
||||
//
|
||||
// An expression sees the variable `values`, every binding in let, and four
|
||||
// functions: instanceType(name) and preset(name), which return a map of
|
||||
// quantities keyed by quota key, quantity(x), which takes an int or a
|
||||
// quantity string, and fail(reason), which raises an evaluation error with
|
||||
// that reason, for a spec the kind's chart would refuse to render. CEL's
|
||||
// logical operators absorb an error when the other operand decides the
|
||||
// result, so fail() refuses the spec only from a branch of a conditional. A
|
||||
// quantity is scaled with q.mul(n). An expression may
|
||||
// return an int, a double, a quantity string or a quantity; a key that
|
||||
// evaluates to zero reserves nothing.
|
||||
// Its fields are owned together: expressions refer to bindings by name, so a
|
||||
// partial update could leave an expression whose binding is gone.
|
||||
// +structType=atomic
|
||||
// +kubebuilder:validation:XValidation:rule="!(has(self.exempt) && self.exempt) || (!has(self.__let__) && !has(self.resources))",message="an exempt declaration carries neither let nor resources"
|
||||
// +kubebuilder:validation:XValidation:rule="(has(self.exempt) && self.exempt) || (has(self.resources) && size(self.resources) > 0)",message="a declaration either is exempt or names at least one resource"
|
||||
type ApplicationDefinitionConsumption struct {
|
||||
// Exempt declares that the kind consumes nothing from a tenant's budget.
|
||||
// +optional
|
||||
Exempt bool `json:"exempt,omitempty"`
|
||||
|
||||
// Let binds intermediate expressions, evaluated in order. A binding
|
||||
// reads only the bindings before it; a resources expression reads them
|
||||
// all. The list is replaced as a whole, since a binding left behind by a
|
||||
// partial update could refer to one that is gone.
|
||||
// +optional
|
||||
// +listType=atomic
|
||||
// +kubebuilder:validation:MaxItems=64
|
||||
// +kubebuilder:validation:XValidation:rule="self.all(b, self.exists_one(c, c.name == b.name))",message="binding names must be unique"
|
||||
Let []ApplicationDefinitionConsumptionBinding `json:"let,omitempty"`
|
||||
|
||||
// Resources maps a quota key, as a Tenant's resourceQuotas spells it,
|
||||
// to the expression computing how much of it the application reserves.
|
||||
// +optional
|
||||
// +kubebuilder:validation:MaxProperties=64
|
||||
// +kubebuilder:validation:XValidation:rule="self.all(k, size(k) > 0)",message="a quota key must not be empty"
|
||||
Resources map[string]string `json:"resources,omitempty"`
|
||||
}
|
||||
|
||||
// ApplicationDefinitionConsumptionBinding names one intermediate expression.
|
||||
type ApplicationDefinitionConsumptionBinding struct {
|
||||
// Name is how later expressions refer to the binding. `values` is taken
|
||||
// by the application's values, and CEL's reserved words cannot name a
|
||||
// variable.
|
||||
// +kubebuilder:validation:Pattern=`^[a-zA-Z_][a-zA-Z0-9_]*$`
|
||||
// +kubebuilder:validation:MaxLength=63
|
||||
// +kubebuilder:validation:XValidation:rule="!(self in ['values', 'true', 'false', 'null', 'in', 'as', 'break', 'const', 'continue', 'else', 'for', 'function', 'if', 'import', 'let', 'loop', 'package', 'namespace', 'return', 'var', 'void', 'while'])",message="the name is reserved"
|
||||
Name string `json:"name"`
|
||||
// +kubebuilder:validation:MinLength=1
|
||||
Expression string `json:"expression"`
|
||||
}
|
||||
|
||||
type ApplicationDefinitionApplication struct {
|
||||
|
||||
Generated
+47
@@ -70,6 +70,48 @@ func (in *ApplicationDefinitionApplication) DeepCopy() *ApplicationDefinitionApp
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ApplicationDefinitionConsumption) DeepCopyInto(out *ApplicationDefinitionConsumption) {
|
||||
*out = *in
|
||||
if in.Let != nil {
|
||||
in, out := &in.Let, &out.Let
|
||||
*out = make([]ApplicationDefinitionConsumptionBinding, len(*in))
|
||||
copy(*out, *in)
|
||||
}
|
||||
if in.Resources != nil {
|
||||
in, out := &in.Resources, &out.Resources
|
||||
*out = make(map[string]string, len(*in))
|
||||
for key, val := range *in {
|
||||
(*out)[key] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationDefinitionConsumption.
|
||||
func (in *ApplicationDefinitionConsumption) DeepCopy() *ApplicationDefinitionConsumption {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ApplicationDefinitionConsumption)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ApplicationDefinitionConsumptionBinding) DeepCopyInto(out *ApplicationDefinitionConsumptionBinding) {
|
||||
*out = *in
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationDefinitionConsumptionBinding.
|
||||
func (in *ApplicationDefinitionConsumptionBinding) DeepCopy() *ApplicationDefinitionConsumptionBinding {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := new(ApplicationDefinitionConsumptionBinding)
|
||||
in.DeepCopyInto(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
|
||||
func (in *ApplicationDefinitionDashboard) DeepCopyInto(out *ApplicationDefinitionDashboard) {
|
||||
*out = *in
|
||||
@@ -241,6 +283,11 @@ func (in *ApplicationDefinitionSpec) DeepCopyInto(out *ApplicationDefinitionSpec
|
||||
*out = new(ApplicationDefinitionDashboard)
|
||||
(*in).DeepCopyInto(*out)
|
||||
}
|
||||
if in.Consumption != nil {
|
||||
in, out := &in.Consumption, &out.Consumption
|
||||
*out = new(ApplicationDefinitionConsumption)
|
||||
(*in).DeepCopyInto(*out)
|
||||
}
|
||||
}
|
||||
|
||||
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApplicationDefinitionSpec.
|
||||
|
||||
@@ -26,6 +26,7 @@ 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
|
||||
@@ -130,7 +131,6 @@ 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
|
||||
|
||||
@@ -153,10 +153,16 @@ spec:
|
||||
md0 with roles: [ingress-nginx]; that default is gone with the split, so the
|
||||
module materialises the same md0 here, otherwise the pinned ingress-nginx
|
||||
addon would have no node to schedule onto and stay Pending forever.
|
||||
|
||||
The default md0 carries its whole size, not only what differs from the pool
|
||||
chart's defaults: those defaults live in the pool's schema and are never
|
||||
written into a release rendered here, so without them the release would not
|
||||
say what the pool can grow to, and a reservation read from it would have to
|
||||
know another chart's defaults.
|
||||
*/}}
|
||||
{{- $pools := .Values.nodeGroups }}
|
||||
{{- if not $pools }}
|
||||
{{- $pools = dict "md0" (dict "roles" (list "ingress-nginx") "minReplicas" 0) }}
|
||||
{{- $pools = dict "md0" (dict "roles" (list "ingress-nginx") "minReplicas" 0 "maxReplicas" 10 "instanceType" "u1.medium" "diskSize" "20Gi") }}
|
||||
{{- end }}
|
||||
{{- range $pool, $group := $pools }}
|
||||
---
|
||||
|
||||
@@ -125,6 +125,21 @@ tests:
|
||||
- equal:
|
||||
path: spec.values.roles[0]
|
||||
value: ingress-nginx
|
||||
# The pool's size is written out rather than left to the pool chart's
|
||||
# schema defaults, which a platform-rendered release never carries, so
|
||||
# the release alone says what the pool can reserve.
|
||||
- equal:
|
||||
path: spec.values.minReplicas
|
||||
value: 0
|
||||
- equal:
|
||||
path: spec.values.maxReplicas
|
||||
value: 10
|
||||
- equal:
|
||||
path: spec.values.instanceType
|
||||
value: u1.medium
|
||||
- equal:
|
||||
path: spec.values.diskSize
|
||||
value: 20Gi
|
||||
# canonical KubernetesNodes pool shape (mirrors rest.go): RetryOnFailure
|
||||
# strategy + disableWait, not the parent module's remediation style.
|
||||
- equal:
|
||||
|
||||
+69
@@ -62,6 +62,75 @@ spec:
|
||||
- plural
|
||||
- singular
|
||||
type: object
|
||||
consumption:
|
||||
description: |-
|
||||
Consumption declares what an application of this kind reserves from
|
||||
its tenant's quota budget, computed from its values. Unset means the
|
||||
kind has not declared it, which is not the same as consuming nothing:
|
||||
a kind that consumes nothing sets exempt.
|
||||
properties:
|
||||
exempt:
|
||||
description: Exempt declares that the kind consumes nothing from
|
||||
a tenant's budget.
|
||||
type: boolean
|
||||
let:
|
||||
description: |-
|
||||
Let binds intermediate expressions, evaluated in order. A binding
|
||||
reads only the bindings before it; a resources expression reads them
|
||||
all. The list is replaced as a whole, since a binding left behind by a
|
||||
partial update could refer to one that is gone.
|
||||
items:
|
||||
description: ApplicationDefinitionConsumptionBinding names one
|
||||
intermediate expression.
|
||||
properties:
|
||||
expression:
|
||||
minLength: 1
|
||||
type: string
|
||||
name:
|
||||
description: |-
|
||||
Name is how later expressions refer to the binding. `values` is taken
|
||||
by the application's values, and CEL's reserved words cannot name a
|
||||
variable.
|
||||
maxLength: 63
|
||||
pattern: ^[a-zA-Z_][a-zA-Z0-9_]*$
|
||||
type: string
|
||||
x-kubernetes-validations:
|
||||
- message: the name is reserved
|
||||
rule: '!(self in [''values'', ''true'', ''false'', ''null'',
|
||||
''in'', ''as'', ''break'', ''const'', ''continue'',
|
||||
''else'', ''for'', ''function'', ''if'', ''import'',
|
||||
''let'', ''loop'', ''package'', ''namespace'', ''return'',
|
||||
''var'', ''void'', ''while''])'
|
||||
required:
|
||||
- expression
|
||||
- name
|
||||
type: object
|
||||
maxItems: 64
|
||||
type: array
|
||||
x-kubernetes-list-type: atomic
|
||||
x-kubernetes-validations:
|
||||
- message: binding names must be unique
|
||||
rule: self.all(b, self.exists_one(c, c.name == b.name))
|
||||
resources:
|
||||
additionalProperties:
|
||||
type: string
|
||||
description: |-
|
||||
Resources maps a quota key, as a Tenant's resourceQuotas spells it,
|
||||
to the expression computing how much of it the application reserves.
|
||||
maxProperties: 64
|
||||
type: object
|
||||
x-kubernetes-validations:
|
||||
- message: a quota key must not be empty
|
||||
rule: self.all(k, size(k) > 0)
|
||||
type: object
|
||||
x-kubernetes-map-type: atomic
|
||||
x-kubernetes-validations:
|
||||
- message: an exempt declaration carries neither let nor resources
|
||||
rule: '!(has(self.exempt) && self.exempt) || (!has(self.__let__)
|
||||
&& !has(self.resources))'
|
||||
- message: a declaration either is exempt or names at least one resource
|
||||
rule: (has(self.exempt) && self.exempt) || (has(self.resources)
|
||||
&& size(self.resources) > 0)
|
||||
dashboard:
|
||||
description: Dashboard configuration for this resource
|
||||
properties:
|
||||
|
||||
@@ -46,3 +46,40 @@ spec:
|
||||
services:
|
||||
exclude: []
|
||||
include: []
|
||||
consumption:
|
||||
let:
|
||||
# The cluster-autoscaler scales the MachineDeployment without writing the
|
||||
# pool, so its ceiling is what is reserved, or its floor where that is
|
||||
# higher, since CAPI seeds the pool from the floor. Proxmox workers and
|
||||
# their disks live on the external hypervisor.
|
||||
- name: count
|
||||
expression: "values.substrate == 'proxmox' ? 0 : values.minReplicas > values.maxReplicas ? values.minReplicas : values.maxReplicas"
|
||||
# On KubeVirt a cpu other than a bare numeric zero becomes the worker's
|
||||
# uint32 core count, so the chart refuses anything but a whole number.
|
||||
# Proxmox rounds a fraction up to whole cores.
|
||||
- name: checkCores
|
||||
expression: "values.substrate != 'proxmox' && has(values.resources.cpu) && !(type(values.resources.cpu) == int && values.resources.cpu == 0)"
|
||||
- name: cores
|
||||
expression: "!checkCores ? 0.0 : type(values.resources.cpu) == int ? double(values.resources.cpu) : values.resources.cpu.matches('^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$') ? double(values.resources.cpu) : -1.0"
|
||||
- name: coresValid
|
||||
expression: "!checkCores || (cores > 0.0 && cores < 4294967296.0 && double(int(cores)) == cores)"
|
||||
# The chart reads cpu and memory by truth: a bare numeric zero or an
|
||||
# empty string is unset, anything else, a quoted "0" included, is set.
|
||||
# It sizes the worker from resources when both are set and from its
|
||||
# instance type when neither is, and refuses one without the other.
|
||||
- name: cpuSet
|
||||
expression: "has(values.resources.cpu) && !(type(values.resources.cpu) == int && values.resources.cpu == 0) && !(type(values.resources.cpu) == string && values.resources.cpu == '')"
|
||||
- name: memorySet
|
||||
expression: "has(values.resources.memory) && !(type(values.resources.memory) == int && values.resources.memory == 0) && !(type(values.resources.memory) == string && values.resources.memory == '')"
|
||||
- name: sized
|
||||
expression: cpuSet && memorySet
|
||||
resources:
|
||||
cpu: "values.substrate == 'proxmox' && !(cpuSet && memorySet) ? fail('substrate proxmox requires resources.cpu and resources.memory') : !coresValid ? fail('resources.cpu must be a whole number of cores between 1 and 4294967295') : cpuSet != memorySet ? fail('resources must set cpu and memory together, or neither') : count == 0 ? quantity(0) : (sized ? quantity(values.resources.cpu) : instanceType(values.instanceType).cpu).mul(count)"
|
||||
dedicated-cpu: "count == 0 || sized ? quantity(0) : instanceType(values.instanceType)['dedicated-cpu'].mul(count)"
|
||||
memory: "count == 0 ? quantity(0) : (sized ? quantity(values.resources.memory) : instanceType(values.instanceType).memory).mul(count)"
|
||||
hugepages-2Mi: "count == 0 || sized ? quantity(0) : instanceType(values.instanceType)['hugepages-2Mi'].mul(count)"
|
||||
hugepages-1Gi: "count == 0 || sized ? quantity(0) : instanceType(values.instanceType)['hugepages-1Gi'].mul(count)"
|
||||
overcommitted-memory: "count == 0 || sized ? quantity(0) : instanceType(values.instanceType)['overcommitted-memory'].mul(count)"
|
||||
# The chart takes 20Gi for an absent or empty diskSize, as Helm's
|
||||
# default does.
|
||||
storage: "count == 0 ? quantity(0) : (!has(values.diskSize) || (type(values.diskSize) == int && values.diskSize == 0) || (type(values.diskSize) == string && values.diskSize == '') ? quantity('20Gi') : quantity(values.diskSize)).mul(count)"
|
||||
@@ -71,3 +71,33 @@ spec:
|
||||
- resourceNames:
|
||||
- kubernetes-{{ .name }}
|
||||
- kubernetes-{{ .name }}-ingress-nginx
|
||||
consumption:
|
||||
# Each control-plane replica runs all four components. cozy-lib fills a
|
||||
# component's preset per key, so cpu and memory are overridden apart.
|
||||
let:
|
||||
- name: cp
|
||||
expression: values.controlPlane
|
||||
- name: apiServerCpu
|
||||
expression: "has(cp.apiServer.resources.cpu) ? quantity(cp.apiServer.resources.cpu) : preset(cp.apiServer.resourcesPreset).cpu"
|
||||
- name: apiServerMemory
|
||||
expression: "has(cp.apiServer.resources.memory) ? quantity(cp.apiServer.resources.memory) : preset(cp.apiServer.resourcesPreset).memory"
|
||||
- name: controllerManagerCpu
|
||||
expression: "has(cp.controllerManager.resources.cpu) ? quantity(cp.controllerManager.resources.cpu) : preset(cp.controllerManager.resourcesPreset).cpu"
|
||||
- name: controllerManagerMemory
|
||||
expression: "has(cp.controllerManager.resources.memory) ? quantity(cp.controllerManager.resources.memory) : preset(cp.controllerManager.resourcesPreset).memory"
|
||||
- name: schedulerCpu
|
||||
expression: "has(cp.scheduler.resources.cpu) ? quantity(cp.scheduler.resources.cpu) : preset(cp.scheduler.resourcesPreset).cpu"
|
||||
- name: schedulerMemory
|
||||
expression: "has(cp.scheduler.resources.memory) ? quantity(cp.scheduler.resources.memory) : preset(cp.scheduler.resourcesPreset).memory"
|
||||
- name: konnectivityCpu
|
||||
expression: "has(cp.konnectivity.server.resources.cpu) ? quantity(cp.konnectivity.server.resources.cpu) : preset(cp.konnectivity.server.resourcesPreset).cpu"
|
||||
- name: konnectivityMemory
|
||||
expression: "has(cp.konnectivity.server.resources.memory) ? quantity(cp.konnectivity.server.resources.memory) : preset(cp.konnectivity.server.resourcesPreset).memory"
|
||||
resources:
|
||||
cpu: apiServerCpu.add(controllerManagerCpu).add(schedulerCpu).add(konnectivityCpu).mul(cp.replicas)
|
||||
memory: apiServerMemory.add(controllerManagerMemory).add(schedulerMemory).add(konnectivityMemory).mul(cp.replicas)
|
||||
# Proxmox workers cannot route to a ClusterIP, so the apiserver Service
|
||||
# is published instead. On KubeVirt the tenant cluster's cloud
|
||||
# controller realizes the ingress controller's LoadBalancer Service in
|
||||
# the tenant namespace.
|
||||
services.loadbalancers: "values.substrate == 'proxmox' ? 1 : values.addons.ingressNginx.enabled && values.addons.ingressNginx.exposeMethod == 'LoadBalancer' ? 1 : 0"
|
||||
+3
@@ -35,3 +35,6 @@ spec:
|
||||
secrets:
|
||||
exclude: []
|
||||
include: []
|
||||
consumption:
|
||||
resources:
|
||||
storage: quantity(values.storage)
|
||||
@@ -39,3 +39,35 @@ spec:
|
||||
include:
|
||||
- matchLabels:
|
||||
apps.cozystack.io/user-service: "true"
|
||||
consumption:
|
||||
let:
|
||||
# cpu and sockets become KubeVirt's uint32 cores and sockets. The chart
|
||||
# decodes them as YAML, so 2.0, +2 and 1e1 are whole numbers to it, and
|
||||
# it refuses a leading zero, which YAML would read as octal.
|
||||
- name: cpuCount
|
||||
expression: "!has(values.resources.cpu) ? 0.0 : type(values.resources.cpu) == int ? double(values.resources.cpu) : values.resources.cpu.matches('^[+]?0[0-9]') || !values.resources.cpu.matches('^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$') ? -1.0 : double(values.resources.cpu)"
|
||||
- name: socketCount
|
||||
expression: "!has(values.resources.sockets) ? 0.0 : type(values.resources.sockets) == int ? double(values.resources.sockets) : values.resources.sockets.matches('^[+]?0[0-9]') || !values.resources.sockets.matches('^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$') ? -1.0 : double(values.resources.sockets)"
|
||||
# A count that is not whole, or a memory below the 1M KubeVirt admits,
|
||||
# fails the render whenever it is present, with or without an instance
|
||||
# type.
|
||||
- name: resourcesValid
|
||||
expression: "(!has(values.resources.memory) || quantity(values.resources.memory).compareTo(quantity('1M')) >= 0) && (!has(values.resources.cpu) || (cpuCount > 0.0 && cpuCount <= 4294967295.0 && double(int(cpuCount)) == cpuCount)) && (!has(values.resources.sockets) || (socketCount > 0.0 && socketCount <= 4294967295.0 && double(int(socketCount)) == socketCount))"
|
||||
# The chart emits a CPU topology only from cpu and sockets together,
|
||||
# cpu being cores per socket, and emits memory on its own. All of it
|
||||
# sizes the VM in place of the instance type; part of it fails the
|
||||
# render.
|
||||
- name: emitsCpu
|
||||
expression: has(values.resources.cpu) && has(values.resources.sockets)
|
||||
- name: sized
|
||||
expression: emitsCpu && has(values.resources.memory)
|
||||
- name: partial
|
||||
expression: emitsCpu != has(values.resources.memory)
|
||||
resources:
|
||||
cpu: "!resourcesValid ? fail('resources.cpu and resources.sockets must be positive whole numbers and resources.memory at least 1M') : partial ? fail('resources must set cpu, sockets and memory together, or none of them') : sized ? quantity(int(cpuCount)).mul(int(socketCount)) : instanceType(values.instanceType).cpu"
|
||||
dedicated-cpu: "sized ? 0 : instanceType(values.instanceType)['dedicated-cpu']"
|
||||
memory: "sized ? quantity(values.resources.memory) : instanceType(values.instanceType).memory"
|
||||
hugepages-2Mi: "sized ? 0 : instanceType(values.instanceType)['hugepages-2Mi']"
|
||||
hugepages-1Gi: "sized ? 0 : instanceType(values.instanceType)['hugepages-1Gi']"
|
||||
overcommitted-memory: "sized ? 0 : instanceType(values.instanceType)['overcommitted-memory']"
|
||||
services.loadbalancers: "values.external ? 1 : 0"
|
||||
@@ -99,6 +99,13 @@ func Compile(decl *Declaration, schema *structuralschema.Structural) (*Evaluator
|
||||
cel.Function(presetFunc,
|
||||
cel.Overload("preset_string", []*cel.Type{cel.StringType}, cel.MapType(cel.StringType, cel.DynType),
|
||||
cel.LateFunctionBinding())),
|
||||
// fail refuses a spec the kind's chart would refuse to render, with
|
||||
// the declaration's reason, rather than reserving for it.
|
||||
cel.Function("fail",
|
||||
cel.Overload("fail_string", []*cel.Type{cel.StringType}, cel.DynType,
|
||||
cel.UnaryBinding(func(msg ref.Val) ref.Val {
|
||||
return types.NewErr("%s", msg.(types.String))
|
||||
}))),
|
||||
cel.Function("quantity",
|
||||
cel.Overload("quantity_int", []*cel.Type{cel.IntType}, apiservercel.QuantityType,
|
||||
cel.UnaryBinding(func(v ref.Val) ref.Val {
|
||||
@@ -191,9 +198,19 @@ func (e *Evaluator) Evaluate(values map[string]any, env Environment) (ResourceLi
|
||||
if err := checkTypes(defaulted, e.schema, ""); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Helm deletes a key its values set to null, the chart's own default
|
||||
// included, so a nulled scalar is kept out after defaulting. A nulled
|
||||
// object or list keeps its default: charts read those through
|
||||
// `default dict` and `default list`, which renders the same as the empty
|
||||
// default the schema puts back.
|
||||
nulled := takeNulls(defaulted, nil)
|
||||
if err := defaulting.Apply(&defaulted, e.schema); err != nil {
|
||||
return nil, fmt.Errorf("default values: %w", err)
|
||||
}
|
||||
for _, path := range nulled {
|
||||
deleteScalarAt(defaulted, path)
|
||||
}
|
||||
dropNulls(defaulted)
|
||||
|
||||
// The environment differs per call, so instanceType and preset are
|
||||
// declared with a late binding and bound here, per program; cel.Functions
|
||||
@@ -276,7 +293,7 @@ func lookup(resolve func(string) (ResourceList, error), zeroKeys []string) funct
|
||||
}
|
||||
|
||||
func mulQuantity(q, n ref.Val) ref.Val {
|
||||
qq, ok := q.(apiservercel.Quantity)
|
||||
qq, ok := asQuantity(q)
|
||||
if !ok {
|
||||
return types.MaybeNoSuchOverloadErr(q)
|
||||
}
|
||||
@@ -285,16 +302,36 @@ func mulQuantity(q, n ref.Val) ref.Val {
|
||||
return types.MaybeNoSuchOverloadErr(n)
|
||||
}
|
||||
out := qq.DeepCopy()
|
||||
if !out.Mul(int64(nn)) {
|
||||
return types.NewErr("quantity %s * %d overflows", qq.String(), int64(nn))
|
||||
}
|
||||
// Mul reports whether the product still fits an int64 coefficient, not
|
||||
// whether it is exact: past that it carries on in arbitrary precision,
|
||||
// which a fractional binary quantity such as 20.5Gi reaches at any size
|
||||
// worth reserving.
|
||||
out.Mul(int64(nn))
|
||||
return apiservercel.Quantity{Quantity: &out}
|
||||
}
|
||||
|
||||
func toQuantity(v ref.Val) (resource.Quantity, error) {
|
||||
// asQuantity reads a CEL quantity whichever form it takes: the Kubernetes
|
||||
// library returns a pointer from add and sub, and a value from quantity().
|
||||
// It matches the types rather than calling Value(), which would first
|
||||
// materialize any other result, a list included, outside the cost limit.
|
||||
func asQuantity(v ref.Val) (*resource.Quantity, bool) {
|
||||
switch t := v.(type) {
|
||||
case apiservercel.Quantity:
|
||||
return t.DeepCopy(), nil
|
||||
return t.Quantity, t.Quantity != nil
|
||||
case *apiservercel.Quantity:
|
||||
if t == nil || t.Quantity == nil {
|
||||
return nil, false
|
||||
}
|
||||
return t.Quantity, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func toQuantity(v ref.Val) (resource.Quantity, error) {
|
||||
if q, ok := asQuantity(v); ok {
|
||||
return q.DeepCopy(), nil
|
||||
}
|
||||
switch t := v.(type) {
|
||||
case types.Int:
|
||||
return *resource.NewQuantity(int64(t), resource.DecimalSI), nil
|
||||
case types.Uint:
|
||||
@@ -451,3 +488,57 @@ func normalizeNumbers(v any) any {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// takeNulls removes, in place, every null-valued key of the objects nested in
|
||||
// m through objects, and returns their paths.
|
||||
func takeNulls(m map[string]any, prefix []string) [][]string {
|
||||
var paths [][]string
|
||||
for k, v := range m {
|
||||
path := append(append([]string(nil), prefix...), k)
|
||||
switch t := v.(type) {
|
||||
case nil:
|
||||
delete(m, k)
|
||||
paths = append(paths, path)
|
||||
case map[string]any:
|
||||
paths = append(paths, takeNulls(t, path)...)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// deleteScalarAt removes the key at path when it holds neither an object nor
|
||||
// a list, if every object on the way exists.
|
||||
func deleteScalarAt(m map[string]any, path []string) {
|
||||
for _, k := range path[:len(path)-1] {
|
||||
next, ok := m[k].(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
m = next
|
||||
}
|
||||
last := path[len(path)-1]
|
||||
switch m[last].(type) {
|
||||
case map[string]any, []any:
|
||||
return
|
||||
}
|
||||
delete(m, last)
|
||||
}
|
||||
|
||||
// dropNulls removes, in place, every null-valued key of m and of the objects
|
||||
// nested in it, lists included.
|
||||
func dropNulls(v any) {
|
||||
switch t := v.(type) {
|
||||
case map[string]any:
|
||||
for k, vv := range t {
|
||||
if vv == nil {
|
||||
delete(t, k)
|
||||
continue
|
||||
}
|
||||
dropNulls(vv)
|
||||
}
|
||||
case []any:
|
||||
for _, vv := range t {
|
||||
dropNulls(vv)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ package reservation
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
@@ -437,6 +438,133 @@ func TestCompile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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"},
|
||||
}
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
/*
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ import (
|
||||
"sort"
|
||||
|
||||
"k8s.io/apimachinery/pkg/api/resource"
|
||||
|
||||
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
|
||||
)
|
||||
|
||||
// Quota keys for KubeVirt instance-type classes. A shared vCPU and a pinned
|
||||
@@ -45,31 +47,18 @@ const (
|
||||
KeyHugepagesPrefix = "hugepages-"
|
||||
)
|
||||
|
||||
// Declaration is how a kind's reservation is computed from its values.
|
||||
// Declaration is how a kind's reservation is computed from its values. It is
|
||||
// the type an ApplicationDefinition carries, so a definition is compiled
|
||||
// as read, with no conversion in between.
|
||||
//
|
||||
// Exactly one of Exempt or Resources is meaningful: a kind that consumes
|
||||
// nothing says so with Exempt rather than with an empty Resources map, so
|
||||
// that a zero reservation is always a reviewed statement and never an
|
||||
// omission.
|
||||
type Declaration struct {
|
||||
// Exempt declares that the kind consumes nothing from a tenant's budget.
|
||||
Exempt bool `json:"exempt,omitempty"`
|
||||
|
||||
// Let binds intermediate CEL expressions, evaluated in order, each one
|
||||
// visible to the later bindings and to every Resources expression.
|
||||
Let []Binding `json:"let,omitempty"`
|
||||
|
||||
// Resources maps a quota key to the CEL expression computing the
|
||||
// amount of it the application reserves. An expression may return an
|
||||
// int, a double, a quantity string or a quantity.
|
||||
Resources map[string]string `json:"resources,omitempty"`
|
||||
}
|
||||
type Declaration = cozyv1alpha1.ApplicationDefinitionConsumption
|
||||
|
||||
// Binding names one intermediate CEL expression of a Declaration.
|
||||
type Binding struct {
|
||||
Name string `json:"name"`
|
||||
Expression string `json:"expression"`
|
||||
}
|
||||
type Binding = cozyv1alpha1.ApplicationDefinitionConsumptionBinding
|
||||
|
||||
// ResourceList is a reservation, keyed by quota key.
|
||||
type ResourceList map[string]resource.Quantity
|
||||
|
||||
Reference in new issue
Block a user