mirror of
https://github.com/cozystack/cozystack.git
synced 2026-12-06 23:23:23 +09:00
hack/values-injection renders every chart under packages/apps and packages/extra with generated values for each string field and map key its schema allows, including the charts its HelmReleases install, and fails when a value changes the structure of the output rather than only its content. Fields multiline by design are listed in hack/testdata/values-injection/allowlist.txt. It runs as values-injection-check, a prerequisite of unit-tests, and the Helm Charts conventions in docs/agents/overview.md gain the rule it enforces. Assisted-by: LLM Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
316 lines
8.1 KiB
Go
316 lines
8.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
fixturePath = "hack/testdata/render-fixtures/configured.yaml"
|
|
namespace = "tenant-test"
|
|
)
|
|
|
|
type chartConfig struct {
|
|
release string
|
|
namespace string
|
|
args []string
|
|
values map[string]any
|
|
}
|
|
|
|
// chartConfigs is the render contract per chart, mirroring
|
|
// hack/check-render-matrix.sh. The two lookup-gated charts are sized by
|
|
// resources instead of a cluster instancetype.
|
|
var chartConfigs = map[string]chartConfig{
|
|
"postgres": {args: []string{"--api-versions", "keda.sh/v1alpha1"}},
|
|
"kubernetes": {args: []string{"--api-versions", "sdn.cozystack.io/v1alpha1/VPC"}},
|
|
"tenant": {release: "tenant-sub", args: []string{"--api-versions", "v1.edp.epam.com/v1"}},
|
|
"kubernetes-nodes": {
|
|
release: "kubernetes-nodes-render-check",
|
|
args: []string{"--set-string", "cluster=render", "--api-versions", "sdn.cozystack.io/v1alpha1/VPC"},
|
|
values: map[string]any{"instanceType": "", "resources": map[string]any{"cpu": 2, "memory": "4Gi"}},
|
|
},
|
|
"vm-instance": {
|
|
values: map[string]any{"instanceType": "", "instanceProfile": "",
|
|
"resources": map[string]any{"cpu": 1, "sockets": 1, "memory": "1Gi"}},
|
|
},
|
|
"external-dns": {values: map[string]any{"provider": "inmemory"}},
|
|
"bootbox": {namespace: "tenant-root"},
|
|
}
|
|
|
|
type renderResult struct {
|
|
rc int
|
|
out string
|
|
err string
|
|
}
|
|
|
|
type renderer struct {
|
|
dir string
|
|
name string
|
|
release string
|
|
namespace string
|
|
args []string
|
|
base map[string]any
|
|
fixture string
|
|
tmp string
|
|
}
|
|
|
|
func newRenderer(root, chart, tmp, release, ns string) *renderer {
|
|
dir := chart
|
|
if !filepath.IsAbs(dir) {
|
|
dir = filepath.Join(root, chart)
|
|
}
|
|
name := filepath.Base(dir)
|
|
conf := chartConfigs[name]
|
|
if release == "" {
|
|
release = conf.release
|
|
}
|
|
if release == "" {
|
|
// A tenant module refuses any release name but its own.
|
|
release = name + "-render-check"
|
|
if filepath.Base(filepath.Dir(dir)) == "extra" {
|
|
release = name
|
|
}
|
|
}
|
|
if ns == "" {
|
|
ns = conf.namespace
|
|
}
|
|
if ns == "" {
|
|
ns = namespace
|
|
}
|
|
fixture := filepath.Join(root, fixturePath)
|
|
if _, err := os.Stat(fixture); err != nil {
|
|
fixture = fixturePath
|
|
}
|
|
base := conf.values
|
|
if base == nil {
|
|
base = map[string]any{}
|
|
}
|
|
return &renderer{dir: dir, name: name, release: release, namespace: ns, args: conf.args, base: base,
|
|
fixture: fixture, tmp: tmp}
|
|
}
|
|
|
|
// render runs helm template with values over the chart's own and the fixture.
|
|
// An error means helm could not be run at all, not that the chart failed.
|
|
func (r *renderer) render(values map[string]any, skipSchema bool) (renderResult, error) {
|
|
blob, err := encodeValues(merge(r.base, values))
|
|
if err != nil {
|
|
return renderResult{}, err
|
|
}
|
|
vf, err := os.CreateTemp(r.tmp, r.name+"-*.json")
|
|
if err != nil {
|
|
return renderResult{}, err
|
|
}
|
|
defer os.Remove(vf.Name())
|
|
if _, err := vf.Write(blob); err != nil {
|
|
vf.Close()
|
|
return renderResult{}, err
|
|
}
|
|
if err := vf.Close(); err != nil {
|
|
return renderResult{}, err
|
|
}
|
|
args := []string{"template", r.release, r.dir, "--namespace", r.namespace}
|
|
args = append(args, r.args...)
|
|
args = append(args, "--values", r.fixture, "--values", vf.Name())
|
|
if skipSchema {
|
|
args = append(args, "--skip-schema-validation")
|
|
}
|
|
cmd := exec.Command("helm", args...)
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
|
rc := 0
|
|
if err := cmd.Run(); err != nil {
|
|
var exit *exec.ExitError
|
|
if !errors.As(err, &exit) {
|
|
return renderResult{}, fmt.Errorf("helm: %w", err)
|
|
}
|
|
rc = exit.ExitCode()
|
|
if rc == 0 {
|
|
rc = -1
|
|
}
|
|
}
|
|
var kept []string
|
|
for _, l := range splitLines(stderr.String()) {
|
|
if !strings.HasPrefix(l, "level=INFO") {
|
|
kept = append(kept, l)
|
|
}
|
|
}
|
|
return renderResult{rc: rc, out: stdout.String(), err: strings.Join(kept, "\n")}, nil
|
|
}
|
|
|
|
// renderFunc renders a chart with values over its own; an error means the
|
|
// renderer could not run at all, not that the chart failed.
|
|
type renderFunc func(values map[string]any, skipSchema bool) (renderResult, error)
|
|
|
|
// renderCache remembers renders, for a field that tries the same values under
|
|
// several attempts, or a chart a HelmRelease installs that is rendered from
|
|
// the same reference values for every payload. Charts that generate secrets
|
|
// render differently every time, so a reference is rendered once.
|
|
type renderCache struct {
|
|
render renderFunc
|
|
seen map[string]renderResult
|
|
}
|
|
|
|
func newRenderCache(r renderFunc) *renderCache {
|
|
return &renderCache{r, map[string]renderResult{}}
|
|
}
|
|
|
|
func (c *renderCache) get(values map[string]any, skipSchema bool) (renderResult, error) {
|
|
blob, err := encodeValues(values)
|
|
if err != nil {
|
|
return renderResult{}, err
|
|
}
|
|
key := fmt.Sprintf("%t:%s", skipSchema, blob)
|
|
if res, ok := c.seen[key]; ok {
|
|
return res, nil
|
|
}
|
|
res, err := c.render(values, skipSchema)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
c.seen[key] = res
|
|
return res, nil
|
|
}
|
|
|
|
func firstError(err string) string {
|
|
var lines []string
|
|
for _, l := range splitLines(err) {
|
|
if strip(l) != "" {
|
|
lines = append(lines, l)
|
|
}
|
|
}
|
|
for _, l := range lines {
|
|
if strings.HasPrefix(l, "Error:") {
|
|
return truncate(l, 240)
|
|
}
|
|
}
|
|
if len(lines) > 0 {
|
|
return truncate(lines[0], 240)
|
|
}
|
|
return "render failed"
|
|
}
|
|
|
|
var yamlErrors = []string{"YAML parse error", "error converting YAML to JSON", "unable to parse YAML",
|
|
"yaml: line", "mapping values are not allowed", "did not find expected"}
|
|
|
|
func classifyError(err string) string {
|
|
if strings.Contains(err, "don't meet the specifications of the schema") {
|
|
return "schema"
|
|
}
|
|
for _, s := range yamlErrors {
|
|
if strings.Contains(err, s) {
|
|
return "yaml"
|
|
}
|
|
}
|
|
if strings.Contains(err, "execution error at") {
|
|
return "template"
|
|
}
|
|
return "other"
|
|
}
|
|
|
|
var yamlParseErrorOn = regexp.MustCompile(`YAML parse error on ([^:]+)`)
|
|
|
|
// artifacts maps an ExternalArtifact name to its chart dir, from the
|
|
// platform's PackageSources.
|
|
func artifacts(root string) (map[string]string, error) {
|
|
out := map[string]string{}
|
|
files, err := filepath.Glob(filepath.Join(root, "packages/core/platform/sources/*.yaml"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, f := range files {
|
|
text, err := os.ReadFile(f)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
docs, err := decodeStream(string(text))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s: %w", f, err)
|
|
}
|
|
for _, d := range docs {
|
|
obj, ok := d.obj.(map[string]any)
|
|
if !ok || obj["kind"] != "PackageSource" {
|
|
continue
|
|
}
|
|
base := strings.ReplaceAll(pyStr(asMap(obj["metadata"])["name"]), ".", "-")
|
|
variants, _ := asMap(obj["spec"])["variants"].([]any)
|
|
for _, v := range variants {
|
|
vm := asMap(v)
|
|
comps, _ := vm["components"].([]any)
|
|
for _, comp := range comps {
|
|
cm := asMap(comp)
|
|
out[fmt.Sprintf("%s-%s-%s", base, pyStr(vm["name"]), pyStr(cm["name"]))] = "packages/" + pyStr(cm["path"])
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// release is a HelmRelease of a render that installs an in-tree chart.
|
|
type release struct {
|
|
index int
|
|
name string
|
|
chart string
|
|
release string
|
|
namespace string
|
|
values map[string]any
|
|
remote bool // applied through a kubeConfig into the tenant's own cluster
|
|
}
|
|
|
|
func or(vals ...any) any {
|
|
for _, v := range vals {
|
|
if truthy(v) {
|
|
return v
|
|
}
|
|
}
|
|
return vals[len(vals)-1]
|
|
}
|
|
|
|
func releases(docs []doc, arts map[string]string) []release {
|
|
var out []release
|
|
for i, d := range docs {
|
|
obj, ok := d.obj.(map[string]any)
|
|
if !ok || obj["kind"] != "HelmRelease" {
|
|
continue
|
|
}
|
|
spec := asMap(obj["spec"])
|
|
ref := asMap(spec["chartRef"])
|
|
chart := ""
|
|
if ref["kind"] == "ExternalArtifact" {
|
|
if name, ok := ref["name"].(string); ok {
|
|
chart = arts[name]
|
|
}
|
|
}
|
|
values, ok := spec["values"].(map[string]any)
|
|
if chart == "" || !ok {
|
|
continue
|
|
}
|
|
meta := asMap(obj["metadata"])
|
|
name, hasName := meta["name"]
|
|
if !hasName {
|
|
name = "?"
|
|
}
|
|
relName, hasName := meta["name"]
|
|
if !hasName {
|
|
relName = "x"
|
|
}
|
|
_, remote := spec["kubeConfig"]
|
|
out = append(out, release{
|
|
index: i,
|
|
name: pyStr(name),
|
|
chart: chart,
|
|
release: pyStr(or(spec["releaseName"], relName)),
|
|
namespace: pyStr(or(spec["targetNamespace"], meta["namespace"], namespace)),
|
|
values: values,
|
|
remote: remote,
|
|
})
|
|
}
|
|
return out
|
|
}
|