Files
mesh-host/internal/agent/composition.go
T
jschoubben 1c32872fcc H-A-374: set a drifted directory the mesh made right at the engine's start
ace's Node toolchain cache directory stood at 0700 against its entry's 0711
while the engine said its composition was unchanged: an unchanged
composition is never applied, and the judgement reads the compositions, not
the disk. Each module taken as running at the engine's start now has every
directory entry its record says the mesh made given its declared owner and
mode where they drifted on disk, one journal line each; one the mesh never
made stays used as found and is said (issue 339). The verb composition's
diff names a drifted directory the mesh made. The agent test that marks
modules not composed now waits for every want it marks.

Builds: design 47 H2 §813; H-A-374, H-A-392
2026-11-22 00:26:18 +01:00

515 lines
20 KiB
Go

package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
engcomp "github.com/novox/mesh-host/internal/compositions"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/judge"
)
// The node-engine seat's read verb composition (issue 774): one module's composition beside what runs of it, so why a
// record module waits for a yes, or what its next apply would change, is read from the engine and not guessed from its
// have's words. It changes nothing.
// CompositionView is what the verb composition answers.
type CompositionView struct {
Node string `json:"node"`
Module string `json:"module"`
// Want is the module's want as the agent holds it; nil when it holds none.
Want *WantView `json:"want,omitempty"`
// Attempt is what the agent holds of the module's last apply that did not end running: failed, failed for a moment
// of the bus, or held for a failed backup, with the want's revision that hold took as answered; nil when none
// (issue 1585: why a module stays held was not readable from the engine).
Attempt *AttemptView `json:"attempt,omitempty"`
// Started says the agent has looked at the module once since it started (its baseline): what runs was taken from its
// have, or it was applied.
Started bool `json:"started"`
// Have is what the module's have key says now; nil when it says nothing.
Have *HaveView `json:"have,omitempty"`
// Composition is the revision read: the latest of the want's build, or the one whose digest was asked.
Composition RevisionView `json:"composition"`
// Revisions are the revisions of its key the bucket keeps, oldest first, each with its digest.
Revisions []RevisionView `json:"revisions,omitempty"`
// Runs is what runs of the module, and where that is known from; nil when nothing of it runs.
Runs *RunsView `json:"runs,omitempty"`
// RunsManifest is the manifest of the build that runs of the module, as the one place reads it (design 47 G A-484): which
// source answered, or the words naming the three it tried. Said also where the want's build has no composition.
RunsManifest *RunsManifestView `json:"runs-manifest,omitempty"`
// Judged is the move from what runs to the composition read, as the agent judges it before an apply.
Judged JudgedView `json:"judged"`
// Diff is every resource that differs from what runs, when asked.
Diff []judge.ResourceChange `json:"diff,omitempty"`
// Drift is, when the diff is asked, each directory entry of what runs that the mesh made, as its record holds, whose
// owner or mode on disk differ from it (H-A-374, H-A-392): read-only; the engine sets it right at its next start or
// apply of the module.
Drift []DriftView `json:"drift,omitempty"`
// Own is, of the node's own composition (module node), its own fields beside what runs names (issue 774: ace's
// own composition dropped the provisioner client's account, and nothing read could show it).
Own *OwnView `json:"own,omitempty"`
// Withheld are the module's marked subjects the grants part withholds from this node's runtime, each with why, read
// through the seat mesh-grants' verb withheld; WithheldUnknown says when that verb did not answer (design 46 approval
// mark §6, lead answer A-239).
Withheld []WithheldView `json:"withheld,omitempty"`
WithheldUnknown string `json:"withheld-unknown,omitempty"`
// WithheldParts are the parts a compose kept because its read did not answer, each with why (design 08 control-verbs §4,
// H-A-321): for the packet filter's holder the part node-packet-filter.allowed, its filter file kept as it runs.
WithheldParts []WithheldPartView `json:"withheld-parts,omitempty"`
}
// WithheldPartView is one part a compose kept because its read did not answer, and why.
type WithheldPartView struct {
Part string `json:"part"`
Why string `json:"why"`
}
// WithheldView is one marked subject withheld, and why.
type WithheldView struct {
Subject string `json:"subject"`
Why string `json:"why"`
}
// OwnView is the node's own fields of a composition (engcomp.NodeOwn) beside what runs of them, and what the node's
// composer held in its last pass.
type OwnView struct {
// Provisioner is the account the provisioner's client runs as, as the revision read names it; RunsProvisioner as
// what runs names it. Empty: the declaration names none, and every filled write is refused.
Provisioner string `json:"provisioner_account"`
RunsProvisioner string `json:"runs_provisioner_account,omitempty"`
// Adoption is the revision's adoption: the node adopted, and which of its modules are taken; nil for a converged node.
Adoption *declaration.Adoption `json:"adoption,omitempty"`
// Identities, Groups and Libraries count what the revision names of each.
Identities int `json:"identities,omitempty"`
Groups int `json:"groups,omitempty"`
Libraries int `json:"libraries,omitempty"`
// Held is each module the node's composer held in its last pass, with why.
Held map[string]string `json:"held,omitempty"`
}
// WantView is a want as the verb shows it: as the agent holds it, at the revision of its key it last read.
type WantView struct {
FP string `json:"fp"`
Composed string `json:"composed,omitempty"`
Yes string `json:"yes,omitempty"`
Removed bool `json:"removed,omitempty"`
// Self says the node composes the module itself (ADR 0547 §2).
Self bool `json:"self,omitempty"`
// Backup is the operator's answer to a failed backup the want carries, again or skip (ADR 0539 §16); empty when none.
Backup string `json:"backup,omitempty"`
Words string `json:"words,omitempty"`
// Revision is the revision of the want's key the agent read last.
Revision uint64 `json:"revision"`
}
// AttemptView is the agent's record of a module's last apply that did not end running.
type AttemptView struct {
FP string `json:"fp"`
Composed string `json:"composed,omitempty"`
// WantRevision and CompositionRevision are the revisions of the want's and the composition's keys it was tried at.
WantRevision uint64 `json:"want_revision"`
CompositionRevision uint64 `json:"composition_revision"`
// Held says it is held for a failed backup; AnsweredRevision is the want's revision the hold took, so an answer
// (again or skip) in a later revision releases it.
Held bool `json:"held,omitempty"`
AnsweredRevision uint64 `json:"answered_revision,omitempty"`
// Transient says it failed because the bus did not answer for a moment, and is tried again by the clock.
Transient bool `json:"transient,omitempty"`
}
// HaveView is a have as the verb shows it.
type HaveView struct {
FP string `json:"fp,omitempty"`
Composed string `json:"composed,omitempty"`
Phase string `json:"phase"`
Detail string `json:"detail,omitempty"`
Judgement string `json:"judgement,omitempty"`
Waits string `json:"waits,omitempty"`
}
// RevisionView is one revision of a composition key.
type RevisionView struct {
Key string `json:"key"`
Revision uint64 `json:"revision,omitempty"`
Digest string `json:"digest,omitempty"`
Resources int `json:"resources,omitempty"`
Latest bool `json:"latest,omitempty"`
// Refused is why the revision cannot be read or trusted.
Refused string `json:"refused,omitempty"`
}
// RunsView is what runs of a module.
type RunsView struct {
FP string `json:"fp,omitempty"`
Composed string `json:"composed,omitempty"`
Phase string `json:"phase,omitempty"`
// From is applied (what this engine applied), have (what its have named at the start) or kept (the declaration the
// node kept before the switch).
From string `json:"from"`
Resources int `json:"resources"`
}
// RunsManifestView is what the one place answers of the build a module runs here.
type RunsManifestView struct {
// Source is the source that answered; empty when none did.
Source string `json:"source,omitempty"`
FP string `json:"fp,omitempty"`
Words string `json:"words"`
}
// JudgedView is a move's judgement.
type JudgedView struct {
Judgement string `json:"judgement"`
Words string `json:"words"`
// WaitsForYes says the agent would wait for a person's yes before applying it: a module of policy record, a move that
// recreates a container, moves data or cannot be judged, and no yes in its want for this digest.
WaitsForYes bool `json:"waits_for_yes"`
}
// Composition reads one module's composition beside what runs of it: the want's build (else the have's), its latest
// revision or the one whose digest is given, and the move's judgement; with diff, the resources that differ.
func (a *Agent) Composition(ctx context.Context, module, digest string, diff bool) (CompositionView, error) {
if module == "" {
return CompositionView{}, errors.New("name the module, or node for the node's own composition")
}
view := CompositionView{Node: a.env.Node, Module: module}
var have *Have
if a.env.Haves != nil {
if h, ok := a.env.Haves.Read(ctx, module); ok {
have = &h
phase := h.Phase
if phase == "" {
phase = string(nodeengineclient.PhaseRunning)
}
view.Have = &HaveView{FP: h.FP, Composed: h.Composed, Phase: phase, Detail: h.Detail, Judgement: h.Judgement, Waits: h.Waits}
}
}
a.mu.Lock()
w := a.wants[module]
fp := ""
if w.Present {
fp = w.Want.Fp
view.Want = &WantView{FP: w.Want.Fp, Composed: w.Composed, Yes: w.Want.Yes, Removed: w.Want.Removed,
Self: w.Want.Self, Backup: w.Want.Backup, Words: w.Want.Words, Revision: w.Rev}
} else if have != nil {
fp = have.FP
}
if att, ok := a.attempt[module]; ok {
view.Attempt = &AttemptView{FP: att.FP, Composed: att.Composed, WantRevision: att.WantRev, CompositionRevision: att.CompRev,
Held: att.Held, AnsweredRevision: att.AnsweredRev, Transient: att.Transient}
}
view.Started = a.checked[module]
latest, haveLatest := a.compositionFor(module, fp)
r, ran := a.running[module]
from, known := a.runningComposition(module)
source := "applied"
if _, ok := a.applied[module]; !ok {
if _, ok := a.had[module]; ok {
source = "have"
} else {
source = "kept"
}
}
a.mu.Unlock()
// Read outside the lock: the one place reads what the agent runs (Agent.Running takes it), and nothing it does is asked of the bus.
if a.env.RunningManifest != nil && module != NodeModule {
src, rfp, words := a.env.RunningManifest(module)
view.RunsManifest = &RunsManifestView{Source: src, FP: rfp, Words: words}
}
if module != NodeModule && fp == "" {
return view, fmt.Errorf("%s has no want and no have on %s, so no build of it is composed here", module, a.env.Node)
}
key, err := a.compositionKey(module, fp)
if err != nil {
return view, err
}
revs, err := a.revisionsOf(ctx, key)
if err != nil {
return view, fmt.Errorf("the revisions of %s cannot be read: %w", key, err)
}
var read *compNow
for i := range revs {
c := revs[i]
rv := RevisionView{Key: key, Revision: c.Rev, Digest: c.Dig, Resources: len(c.C.Resources),
Latest: haveLatest && c.Rev == latest.Rev}
if c.Err != nil {
rv.Refused = c.Err.Error()
}
view.Revisions = append(view.Revisions, rv)
if digest != "" && c.Err == nil && c.Dig == digest {
read = &revs[i]
}
}
switch {
case digest != "" && read == nil && haveLatest && latest.Err == nil && latest.Dig == digest:
read = &latest
case digest != "" && read == nil:
return view, fmt.Errorf("no revision of %s the bucket keeps has the digest %s; revisions lists those it keeps", key, digest)
case read == nil && !haveLatest:
// What runs of the module is still said, through the one place (A-484): the composition read is the want's build, and a
// module held at another build has none of it.
words := fmt.Sprintf("the bucket holds no composition of %s at %s", module, fp)
if a.env.SelfComposed && a.env.WhyUnmade != nil && module != NodeModule {
if why := a.env.WhyUnmade(module); why != "" {
words = fmt.Sprintf("the bucket holds no composition of %s at %s; the agent waits for the composer: %s", module, fp, why)
}
}
if view.RunsManifest == nil {
return view, errors.New(words)
}
view.Composition = RevisionView{Key: key, Refused: words}
return view, nil
case read == nil:
read = &latest
}
view.Composition = RevisionView{Key: key, Revision: read.Rev, Digest: read.Dig, Resources: len(read.C.Resources),
Latest: haveLatest && read.Rev == latest.Rev}
if read.Err != nil {
view.Composition.Refused = read.Err.Error()
return view, nil
}
var running *engcomp.Composed
if known {
running = &from
rv := &RunsView{From: source, Resources: len(from.Resources), FP: from.FP}
if ran {
rv.FP, rv.Composed, rv.Phase = r.Fp, r.Composed, string(r.Phase)
}
view.Runs = rv
}
if module == NodeModule {
o := read.C.Own
view.Own = &OwnView{Provisioner: o.Provisioner, Adoption: o.Adoption, Identities: len(o.Identities), Groups: len(o.Groups),
Libraries: len(o.Libraries)}
if running != nil {
view.Own.RunsProvisioner = running.Own.Provisioner
}
if a.env.Held != nil {
view.Own.Held = a.env.Held()
}
}
j := judge.JudgeMove(running, read.C)
view.Judged = JudgedView{Judgement: string(j.Judgement), Words: j.Words}
if a.env.SelfComposed && a.env.Policy != nil && module != NodeModule && (!w.Present || w.Want.Yes != read.Dig) {
switch j.Judgement {
case nodeengineclient.JudgedRecreates, nodeengineclient.JudgedMovesData, nodeengineclient.JudgedCannot:
view.Judged.WaitsForYes = a.env.Policy(ctx, module) == catalogue.PolicyRecord
}
}
if diff {
view.Diff = judge.ChangedResources(running, read.C)
if running != nil && a.env.DirectoryDrift != nil {
view.Drift = a.env.DirectoryDrift(*running)
}
}
return view, nil
}
// compositionKey is a module's composition key at a build, or the node's own.
func (a *Agent) compositionKey(module, fp string) (string, error) {
if module == NodeModule {
return engcomp.NodeKey(a.env.Node)
}
return engcomp.Key(a.env.Node, module, fp)
}
// revisionsOf is every revision of a composition key the state keeps, oldest first, each with its digest (unsigned, ADR
// 0593 §6), or why it is refused. Nil Revisions
// reads none.
func (a *Agent) revisionsOf(ctx context.Context, key string) ([]compNow, error) {
if a.env.Revisions == nil {
return nil, nil
}
revs, err := a.env.Revisions(ctx, key)
if err != nil {
return nil, err
}
var out []compNow
for _, u := range revs {
if u.Deleted || u.Key != key {
continue
}
c, err := engcomp.Decode(u.Value)
if err != nil {
out = append(out, compNow{Raw: u.Value, Rev: u.Revision, Err: err})
continue
}
dig, err := engcomp.DigestOf(c) // unsigned: a record, never verified (ADR 0593 §6)
out = append(out, compNow{Raw: u.Value, C: c, Dig: dig, Rev: u.Revision, Err: err})
}
return out, nil
}
// DriftView is one directory entry the mesh made whose owner or mode on disk differ from it, as the verb composition's
// diff names it (H-A-392): its id, its path and how, in words.
type DriftView struct {
ID string `json:"id"`
Path string `json:"path"`
Drift string `json:"drift"`
}
// CompositionDiff answers the node-engine seat's read verb composition-diff (design 47 H2 §813 (3), H-A-349 DQ-12b): one
// module's composition that runs beside another revision of its composition key, given by its revision or its digest,
// as the entries that differ per resource; environment entries by name, a secret's value masked. It changes nothing.
func (a *Agent) CompositionDiff(ctx context.Context, module string, revision int64, digest string) (nodeengine.CompositionDiffAnswer, error) {
answer := nodeengine.CompositionDiffAnswer{Node: a.env.Node, Module: module, Resources: []nodeengine.CompositionDiffResource{}}
switch {
case module == "":
return answer, errors.New("name the module, or node for the node's own composition")
case (revision == 0) == (digest == ""):
return answer, errors.New("give the revision or the digest of the composition to compare with, one of the two")
}
a.mu.Lock()
fp := ""
if w := a.wants[module]; w.Present {
fp = w.Want.Fp
}
running, known := a.runningComposition(module)
a.mu.Unlock()
if fp == "" && known {
fp = running.FP
}
if module != NodeModule && fp == "" {
return answer, fmt.Errorf("%s has no want and nothing runs of it on %s, so no composition of it is kept here", module, a.env.Node)
}
key, err := a.compositionKey(module, fp)
if err != nil {
return answer, err
}
revs, err := a.revisionsOf(ctx, key)
if err != nil {
return answer, fmt.Errorf("the revisions of %s cannot be read: %w", key, err)
}
var other *compNow
for i := range revs {
if (revision != 0 && revs[i].Rev == uint64(revision)) || (digest != "" && revs[i].Err == nil && revs[i].Dig == digest) {
other = &revs[i]
}
}
if other == nil {
return answer, fmt.Errorf("no revision of %s the bucket keeps is the one asked; composition lists those it keeps", key)
}
answer.Other = &nodeengine.Revision{Key: key, Revision: int64(other.Rev), Digest: other.Dig, Resources: int64(len(other.C.Resources)),
Latest: other.Rev == revs[len(revs)-1].Rev}
if other.Err != nil {
answer.Other.Refused = other.Err.Error()
return answer, nil
}
var from []json.RawMessage
if known {
from = running.Resources
if answer.Running, err = engcomp.DigestOf(running); err != nil {
return answer, fmt.Errorf("the composition that runs of %s has no digest: %w", module, err)
}
}
answer.Resources = DiffResources(from, other.C.Resources)
return answer, nil
}
// DiffResources is, per resource by its id, the entries that differ from running to other (design 47 H2 §813 (3)): each
// top-level field by its name, the environment's entries each by `env.<name>`, and a value the declaration keeps secret
// (a file's sealed, vault-sealed or secrets, and the content of a file that has any of them) masked. Resources in id
// order, entries in name order; none that is the same in both.
func DiffResources(running, other []json.RawMessage) []nodeengine.CompositionDiffResource {
was, now := entriesByID(running), entriesByID(other)
ids := map[string]bool{}
for id := range was {
ids[id] = true
}
for id := range now {
ids[id] = true
}
out := []nodeengine.CompositionDiffResource{}
for _, id := range slices.Sorted(maps.Keys(ids)) {
w, n := was[id], now[id]
names := map[string]bool{}
for k := range w.values {
names[k] = true
}
for k := range n.values {
names[k] = true
}
var entries []nodeengine.CompositionDiffEntry
for _, name := range slices.Sorted(maps.Keys(names)) {
rv, rok := w.values[name]
ov, ook := n.values[name]
if rok == ook && rv == ov {
continue
}
e := nodeengine.CompositionDiffEntry{Name: name}
if w.secret[name] || n.secret[name] {
e.Masked = true
} else {
e.Running, e.Other = rv, ov
}
entries = append(entries, e)
}
if len(entries) > 0 {
out = append(out, nodeengine.CompositionDiffResource{Resource: id, Entries: entries})
}
}
return out
}
// resourceEntries are one resource's entries by name, as text, and which of them hold a secret.
type resourceEntries struct {
values map[string]string
secret map[string]bool
}
// secretFields are the fields of a resource the declaration keeps secret (declaration.File.Secret, its Secrets).
var secretFields = []string{"sealed", "vault-sealed", "secrets"}
func entriesByID(resources []json.RawMessage) map[string]resourceEntries {
out := map[string]resourceEntries{}
for _, raw := range resources {
var fields map[string]json.RawMessage
if json.Unmarshal(raw, &fields) != nil {
continue
}
var id string
_ = json.Unmarshal(fields["id"], &id)
r := resourceEntries{values: map[string]string{}, secret: map[string]bool{}}
hasSecret := false
for _, f := range secretFields {
if _, ok := fields[f]; ok {
hasSecret = true
}
}
for name, value := range fields {
if name == "env" {
var env map[string]string
if json.Unmarshal(value, &env) == nil {
for k, v := range env {
r.values["env."+k] = v
}
continue
}
}
r.values[name] = entryText(value)
if slices.Contains(secretFields, name) || (hasSecret && name == "content") {
r.secret[name] = true
}
}
out[id] = r
}
return out
}
// entryText is a field's value as the answer says it: a string as itself, anything else as its JSON.
func entryText(value json.RawMessage) string {
var s string
if json.Unmarshal(value, &s) == nil {
return s
}
return string(value)
}