solutions: Solutions Guide engine (catalog, rules, wizard state, native config, knowledge index, CLI)

New nested module yetano.dev/yetano/core/solutions: loads the catalog
in assets/solutions on top of the Big Picture, evaluates questions and
conditions, resolves packages/modules/capabilities, generates native
configuration from typed fragments with per-value origins, and builds
architecture graph, plan, lock file and handbook. Knowledge index with
yetano: references, search and lint (incl. manual sections). CLI with
yet's conventions (solution, task, knowledge, open), standalone as
yetano-solutions. No execution, no network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
terminarandClaude Opus 5.5 committed 2026-12-01 08:42:58 +01:00
1 parent 586e76889c
commit 2481a0dd27
48 files changed
+10304

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
package engine
import (
"os"
"path/filepath"
"testing"
"yetano.dev/yetano/core/solutions/catalog"
)
// The meta-repo's catalog, when this module is checked out inside it.
func assetsCatalog(t *testing.T) *catalog.Catalog {
t.Helper()
dir, _ := filepath.Abs("../../../assets/solutions")
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
t.Skip("assets/solutions not present (module outside the meta-repo)")
}
c, err := catalog.Load(dir)
if err != nil {
for _, i := range c.Issues {
t.Log(i)
}
t.Fatal(err)
}
return c
}
func TestAssetsCatalog(t *testing.T) {
c := assetsCatalog(t)
for _, i := range c.Validate() {
if i.Severity == "error" {
t.Error(i)
} else {
t.Log(i)
}
}
e := New(c)
for _, key := range catalog.SortedIDs(c.Examples) {
x := c.Examples[key]
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
in.Spec.Parameters = x.Spec.Parameters
st, err := e.Evaluate(in, nil)
if err != nil {
t.Fatalf("%s: %v", key, err)
}
if !st.Complete {
t.Errorf("%s: not complete: %s", key, incompleteText(st))
}
for _, m := range st.Messages {
t.Logf("%s: %s %s", key, m.Severity, m.Text)
}
}
}
+398
View File
@@ -0,0 +1,398 @@
package engine
import (
"bytes"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/solutions/catalog"
)
// placeholder: ${name}, ${name[0]}, ${name.count}, ${name.join}; $${ is a literal "${".
var placeholderRE = regexp.MustCompile(`\$\$\{|\$\{((?:instance|solution)\.[a-z]+|[A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)\]|\.(count|join))?\}`)
type genFile struct {
path string
pkg string
root *yaml.Node // mapping
origins map[string]Origin
}
func (ev *evaluation) vars() map[string]any {
v := map[string]any{}
for k, a := range ev.answers {
v[k] = a
}
v["instance.name"] = ev.in.Metadata.Name
v["solution.id"] = ev.s.Meta.ID
v["solution.version"] = ev.s.Meta.Version
return v
}
func (ev *evaluation) config() {
files := map[string]*genFile{}
var order []string
get := func(path string) *genFile {
f, ok := files[path]
if !ok {
pkg, _, _ := strings.Cut(path, "/")
f = &genFile{path: path, pkg: pkg, root: &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}, origins: map[string]Origin{}}
files[path] = f
order = append(order, path)
}
return f
}
vars := ev.vars()
applyFrag := func(fr catalog.Fragment, origin Origin) {
pkg, _, _ := strings.Cut(fr.File, "/")
if !ev.pkgSelected(pkg) {
return
}
if fr.Module != "" {
mp, mm := pkg, fr.Module
if a, b, ok := strings.Cut(fr.Module, "/"); ok {
mp, mm = a, b
}
if !ev.moduleEnabled(mp, mm) {
return
}
}
node := deepCopy(&fr.Set)
params := map[string]bool{}
if err := interpolate(node, vars, params); err != nil {
ev.msg("error", "config", fmt.Sprintf("%s: %v", origin.Source, err), origin.Source)
return
}
for p := range params {
origin.Params = append(origin.Params, p)
}
sort.Strings(origin.Params)
if node.Kind != yaml.MappingNode {
ev.msg("error", "config", fmt.Sprintf("%s: fragment for %s is not a map", origin.Source, fr.File), origin.Source)
return
}
f := get(fr.File)
mergeMap(f.root, node, "", origin, f.origins)
}
// layer 2: profiles (base first), in package order
ids := append([]string{}, ev.pkgSeen...)
sort.Strings(ids)
for _, id := range ids {
p := ev.pkgs[id]
if !p.Selected || p.Profile == "" {
continue
}
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
if err != nil {
continue
}
for _, prof := range chain {
for _, fr := range prof.Spec.Config {
applyFrag(fr, Origin{Layer: "profile", Source: "profile:" + prof.Key()})
}
}
}
// layer 3: the solution's fragments
for i, fr := range ev.s.Spec.Config {
if len(fr.When) > 0 && !fr.When.Holds(ev.env) {
continue
}
id := fr.ID
if id == "" {
id = strconv.Itoa(i)
}
applyFrag(fr, Origin{Layer: "solution", Source: "solution:" + ev.s.Meta.ID + "#" + id})
}
// layer 6: explicit overrides
for _, o := range ev.in.Spec.Overrides {
if !catalog.SafeRelPath(o.File) || o.Path == "" {
ev.msg("error", "override", fmt.Sprintf("override %s %s: bad file or path", o.File, o.Path), "override")
continue
}
f, ok := files[o.File]
if !ok {
ev.msg("warning", "override", fmt.Sprintf("override for %s: the solution generates no such file", o.File), "override")
continue
}
var val yaml.Node
if err := val.Encode(o.Value); err != nil {
ev.msg("error", "override", err.Error(), "override")
continue
}
setPath(f.root, strings.Split(o.Path, "."), &val)
f.origins[o.Path] = Origin{Layer: "override", Source: "override"}
ev.msg("info", "override", fmt.Sprintf("%s: %s is set directly, not through a question", o.File, o.Path), "override")
}
sort.Strings(order)
for _, path := range order {
f := files[path]
body, err := render(f.root, ev.s, path)
if err != nil {
ev.msg("error", "config", err.Error(), path)
continue
}
ev.st.Files = append(ev.st.Files, FilePreview{Path: "config/" + path, Package: f.pkg, Content: body, Origins: f.origins})
}
}
func render(root *yaml.Node, s *catalog.Solution, path string) (string, error) {
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
doc.HeadComment = fmt.Sprintf("Generated by the Yetano Solutions Guide from %s %s.\n"+
"This is a native configuration file: edit it like any other. See\n"+
"solution.lock.yaml before regenerating over hand edits.", s.Meta.ID, s.Meta.Version)
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
return "", fmt.Errorf("%s: %v", path, err)
}
enc.Close()
return buf.String(), nil
}
func deepCopy(n *yaml.Node) *yaml.Node {
if n == nil {
return nil
}
c := *n
if c.Kind == yaml.MappingNode || c.Kind == yaml.SequenceNode {
c.Style = 0 // generated files use block style, whatever the catalog wrote
}
c.Line, c.Column = 0, 0
c.Content = make([]*yaml.Node, len(n.Content))
for i, ch := range n.Content {
c.Content[i] = deepCopy(ch)
}
if n.Kind == yaml.DocumentNode && len(c.Content) == 1 {
return c.Content[0]
}
return &c
}
// interpolate replaces placeholders in scalars (ADR-0005).
func interpolate(n *yaml.Node, vars map[string]any, used map[string]bool) error {
switch n.Kind {
case yaml.MappingNode:
for i := 1; i < len(n.Content); i += 2 {
if err := interpolate(n.Content[i], vars, used); err != nil {
return err
}
}
case yaml.SequenceNode:
for _, ch := range n.Content {
if err := interpolate(ch, vars, used); err != nil {
return err
}
}
case yaml.ScalarNode:
if !strings.Contains(n.Value, "${") {
return nil
}
whole := placeholderRE.FindStringSubmatchIndex(n.Value)
if whole != nil && whole[0] == 0 && whole[1] == len(n.Value) && n.Value != "$${" {
v, err := lookup(n.Value, vars, used)
if err != nil {
return err
}
var repl yaml.Node
if err := repl.Encode(v); err != nil {
return err
}
repl.Style = 0
*n = repl
return nil
}
var firstErr error
out := placeholderRE.ReplaceAllStringFunc(n.Value, func(m string) string {
if m == "$${" {
return "${"
}
v, err := lookup(m, vars, used)
if err != nil && firstErr == nil {
firstErr = err
}
return text(v)
})
if firstErr != nil {
return firstErr
}
n.Value = out
n.Tag = "!!str"
n.Style = 0
}
return nil
}
func lookup(ph string, vars map[string]any, used map[string]bool) (any, error) {
m := placeholderRE.FindStringSubmatch(ph)
name := m[1]
v, ok := vars[name]
if !ok {
return nil, fmt.Errorf("placeholder ${%s}: no answer for %q", name, name)
}
used[name] = true
switch {
case m[2] != "":
i, _ := strconv.Atoi(m[2])
l := listOf(v)
if i >= len(l) {
return nil, fmt.Errorf("placeholder %s: %q has only %d item(s)", ph, name, len(l))
}
return l[i], nil
case m[3] == "count":
return len(listOf(v)), nil
case m[3] == "join":
var parts []string
for _, x := range listOf(v) {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ","), nil
}
return v, nil
}
func text(v any) string {
if l, ok := v.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ",")
}
return catalog.Scalar(v)
}
// mergeMap merges src into dst like core/config: maps key by key, lists
// and scalars replace, null removes. Origins are recorded per path.
func mergeMap(dst, src *yaml.Node, prefix string, origin Origin, origins map[string]Origin) {
for i := 0; i+1 < len(src.Content); i += 2 {
k, v := src.Content[i], src.Content[i+1]
path := k.Value
if prefix != "" {
path = prefix + "." + k.Value
}
idx := -1
for j := 0; j+1 < len(dst.Content); j += 2 {
if dst.Content[j].Value == k.Value {
idx = j
break
}
}
if v.Kind == yaml.ScalarNode && v.Tag == "!!null" {
if idx >= 0 {
dst.Content = append(dst.Content[:idx], dst.Content[idx+2:]...)
}
for p := range origins {
if p == path || strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
continue
}
if idx >= 0 && v.Kind == yaml.MappingNode && dst.Content[idx+1].Kind == yaml.MappingNode {
mergeMap(dst.Content[idx+1], v, path, origin, origins)
continue
}
for p := range origins {
if strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
if idx >= 0 {
dst.Content[idx+1] = v
} else {
dst.Content = append(dst.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k.Value}, v)
}
recordLeaves(v, path, origin, origins)
}
}
func recordLeaves(v *yaml.Node, path string, origin Origin, origins map[string]Origin) {
if v.Kind == yaml.MappingNode {
for i := 0; i+1 < len(v.Content); i += 2 {
recordLeaves(v.Content[i+1], path+"."+v.Content[i].Value, origin, origins)
}
return
}
origins[path] = origin
}
func setPath(root *yaml.Node, keys []string, val *yaml.Node) {
cur := root
for i, k := range keys {
idx := -1
for j := 0; j+1 < len(cur.Content); j += 2 {
if cur.Content[j].Value == k {
idx = j
}
}
if i == len(keys)-1 {
if idx >= 0 {
cur.Content[idx+1] = val
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, val)
}
return
}
if idx < 0 || cur.Content[idx+1].Kind != yaml.MappingNode {
m := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
if idx >= 0 {
cur.Content[idx+1] = m
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, m)
}
cur = m
} else {
cur = cur.Content[idx+1]
}
}
}
// Explanation answers "where does this value come from?" (PROF-05).
type Explanation struct {
File string `json:"file"`
Path string `json:"path"`
Found bool `json:"found"`
Origin Origin `json:"origin"`
Answers map[string]any `json:"answers,omitempty"` // the answers it used, with their origin
Origins map[string]string `json:"answerOrigins,omitempty"`
}
// Explain finds the origin of a value in a generated file. file may omit
// the "config/" prefix; path is dot separated.
func Explain(st *State, file, path string) Explanation {
file = strings.TrimPrefix(file, "config/")
ex := Explanation{File: "config/" + file, Path: path}
for _, f := range st.Files {
if f.Path != "config/"+file {
continue
}
p := path
for p != "" {
if o, ok := f.Origins[p]; ok {
ex.Found, ex.Origin = true, o
break
}
i := strings.LastIndex(p, ".")
if i < 0 {
break
}
p = p[:i]
}
}
if ex.Found && len(ex.Origin.Params) > 0 {
ex.Answers, ex.Origins = map[string]any{}, map[string]string{}
for _, p := range ex.Origin.Params {
if a, ok := st.Answers[p]; ok {
ex.Answers[p] = a.Value
ex.Origins[p] = a.Origin
}
}
}
return ex
}
+408
View File
@@ -0,0 +1,408 @@
package engine
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"yetano.dev/yetano/core/solutions/catalog"
)
func testCat(t *testing.T) *catalog.Catalog {
t.Helper()
c, err := catalog.Load("testdata/cat")
if err != nil {
for _, i := range c.Issues {
t.Log(i)
}
t.Fatal(err)
}
for _, i := range c.Validate() {
if i.Severity == "error" {
t.Fatal(i)
}
}
return c
}
func eval(t *testing.T, e *Engine, mode catalog.Level, params map[string]any, p *Preset) *State {
t.Helper()
in := NewInstance("t1", e.Cat.Solutions["app-run"], mode)
for k, v := range params {
in.Spec.Parameters[k] = v
}
st, err := e.Evaluate(in, p)
if err != nil {
t.Fatal(err)
}
return st
}
func pkg(st *State, id string) *PackageState {
for i := range st.Packages {
if st.Packages[i].ID == id {
return &st.Packages[i]
}
}
return nil
}
func capOf(st *State, id string) *CapState {
for i := range st.Capabilities {
if st.Capabilities[i].ID == id {
return &st.Capabilities[i]
}
}
return nil
}
func file(st *State, path string) string {
for _, f := range st.Files {
if f.Path == path {
return f.Content
}
}
return ""
}
func question(st *State, id string) QuestionState { return findQuestion(st, id) }
func findQuestion(st *State, id string) QuestionState {
for _, q := range st.Questions {
if q.ID == id {
return q
}
}
return QuestionState{}
}
func hasMsg(st *State, sub string) bool {
for _, m := range st.Messages {
if strings.Contains(m.Text, sub) {
return true
}
}
return false
}
func TestQuickDefaultPath(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelQuick, nil, nil)
if st.Complete || len(st.Progress.Missing) != 1 || st.Progress.Missing[0] != "hosts" {
t.Fatalf("want only hosts missing, got %v", st.Progress.Missing)
}
if st.Next != "hosts" {
t.Errorf("next = %q", st.Next)
}
// quick asks size and hosts only; guided questions take their defaults
var asked []string
for _, q := range st.Questions {
if q.Asked {
asked = append(asked, q.ID)
}
}
if strings.Join(asked, ",") != "size,hosts" {
t.Errorf("asked %v", asked)
}
st = eval(t, e, catalog.LevelQuick, map[string]any{"hosts": "a.example.org, b.example.org"}, nil)
if !st.Complete {
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
}
if p := pkg(st, "app"); p == nil || !p.Selected || p.Profile != "base" {
t.Fatalf("app: %+v", p)
}
if c := capOf(st, "auth.users"); c == nil || c.Provider != "app/users" {
t.Errorf("auth.users provider: %+v", c)
}
if c := capOf(st, "backup.files"); c == nil || c.Status != StRecommended {
t.Errorf("backup.files should be recommended: %+v", c)
}
if c := capOf(st, "feature.x"); c != nil && c.Status != StExcluded {
t.Errorf("feature.x should be excluded or absent: %+v", c)
}
cfg := file(st, "config/app/app.yaml")
for _, want := range []string{"hosts:\n - a.example.org\n - b.example.org", "owner: admin@a.example.org", "listen: :8080", "first: a.example.org", "n: 2", "max: 10"} {
if !strings.Contains(cfg, want) {
t.Errorf("config lacks %q:\n%s", want, cfg)
}
}
if file(st, "config/bak/bak.yaml") != "" || file(st, "config/idp/idp.yaml") != "" {
t.Error("files for packages that are not selected")
}
if len(st.Steps) != 3 { // 2 hosts + 1 program (server; extra is disabled)
t.Errorf("steps: %+v", st.Steps)
}
}
// Scenario B: local -> central identity and back (ACC-B, RULE-06).
func TestIdentitySwitch(t *testing.T) {
e := New(testCat(t))
base := map[string]any{"hosts": []any{"a.example.org"}}
st := eval(t, e, catalog.LevelGuided, base, nil)
if pkg(st, "idp") != nil {
t.Fatal("idp without central identity")
}
central := map[string]any{"hosts": []any{"a.example.org"}, "identity": "central"}
st = eval(t, e, catalog.LevelGuided, central, nil)
if !question(st, "realm").Visible || st.Complete {
t.Fatal("realm must appear and be required")
}
central["realm"] = "corp"
st = eval(t, e, catalog.LevelGuided, central, nil)
if !st.Complete {
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
}
if p := pkg(st, "idp"); p == nil || !p.Selected {
t.Fatal("idp must be selected")
}
if c := capOf(st, "auth.sso"); c == nil || c.Provider != "idp/sso" {
t.Fatalf("auth.sso must come from idp, not the unimplemented module: %+v", c)
}
if !strings.Contains(file(st, "config/app/app.yaml"), "realm: corp") || file(st, "config/idp/idp.yaml") == "" {
t.Error("central identity config missing")
}
edge := false
for _, ed := range st.Graph.Edges {
edge = edge || (ed.From == "pkg:app" && ed.To == "pkg:idp" && ed.Type == "authenticatesVia")
}
if !edge {
t.Error("confirmed Big Picture connection app -> idp missing from the graph")
}
// back to local: realm is stale, not in the config, idp gone
central["identity"] = "local"
st = eval(t, e, catalog.LevelGuided, central, nil)
if pkg(st, "idp") != nil || strings.Contains(file(st, "config/app/app.yaml"), "realm") {
t.Error("central leftovers after switching back")
}
if len(st.Stale) != 1 || st.Stale[0].Question != "realm" {
t.Errorf("stale: %+v", st.Stale)
}
}
func TestNotImplementedOptionIsVisibleButNotSelectable(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelGuided, map[string]any{"hosts": []any{"a.example.org"}, "identity": "ghost"}, nil)
q := question(st, "identity")
var ghost OptionState
for _, o := range q.Options {
if o.ID == "ghost" {
ghost = o
}
}
if ghost.Enabled || ghost.Disabled != "not built" {
t.Errorf("ghost option: %+v", ghost)
}
if len(st.Stale) != 1 || q.Value != "local" {
t.Errorf("the unselectable answer must be stale and the default used: %+v %v", st.Stale, q.Value)
}
}
func TestModeSwitchKeepsAnswers(t *testing.T) {
e := New(testCat(t))
params := map[string]any{"hosts": []any{"a.example.org"}, "port": 9090}
adv := eval(t, e, catalog.LevelAdvanced, params, nil)
quick := eval(t, e, catalog.LevelQuick, params, nil)
if file(adv, "config/app/app.yaml") != file(quick, "config/app/app.yaml") {
t.Error("the mode must not change the result")
}
if !strings.Contains(file(quick, "config/app/app.yaml"), ":9090") {
t.Error("an advanced answer is lost in quick mode")
}
if question(quick, "port").Asked {
t.Error("quick mode asks an advanced question")
}
}
func TestValidationAndSecrets(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"not a host"}, "token": "hunter2"}, nil)
if len(question(st, "hosts").Errors) == 0 {
t.Error("an invalid host name is accepted")
}
if len(question(st, "token").Errors) == 0 {
t.Error("a plain secret is accepted")
}
st = eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"a.example.org"}, "token": "secret://app/token"}, nil)
if !st.Complete || !strings.Contains(file(st, "config/app/app.yaml"), "token: secret://app/token") {
t.Errorf("secret reference not taken: %v", st.Messages)
}
for _, p := range e.Handbook(st, nil) {
if strings.Contains(string(p.Content), "secret://app/token") && strings.HasSuffix(p.Path, "index.md") {
t.Error("the handbook's decision table shows a secret reference")
}
}
}
// Scenario G: a preset answers everything but the instance-specific questions.
func TestPreset(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelGuided)
in.Spec.Parameters = map[string]any{"hosts": []any{"a.example.org"}, "size": "big", "backup": "mine", "token": "secret://x"}
p := PresetFrom("mine", in, e.Cat.Solutions["app-run"])
if _, ok := p.Spec.Parameters["hosts"]; ok {
t.Error("an instance-specific answer in the preset")
}
if _, ok := p.Spec.Parameters["token"]; ok {
t.Error("a secret in the preset")
}
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"new.example.org"}}, p)
if !st.Complete || pkg(st, "app").Profile != "big" || st.Answers["size"].Origin != "preset:mine" {
t.Fatalf("preset not applied: %+v %v", st.Answers["size"], st.Messages)
}
if question(st, "size").Asked {
t.Error("a question the preset answered is asked again")
}
if !question(st, "hosts").Asked {
t.Error("the instance-specific question must be asked")
}
if !hasMsg(st, "Big needs more memory") {
t.Error("rule message missing")
}
if !strings.Contains(file(st, "config/app/extra.yaml"), "on: true") || !strings.Contains(file(st, "config/app/app.yaml"), "max: 100") {
t.Error("profile inheritance (big extends base) not applied")
}
if c := capOf(st, "backup.files"); c == nil || c.Status != StExternal {
t.Errorf("backup by own tool must be external: %+v", c)
}
}
func TestExplainAndOverride(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
in.Spec.Overrides = []Override{{File: "app/app.yaml", Path: "limits.min", Value: 5}}
st, err := e.Evaluate(in, nil)
if err != nil {
t.Fatal(err)
}
ex := Explain(st, "app/app.yaml", "owner")
if !ex.Found || ex.Origin.Source != "solution:app-run#main" || ex.Origins["owner"] != "default" {
t.Errorf("explain owner: %+v", ex)
}
if ex := Explain(st, "config/app/app.yaml", "limits.max"); ex.Origin.Source != "profile:app/base" {
t.Errorf("explain limits.max: %+v", ex)
}
if ex := Explain(st, "app/app.yaml", "limits.min"); ex.Origin.Layer != "override" {
t.Errorf("explain override: %+v", ex)
}
if !strings.Contains(file(st, "config/app/app.yaml"), "min: 5") {
t.Error("override not applied")
}
}
func TestDeterministicAndJSON(t *testing.T) {
e := New(testCat(t))
p := map[string]any{"hosts": []any{"a.example.org", "b.example.org"}, "identity": "central", "realm": "r"}
a, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
for i := 0; i < 5; i++ {
b, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
if string(a) != string(b) {
t.Fatal("evaluation is not deterministic")
}
}
}
func TestGenerateWriteAndProtect(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
st, _ := e.Evaluate(in, nil)
out, err := e.Generate(st, in, nil, false)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if err := Write(dir, out, false); err != nil {
t.Fatal(err)
}
// regenerating unchanged is fine
if err := Write(dir, out, false); err != nil {
t.Fatal(err)
}
// a hand edit blocks regeneration (CONF-06)
cfg := filepath.Join(dir, "config", "app", "app.yaml")
if err := os.WriteFile(cfg, []byte("# mine\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := Write(dir, out, false); !errors.Is(err, ErrModified) {
t.Fatalf("hand edit overwritten: %v", err)
}
if err := Write(dir, out, true); err != nil {
t.Fatal(err)
}
// an incomplete state does not generate
in2 := NewInstance("t2", e.Cat.Solutions["app-run"], catalog.LevelQuick)
st2, _ := e.Evaluate(in2, nil)
if _, err := e.Generate(st2, in2, nil, false); !errors.Is(err, ErrIncomplete) {
t.Errorf("incomplete generated: %v", err)
}
}
func TestLockDrift(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
st, _ := e.Evaluate(in, nil)
out, _ := e.Generate(st, in, nil, false)
out2, _ := e.Generate(st, in, nil, false)
if d := LockDrift(out.Lock, out2.Lock); len(d) != 0 {
t.Errorf("drift without change: %v", d)
}
changed := *out.Lock
changed.Spec.Profiles = append([]Pinned{}, out.Lock.Spec.Profiles...)
changed.Spec.Profiles[0].Hash = "x"
if d := LockDrift(&changed, out2.Lock); len(d) != 1 || !strings.Contains(d[0], "profile app/base changed") {
t.Errorf("profile change not detected: %v", d)
}
}
func TestStepsChecksGraph(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"a.example.org"}, "size": "big"}, nil)
if st.Steps[0].Phase != "install" || len(st.Steps) != 3 {
t.Errorf("steps: %+v", st.Steps)
}
if st.Steps[0].Run != "yet install app-server" || st.Steps[1].Run != "yet install app-extra" {
t.Errorf("module steps: %+v", st.Steps)
}
for _, c := range st.Checks {
switch c.ID {
case "port":
if c.Status != CheckNotChecked || c.Params["port"] != "8080" {
t.Errorf("port check: %+v", c)
}
case "bigonly":
if c.Status != CheckNotChecked {
t.Errorf("bigonly: %+v", c)
}
}
}
found := false
for _, n := range st.Graph.Nodes {
found = found || n.Title == "Users of a.example.org"
}
if !found {
t.Error("node title not interpolated")
}
if !strings.Contains(GraphText(st.Graph), "app-extra") {
t.Error(GraphText(st.Graph))
}
}
func TestConditionOrderIsEnforced(t *testing.T) {
c := testCat(t)
s := c.Solutions["app-run"]
q, _ := s.Question("size")
q.VisibleWhen = catalog.Cond{"hosts": map[string]any{"set": true}}
defer func() { q.VisibleWhen = nil }()
found := false
for _, i := range c.Validate() {
found = found || i.Code == "condition-order"
}
if !found {
t.Error("a condition on a later question is not reported")
}
}
+998
View File
@@ -0,0 +1,998 @@
package engine
import (
"errors"
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// GeneratorVersion is stamped into lock files; the program embedding the
// engine may set it to its own version.
var GeneratorVersion = "dev"
// ErrNotFound is returned for unknown solutions, tasks, examples.
var ErrNotFound = errors.New("not found")
// Engine evaluates instances against one catalog. It is safe for
// concurrent use: Evaluate does not modify the catalog.
type Engine struct {
Cat *catalog.Catalog
}
// New returns an engine for a validated catalog.
func New(c *catalog.Catalog) *Engine { return &Engine{Cat: c} }
type evaluation struct {
e *Engine
s *catalog.Solution
in *Instance
preset *Preset
st *State
answers map[string]any
env catalog.Env
reqPkg, recPkg, discPkg, conflPkg map[string][]string
reqCap, recCap, discCap, exclCap, implCap map[string][]string
extCap map[string]string
exclMod, reqMod map[string][]string
pkgs map[string]*PackageState
mods map[string]map[string]*ModuleState // pkg -> module -> state
caps map[string]*CapState
pkgSeen []string
}
// Evaluate computes the full State of an instance (and an optional preset).
func (e *Engine) Evaluate(in *Instance, preset *Preset) (*State, error) {
s := e.Cat.Lookup(in.Spec.Solution.ID)
if s == nil {
return nil, fmt.Errorf("%w: solution or task %q", ErrNotFound, in.Spec.Solution.ID)
}
mode := in.Spec.Mode
if mode == "" {
mode = catalog.LevelQuick
}
loc := in.Spec.Locale
if loc == "" {
loc = "en"
}
st := &State{
Solution: SolutionInfo{
ID: s.Meta.ID, Kind: s.Kind, TaskKind: s.Spec.Kind, Version: s.Meta.Version,
Title: e.title(s, loc), Summary: e.summary(s, loc), Status: statusOf(s.Meta.Status),
Category: s.Meta.Category, BigPicture: s.Spec.BigPicture,
},
Instance: in.Metadata.Name, Mode: mode, Locale: loc, Platform: in.Spec.Platform,
Answers: map[string]Answer{},
Messages: []Message{}, Rules: []AppliedRule{}, Packages: []PackageState{},
Capabilities: []CapState{}, Files: []FilePreview{}, Steps: []PlannedStep{},
Checks: []CheckResult{}, References: []string{},
}
ev := &evaluation{
e: e, s: s, in: in, preset: preset, st: st, answers: map[string]any{},
reqPkg: map[string][]string{}, recPkg: map[string][]string{}, discPkg: map[string][]string{}, conflPkg: map[string][]string{},
reqCap: map[string][]string{}, recCap: map[string][]string{}, discCap: map[string][]string{},
exclCap: map[string][]string{}, implCap: map[string][]string{}, extCap: map[string]string{},
exclMod: map[string][]string{}, reqMod: map[string][]string{},
pkgs: map[string]*PackageState{}, mods: map[string]map[string]*ModuleState{}, caps: map[string]*CapState{},
}
ev.env = catalog.Env{Answers: ev.answers, Mode: mode, Platform: in.Spec.Platform}
if in.Spec.Solution.Version != "" && in.Spec.Solution.Version != s.Meta.Version {
ev.msg("warning", "version", fmt.Sprintf("these answers were made for %s %s; the catalog now has %s. Review the answers (LOCK-02).", s.Meta.ID, in.Spec.Solution.Version, s.Meta.Version), "")
}
if preset != nil && preset.Spec.Solution != "" && preset.Spec.Solution != s.Meta.ID {
ev.msg("warning", "preset", fmt.Sprintf("preset %q is for %s, not %s; only matching answers are used", preset.Metadata.Name, preset.Spec.Solution, s.Meta.ID), "")
}
for k := range in.Spec.Parameters {
if q, _ := s.Question(k); q == nil {
ev.msg("warning", "unknown-parameter", fmt.Sprintf("parameter %q is not a question of %s and is ignored", k, s.Meta.ID), "")
}
}
ev.questions()
ev.effects()
ev.packages()
ev.capabilities()
ev.finishModules()
ev.config()
ev.steps()
ev.checks()
ev.graph()
ev.finish()
return st, nil
}
func statusOf(s catalog.Support) catalog.Support {
if s == "" {
return catalog.Supported
}
return s
}
// ---- text ----------------------------------------------------------------
// Tr returns the translation of field in loc, or base.
func Tr(t catalog.Translations, loc, field, base string) string {
if loc != "" && loc != "en" {
if m, ok := t[loc]; ok {
if v, ok := m[field]; ok && v != "" {
return v
}
}
}
return base
}
func (e *Engine) title(s *catalog.Solution, loc string) string {
base := s.Meta.Title
if base == "" && e.Cat.BigPicture != nil {
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
base = g.Title
}
}
return Tr(s.Meta.Translations, loc, "title", base)
}
func (e *Engine) summary(s *catalog.Solution, loc string) string {
base := s.Meta.Summary
if base == "" && e.Cat.BigPicture != nil {
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
base = g.Intent
}
}
return Tr(s.Meta.Translations, loc, "summary", base)
}
// PackageTitle and PackageSummary come from the Big Picture (ADR-0002).
func (e *Engine) PackageSummary(id string) string {
p := e.Cat.Packages[id]
if p == nil {
return ""
}
if p.Meta.Summary != "" {
return p.Meta.Summary
}
if e.Cat.BigPicture != nil {
if bp, ok := e.Cat.BigPicture.Products[p.Spec.BigPicture]; ok {
return bp.Summary
}
}
return ""
}
func (ev *evaluation) msg(sev, code, text, source string) {
ev.st.Messages = append(ev.st.Messages, Message{Severity: sev, Code: code, Text: text, Source: source})
}
func add(m map[string][]string, k, reason string) {
for _, r := range m[k] {
if r == reason {
return
}
}
m[k] = append(m[k], reason)
}
// ---- questions -------------------------------------------------------------
func platformOK(list []string, p string) bool {
if len(list) == 0 || p == "" {
return true
}
for _, x := range list {
if x == p {
return true
}
}
return false
}
func (ev *evaluation) stale(q string, v any, reason string) {
ev.st.Stale = append(ev.st.Stale, StaleAnswer{Question: q, Value: v, Reason: reason})
}
func (ev *evaluation) questions() {
s, st, loc := ev.s, ev.st, ev.st.Locale
mode := st.Mode
askedIdx := 0
for i := range s.Spec.Questions {
q := &s.Spec.Questions[i]
qs := QuestionState{
ID: q.ID, Type: q.Type, Item: q.Item, Group: q.Group, Level: levelOf(q.Level),
Title: Tr(q.Translations, loc, "title", q.Title),
Help: Tr(q.Translations, loc, "help", q.Help),
Description: Tr(q.Translations, loc, "description", q.Description),
Decide: Tr(q.Translations, loc, "decide", q.Decide),
Placeholder: Tr(q.Translations, loc, "placeholder", q.Placeholder),
Examples: q.Examples, InstanceSpecific: q.InstanceSpecific,
Recommended: q.Recommended, Reason: Tr(q.Translations, loc, "reason", q.Reason),
References: q.References,
}
explicit, hasExplicit := ev.in.Spec.Parameters[q.ID]
qs.Visible = q.VisibleWhen.Holds(ev.env) && platformOK(q.Platforms, ev.in.Spec.Platform)
if !qs.Visible {
if hasExplicit {
ev.stale(q.ID, explicit, "the question does not apply to the current answers")
}
st.Questions = append(st.Questions, qs)
continue
}
qs.Required = q.Required || (len(q.RequiredWhen) > 0 && q.RequiredWhen.Holds(ev.env))
// options and their availability
enabled := map[string]bool{}
for _, o := range q.Options {
os := OptionState{
ID: o.ID, Title: Tr(o.Translations, loc, "title", o.Title),
Description: Tr(o.Translations, loc, "description", o.Description),
Recommended: o.Recommended, Reason: Tr(o.Translations, loc, "reason", o.Reason),
Support: statusOf(o.Support), SupportNote: Tr(o.Translations, loc, "supportNote", o.SupportNote),
References: o.References,
}
os.Enabled = o.Support.Selectable()
if !os.Enabled {
os.Disabled = os.SupportNote
} else if len(o.EnabledWhen) > 0 && !o.EnabledWhen.Holds(ev.env) {
os.Enabled = false
os.Disabled = "not available with the answers given before"
}
enabled[o.ID] = os.Enabled
for _, t := range []*catalog.Targets{o.Effects.Requires, o.Effects.Implies} {
if t != nil {
for _, p := range t.Packages {
os.Adds = append(os.Adds, "package:"+p)
}
for _, c := range t.Capabilities {
os.Adds = append(os.Adds, "capability:"+c)
}
}
}
qs.Options = append(qs.Options, os)
}
checkOpts := func(v any) string {
if q.Type != "select" && q.Type != "multiselect" {
return ""
}
for _, x := range listOf(v) {
if !enabled[catalog.Scalar(x)] {
for _, o := range qs.Options {
if o.ID == catalog.Scalar(x) {
return fmt.Sprintf("option %q is not available: %s", o.ID, o.Disabled)
}
}
}
}
return ""
}
// default (defaultWhen first match wins)
def := q.Default
for _, dw := range q.DefaultWhen {
if dw.When.Holds(ev.env) {
def = dw.Value
break
}
}
if ds, ok := def.(string); ok && strings.Contains(ds, "${") {
// a default built from earlier answers (postmaster@${domains[0]})
if x, err := expand(ds, ev.vars()); err == nil {
def = strings.Trim(x, "'")
} else {
def = nil
}
}
if def != nil {
if n, err := Normalize(q, def); err == nil {
def = n
if bad := checkOpts(def); bad != "" {
def = ev.fallbackOption(q, enabled)
}
} else {
ev.msg("error", "default", fmt.Sprintf("question %s: default %v is invalid: %v", q.ID, def, err), "catalog")
def = nil
}
}
qs.Default = def
var val any
origin := ""
if hasExplicit {
n, err := Normalize(q, explicit)
switch {
case err != nil:
qs.Errors = append(qs.Errors, err.Error())
case checkOpts(n) != "":
ev.stale(q.ID, explicit, checkOpts(n))
default:
val, origin = n, "instance"
}
}
if origin == "" && ev.preset != nil && !q.InstanceSpecific && q.Type != "secret" &&
(ev.preset.Spec.Solution == "" || ev.preset.Spec.Solution == ev.s.Meta.ID) {
if pv, ok := ev.preset.Spec.Parameters[q.ID]; ok {
if n, err := Normalize(q, pv); err == nil && checkOpts(n) == "" {
val, origin = n, "preset:"+ev.preset.Metadata.Name
} else {
ev.msg("warning", "preset", fmt.Sprintf("preset value for %s is not valid any more and is ignored", q.ID), "preset:"+ev.preset.Metadata.Name)
}
}
}
if origin == "" && len(qs.Errors) == 0 && def != nil {
val, origin = def, "default"
}
if val != nil && len(qs.Errors) == 0 {
for _, vw := range q.ValidateWhen {
if vw.When.Holds(ev.env) {
var err error
if l, isList := val.([]any); isList {
err = checkCount(vw.Validation, len(l))
} else {
err = checkValue(vw.Validation, val)
}
if err != nil {
qs.Errors = append(qs.Errors, err.Error())
}
}
}
}
levelAsked := qs.Level.Rank() <= mode.Rank()
missing := qs.Required && (!catalog.IsSet(val) || len(qs.Errors) > 0)
qs.Asked = (levelAsked && !strings.HasPrefix(origin, "preset:")) || missing || len(qs.Errors) > 0
if qs.Asked && q.InstanceSpecific {
qs.Asked = true
}
if val != nil && len(qs.Errors) == 0 {
ev.answers[q.ID] = val
st.Answers[q.ID] = Answer{Value: val, Origin: origin}
qs.Value, qs.Origin = val, origin
}
for j := range qs.Options {
for _, x := range listOf(qs.Value) {
if catalog.Scalar(x) == qs.Options[j].ID {
qs.Options[j].Selected = true
if sup := qs.Options[j].Support; sup == catalog.Experimental || sup == catalog.Untested || sup == catalog.Discouraged || sup == catalog.NeedsPrereq {
ev.msg("warning", "support-"+string(sup), fmt.Sprintf("%s: %q is %s. %s", qs.Title, qs.Options[j].Title, sup, qs.Options[j].SupportNote), "question:"+q.ID)
}
}
}
}
for _, w := range q.Warnings {
if w.When.Holds(ev.env) {
sev := w.Severity
if sev == "" {
sev = "warning"
}
m := Message{Severity: sev, Code: "question", Text: Tr(q.Translations, loc, "warning", w.Text), Source: "question:" + q.ID}
qs.Warnings = append(qs.Warnings, m)
st.Messages = append(st.Messages, m)
}
}
if missing {
st.Progress.Missing = append(st.Progress.Missing, q.ID)
}
if qs.Asked {
st.Progress.Asked++
askedIdx++
if origin == "instance" {
st.Progress.Answered++
} else if st.Next == "" {
st.Next = q.ID
st.Progress.Step = askedIdx
}
}
st.Questions = append(st.Questions, qs)
}
if st.Next == "" {
st.Progress.Step = askedIdx
}
// what needs attention first: a missing or invalid answer
idx := 0
for _, q := range st.Questions {
if q.Visible && q.Asked {
idx++
if len(q.Errors) > 0 || (q.Required && !catalog.IsSet(q.Value)) {
st.Next, st.Progress.Step = q.ID, idx
break
}
}
}
}
func levelOf(l catalog.Level) catalog.Level {
if l == "" {
return catalog.LevelQuick
}
return l
}
// fallbackOption: the recommended enabled option, else the first enabled.
func (ev *evaluation) fallbackOption(q *catalog.Question, enabled map[string]bool) any {
for _, o := range q.Options {
if o.Recommended && enabled[o.ID] {
return o.ID
}
}
for _, o := range q.Options {
if enabled[o.ID] {
return o.ID
}
}
return nil
}
// ---- effects of options and rules ----------------------------------------
func (ev *evaluation) effects() {
for i := range ev.s.Spec.Questions {
q := &ev.s.Spec.Questions[i]
v, ok := ev.answers[q.ID]
if !ok {
continue
}
for _, o := range q.Options {
for _, x := range listOf(v) {
if catalog.Scalar(x) == o.ID {
ev.apply("option "+q.ID+"="+o.ID, "option", o.Effects, o.Reason)
}
}
}
}
for _, r := range ev.s.Spec.Rules {
if !r.When.Holds(ev.env) {
continue
}
ev.apply("rule "+r.ID, "rule", r.Effects, r.Reason)
if r.Message != "" {
sev := r.Severity
if sev == "" {
sev = "warning"
}
ev.msg(sev, "rule", r.Message, "rule:"+r.ID)
}
}
}
func (ev *evaluation) apply(source, kind string, fx catalog.Effects, reason string) {
var parts []string
put := func(t *catalog.Targets, pk, cp map[string][]string, verb string) {
if t == nil {
return
}
for _, p := range t.Packages {
if pk != nil {
add(pk, p, source)
}
parts = append(parts, verb+" package "+p)
}
for _, c := range t.Capabilities {
if cp != nil {
add(cp, c, source)
}
parts = append(parts, verb+" "+c)
}
for _, m := range t.Modules {
if verb == "excludes" {
add(ev.exclMod, m, source)
} else if verb == "requires" || verb == "implies" {
add(ev.reqMod, m, source)
}
parts = append(parts, verb+" module "+m)
}
for q, want := range t.Answers {
parts = append(parts, fmt.Sprintf("%s %s=%v", verb, q, want))
if verb == "excludes" || verb == "conflicts" {
if have, ok := ev.answers[q]; ok && matchesAnswer(have, want) {
ev.msg("error", "conflict", fmt.Sprintf("%s=%v cannot be combined with this choice (%s)", q, catalog.Scalar(want), source), source)
}
}
if verb == "requires" {
if have, ok := ev.answers[q]; !ok || !matchesAnswer(have, want) {
ev.msg("error", "requires-answer", fmt.Sprintf("%s requires %s=%v", source, q, catalog.Scalar(want)), source)
}
}
}
}
put(fx.Requires, ev.reqPkg, ev.reqCap, "requires")
put(fx.Implies, ev.reqPkg, ev.implCap, "implies")
put(fx.Excludes, nil, ev.exclCap, "excludes")
put(fx.Conflicts, ev.conflPkg, ev.exclCap, "conflicts")
put(fx.Recommends, ev.recPkg, ev.recCap, "recommends")
put(fx.Discourages, ev.discPkg, ev.discCap, "discourages")
for _, c := range fx.Provides {
ev.extCap[c] = source
parts = append(parts, "provides "+c+" (external)")
}
if len(parts) == 0 && kind == "option" {
return
}
sort.Strings(parts)
ev.st.Rules = append(ev.st.Rules, AppliedRule{ID: source, Source: kind, Effect: strings.Join(parts, "; "), Reason: reason})
}
func matchesAnswer(have, want any) bool {
for _, h := range listOf(have) {
for _, w := range listOf(want) {
if catalog.Equal(h, w) {
return true
}
}
}
return false
}
// ---- packages, capabilities, modules ---------------------------------------
func (ev *evaluation) pkg(id, status, reason string) *PackageState {
p, ok := ev.pkgs[id]
if !ok {
cp := ev.e.Cat.Packages[id]
title := id
_ = cp
p = &PackageState{ID: id, Title: title, Summary: ev.e.PackageSummary(id), Status: status, Reasons: []string{}}
ev.pkgs[id] = p
ev.pkgSeen = append(ev.pkgSeen, id)
}
if rank(status) > rank(p.Status) {
p.Status = status
}
if status == StRequired || status == StSelected || status == StOptional {
p.Selected = true
}
for _, r := range p.Reasons {
if r == reason {
return p
}
}
if reason != "" {
p.Reasons = append(p.Reasons, reason)
}
return p
}
func rank(s string) int {
switch s {
case StRequired:
return 4
case StSelected:
return 3
case StOptional:
return 2
case StRecommended:
return 1
}
return 0
}
func (ev *evaluation) packages() {
for _, pu := range ev.s.Spec.Packages {
holds := len(pu.When) == 0 || pu.When.Holds(ev.env)
if pu.Recommended {
// a recommendation never selects a package
if holds {
ev.pkg(pu.ID, StRecommended, firstNonEmpty(pu.Reason, "recommended for this solution"))
}
continue
}
if !holds {
continue
}
status := StRequired
if pu.Role == "optional" {
status = StOptional
}
p := ev.pkg(pu.ID, status, firstNonEmpty(pu.Reason, "part of this solution"))
if pu.Profile != "" {
p.Profile = pu.Profile
}
}
for _, id := range catalog.SortedIDs(ev.reqPkg) {
for _, r := range ev.reqPkg[id] {
ev.pkg(id, StRequired, r)
}
}
for _, id := range catalog.SortedIDs(ev.recPkg) {
for _, r := range ev.recPkg[id] {
ev.pkg(id, StRecommended, r)
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: id, Reason: r, Source: r})
}
}
// modules from profiles
for _, id := range ev.pkgSeen {
p := ev.pkgs[id]
if !p.Selected {
continue
}
ev.mods[id] = map[string]*ModuleState{}
cp := ev.e.Cat.Packages[id]
for _, m := range cp.Spec.Modules {
ev.mods[id][m.ID] = &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
}
if p.Profile == "" {
// no profile: every selectable module of the package is used
for _, m := range cp.Spec.Modules {
if m.Support.Selectable() {
ms := ev.mods[id][m.ID]
ms.Enabled = true
ms.Reason = "package " + id
}
}
continue
}
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
if err != nil {
ev.msg("error", "profile", err.Error(), "package:"+id)
continue
}
for _, prof := range chain {
for mid, state := range prof.Spec.Modules {
if ms := ev.mods[id][mid]; ms != nil {
ms.Enabled = state == "enabled"
ms.Reason = "profile " + prof.Key()
}
}
for _, r := range prof.Spec.Recommendations {
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: r.Package, Capability: r.Capability, Reason: r.Reason, Source: "profile:" + prof.Key()})
if r.Package != "" {
ev.pkg(r.Package, StRecommended, r.Reason)
}
}
}
}
for _, m := range catalog.SortedIDs(ev.reqMod) {
pkg, mod, _ := strings.Cut(m, "/")
ev.pkg(pkg, StRequired, ev.reqMod[m][0])
ev.ensureMods(pkg)
if ms := ev.mods[pkg][mod]; ms != nil {
ms.Enabled = true
ms.Reason = ev.reqMod[m][0]
}
}
for _, m := range catalog.SortedIDs(ev.exclMod) {
pkg, mod, _ := strings.Cut(m, "/")
if ms := ev.mods[pkg][mod]; ms != nil {
if _, needed := ev.reqMod[m]; needed {
ev.msg("error", "module-conflict", fmt.Sprintf("module %s is both required and excluded (%s)", m, ev.exclMod[m][0]), ev.exclMod[m][0])
continue
}
ms.Enabled = false
ms.Reason = "excluded by " + ev.exclMod[m][0]
}
}
}
func (ev *evaluation) ensureMods(pkg string) {
if ev.mods[pkg] != nil {
return
}
ev.mods[pkg] = map[string]*ModuleState{}
cp := ev.e.Cat.Packages[pkg]
if cp == nil {
return
}
profile := ""
if p := ev.pkgs[pkg]; p != nil {
profile = p.Profile
}
for _, m := range cp.Spec.Modules {
ms := &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
if profile == "" && m.Support.Selectable() {
ms.Enabled, ms.Reason = true, "package "+pkg
}
ev.mods[pkg][m.ID] = ms
}
}
func firstNonEmpty(a ...string) string {
for _, s := range a {
if s != "" {
return s
}
}
return ""
}
func (ev *evaluation) capTitle(id string) string {
if c, ok := ev.e.Cat.Capabilities[id]; ok {
return Tr(c.Translations, ev.st.Locale, "title", c.Title)
}
return id
}
func (ev *evaluation) capState(id string) *CapState {
c, ok := ev.caps[id]
if !ok {
c = &CapState{ID: id, Title: ev.capTitle(id), Reasons: []string{}}
ev.caps[id] = c
}
return c
}
func (ev *evaluation) capabilities() {
type need struct{ id, reason string }
var queue []need
for _, c := range ev.s.Spec.Capabilities.Required {
queue = append(queue, need{c, "required by the solution"})
}
for _, m := range []map[string][]string{ev.reqCap, ev.implCap} {
for _, c := range catalog.SortedIDs(m) {
queue = append(queue, need{c, m[c][0]})
}
}
// requirements of modules the profiles enabled
for _, pid := range ev.pkgSeen {
cp := ev.e.Cat.Packages[pid]
for _, m := range cp.Spec.Modules {
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
for _, r := range m.Requires {
queue = append(queue, need{r, "needed by " + pid + "/" + m.ID})
}
}
}
}
done := map[string]bool{}
for steps := 0; len(queue) > 0 && steps < 10000; steps++ {
n := queue[0]
queue = queue[1:]
cs := ev.capState(n.id)
add2(&cs.Reasons, n.reason)
if done[n.id] {
continue
}
done[n.id] = true
cs.Status = StRequired
if src, ok := ev.exclCap[n.id]; ok {
cs.Status = StConflicting
ev.msg("error", "capability-conflict", fmt.Sprintf("%s is needed (%s) but excluded (%s)", n.id, n.reason, src[0]), src[0])
continue
}
if src, ok := ev.extCap[n.id]; ok {
cs.Status = StExternal
cs.Provider = "external:" + src
continue
}
var chosen *catalog.ModuleRef
var alts []string
providers := ev.e.Cat.ProvidersOf(n.id)
// a module that already provides it wins, then a selected package
pick := func(f func(catalog.ModuleRef) bool) {
for i := range providers {
if chosen == nil && providers[i].Support.Selectable() && f(providers[i]) {
chosen = &providers[i]
}
}
}
pick(func(r catalog.ModuleRef) bool {
ms := ev.mods[r.Package][r.Module]
return ms != nil && ms.Enabled
})
pick(func(r catalog.ModuleRef) bool { return ev.pkgs[r.Package] != nil && ev.pkgs[r.Package].Selected })
pick(func(r catalog.ModuleRef) bool { return true })
for _, pr := range providers {
if chosen == nil || pr != *chosen {
alts = append(alts, pr.String())
}
}
if c, ok := ev.e.Cat.Capabilities[n.id]; ok {
for _, x := range c.External {
alts = append(alts, "external:"+x.ID)
}
for _, r := range c.Requires {
queue = append(queue, need{r, "needed by " + n.id})
}
}
cs.Alternatives = alts
if chosen == nil {
cs.Status = StMissing
ev.msg("error", "capability-missing", fmt.Sprintf("no available provider for %s (%s)", n.id, n.reason), "")
continue
}
cs.Provider = chosen.String()
p := ev.pkg(chosen.Package, StRequired, "provides "+n.id)
_ = p
ev.ensureMods(chosen.Package)
ms := ev.mods[chosen.Package][chosen.Module]
if !ms.Enabled {
if src, excluded := ev.exclMod[chosen.String()]; excluded {
cs.Status = StConflicting
ev.msg("error", "module-conflict", fmt.Sprintf("%s needs module %s, which is excluded (%s)", n.id, chosen, src[0]), src[0])
continue
}
ms.Enabled = true
ms.Reason = "provides " + n.id
}
cm := ev.e.Cat.Packages[chosen.Package].Module(chosen.Module)
for _, r := range cm.Requires {
queue = append(queue, need{r, "needed by " + chosen.String()})
}
}
// capabilities provided as a side effect, recommended, optional, excluded
for _, pid := range ev.pkgSeen {
for _, m := range ev.e.Cat.Packages[pid].Spec.Modules {
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
for _, c := range m.Provides {
if !ev.requiresMet(c) {
continue // e.g. AI analysis without an AI server
}
cs := ev.capState(c)
if cs.Status == "" {
cs.Status = StSelected
cs.Provider = pid + "/" + m.ID
add2(&cs.Reasons, "provided by "+pid+"/"+m.ID)
}
}
}
}
}
// capabilities the user's answers say exist outside Yetano
for _, c := range catalog.SortedIDs(ev.extCap) {
cs := ev.capState(c)
if cs.Status == "" {
cs.Status = StExternal
cs.Provider = "external:" + ev.extCap[c]
add2(&cs.Reasons, "provided outside Yetano ("+ev.extCap[c]+")")
}
}
soft := func(list []string, m map[string][]string, status, why string) {
ids := append([]string{}, list...)
ids = append(ids, catalog.SortedIDs(m)...)
for _, c := range ids {
cs := ev.capState(c)
if cs.Status != "" {
continue
}
cs.Status = status
r := why
if rs, ok := m[c]; ok {
r = rs[0]
}
add2(&cs.Reasons, r)
for _, pr := range ev.e.Cat.ProvidersOf(c) {
cs.Alternatives = append(cs.Alternatives, pr.String())
}
if status == StRecommended {
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Capability: c, Reason: r, Source: r})
}
}
}
soft(ev.s.Spec.Capabilities.Recommended, ev.recCap, StRecommended, "recommended by the solution")
soft(ev.s.Spec.Capabilities.Optional, nil, StOptional, "optional for this solution")
for _, c := range catalog.SortedIDs(ev.exclCap) {
cs := ev.capState(c)
// required and excluded was reported above; a capability an enabled
// module merely could provide is just not used
if cs.Status == "" || cs.Status == StSelected {
cs.Status = StExcluded
cs.Provider = ""
add2(&cs.Reasons, "excluded by "+ev.exclCap[c][0])
}
}
// capability-level conflicts between provided capabilities
for _, id := range catalog.SortedIDs(ev.caps) {
cs := ev.caps[id]
if c, ok := ev.e.Cat.Capabilities[id]; ok && provided(cs.Status) {
for _, other := range c.Conflicts {
if o, ok := ev.caps[other]; ok && provided(o.Status) && id < other {
ev.msg("error", "capability-conflict", fmt.Sprintf("%s and %s cannot be combined", id, other), "capability:"+id)
}
}
}
}
for _, c := range catalog.SortedIDs(ev.discCap) {
if cs, ok := ev.caps[c]; ok && provided(cs.Status) {
ev.msg("warning", "discouraged", fmt.Sprintf("%s is possible but not recommended here (%s)", c, ev.discCap[c][0]), ev.discCap[c][0])
}
}
}
// requiresMet: every capability c requires is required/provided already.
func (ev *evaluation) requiresMet(c string) bool {
cp, ok := ev.e.Cat.Capabilities[c]
if !ok {
return true
}
for _, r := range cp.Requires {
if cs, ok := ev.caps[r]; !ok || !provided(cs.Status) {
if _, ext := ev.extCap[r]; !ext {
return false
}
}
}
return true
}
func provided(s string) bool {
return s == StRequired || s == StSelected || s == StExternal
}
func add2(list *[]string, s string) {
for _, x := range *list {
if x == s {
return
}
}
*list = append(*list, s)
}
func (ev *evaluation) finishModules() {
for _, id := range catalog.SortedIDs(ev.conflPkg) {
if p, ok := ev.pkgs[id]; ok && p.Selected {
ev.msg("error", "package-conflict", fmt.Sprintf("package %s cannot be used with this choice (%s)", id, ev.conflPkg[id][0]), ev.conflPkg[id][0])
}
}
for _, id := range catalog.SortedIDs(ev.discPkg) {
if p, ok := ev.pkgs[id]; ok && p.Selected {
ev.msg("warning", "discouraged", fmt.Sprintf("package %s is possible but not recommended here (%s)", id, ev.discPkg[id][0]), ev.discPkg[id][0])
}
}
ids := append([]string{}, ev.pkgSeen...)
sort.Strings(ids)
for _, id := range ids {
p := ev.pkgs[id]
if p.Selected {
cp := ev.e.Cat.Packages[id]
for _, m := range cp.Spec.Modules {
ms := ev.mods[id][m.ID]
if ms == nil {
continue
}
if ms.Enabled && (m.Support == catalog.Experimental || m.Support == catalog.Untested) {
ev.msg("warning", "support-"+string(m.Support), fmt.Sprintf("module %s/%s is %s", id, m.ID, m.Support), "package:"+id)
}
p.Modules = append(p.Modules, *ms)
}
}
ev.st.Packages = append(ev.st.Packages, *p)
}
for _, id := range catalog.SortedIDs(ev.caps) {
ev.st.Capabilities = append(ev.st.Capabilities, *ev.caps[id])
}
}
// moduleEnabled reports whether pkg/module is enabled in this evaluation.
func (ev *evaluation) moduleEnabled(pkg, mod string) bool {
ms := ev.mods[pkg][mod]
return ms != nil && ms.Enabled
}
func (ev *evaluation) pkgSelected(id string) bool {
p, ok := ev.pkgs[id]
return ok && p.Selected
}
func (ev *evaluation) finish() {
st := ev.st
refs := append([]string{}, ev.s.Spec.References.All()...)
for _, q := range st.Questions {
if q.Visible {
refs = append(refs, q.References...)
}
}
seen := map[string]bool{}
for _, r := range refs {
if !seen[r] {
seen[r] = true
st.References = append(st.References, r)
}
}
st.Related = ev.s.Spec.Related
sort.SliceStable(st.Messages, func(i, j int) bool { return sevRank(st.Messages[i].Severity) > sevRank(st.Messages[j].Severity) })
errs := 0
for _, m := range st.Messages {
if m.Severity == "error" {
errs++
}
}
st.Complete = len(st.Progress.Missing) == 0 && errs == 0
}
func sevRank(s string) int {
switch s {
case "error":
return 2
case "warning":
return 1
}
return 0
}
+266
View File
@@ -0,0 +1,266 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// Graph is the resolved architecture of a state (BP-03/BP-04). Node IDs:
// "pkg:<id>", "mod:<pkg>/<module>", "cap:<id>", "ext:<id>" and the
// solution's own node IDs ("n:<id>").
type Graph struct {
Nodes []GraphNode `json:"nodes"`
Edges []GraphEdge `json:"edges"`
}
// GraphNode is one node with its state (required, selected, ...).
type GraphNode struct {
ID string `json:"id"`
Type string `json:"type"` // package | module | capability | external | client | storage | network | identity | target | solution
Title string `json:"title"`
Status string `json:"status"`
Parent string `json:"parent,omitempty"` // module -> package
Ref string `json:"ref,omitempty"` // yetano: reference to open
}
// GraphEdge is a typed relation (requires, provides, connectsTo, ...).
type GraphEdge struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
Label string `json:"label,omitempty"`
Status string `json:"status,omitempty"`
}
func (ev *evaluation) graph() {
g := Graph{Nodes: []GraphNode{}, Edges: []GraphEdge{}}
have := map[string]bool{}
node := func(n GraphNode) {
if !have[n.ID] {
have[n.ID] = true
g.Nodes = append(g.Nodes, n)
}
}
edge := func(e GraphEdge) { g.Edges = append(g.Edges, e) }
solID := "sol:" + ev.s.Meta.ID
node(GraphNode{ID: solID, Type: "solution", Title: ev.st.Solution.Title, Status: StSelected, Ref: "yetano:solution/" + ev.s.Meta.ID})
for _, p := range ev.st.Packages {
status := p.Status
switch {
case !p.Selected:
status = StRecommended
case status == StOptional:
status = StSelected // an optional package the answers chose
}
pid := "pkg:" + p.ID
node(GraphNode{ID: pid, Type: "package", Title: p.ID, Status: status, Ref: "yetano:package/" + p.ID})
if p.Selected {
edge(GraphEdge{From: solID, To: pid, Type: "requires", Status: status})
} else {
edge(GraphEdge{From: solID, To: pid, Type: "optional", Label: "recommended", Status: StRecommended})
}
for _, m := range p.Modules {
st := StDisabled
if m.Enabled {
st = StSelected
}
if !m.Support.Selectable() {
st = StUnsupported
}
if !m.Enabled {
continue // disabled modules stay out of the picture; the package detail lists them
}
mid := "mod:" + p.ID + "/" + m.ID
node(GraphNode{ID: mid, Type: "module", Title: firstNonEmpty(m.Program, m.ID), Status: st, Parent: pid, Ref: "yetano:module/" + p.ID + "/" + m.ID})
}
}
for _, c := range ev.st.Capabilities {
cid := "cap:" + c.ID
node(GraphNode{ID: cid, Type: "capability", Title: c.Title, Status: c.Status, Ref: "yetano:capability/" + c.ID})
switch {
case strings.HasPrefix(c.Provider, "external:"):
xid := "ext:" + c.ID
node(GraphNode{ID: xid, Type: "external", Title: "existing " + c.Title, Status: StExternal})
edge(GraphEdge{From: xid, To: cid, Type: "provides", Status: StExternal})
case c.Provider != "":
pkg, _, _ := strings.Cut(c.Provider, "/")
from := "mod:" + c.Provider
if !have[from] {
from = "pkg:" + pkg
}
edge(GraphEdge{From: from, To: cid, Type: "provides", Status: c.Status})
}
if c.Status == StRecommended || c.Status == StOptional || c.Status == StMissing {
for _, alt := range c.Alternatives {
if strings.HasPrefix(alt, "external:") {
continue
}
pkg, _, _ := strings.Cut(alt, "/")
if !have["pkg:"+pkg] {
node(GraphNode{ID: "pkg:" + pkg, Type: "package", Title: pkg, Status: StAlternative, Ref: "yetano:package/" + pkg})
}
edge(GraphEdge{From: "pkg:" + pkg, To: cid, Type: "alternativeTo", Status: StAlternative})
}
}
if c.Status == StRequired || c.Status == StMissing || c.Status == StConflicting {
edge(GraphEdge{From: solID, To: cid, Type: "requires", Status: c.Status})
}
}
// not implemented options of visible questions: shown as unsupported alternatives
for _, q := range ev.st.Questions {
if !q.Visible {
continue
}
for _, o := range q.Options {
if o.Support.Selectable() {
continue
}
for _, a := range o.Adds {
if p, ok := strings.CutPrefix(a, "package:"); ok && !have["pkg:"+p] {
node(GraphNode{ID: "pkg:" + p, Type: "package", Title: p, Status: StUnsupported, Ref: "yetano:package/" + p})
}
}
}
}
// solution-specific nodes and edges
for _, n := range ev.s.Spec.Architecture.Nodes {
if len(n.When) > 0 && !n.When.Holds(ev.env) {
continue
}
st := StSelected
if n.Type == "external" || n.Type == "client" {
st = StExternal
}
title, err := expand(n.Title, ev.vars())
if err != nil {
title = n.Title
}
node(GraphNode{ID: "n:" + n.ID, Type: n.Type, Title: strings.Trim(title, "'"), Status: st})
}
resolve := func(id string) string {
if strings.Contains(id, ":") {
return id
}
return "n:" + id
}
for _, e := range ev.s.Spec.Architecture.Edges {
if len(e.When) > 0 && !e.When.Holds(ev.env) {
continue
}
from, to := resolve(e.From), resolve(e.To)
if !have[from] || !have[to] || !inUse(g, from) || !inUse(g, to) {
continue // an end that is not part of this resolution
}
edge(GraphEdge{From: from, To: to, Type: e.Type, Label: e.Label})
}
// confirmed Big Picture connections between selected packages
if bp := ev.e.Cat.BigPicture; bp != nil {
byProduct := map[string]string{}
for _, p := range ev.st.Packages {
if cp := ev.e.Cat.Packages[p.ID]; cp != nil && p.Selected {
byProduct[cp.Spec.BigPicture] = "pkg:" + p.ID
}
}
for _, c := range bp.Connections {
f, okf := byProduct[c.From]
t, okt := byProduct[c.To]
if okf && okt && c.Review == "confirmed" {
edge(GraphEdge{From: f, To: t, Type: c.Type, Label: c.Label})
}
}
}
sort.SliceStable(g.Edges, func(i, j int) bool {
a, b := g.Edges[i], g.Edges[j]
return fmt.Sprint(a.From, a.To, a.Type) < fmt.Sprint(b.From, b.To, b.Type)
})
ev.st.Graph = g
}
// inUse: the node is part of the solution (not only an alternative).
func inUse(g Graph, id string) bool {
for _, n := range g.Nodes {
if n.ID == id {
switch n.Status {
case StRequired, StSelected, StExternal:
return true
}
return false
}
}
return false
}
// GraphText renders a graph as indented text for the CLI (BP-06).
func GraphText(g Graph) string {
var b strings.Builder
byID := map[string]GraphNode{}
for _, n := range g.Nodes {
byID[n.ID] = n
}
mark := func(status string) string {
switch status {
case StRequired, StSelected:
return "+"
case StRecommended, StOptional, StAlternative:
return "?"
case StExternal:
return "~"
case StMissing, StConflicting, StUnsupported:
return "!"
}
return " "
}
for _, n := range g.Nodes {
if n.Type != "package" {
continue
}
fmt.Fprintf(&b, "%s %s [%s]\n", mark(n.Status), n.Title, n.Status)
for _, m := range g.Nodes {
if m.Parent == n.ID {
fmt.Fprintf(&b, " %s %s\n", mark(m.Status), m.Title)
for _, e := range g.Edges {
if e.From == m.ID && e.Type == "provides" {
fmt.Fprintf(&b, " provides %s\n", byID[e.To].Title)
}
}
}
}
}
var other []string
for _, n := range g.Nodes {
switch n.Type {
case "external", "client", "storage", "network", "identity", "target":
other = append(other, fmt.Sprintf("%s %s (%s)", mark(n.Status), n.Title, n.Type))
}
}
if len(other) > 0 {
b.WriteString("around it:\n")
for _, o := range other {
fmt.Fprintf(&b, " %s\n", o)
}
}
var rel []string
for _, e := range g.Edges {
f, t := byID[e.From], byID[e.To]
if e.Type == "provides" || e.Type == "requires" || e.Type == "optional" || f.Type == "solution" {
continue
}
label := e.Type
if e.Label != "" {
label += " (" + e.Label + ")"
}
rel = append(rel, fmt.Sprintf(" %s --%s--> %s", f.Title, label, t.Title))
}
if len(rel) > 0 {
b.WriteString("connections:\n")
b.WriteString(strings.Join(rel, "\n"))
b.WriteString("\n")
}
b.WriteString("legend: + used ? recommended/optional ~ external ! missing/unsupported\n")
return b.String()
}
var _ = catalog.Supported
+278
View File
@@ -0,0 +1,278 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// HandbookPage is one Markdown page of a solution handbook (HB-01).
type HandbookPage struct {
Path string
Content []byte
}
// Handbook composes the handbook of a state from the solution, the
// decisions, the generated files and existing manual text (via mr). It
// covers only what was chosen (HB-02) and never prints secret values
// (HB-04): secret answers are references and are shown as such.
func (e *Engine) Handbook(st *State, mr ManualReader) []HandbookPage {
s := e.Cat.Lookup(st.Solution.ID)
link := func(ref string) string {
if mr != nil {
if l := mr.Link(ref); l != "" {
return l
}
}
return "`" + ref + "`"
}
excerpt := func(b *strings.Builder, ref string) {
if mr == nil {
fmt.Fprintf(b, "- %s\n", link(ref))
return
}
title, md, ok := mr.Excerpt(ref, 40)
if !ok {
fmt.Fprintf(b, "- %s\n", link(ref))
return
}
fmt.Fprintf(b, "> From the manual: **%s** (%s)\n>\n", title, link(ref))
for _, line := range strings.Split(strings.TrimRight(md, "\n"), "\n") {
fmt.Fprintf(b, "> %s\n", line)
}
b.WriteString("\n")
}
var pages []HandbookPage
page := func(name, title string, body func(b *strings.Builder)) {
var b strings.Builder
fmt.Fprintf(&b, "# %s\n\n", title)
body(&b)
pages = append(pages, HandbookPage{Path: "handbook/" + name, Content: []byte(b.String())})
}
selected := []PackageState{}
for _, p := range st.Packages {
if p.Selected {
selected = append(selected, p)
}
}
hasCap := func(prefix string) bool {
for _, c := range st.Capabilities {
if strings.HasPrefix(c.ID, prefix) && provided(c.Status) {
return true
}
}
return false
}
secretQ := map[string]bool{}
for _, q := range s.Spec.Questions {
if q.Type == "secret" {
secretQ[q.ID] = true
}
}
page("index.md", "Handbook: "+firstNonEmpty(st.Instance, st.Solution.Title), func(b *strings.Builder) {
fmt.Fprintf(b, "%s\n\n", st.Solution.Summary)
fmt.Fprintf(b, "Solution `%s` %s, status **%s**.\n\n", st.Solution.ID, st.Solution.Version, st.Solution.Status)
b.WriteString("1. [Your architecture](architecture.md)\n2. [Installation and configuration](installation.md)\n3. [Configuration reference](configuration.md)\n4. [Security](security.md)\n5. [Operations and maintenance](operations.md)\n")
if hasCap("backup.") {
b.WriteString("6. [Backup and restore](backup-restore.md)\n7. [Troubleshooting](troubleshooting.md)\n")
} else {
b.WriteString("6. [Troubleshooting](troubleshooting.md)\n")
}
b.WriteString("\n## Your decisions\n\n| Question | Answer | From |\n|---|---|---|\n")
for _, q := range st.Questions {
if !q.Visible || q.Value == nil {
continue
}
val := answerText(q)
if secretQ[q.ID] {
val = "(secret reference)"
}
fmt.Fprintf(b, "| %s | %s | %s |\n", q.Title, val, q.Origin)
}
if len(st.Messages) > 0 {
b.WriteString("\n## Notes and warnings\n\n")
for _, m := range st.Messages {
fmt.Fprintf(b, "- **%s**: %s\n", m.Severity, m.Text)
}
}
})
page("architecture.md", "Your architecture", func(b *strings.Builder) {
b.WriteString("```text\n")
b.WriteString(GraphText(st.Graph))
b.WriteString("```\n\n## Packages\n\n")
for _, p := range selected {
fmt.Fprintf(b, "### %s\n\n%s\n\n", p.ID, p.Summary)
if p.Profile != "" {
fmt.Fprintf(b, "Profile: `%s`. ", p.Profile)
}
fmt.Fprintf(b, "Why: %s.\n\n", strings.Join(p.Reasons, "; "))
var on []string
for _, m := range p.Modules {
if m.Enabled {
on = append(on, fmt.Sprintf("`%s`", firstNonEmpty(m.Program, m.ID)))
}
}
if len(on) > 0 {
fmt.Fprintf(b, "Programs used: %s.\n\n", strings.Join(on, ", "))
}
}
b.WriteString("## Capabilities\n\n| Capability | Status | Provided by |\n|---|---|---|\n")
for _, c := range st.Capabilities {
if c.Status == StExcluded {
continue
}
fmt.Fprintf(b, "| %s | %s | %s |\n", c.Title, c.Status, firstNonEmpty(c.Provider, "–"))
}
if st.Solution.BigPicture != "" {
fmt.Fprintf(b, "\nIn the Big Picture: %s\n", link("yetano:bigpicture/"+st.Solution.BigPicture))
}
})
page("installation.md", "Installation and configuration", func(b *strings.Builder) {
b.WriteString("The guide has not changed any system. These are the steps, in order;\n" +
"`deployment-plan.yaml` has the same list in machine-readable form.\n\n")
phase := ""
n := 0
for _, sp := range st.Steps {
if sp.Phase != phase {
phase = sp.Phase
fmt.Fprintf(b, "## %s\n\n", strings.ToUpper(phase[:1])+phase[1:])
}
n++
fmt.Fprintf(b, "%d. %s\n", n, sp.Title)
if sp.Run != "" {
fmt.Fprintf(b, "\n ```sh\n %s\n ```\n", sp.Run)
}
if sp.Note != "" {
fmt.Fprintf(b, "\n %s\n", sp.Note)
}
if sp.Reversible != nil && !*sp.Reversible {
b.WriteString("\n **Cannot be undone automatically.**\n")
}
b.WriteString("\n")
}
})
page("configuration.md", "Configuration reference", func(b *strings.Builder) {
for _, f := range st.Files {
fmt.Fprintf(b, "## `%s`\n\n```yaml\n%s```\n\n", f.Path, f.Content)
keys := make([]string, 0, len(f.Origins))
for k := range f.Origins {
keys = append(keys, k)
}
sort.Strings(keys)
b.WriteString("| Setting | Comes from | Uses answers |\n|---|---|---|\n")
for _, k := range keys {
o := f.Origins[k]
fmt.Fprintf(b, "| `%s` | %s | %s |\n", k, o.Source, strings.Join(o.Params, ", "))
}
b.WriteString("\n")
}
for _, p := range selected {
if cp := e.Cat.Packages[p.ID]; cp != nil {
for _, m := range cp.Spec.Modules {
if ms := findModule(p, m.ID); ms != nil && ms.Enabled && m.Manual != "" {
fmt.Fprintf(b, "- Full option list of %s: %s\n", firstNonEmpty(m.Program, m.ID), link("yetano:manual/"+m.Manual+"/configuration"))
}
}
}
}
})
page("security.md", "Security", func(b *strings.Builder) {
b.WriteString("Secrets are never written into these files: secret answers are\nreferences (`secret://…` resolved by yaseva, `env:`, `file:`).\n\n")
for _, c := range st.Checks {
if c.Status == CheckNotApplicable {
continue
}
if c.Kind == "tls" || c.Kind == "dns" || strings.Contains(c.ID, "tls") || strings.Contains(c.ID, "relay") {
fmt.Fprintf(b, "- **%s** (%s): %s", c.Title, c.Severity, c.Hint)
if c.Run != "" {
fmt.Fprintf(b, " Check: `%s`", c.Run)
}
b.WriteString("\n")
}
}
for _, r := range s.Spec.References.Manuals {
if strings.Contains(r, "dkim") || strings.Contains(r, "tls") || strings.Contains(r, "security") {
b.WriteString("\n")
excerpt(b, r)
}
}
})
page("operations.md", "Operations and maintenance", func(b *strings.Builder) {
for _, op := range s.Spec.Operations {
fmt.Fprintf(b, "- %s\n", op)
}
b.WriteString("\n## Health checks\n\n")
for _, p := range selected {
if cp := e.Cat.Packages[p.ID]; cp != nil {
for _, m := range cp.Spec.Modules {
if ms := findModule(p, m.ID); ms != nil && ms.Enabled {
for _, d := range m.Doctor {
fmt.Fprintf(b, "- `%s`\n", d)
}
}
}
}
}
if len(st.Related) > 0 {
b.WriteString("\n## Related tasks and solutions\n\n")
for _, r := range st.Related {
kind := "solution"
if e.Cat.Tasks[r] != nil {
kind = "task"
}
fmt.Fprintf(b, "- `yet %s show %s`\n", kind, r)
}
}
})
if hasCap("backup.") {
page("backup-restore.md", "Backup and restore", func(b *strings.Builder) {
for _, c := range st.Capabilities {
if strings.HasPrefix(c.ID, "backup.") && provided(c.Status) {
fmt.Fprintf(b, "- %s: %s\n", c.Title, c.Provider)
}
}
})
}
page("troubleshooting.md", "Troubleshooting", func(b *strings.Builder) {
b.WriteString("Run the health checks from [operations](operations.md) first: they name\nthe failing area and give a hint.\n\n## Manuals\n\n")
refs := append([]string{}, st.References...)
for _, r := range refs {
if strings.HasPrefix(r, "yetano:manual/") {
fmt.Fprintf(b, "- %s\n", link(r))
}
}
})
return pages
}
func findModule(p PackageState, id string) *ModuleState {
for i := range p.Modules {
if p.Modules[i].ID == id {
return &p.Modules[i]
}
}
return nil
}
func answerText(q QuestionState) string {
if l, ok := q.Value.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, optTitle(q, catalog.Scalar(x)))
}
return strings.Join(parts, ", ")
}
return optTitle(q, catalog.Scalar(q.Value))
}
func optTitle(q QuestionState, v string) string {
for _, o := range q.Options {
if o.ID == v {
return o.Title
}
}
return v
}
+190
View File
@@ -0,0 +1,190 @@
// Package engine is the Solutions Engine: it evaluates a solution's
// questions and rules against a user's answers, resolves packages,
// modules, capabilities and providers, generates native configuration
// with the origin of every value, and builds the architecture graph,
// the plan, the lock file and the handbook.
//
// The engine is pure: it reads a loaded catalog and values, and returns
// values. It never touches the network, never runs a command and writes
// files only in Write, into the directory it is given.
package engine
import (
"bytes"
"errors"
"fmt"
"io"
"sort"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/solutions/catalog"
)
// Instance is a user's answers for one solution: a draft wizard session
// (kind WizardSession) or a saved solution instance (SolutionInstance).
// It never contains plain-text secrets (secret answers are references).
type Instance struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
Spec InstanceSpec `yaml:"spec" json:"spec"`
}
// InstanceMeta names an instance.
type InstanceMeta struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Created string `yaml:"created,omitempty" json:"created,omitempty"`
Updated string `yaml:"updated,omitempty" json:"updated,omitempty"`
Favorite bool `yaml:"favorite,omitempty" json:"favorite,omitempty"`
Archived bool `yaml:"archived,omitempty" json:"archived,omitempty"`
}
// InstanceSpec holds the decisions.
type InstanceSpec struct {
Solution SolutionPin `yaml:"solution" json:"solution"`
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
Preset string `yaml:"preset,omitempty" json:"preset,omitempty"`
Locale string `yaml:"locale,omitempty" json:"locale,omitempty"`
Platform string `yaml:"platform,omitempty" json:"platform,omitempty"`
Target string `yaml:"target,omitempty" json:"target,omitempty"`
Parameters map[string]any `yaml:"parameters" json:"parameters"`
Overrides []Override `yaml:"overrides,omitempty" json:"overrides,omitempty"`
// Cursor is the question a wizard session was at (sessions only).
Cursor string `yaml:"cursor,omitempty" json:"cursor,omitempty"`
}
// SolutionPin names the solution and the version the answers were made for.
type SolutionPin struct {
ID string `yaml:"id" json:"id"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
}
// Override sets one value in a generated file directly (layer 6 of
// ARCHITECTURE.md): path is dot-separated map keys.
type Override struct {
File string `yaml:"file" json:"file"`
Path string `yaml:"path" json:"path"`
Value any `yaml:"value" json:"value"`
}
// Preset is a reusable set of answers (PRE-01). Instance-specific and
// secret questions are never taken from a preset.
type Preset struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
Spec PresetSpec `yaml:"spec" json:"spec"`
}
// PresetSpec holds a preset's answers.
type PresetSpec struct {
Solution string `yaml:"solution,omitempty" json:"solution,omitempty"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
Parameters map[string]any `yaml:"parameters" json:"parameters"`
}
// NewInstance starts a session for a solution.
func NewInstance(name string, s *catalog.Solution, mode catalog.Level) *Instance {
if mode == "" {
mode = catalog.LevelQuick
}
return &Instance{
APIVersion: catalog.APIVersion, Kind: catalog.KindSession,
Metadata: InstanceMeta{Name: name},
Spec: InstanceSpec{
Solution: SolutionPin{ID: s.Meta.ID, Version: s.Meta.Version},
Mode: mode,
Parameters: map[string]any{},
},
}
}
// MaxInstanceSize bounds instance and preset files.
const MaxInstanceSize = 1 << 20
// ReadInstance decodes an instance or session (strict).
func ReadInstance(r io.Reader) (*Instance, error) {
var in Instance
if err := strict(r, &in); err != nil {
return nil, err
}
if in.APIVersion != catalog.APIVersion {
return nil, fmt.Errorf("apiVersion %q, want %q", in.APIVersion, catalog.APIVersion)
}
if in.Kind != catalog.KindInstance && in.Kind != catalog.KindSession {
return nil, fmt.Errorf("kind %q, want %s or %s", in.Kind, catalog.KindInstance, catalog.KindSession)
}
if in.Spec.Parameters == nil {
in.Spec.Parameters = map[string]any{}
}
return &in, nil
}
// ReadPreset decodes a preset (strict).
func ReadPreset(r io.Reader) (*Preset, error) {
var p Preset
if err := strict(r, &p); err != nil {
return nil, err
}
if p.APIVersion != catalog.APIVersion || p.Kind != catalog.KindPreset {
return nil, fmt.Errorf("not a %s %s", catalog.APIVersion, catalog.KindPreset)
}
if p.Spec.Parameters == nil {
p.Spec.Parameters = map[string]any{}
}
return &p, nil
}
func strict(r io.Reader, v any) error {
b, err := io.ReadAll(io.LimitReader(r, MaxInstanceSize+1))
if err != nil {
return err
}
if len(b) > MaxInstanceSize {
return fmt.Errorf("larger than %d bytes", MaxInstanceSize)
}
d := yaml.NewDecoder(bytes.NewReader(b))
d.KnownFields(true)
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
return err
}
return nil
}
// Marshal renders any of the user files as YAML with sorted parameters.
func Marshal(v any) ([]byte, error) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(v); err != nil {
return nil, err
}
enc.Close()
return buf.Bytes(), nil
}
// PresetFrom derives a preset from an instance: all answers except
// instance-specific and secret ones (PRE-02, PRE-04).
func PresetFrom(name string, in *Instance, s *catalog.Solution) *Preset {
p := &Preset{
APIVersion: catalog.APIVersion, Kind: catalog.KindPreset,
Metadata: InstanceMeta{Name: name},
Spec: PresetSpec{Solution: s.Meta.ID, Version: s.Meta.Version, Mode: in.Spec.Mode, Parameters: map[string]any{}},
}
keys := make([]string, 0, len(in.Spec.Parameters))
for k := range in.Spec.Parameters {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
q, _ := s.Question(k)
if q == nil || q.InstanceSpecific || q.Type == "secret" {
continue
}
p.Spec.Parameters[k] = in.Spec.Parameters[k]
}
return p
}
+379
View File
@@ -0,0 +1,379 @@
package engine
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// Lock pins what a generation was made from (LOCK-01). It has no
// timestamps, so the same inputs give the same file.
type Lock struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Spec LockSpec `yaml:"spec" json:"spec"`
}
// LockSpec is the content of a lock.
type LockSpec struct {
Generator string `yaml:"generator" json:"generator"`
Catalog Pinned `yaml:"catalog" json:"catalog"`
Solution Pinned `yaml:"solution" json:"solution"`
Profiles []Pinned `yaml:"profiles,omitempty" json:"profiles,omitempty"`
Packages []Pinned `yaml:"packages,omitempty" json:"packages,omitempty"`
Capability string `yaml:"capabilities" json:"capabilities"` // hash of the capability files
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
Answers string `yaml:"answers" json:"answers"`
Files []FileHash `yaml:"files" json:"files"`
}
// Pinned is an entity with version and content hash.
type Pinned struct {
ID string `yaml:"id" json:"id"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
Hash string `yaml:"sha256" json:"sha256"`
}
// FileHash is a generated file and its hash.
type FileHash = catalog.FileHash
// OutFile is one file of a generated solution directory.
type OutFile struct {
Path string `json:"path"`
Kind string `json:"kind"` // instance | lock | config | architecture | handbook | plan | readme
Content []byte `json:"-"`
}
// Output is everything Generate produces.
type Output struct {
Files []OutFile `json:"files"`
Lock *Lock `json:"lock"`
}
// ManualReader gives the handbook existing manual text (implemented by
// package knowledge). It may be nil: the handbook then links instead.
type ManualReader interface {
// Excerpt returns the title and Markdown of a manual reference
// (yetano:manual/...#section), shortened to at most maxLines lines.
Excerpt(ref string, maxLines int) (title, markdown string, ok bool)
// Link returns a human link for a reference (web URL or CLI command).
Link(ref string) string
}
// Generate renders all output files of a complete state. It refuses an
// incomplete state unless allowIncomplete is set.
func (e *Engine) Generate(st *State, in *Instance, mr ManualReader, allowIncomplete bool) (*Output, error) {
if !st.Complete && !allowIncomplete {
return nil, fmt.Errorf("%w: %s", ErrIncomplete, incompleteText(st))
}
s := e.Cat.Lookup(st.Solution.ID)
out := &Output{}
addf := func(path, kind string, b []byte) {
out.Files = append(out.Files, OutFile{Path: path, Kind: kind, Content: b})
}
inst := *in
inst.Kind = catalog.KindInstance
inst.Spec.Solution.Version = s.Meta.Version
inst.Spec.Cursor = ""
b, err := Marshal(&inst)
if err != nil {
return nil, err
}
addf("solution.yaml", "instance", b)
for _, f := range st.Files {
addf(f.Path, "config", []byte(f.Content))
}
gj, _ := json.MarshalIndent(st.Graph, "", " ")
addf("architecture/graph.json", "architecture", append(gj, '\n'))
addf("architecture/graph.txt", "architecture", []byte(GraphText(st.Graph)))
pb, err := Marshal(PlanOf(st))
if err != nil {
return nil, err
}
addf("deployment-plan.yaml", "plan", pb)
for _, h := range e.Handbook(st, mr) {
addf(h.Path, "handbook", h.Content)
}
addf("README.md", "readme", []byte(readme(st)))
sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Path < out.Files[j].Path })
for _, f := range out.Files {
if !catalog.SafeRelPath(f.Path) {
return nil, fmt.Errorf("refusing unsafe output path %q", f.Path)
}
}
out.Lock = e.lock(st, s, in, out.Files)
lb, err := Marshal(out.Lock)
if err != nil {
return nil, err
}
out.Files = append(out.Files, OutFile{Path: "solution.lock.yaml", Kind: "lock", Content: lb})
return out, nil
}
// ErrIncomplete: required answers are missing or errors remain.
var ErrIncomplete = errors.New("the solution is not complete")
func incompleteText(st *State) string {
var parts []string
if len(st.Progress.Missing) > 0 {
parts = append(parts, "missing: "+strings.Join(st.Progress.Missing, ", "))
}
for _, m := range st.Messages {
if m.Severity == "error" {
parts = append(parts, m.Text)
}
}
for _, q := range st.Questions {
for _, e := range q.Errors {
parts = append(parts, q.ID+": "+e)
}
}
return strings.Join(parts, "; ")
}
func hashBytes(b []byte) string {
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
func (e *Engine) lock(st *State, s *catalog.Solution, in *Instance, files []OutFile) *Lock {
c := e.Cat
l := &Lock{APIVersion: catalog.APIVersion, Kind: "SolutionLock"}
l.Spec.Generator = GeneratorVersion
l.Spec.Catalog = Pinned{ID: c.Meta.ID, Version: c.Meta.Version, Hash: c.Hash()}
l.Spec.Solution = Pinned{ID: s.Meta.ID, Version: s.Meta.Version, Hash: s.Hash}
for _, p := range st.Packages {
if !p.Selected {
continue
}
if cp := c.Packages[p.ID]; cp != nil {
l.Spec.Packages = append(l.Spec.Packages, Pinned{ID: p.ID, Hash: cp.Hash})
}
if p.Profile != "" {
chain, _ := c.ProfileChain(p.ID, p.Profile)
for _, pr := range chain {
l.Spec.Profiles = append(l.Spec.Profiles, Pinned{ID: pr.Key(), Hash: pr.Hash})
}
}
}
var capFiles, bpFiles []string
for _, f := range c.Files {
if strings.HasPrefix(f.Path, "bigpicture:") {
bpFiles = append(bpFiles, f.Path+" "+f.Hash)
} else if strings.HasPrefix(f.Path, "capabilities") {
capFiles = append(capFiles, f.Path+" "+f.Hash)
}
}
l.Spec.Capability = hashBytes([]byte(strings.Join(capFiles, "\n")))
if len(bpFiles) > 0 {
l.Spec.BigPicture = hashBytes([]byte(strings.Join(bpFiles, "\n")))
}
ab, _ := json.Marshal(in.Spec.Parameters) // map keys are sorted by encoding/json
ob, _ := json.Marshal(in.Spec.Overrides)
l.Spec.Answers = hashBytes(append(append(ab, '\n'), ob...))
for _, f := range files {
l.Spec.Files = append(l.Spec.Files, FileHash{Path: f.Path, Hash: hashBytes(f.Content)})
}
return l
}
// LockDrift lists what changed meaning between a previous lock and now
// (LOCK-02/03): a changed solution, profile or package definition.
func LockDrift(prev, cur *Lock) []string {
var out []string
if prev.Spec.Solution.Hash != cur.Spec.Solution.Hash {
out = append(out, fmt.Sprintf("solution %s changed (%s -> %s)", cur.Spec.Solution.ID, prev.Spec.Solution.Version, cur.Spec.Solution.Version))
}
cmp := func(kind string, a, b []Pinned) {
m := map[string]string{}
for _, p := range a {
m[p.ID] = p.Hash
}
for _, p := range b {
if h, ok := m[p.ID]; !ok {
out = append(out, fmt.Sprintf("%s %s is new", kind, p.ID))
} else if h != p.Hash {
out = append(out, fmt.Sprintf("%s %s changed", kind, p.ID))
}
delete(m, p.ID)
}
for id := range m {
out = append(out, fmt.Sprintf("%s %s is no longer used", kind, id))
}
}
cmp("profile", prev.Spec.Profiles, cur.Spec.Profiles)
cmp("package", prev.Spec.Packages, cur.Spec.Packages)
if prev.Spec.Capability != cur.Spec.Capability {
out = append(out, "the capability catalog changed")
}
sort.Strings(out)
return out
}
// ReadLock reads dir/solution.lock.yaml; a missing file is (nil, nil).
func ReadLock(dir string) (*Lock, error) {
f, err := os.Open(filepath.Join(dir, "solution.lock.yaml"))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
defer f.Close()
var l Lock
if err := strict(f, &l); err != nil {
return nil, fmt.Errorf("solution.lock.yaml: %w", err)
}
return &l, nil
}
// ErrModified: a file in the output directory was changed by hand.
var ErrModified = errors.New("output directory has changes that would be overwritten")
// Write writes out into dir (CONF-05, CONF-06). Without force it refuses
// to overwrite a file that differs from what the previous lock recorded
// (a hand edit) or a file the previous generation did not write. Files of
// the previous generation that are no longer produced are removed only
// when they are unchanged.
func Write(dir string, out *Output, force bool) error {
prev, err := ReadLock(dir)
if err != nil && !force {
return err
}
known := map[string]string{}
if prev != nil {
for _, f := range prev.Spec.Files {
known[f.Path] = f.Hash
}
known["solution.lock.yaml"] = "*"
}
var conflicts []string
for _, f := range out.Files {
p := filepath.Join(dir, filepath.FromSlash(f.Path))
cur, err := os.ReadFile(p)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
h, isKnown := known[f.Path]
switch {
case h == "*":
case !isKnown && hashBytes(cur) != hashBytes(f.Content):
conflicts = append(conflicts, f.Path+" (not written by the guide)")
case isKnown && hashBytes(cur) != h:
conflicts = append(conflicts, f.Path+" (changed by hand)")
}
}
if len(conflicts) > 0 && !force {
return fmt.Errorf("%w: %s; use --force to overwrite", ErrModified, strings.Join(conflicts, ", "))
}
for _, f := range out.Files {
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, f.Content, 0o644); err != nil {
return err
}
if err := os.Rename(tmp, p); err != nil {
return err
}
}
// stale files of the previous generation
now := map[string]bool{}
for _, f := range out.Files {
now[f.Path] = true
}
if prev != nil {
for _, f := range prev.Spec.Files {
if now[f.Path] || !catalog.SafeRelPath(f.Path) {
continue
}
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if cur, err := os.ReadFile(p); err == nil && hashBytes(cur) == f.Hash {
os.Remove(p)
}
}
}
return nil
}
// Plan is the deployment plan: what an operator (or a later apply) does,
// in order. It is never executed by the engine (LIFE-01).
type Plan struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Spec PlanSpec `yaml:"spec" json:"spec"`
}
// PlanSpec lists files, steps and checks.
type PlanSpec struct {
Solution string `yaml:"solution" json:"solution"`
Instance string `yaml:"instance" json:"instance"`
Target string `yaml:"target" json:"target"`
Apply string `yaml:"apply" json:"apply"`
Packages []string `yaml:"packages" json:"packages"`
Files []string `yaml:"files" json:"files"`
Steps []PlannedStep `yaml:"steps" json:"steps"`
Checks []PlanCheck `yaml:"checks" json:"checks"`
}
// PlanCheck is a check to run after applying.
type PlanCheck struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Run string `yaml:"run,omitempty" json:"run,omitempty"`
}
// PlanOf builds the plan of a state.
func PlanOf(st *State) *Plan {
p := &Plan{APIVersion: catalog.APIVersion, Kind: "DeploymentPlan"}
p.Spec.Solution = st.Solution.ID + " " + st.Solution.Version
p.Spec.Instance = st.Instance
p.Spec.Target = firstNonEmpty(st.Platform, "local")
p.Spec.Apply = "manual: the guide does not apply plans yet; run the steps yourself (LIFE-01)"
for _, pk := range st.Packages {
if pk.Selected {
p.Spec.Packages = append(p.Spec.Packages, pk.ID)
}
}
for _, f := range st.Files {
p.Spec.Files = append(p.Spec.Files, f.Path)
}
p.Spec.Steps = st.Steps
if p.Spec.Steps == nil {
p.Spec.Steps = []PlannedStep{}
}
for _, c := range st.Checks {
if c.Status != CheckNotApplicable {
p.Spec.Checks = append(p.Spec.Checks, PlanCheck{ID: c.ID, Title: c.Title, Run: c.Run})
}
}
return p
}
func readme(st *State) string {
var b strings.Builder
fmt.Fprintf(&b, "# %s\n\n", firstNonEmpty(st.Instance, st.Solution.Title))
fmt.Fprintf(&b, "Solution: %s (`%s` %s), generated by the Yetano Solutions Guide.\n\n", st.Solution.Title, st.Solution.ID, st.Solution.Version)
b.WriteString("| Path | Content |\n|---|---|\n")
b.WriteString("| `solution.yaml` | your answers (SolutionInstance); regenerate with `yet solution generate --file solution.yaml --output .` |\n")
b.WriteString("| `solution.lock.yaml` | what this was generated from (catalog, profiles, file hashes) |\n")
b.WriteString("| `config/` | native configuration files, one directory per package |\n")
b.WriteString("| `deployment-plan.yaml` | the steps to install, configure and check it (not executed by the guide) |\n")
b.WriteString("| `architecture/` | the resolved architecture (`graph.json`, `graph.txt`) |\n")
b.WriteString("| `handbook/` | your handbook: start with `handbook/index.md` |\n\n")
b.WriteString("Nothing here has been installed or changed on any system.\n")
return b.String()
}
+138
View File
@@ -0,0 +1,138 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// phases in plan order.
var phaseOrder = map[string]int{"install": 0, "configure": 1, "data": 2, "dns": 3, "start": 4, "verify": 5}
func (ev *evaluation) steps() {
vars := ev.vars()
for _, s := range ev.s.Spec.Steps {
if len(s.When) > 0 && !s.When.Holds(ev.env) {
continue
}
if s.Package != "" && !ev.pkgSelected(s.Package) {
continue
}
if s.Package != "" && s.Module != "" && s.ForEach != "$modules" && !ev.moduleEnabled(s.Package, s.Module) {
continue
}
items := []any{nil}
switch {
case s.ForEach == "$modules":
// every enabled module of the step's package that is a program
items = nil
if cp := ev.e.Cat.Packages[s.Package]; cp != nil {
for _, m := range cp.Spec.Modules {
if m.Program != "" && ev.moduleEnabled(s.Package, m.ID) && (s.Module == "" || m.Kind == s.Module) {
items = append(items, m.Program)
}
}
}
case s.ForEach != "":
items = listOf(ev.answers[s.ForEach])
}
for i, it := range items {
v := vars
if s.ForEach != "" {
v = map[string]any{}
for k, x := range vars {
v[k] = x
}
v["item"] = it
}
run, err := expand(s.Run, v)
if err != nil {
ev.msg("error", "step", fmt.Sprintf("step %s: %v", s.ID, err), "step:"+s.ID)
continue
}
title, _ := expand(s.Title, v)
note, _ := expand(s.Note, v)
id := s.ID
if s.ForEach != "" {
id = fmt.Sprintf("%s-%d", s.ID, i+1)
}
phase := s.Phase
if phase == "" {
phase = "configure"
}
ev.st.Steps = append(ev.st.Steps, PlannedStep{
ID: id, Title: title, Phase: phase, Package: s.Package, Module: s.Module,
Run: run, Note: note, Mutating: s.Mutating, Reversible: s.Reversible, References: s.References,
})
}
}
sort.SliceStable(ev.st.Steps, func(i, j int) bool {
return phaseOrder[ev.st.Steps[i].Phase] < phaseOrder[ev.st.Steps[j].Phase]
})
}
// expand fills placeholders into a text (steps, notes). Values are
// inserted as text; steps are shown to the operator, never run.
func expand(s string, vars map[string]any) (string, error) {
if !strings.Contains(s, "${") {
return s, nil
}
var firstErr error
used := map[string]bool{}
out := placeholderRE.ReplaceAllStringFunc(s, func(m string) string {
if m == "$${" {
return "${"
}
if strings.HasPrefix(m, "${item") {
if it, ok := vars["item"]; ok {
return catalog.Scalar(it)
}
}
v, err := lookup(m, vars, used)
if err != nil && firstErr == nil {
firstErr = err
}
return shellWord(text(v))
})
return out, firstErr
}
// shellWord quotes a value for display in a command line if needed.
func shellWord(s string) string {
if s == "" {
return "''"
}
for _, r := range s {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("@%+=:,./_-", r)) {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
}
return s
}
func (ev *evaluation) checks() {
vars := ev.vars()
for _, c := range ev.s.Spec.Requirements {
r := CheckResult{ID: c.ID, Title: c.Title, Kind: c.Kind, Severity: firstNonEmpty(c.Severity, "error"),
Local: c.Local, Hint: c.Hint, References: c.References, Params: map[string]string{}}
if len(c.When) > 0 && !c.When.Holds(ev.env) {
r.Status = CheckNotApplicable
ev.st.Checks = append(ev.st.Checks, r)
continue
}
for k, v := range c.Params {
x, err := expand(v, vars)
if err != nil {
x = v
}
r.Params[k] = strings.Trim(x, "'")
}
r.Run, _ = expand(c.Run, vars)
// The engine itself never inspects a system: every check starts
// as NOT_CHECKED; a doctor runner fills in results (DR-03).
r.Status = CheckNotChecked
ev.st.Checks = append(ev.st.Checks, r)
}
}
+33
View File
@@ -0,0 +1,33 @@
package engine
import (
"os/exec"
"strings"
"testing"
)
// SEC-02: the catalog, the engine and the knowledge index never run a
// program or open a network connection; the CLI may (doctor checks).
// core/secretref links os/exec for resolving secret:// through yaseva;
// the engine only uses its Validate, so os/exec is checked on the
// packages' own imports, network packages on all dependencies.
func TestNoExecOrNetwork(t *testing.T) {
for _, pkg := range []string{"../catalog", "../engine", "../knowledge", "../ref"} {
own, err := exec.Command("go", "list", "-f", "{{join .Imports \" \"}}", pkg).Output()
if err != nil {
t.Skip("go list not available")
}
for _, dep := range strings.Fields(string(own)) {
if dep == "os/exec" || dep == "syscall" || dep == "plugin" || dep == "unsafe" {
t.Errorf("%s imports %s", pkg, dep)
}
}
all, _ := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", pkg).Output()
for _, dep := range strings.Fields(string(all)) {
switch dep {
case "net/http", "net/rpc", "net/smtp", "crypto/tls":
t.Errorf("%s depends on %s", pkg, dep)
}
}
}
}
+236
View File
@@ -0,0 +1,236 @@
package engine
import "yetano.dev/yetano/core/solutions/catalog"
// State is the complete result of evaluating an instance: everything a
// client shows. Clients never compute visibility, options or resolution
// themselves (API-02); they render a State.
type State struct {
Solution SolutionInfo `json:"solution"`
Instance string `json:"instance"`
Mode catalog.Level `json:"mode"`
Locale string `json:"locale"`
Platform string `json:"platform,omitempty"`
Questions []QuestionState `json:"questions"`
Next string `json:"next,omitempty"`
Progress Progress `json:"progress"`
Complete bool `json:"complete"`
Answers map[string]Answer `json:"answers"`
Stale []StaleAnswer `json:"stale,omitempty"`
Packages []PackageState `json:"packages"`
Capabilities []CapState `json:"capabilities"`
Rules []AppliedRule `json:"rules"`
Messages []Message `json:"messages"`
Recommended []Recommendation `json:"recommendations,omitempty"`
Files []FilePreview `json:"files"`
Steps []PlannedStep `json:"steps"`
Checks []CheckResult `json:"checks"`
Graph Graph `json:"graph"`
References []string `json:"references"`
Related []string `json:"related,omitempty"`
}
// SolutionInfo identifies the evaluated solution or task.
type SolutionInfo struct {
ID string `json:"id"`
Kind string `json:"kind"`
TaskKind string `json:"taskKind,omitempty"`
Version string `json:"version"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Status catalog.Support `json:"status"`
Category string `json:"category,omitempty"`
BigPicture string `json:"bigpicture,omitempty"`
}
// QuestionState is one question as the client shows it.
type QuestionState struct {
ID string `json:"id"`
Type string `json:"type"`
Item string `json:"item,omitempty"`
Group string `json:"group,omitempty"`
Level catalog.Level `json:"level"`
Title string `json:"title"`
Help string `json:"help,omitempty"`
Description string `json:"description,omitempty"`
Decide string `json:"decide,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Examples []string `json:"examples,omitempty"`
Visible bool `json:"visible"`
Asked bool `json:"asked"` // shown in the current mode
Required bool `json:"required"`
InstanceSpecific bool `json:"instanceSpecific,omitempty"`
Value any `json:"value,omitempty"`
Origin string `json:"origin,omitempty"` // default | preset | instance | ""
Default any `json:"default,omitempty"`
Recommended any `json:"recommended,omitempty"`
Reason string `json:"reason,omitempty"`
Options []OptionState `json:"options,omitempty"`
Errors []string `json:"errors,omitempty"`
Warnings []Message `json:"warnings,omitempty"`
References []string `json:"references,omitempty"`
}
// OptionState is one option with whether and why it can be chosen.
type OptionState struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Recommended bool `json:"recommended,omitempty"`
Reason string `json:"reason,omitempty"`
Support catalog.Support `json:"support"`
SupportNote string `json:"supportNote,omitempty"`
Enabled bool `json:"enabled"`
Disabled string `json:"disabledReason,omitempty"`
Selected bool `json:"selected"`
Adds []string `json:"adds,omitempty"` // packages/capabilities it brings in
References []string `json:"references,omitempty"`
}
// Progress counts asked questions.
type Progress struct {
Asked int `json:"asked"`
Answered int `json:"answered"`
Missing []string `json:"missing,omitempty"`
Step int `json:"step"` // 1-based index of Next among asked questions
}
// Answer is an effective answer and where it came from.
type Answer struct {
Value any `json:"value"`
Origin string `json:"origin"`
}
// StaleAnswer is an explicit answer that no longer counts (RULE-06).
type StaleAnswer struct {
Question string `json:"question"`
Value any `json:"value"`
Reason string `json:"reason"`
}
// Status values of packages, modules and capabilities in a state and a graph (BP-04).
const (
StRequired = "required"
StSelected = "selected"
StRecommended = "recommended"
StOptional = "optional"
StExternal = "external"
StAlternative = "alternative"
StDisabled = "disabled"
StUnsupported = "unsupported"
StMissing = "missing"
StConflicting = "conflicting"
StExcluded = "excluded"
)
// PackageState is a package in the resolved solution.
type PackageState struct {
ID string `json:"id"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Status string `json:"status"`
Profile string `json:"profile,omitempty"`
Reasons []string `json:"reasons"`
Modules []ModuleState `json:"modules,omitempty"`
Selected bool `json:"selected"`
}
// ModuleState is a module of a selected package.
type ModuleState struct {
ID string `json:"id"`
Title string `json:"title"`
Program string `json:"program,omitempty"`
Kind string `json:"kind,omitempty"`
Enabled bool `json:"enabled"`
Support catalog.Support `json:"support,omitempty"`
Reason string `json:"reason,omitempty"`
}
// CapState is a capability in the resolved solution.
type CapState struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
Provider string `json:"provider,omitempty"` // pkg/module or external:<id>
Alternatives []string `json:"alternatives,omitempty"`
Reasons []string `json:"reasons"`
}
// AppliedRule records a rule (or an option's effects) that fired.
type AppliedRule struct {
ID string `json:"id"`
Source string `json:"source"` // rule | option | package | capability
Effect string `json:"effect"`
Reason string `json:"reason,omitempty"`
}
// Message is a warning, error or note.
type Message struct {
Severity string `json:"severity"` // info | warning | error
Code string `json:"code"`
Text string `json:"text"`
Source string `json:"source,omitempty"`
}
// Recommendation suggests an extension.
type Recommendation struct {
Package string `json:"package,omitempty"`
Capability string `json:"capability,omitempty"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
}
// FilePreview is one generated file.
type FilePreview struct {
Path string `json:"path"`
Package string `json:"package"`
Content string `json:"content"`
Origins map[string]Origin `json:"origins"`
}
// Origin says where a configuration value came from (PROF-05).
type Origin struct {
Layer string `json:"layer"` // profile | solution | override
Source string `json:"source"` // profile:yamase/mailbox, solution:mail-server#tls, override
Params []string `json:"params,omitempty"`
}
// PlannedStep is a setup step (never executed by the engine).
type PlannedStep struct {
ID string `json:"id"`
Title string `json:"title"`
Phase string `json:"phase"`
Package string `json:"package,omitempty"`
Module string `json:"module,omitempty"`
Run string `json:"run,omitempty"`
Note string `json:"note,omitempty"`
Mutating bool `json:"mutating"`
Reversible *bool `json:"reversible,omitempty"`
References []string `json:"references,omitempty"`
}
// Check status values (DR-03).
const (
CheckPass = "PASS"
CheckInfo = "INFO"
CheckWarning = "WARNING"
CheckError = "ERROR"
CheckBlocked = "BLOCKED"
CheckNotApplicable = "NOT_APPLICABLE"
CheckNotChecked = "NOT_CHECKED"
)
// CheckResult is a requirement/doctor check and its result.
type CheckResult struct {
ID string `json:"id"`
Title string `json:"title"`
Kind string `json:"kind"`
Severity string `json:"severity"`
Local bool `json:"local"`
Params map[string]string `json:"params,omitempty"`
Run string `json:"run,omitempty"`
Hint string `json:"hint,omitempty"`
Status string `json:"status"`
Note string `json:"note,omitempty"`
References []string `json:"references,omitempty"`
}
+3
View File
@@ -0,0 +1,3 @@
interfaces: []
connections:
- {id: connection.app-idp, from: product.app, to: product.idp, type: authenticatesVia, label: signs in through, scope: general, review: confirmed}
+2
View File
@@ -0,0 +1,2 @@
title: Test Big Picture
content: {topics: topics.yaml, products: products, stories: stories, connections: connections.yaml}
+3
View File
@@ -0,0 +1,3 @@
id: product.app
name: app
summary: The test application.
+3
View File
@@ -0,0 +1,3 @@
id: product.idp
name: idp
summary: An identity provider.
+5
View File
@@ -0,0 +1,5 @@
id: story.run-app
title: Run the app
intent: I want to run the app.
outcome: The app runs.
primaryTopic: topic.t
+2
View File
@@ -0,0 +1,2 @@
topics:
- {id: topic.t, title: Testing, summary: Test topic}
+18
View File
@@ -0,0 +1,18 @@
apiVersion: yetano.dev/v1
kind: Catalog
metadata: {id: test, version: 1.0.0}
spec:
bigpicture: ../bp
webBase: https://example.test/
categories: [{id: t, topic: topic.t}]
---
apiVersion: yetano.dev/v1
kind: Capabilities
metadata: {id: caps}
spec:
capabilities:
- {id: app.serve, title: Serve the app, requires: [auth.users]}
- {id: auth.users, title: Users}
- {id: auth.sso, title: Single sign-on}
- {id: backup.files, title: Backups, external: [{id: tool, title: Your tool}]}
- {id: feature.x, title: Feature X}
+48
View File
@@ -0,0 +1,48 @@
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: app}
spec:
bigpicture: product.app
sources: [test]
modules:
- {id: server, title: Server, program: app-server, kind: daemon, provides: [app.serve]}
- {id: users, title: Local users, kind: library, provides: [auth.users], priority: 10}
- {id: extra, title: Extra, program: app-extra, kind: daemon, provides: [feature.x]}
- {id: ghost, title: Not built, support: not-implemented, provides: [auth.sso]}
---
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: idp}
spec:
bigpicture: product.idp
sources: [test]
modules:
- {id: sso, title: SSO, program: idp, kind: daemon, provides: [auth.sso, auth.users], priority: 1}
---
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: bak, summary: Backups}
spec:
sources: [test]
modules:
- {id: b, title: Backup, program: bak, provides: [backup.files], support: experimental}
---
apiVersion: yetano.dev/v1
kind: Profile
metadata: {id: base, package: app}
spec:
modules: {server: enabled, users: enabled, extra: disabled}
config:
- file: app/app.yaml
set: {log: info, listen: ":8080", limits: {max: 10, min: 1}}
---
apiVersion: yetano.dev/v1
kind: Profile
metadata: {id: big, package: app}
spec:
extends: base
modules: {extra: enabled}
config:
- file: app/app.yaml
set: {limits: {max: 100}}
- {file: app/extra.yaml, module: extra, set: {on: true}}
+60
View File
@@ -0,0 +1,60 @@
apiVersion: yetano.dev/v1
kind: Solution
metadata: {id: app-run, version: 1.0.0, category: t, status: supported}
spec:
bigpicture: story.run-app
capabilities: {required: [app.serve], recommended: [backup.files]}
packages:
- {id: app, profile: base, role: core, when: {size: small}}
- {id: app, profile: big, role: core, when: {size: big}}
questions:
- id: size
type: select
title: How big?
default: small
options:
- {id: small, title: Small, recommended: true, reason: fits most}
- {id: big, title: Big}
- {id: hosts, type: list, item: hostname, title: Host names, required: true, instanceSpecific: true, validation: {minItems: 1}}
- id: identity
type: select
title: Users?
level: guided
default: local
options:
- {id: local, title: Local}
- {id: central, title: Central IdP, requires: {packages: [idp], capabilities: [auth.sso]}}
- {id: ghost, title: Ghost, support: not-implemented, supportNote: not built}
- {id: realm, type: string, title: Realm, visibleWhen: {identity: central}, required: true}
- {id: token, type: secret, level: advanced, title: Token}
- {id: owner, type: email, level: guided, title: Owner, default: "admin@${hosts[0]}"}
- id: backup
type: select
title: Backup
level: guided
default: none
options:
- {id: none, title: None}
- {id: mine, title: My tool, provides: [backup.files]}
- {id: bak, title: bak, requires: {packages: [bak]}}
- {id: port, type: port, level: advanced, title: Port, default: 8080}
rules:
- {id: big-warn, when: {size: big}, message: Big needs more memory., severity: warning}
- {id: no-x-small, when: {size: small}, excludes: {capabilities: [feature.x]}}
configuration:
- id: main
file: app/app.yaml
set: {hosts: "${hosts}", owner: "${owner}", listen: ":${port}", first: "${hosts[0]}", n: "${hosts.count}"}
- {id: sso, file: app/app.yaml, when: {identity: central}, set: {sso: {realm: "${realm}"}}}
- {id: tok, file: app/app.yaml, when: {token: {set: true}}, set: {token: "${token}"}}
- {id: idp, file: idp/idp.yaml, set: {realm: "${realm}"}, when: {identity: central}}
- {id: never, file: bak/bak.yaml, set: {x: 1}}
steps:
- {id: add, title: "Add ${item}", forEach: hosts, run: "app add ${item}", phase: data, mutating: true}
- {id: inst, title: "Install ${item}", package: app, forEach: $modules, run: "yet install ${item}", phase: install}
requirements:
- {id: port, title: Port free, kind: port, params: {port: "${port}"}, local: true}
- {id: bigonly, title: Memory, kind: manual, when: {size: big}}
architecture:
nodes: [{id: users, type: client, title: "Users of ${hosts[0]}"}]
edges: [{from: users, to: "mod:app/server", type: connectsTo}]
+306
View File
@@ -0,0 +1,306 @@
package engine
import (
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"yetano.dev/yetano/core/secretref"
"yetano.dev/yetano/core/solutions/catalog"
)
// MaxAnswerLen bounds a single text answer (SEC-03).
const MaxAnswerLen = 64 << 10
var (
hostnameRE = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
emailRE = regexp.MustCompile(`^[^@\s]+@[^@\s]+$`)
dateRE = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
)
// TypeValidator checks and normalizes one scalar answer of a type. New
// question types are added with RegisterType (WIZ-04).
type TypeValidator func(v any) (any, error)
var extraTypes = map[string]TypeValidator{}
// RegisterType adds a question type. It must be called before catalogs
// using the type are validated; built-in types cannot be replaced.
func RegisterType(name string, fn TypeValidator) error {
if catalog.QuestionTypes[name] {
return fmt.Errorf("type %q is built in", name)
}
extraTypes[name] = fn
catalog.QuestionTypes[name] = true
return nil
}
// Normalize converts an answer given as text (CLI --set, interactive
// input) or as decoded YAML/JSON into the canonical value for the
// question and validates it. It does not check option enablement.
func Normalize(q *catalog.Question, v any) (any, error) {
switch q.Type {
case "multiselect", "list":
items := listOf(v)
out := make([]any, 0, len(items))
seen := map[string]bool{}
for _, it := range items {
var n any
var err error
if q.Type == "multiselect" {
n, err = optionValue(q, it)
} else {
n, err = scalar(q.Item, it)
}
if err != nil {
return nil, err
}
k := catalog.Scalar(n)
if seen[k] {
continue
}
seen[k] = true
out = append(out, n)
}
if err := checkCount(q.Validation, len(out)); err != nil {
return nil, err
}
return out, nil
case "select":
return optionValue(q, v)
case "keyvalue":
m, ok := v.(map[string]any)
if !ok {
s, isStr := v.(string)
if !isStr {
return nil, fmt.Errorf("want key=value pairs")
}
m = map[string]any{}
for _, part := range splitList(s) {
k, val, ok := strings.Cut(part, "=")
if !ok || strings.TrimSpace(k) == "" {
return nil, fmt.Errorf("%q: want key=value", part)
}
m[strings.TrimSpace(k)] = strings.TrimSpace(val)
}
}
return m, nil
}
n, err := scalar(q.Type, v)
if err != nil {
return nil, err
}
return n, checkValue(q.Validation, n)
}
func optionValue(q *catalog.Question, v any) (any, error) {
s := strings.TrimSpace(catalog.Scalar(v))
for _, o := range q.Options {
if o.ID == s {
return o.ID, nil
}
}
// a number picks the n-th option (interactive CLI)
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= len(q.Options) {
return q.Options[n-1].ID, nil
}
ids := make([]string, len(q.Options))
for i, o := range q.Options {
ids[i] = o.ID
}
return nil, fmt.Errorf("%q is not one of %s", s, strings.Join(ids, ", "))
}
func listOf(v any) []any {
switch x := v.(type) {
case []any:
return x
case []string:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
case string:
var out []any
for _, p := range splitList(x) {
out = append(out, p)
}
return out
case nil:
return nil
}
return []any{v}
}
func splitList(s string) []string {
var out []string
for _, p := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' || r == ';' }) {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// scalar validates one value of a scalar type.
func scalar(typ string, v any) (any, error) {
if fn, ok := extraTypes[typ]; ok {
return fn(v)
}
if b, ok := v.(bool); ok && typ == "boolean" {
return b, nil
}
s := strings.TrimSpace(catalog.Scalar(v))
if len(s) > MaxAnswerLen || !utf8.ValidString(s) {
return nil, fmt.Errorf("value too long or not UTF-8")
}
switch typ {
case "boolean":
switch strings.ToLower(s) {
case "true", "yes", "y", "on", "1", "ja", "j":
return true, nil
case "false", "no", "n", "off", "0", "nein":
return false, nil
}
return nil, fmt.Errorf("%q: want yes or no", s)
case "integer":
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a whole number", s)
}
return int(n), nil
case "decimal":
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a number", s)
}
return f, nil
case "port":
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > 65535 {
return nil, fmt.Errorf("%q: want a port 1-65535", s)
}
return n, nil
case "hostname", "domain":
s = strings.ToLower(strings.TrimSuffix(s, "."))
if !hostnameRE.MatchString(s) || len(s) > 253 {
return nil, fmt.Errorf("%q: not a valid %s", s, typ)
}
if typ == "domain" && !strings.Contains(s, ".") {
return nil, fmt.Errorf("%q: a domain needs a dot (example.org)", s)
}
return s, nil
case "email":
if !emailRE.MatchString(s) {
return nil, fmt.Errorf("%q: not an e-mail address", s)
}
return s, nil
case "ip":
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not an IP address", s)
}
return s, nil
case "cidr":
if _, _, err := net.ParseCIDR(s); err != nil {
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not a network (CIDR) or address", s)
}
}
return s, nil
case "url":
u, err := url.Parse(s)
if err != nil || u.Scheme == "" || u.Host == "" {
return nil, fmt.Errorf("%q: not a URL", s)
}
return s, nil
case "duration":
if _, err := time.ParseDuration(s); err != nil {
return nil, fmt.Errorf("%q: want a duration like 30s, 5m, 4h", s)
}
return s, nil
case "date":
if !dateRE.MatchString(s) {
return nil, fmt.Errorf("%q: want YYYY-MM-DD", s)
}
if _, err := time.Parse("2006-01-02", s); err != nil {
return nil, fmt.Errorf("%q: not a date", s)
}
return s, nil
case "path", "dir":
if s == "" || strings.ContainsRune(s, 0) {
return nil, fmt.Errorf("want a path")
}
return s, nil
case "secret":
// SEC-01/WIZ-07: only references, never the secret itself.
if err := secretref.Validate(s); err != nil || s == "" {
return nil, fmt.Errorf("give a reference (secret://name, env:VAR, file:path), never the secret itself")
}
return s, nil
case "string", "text", "package", "profile", "capability", "provider", "target":
return s, nil
}
return nil, fmt.Errorf("unknown type %q", typ)
}
func checkValue(val catalog.Validation, v any) error {
msg := func(err string) error {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("%s", err)
}
if f, ok := v.(float64); ok {
return checkRange(val, f, msg)
}
if n, ok := v.(int); ok {
return checkRange(val, float64(n), msg)
}
if s, ok := v.(string); ok {
if val.MinLength > 0 && len(s) < val.MinLength {
return msg(fmt.Sprintf("at least %d characters", val.MinLength))
}
if val.MaxLength > 0 && len(s) > val.MaxLength {
return msg(fmt.Sprintf("at most %d characters", val.MaxLength))
}
if val.Pattern != "" {
re, err := regexp.Compile(val.Pattern)
if err != nil {
return fmt.Errorf("bad pattern in catalog: %v", err)
}
if !re.MatchString(s) {
return msg(fmt.Sprintf("%q does not match %s", s, val.Pattern))
}
}
}
return nil
}
func checkRange(val catalog.Validation, f float64, msg func(string) error) error {
if val.Min != nil && f < *val.Min {
return msg(fmt.Sprintf("at least %v", *val.Min))
}
if val.Max != nil && f > *val.Max {
return msg(fmt.Sprintf("at most %v", *val.Max))
}
return nil
}
func checkCount(val catalog.Validation, n int) error {
if val.MinItems > 0 && n < val.MinItems {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("at least %d item(s)", val.MinItems)
}
if val.MaxItems > 0 && n > val.MaxItems {
return fmt.Errorf("at most %d item(s)", val.MaxItems)
}
return nil
}
+28
View File
@@ -0,0 +1,28 @@
package engine
import (
"os"
"testing"
)
func TestZZDump(t *testing.T) {
if os.Getenv("DUMP") == "" {
t.Skip()
}
c := assetsCatalog(t)
e := New(c)
x := c.Examples[os.Getenv("DUMP")]
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
in.Spec.Parameters = x.Spec.Parameters
st, _ := e.Evaluate(in, nil)
for _, f := range st.Files {
t.Logf("=== %s\n%s", f.Path, f.Content)
}
for _, s := range st.Steps {
t.Logf("step %s [%s] %s", s.Phase, s.Run, s.Title)
}
for _, p := range st.Packages {
t.Logf("pkg %s %s %v", p.ID, p.Status, p.Reasons)
}
t.Log(GraphText(st.Graph))
}