Design 47 H2's corrections: the owner pass with units stopped, MESH_FINGERPRINT for daemons (issue 1984) #259

Merged
mesh-tools merged 13 commits from feat/47-H2-corrections into main 2026-11-25 20:11:48 +00:00
28 changed files with 766 additions and 85 deletions
+7 -1
View File
@@ -1044,7 +1044,13 @@ func runLink(ctx context.Context, opts options) error {
}
ctx, cancel := context.WithTimeout(context.Background(), lookBound)
defer cancel()
return processbuilds.Reader{Node: mine.Node, Run: processbuilds.Runner(opts.run())}.Read(ctx, d, module), nil
have := func(ctx context.Context, module string) string {
if ag := current.get(); ag != nil {
return ag.HaveFingerprint(ctx, module)
}
return ""
}
return processbuilds.Reader{Node: mine.Node, Run: processbuilds.Runner(opts.run()), Have: have}.Read(ctx, d, module), nil
}
queue.Acts.Converged = func() (any, error) {
return convergedOf(opts.state, func() ([]string, error) { return outward.Links("", "") })
+9 -4
View File
@@ -281,7 +281,7 @@ func awaitBackup(ctx context.Context, events <-chan []byte, node, module string,
// its processes written again where it lacks its node's name (H-A-713), one line each.
func takenAtStartIn(opts options, say func(string)) func(module string, runs compositions.Composed) {
return func(module string, runs compositions.Composed) {
for _, line := range convergeDirectories(opts.state, runs) {
for _, line := range convergeDirectories(context.Background(), opts, runs) {
say(line)
}
for _, line := range convergeUnits(context.Background(), opts, runs) {
@@ -322,16 +322,21 @@ func convergeUnits(ctx context.Context, opts options, runs compositions.Composed
// convergeDirectories gives each directory entry of runs that this node's record holds, drifted on disk, its declared
// owner and mode (apply.ConvergeDirectories, H-A-374, H-A-392): one line per directory, and one when the record or the
// composition does not read.
func convergeDirectories(statePath string, runs compositions.Composed) []string {
func convergeDirectories(ctx context.Context, opts options, runs compositions.Composed) []string {
d, err := declarationOf(runs)
if err != nil {
return []string{fmt.Sprintf("the directories of %s are not judged at this start: its composition does not read: %v", runs.Module, err)}
}
known, err := store.Load(statePath)
known, err := store.Load(opts.state)
if err != nil {
return []string{fmt.Sprintf("the directories of %s are not judged at this start: %v", runs.Module, err)}
}
return apply.ConvergeDirectories(d, known)
// Read only where a pass needs its units stopped: a host that is not built for a system says so there.
built, builtErr := system.For(builtFor)
if builtErr != nil {
built = nil
}
return apply.ConvergeDirectories(ctx, built, d, known, opts.run())
}
// declarationOf is the declaration the compositions make together: their resources, and the node's own parts when the
+17 -4
View File
@@ -936,7 +936,8 @@ func mustComposedKey(t *testing.T, module, fp string) string {
// of it (issue 774): what the bus server's container met is read from it, never from a real runtime.
type recordingRuntime struct {
mu sync.Mutex
containers map[string]string // name: the spec label it was made with
containers map[string]string // name: the spec label it was made with
envs map[string][]string // name: the env it was made with (--env), as `{{json .Config.Env}}` answers it
asked []string
}
@@ -956,6 +957,10 @@ func (r *recordingRuntime) run(_ context.Context, name string, args ...string) (
if !ok {
return "", errors.New("no such container")
}
if strings.Contains(strings.Join(args, " "), ".Config.Env") {
raw, _ := json.Marshal(r.envs[args[len(args)-1]])
return string(raw) + "\n", nil
}
return "true\t" + spec + "\n", nil
}
case "image":
@@ -968,18 +973,25 @@ func (r *recordingRuntime) run(_ context.Context, name string, args ...string) (
if spec, ok := r.containers[args[1]]; ok {
delete(r.containers, args[1])
r.containers[args[2]] = spec
r.envs[args[2]] = r.envs[args[1]]
delete(r.envs, args[1])
}
case "run", "create":
var made, spec string
var env []string
for i, a := range args {
if a == "--name" && i+1 < len(args) {
made = args[i+1]
}
if a == "--env" && i+1 < len(args) {
env = append(env, args[i+1])
}
if a == "--label" && i+1 < len(args) && strings.HasPrefix(args[i+1], "mesh-host.spec=") {
spec = strings.TrimPrefix(args[i+1], "mesh-host.spec=")
}
}
r.containers[made] = spec
r.envs[made] = env
return "made\n", nil
}
return "", nil
@@ -1011,7 +1023,7 @@ func (r *recordingRuntime) moved(container string) []string {
// backup seat to back it up, as for every module that keeps data, and applies only once the backup says it is done.
func TestNatsTheBusServerIsTakenOverAndReplacedOnlyWhenItsBuildChangesIt(t *testing.T) {
b := newItBed(t)
runtime := &recordingRuntime{containers: map[string]string{}}
runtime := &recordingRuntime{containers: map[string]string{}, envs: map[string][]string{}}
b.opts.runner = runtime.run
const server = "mesh-broker-it"
conf := filepath.Join(b.dir, "nats.conf")
@@ -1025,8 +1037,9 @@ func TestNatsTheBusServerIsTakenOverAndReplacedOnlyWhenItsBuildChangesIt(t *test
folded, err := declaration.Parse([]byte(`{"declaration":1,"resources":[` +
`{"id":"nats.server-conf","type":"file","path":"` + conf + `","mode":"0644","content":"listen: old\n"},` +
`{"id":"nats.server","type":"container","name":"` + server + `","image":"` + image + `",` +
// As the node-engine starts every container since the fingerprint handover (47/G W13.1): the fingerprint of the
// want it applies, here the first want's, so that want changes the server's spec in nothing.
// As the node-engine started every container from the fingerprint handover (47/G W13.1) to H2: the fingerprint of the
// want it applies, here the first want's. A container is handed none since H2, so the first want, which composes
// the server with none, finds its label differing by that value alone and moves nothing (H-A-710 (2)).
`"env":{"MESH_FINGERPRINT":"` + fpIt("e") + `"}}]}`))
if err != nil {
t.Fatal(err)
+3
View File
@@ -25,6 +25,9 @@ func TestTheNodeAgentsStopStopsAModuleAndRemovesNothing(t *testing.T) {
var asked []string
opts := options{state: path, runner: func(_ context.Context, name string, args ...string) (string, error) {
asked = append(asked, name+" "+strings.Join(args, " "))
if len(args) > 1 && args[0] == "container" && args[1] == "inspect" {
return "true\t\n", nil // found running: a container found stopped is not stopped (H-A-752)
}
return "", nil
}}
if res := stopComposition(context.Background(), opts, "app"); res.Failed {
+14
View File
@@ -977,6 +977,20 @@ func (a *Agent) Running() []compositions.Composed {
return out
}
// HaveFingerprint is the fingerprint the have of module names, the want's build the node-engine applied it from, and empty
// when its have names none or cannot be read: a container is handed no fingerprint, so this is the build the seat's
// process-builds answers for it (design 47 H2, H-A-710 (4)).
func (a *Agent) HaveFingerprint(ctx context.Context, module string) string {
if a.env.Haves == nil {
return ""
}
h, ok := a.env.Haves.Read(ctx, module)
if !ok {
return ""
}
return h.FP
}
// takeWant takes a change of a want key and returns the module it concerns, or "" for a key that is not a want.
func (a *Agent) takeWant(u Update) string {
a.mu.Lock()
+49 -5
View File
@@ -1827,7 +1827,7 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
b := newBed(t)
b.env.SelfComposed = true
b.env.Policy = func(_ context.Context, m string) string {
if m == "db" || m == "rec" {
if m == "db" || m == "rec" || m == "fpd" {
return catalogue.PolicyRecord
}
return catalogue.PolicyRoll
@@ -2128,12 +2128,29 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
if _, err := b.ag.CompositionDiff(context.Background(), "db", 0, ""); err == nil {
t.Error("composition-diff with neither a revision nor a digest was answered")
}
var leftSaid []string
wasLine := journalLine
journalLine = func(l string) { leftSaid = append(leftSaid, l) }
defer func() { journalLine = wasLine }()
fingerprintLeftSaid.Clear()
defer func() {
if len(leftSaid) != 1 || !strings.Contains(leftSaid[0], "web.box") || !strings.Contains(leftSaid[0], "left from before H2, taken out at the container's next recreate") {
t.Errorf("the container's difference was said as %q, want one journal line", leftSaid)
}
}()
if got := DiffResources([]json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"a","content":"x"}`),
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"a","GONE":"1"}}`)},
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"a","GONE":"1"}}`),
json.RawMessage(`{"id":"web.box","type":"container","env":{"MESH_FINGERPRINT":"src2:a"}}`),
json.RawMessage(`{"id":"web.d","type":"process","env":{"MESH_FINGERPRINT":"src2:a"}}`)},
[]json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"b","content":"y"}`),
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"b"}}`)}); len(got) != 2 ||
!slices.Equal(got[0].Entries, []nodeengine.CompositionDiffEntry{{Name: "content", Masked: true}, {Name: "sealed", Masked: true}}) ||
!slices.Equal(got[1].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.GONE", Running: "1"}, {Name: "env.MODE", Running: "a", Other: "b"}}) {
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"b"}}`),
json.RawMessage(`{"id":"web.box","type":"container"}`),
json.RawMessage(`{"id":"web.d","type":"process","env":{"MESH_FINGERPRINT":"src2:b"}}`)}); len(got) != 4 ||
!slices.Equal(got[2].Entries, []nodeengine.CompositionDiffEntry{{Name: "content", Masked: true}, {Name: "sealed", Masked: true}}) ||
// H-A-710 (4): a container's difference of MESH_FINGERPRINT is left from before H2; a daemon's is an ordinary entry.
!slices.Equal(got[0].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.MESH_FINGERPRINT", Running: "src2:a"}}) ||
!slices.Equal(got[1].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.MESH_FINGERPRINT", Running: "src2:a", Other: "src2:b"}}) ||
!slices.Equal(got[3].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.GONE", Running: "1"}, {Name: "env.MODE", Running: "a", Other: "b"}}) {
t.Errorf("the entries that differ, a secret masked, read %+v", got)
}
// Issue 774 (ace, 2026-11-04 01:29): the node's own revision shows its own fields, the provisioner client's account
@@ -2209,6 +2226,33 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
return len(b.appliedList()) == applied+2 && h.Phase == string(nodeengineclient.PhaseRunning) && h.FP == fpB &&
r.Phase == string(nodeengineclient.PhaseRunning) && r.FP == fpB && r.Composed == rdig
})
// Design 47 H2 H-A-710 (2), (3): a record module whose container an earlier node-engine composed with MESH_FINGERPRINT,
// moved to the composition of another build that differs by that value alone, is no move: it is applied with no yes, and
// its have never waits (before H2 the same pair was judged to recreate the container and waited for a person).
fpContainer := func(env map[string]string) json.RawMessage {
raw, _ := json.Marshal(map[string]any{"id": "fpd.server", "type": "container", "module": "fpd", "name": "fpd",
"image": "fpd@sha256:" + strings.Repeat("4", 64), "env": env})
return raw
}
fpA, fpC := fpOf("a"), fpOf("c")
k1, raw1, _ := unsigned("fpd", fpA, fpContainer(map[string]string{"MESH_FINGERPRINT": fpA}))
b.comps.put(k1, raw1)
want("fpd", fpA, "")
eventually(t, "fpd's first composition was not applied", func() bool {
return len(b.appliedList()) == applied+3 && b.haves.last("fpd").Phase == string(nodeengineclient.PhaseRunning)
})
k2, raw2, dig2fp := unsigned("fpd", fpC, json.RawMessage(`{"id":"fpd.server","type":"container","module":"fpd","name":"fpd","image":"fpd@sha256:`+strings.Repeat("4", 64)+`"}`))
b.comps.put(k2, raw2)
want("fpd", fpC, "")
eventually(t, "a move that changes the container's fingerprint alone was not applied with no yes", func() bool {
h := b.haves.last("fpd")
return len(b.appliedList()) == applied+4 && h.Phase == string(nodeengineclient.PhaseRunning) && h.Composed == dig2fp
})
for _, h := range b.haves.log {
if h.Module == "fpd" && h.Phase == string(nodeengineclient.PhaseWaitingYes) {
t.Errorf("fpd waited for a yes: %+v", h)
}
}
}
// 1957/AC1 and AC4 (unit; ADR 0568 §1, §4): an engine start takes a module from what the machine shows, not only from the
+17
View File
@@ -6,7 +6,9 @@ import (
"errors"
"fmt"
"maps"
"os"
"slices"
"sync"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
@@ -406,6 +408,14 @@ func (a *Agent) CompositionDiff(ctx context.Context, module string, revision int
return answer, nil
}
// fingerprintLeft says what a container's difference of its env MESH_FINGERPRINT is (design 47 H2, H-A-710 (4)).
const fingerprintLeft = "left from before H2, taken out at the container's next recreate"
// fingerprintLeftSaid is each container whose difference was said, once per node-engine process; journalLine says a line
// in the node-engine's journal (its standard error), a variable so a test reads it.
var fingerprintLeftSaid sync.Map
var journalLine = func(line string) { fmt.Fprintf(os.Stderr, "mesh-host: %s\n", line) }
// 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
@@ -437,6 +447,13 @@ func DiffResources(running, other []json.RawMessage) []nodeengine.CompositionDif
continue
}
e := nodeengine.CompositionDiffEntry{Name: name}
if name == "env."+engcomp.FingerprintVar && (w.values["type"] == string(declaration.TypeContainer) || n.values["type"] == string(declaration.TypeContainer)) {
// A container is handed none since H2 (H-A-710 (4)): what a composition from before holds is no change to make.
// The entry keeps its name; the words are the verb's description and one journal line per container and process.
if _, said := fingerprintLeftSaid.LoadOrStore(id, true); !said {
journalLine(fmt.Sprintf("%s: %s: %s", id, name, fingerprintLeft))
}
}
if w.secret[name] || n.secret[name] {
e.Masked = true
} else {
+63
View File
@@ -18,12 +18,15 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"os/exec"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-sdk/go/declaration"
@@ -975,6 +978,16 @@ func applyScoped(
// not being up, and nothing of the machine would be applied.
var fetchFailures []*Error
fetchFirst(ctx, ordered, d, &in, &fetchFailures, gated, gatedWhy, log)
// **A module's units are stopped before the first owner pass of its directories** (design 47 H2, H-A-641): the apply
// below starts them again, and a pass that fails gates the module, so they stay stopped until a pass completes (H-A-701).
stopFailed := stopForOwnerPass(ctx, sys, d, known, in, run, log)
for _, module := range slices.Sorted(maps.Keys(stopFailed)) {
err := stopFailed[module]
failures = append(failures, &Error{Resource: module + " units stopped for an owner pass", Err: err, Done: report, Gated: true})
gated[module] = true
gatedWhy[module] = err.Error() + ", so nothing more of this module was attempted"
log(" failed " + module + ": " + err.Error())
}
for i, resource := range ordered {
if !orphansRemoved && i == guardFirst {
// **Only a guard that is up may let the filter go.** Removing the derived filter's
@@ -2908,6 +2921,45 @@ func (in inputs) reads(r *declaration.Container) map[string]string {
return out
}
// fingerprintVar is the value the node-engine handed a container before H2 and hands no container now (H-A-710).
const fingerprintVar = "MESH_FINGERPRINT"
// keptFingerprintSaid is each container a kept fingerprint was said for, once per node-engine process.
var keptFingerprintSaid sync.Map
// labelledFingerprint says whether the running container name was created with the value fingerprintVar in its env and
// nothing else differing from r's composed spec: its spec label (a digest) equals r's spec with that value put back
// (H-A-710 (2)). It answers the value. False for a container that declares the value itself, that holds none, or whose
// env cannot be read.
func labelledFingerprint(ctx context.Context, run Runner, cri string, r *declaration.Container, label string, declares, reads map[string]string) (string, bool) {
if _, declared := r.Env[fingerprintVar]; declared {
return "", false
}
out, err := run(ctx, cri, "container", "inspect", "--format", "{{json .Config.Env}}", r.Name)
if err != nil {
return "", false
}
var held []string
if json.Unmarshal([]byte(strings.TrimSpace(out)), &held) != nil {
return "", false
}
fp := ""
for _, e := range held {
if v, ok := strings.CutPrefix(e, fingerprintVar+"="); ok {
fp = v
}
}
if fp == "" {
return "", false
}
with := *r
with.Env = map[string]string{fingerprintVar: fp}
for k, v := range r.Env {
with.Env[k] = v
}
return fp, containerSpecReading(&with, declares, reads) == label
}
// containerSpec is the identity of a declared container: everything that, if changed, means
// the running container is no longer what was asked for.
func containerSpec(r *declaration.Container, in inputs) string {
@@ -3188,6 +3240,17 @@ func applyContainer(ctx context.Context, r *declaration.Container, run Runner,
// not be by the alternative either, which recreates it without knowing whether it needed to.
legacy := len(reads) > 0 && before.Spec == containerSpecReading(r, in.declares, nil) &&
(wasReading == nil || sameReads(wasReading, reads))
// **A container labelled with the fingerprint an earlier node-engine handed it is accepted, not recreated** (design 47
// H2, H-A-710 (2)): a container is handed none now, so its label differs from the composed spec by that value alone;
// the label is written again at its next recreate for another cause, which takes the value out.
if existed && !legacy && before.Spec != want {
if fp, keeps := labelledFingerprint(ctx, run, cri, r, before.Spec, in.declares, reads); keeps {
legacy = true
if _, said := keptFingerprintSaid.LoadOrStore(r.Name, true); !said {
journal(fmt.Sprintf("%s keeps %s %s: a container is handed none, H-A-710", r.Name, fingerprintVar, fp))
}
}
}
// **A container a maintenance window holds still is left as it is** (novox/hq issue 224, ADR
// 0189). Everywhere else stopped means broken, and the rule below replaces it; during a window
+77 -2
View File
@@ -10,19 +10,23 @@ package apply
// followed (a link is owned as a link, Lchown), and the walk stays on the directory's file system.
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/store"
"github.com/novox/mesh-host/internal/system"
)
// giveContents gives every entry below dir whose user is from's (uid) to the new user to's, and the new group to's only
// where the entry's group was from's (H-A-554 (2)); but for the paths placed names (cleaned paths the declaration places)
// and what lies below them, an entry of another user and what lies below it, and what lies on another file system. An
// entry gone while the walk runs is nothing to give. Answers how many entries changed hands. Called before the directory's
// entry with more than one hard link is left with its owner, said in the journal with its path and link count (H-A-579 (2)). An entry gone while the walk runs is nothing to give. Answers how many entries changed hands. Called before the directory's
// own owner changes (H-A-554 (2)), so a walk that failed is walked again at the next apply.
func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, error) {
root := filepath.Clean(dir)
@@ -57,7 +61,7 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err
if err != nil {
return err
}
uid, gid, ok := statOwner(info)
uid, gid, ok := ownerRead(info)
if !ok || uid != from[0] {
return skip()
}
@@ -65,6 +69,11 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err
if d, derr := deviceOf(path); derr != nil || d != device {
return filepath.SkipDir
}
} else if links := linkCount(info); links > 1 {
// An entry with more than one name is left with its owner (H-A-579 (2)): its other names may lie outside the
// directory, which the pass never crosses.
journal(fmt.Sprintf("%s has %d hard links, and is left with its owner when the directory %s is given its new one", path, links, root))
return nil
}
group := gid
if gid == from[1] {
@@ -82,9 +91,15 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err
return given, err
}
// journal says one line in the node-engine's journal (its standard error); a variable so a test reads what was said.
var journal = func(line string) { fmt.Fprintf(os.Stderr, "mesh-host: %s\n", line) }
// lchownContent owns one entry as itself, a link as a link; a variable so a test sees what was given without being root.
var lchownContent = os.Lchown
// ownerRead reads an entry's owner; a variable so a test shows entries owned by an account it is not without being root.
var ownerRead = statOwner
// placedPaths is every path the resources place, cleaned: what giveContents leaves to its own resource.
func placedPaths(resources ...[]declaration.Resource) map[string]bool {
out := map[string]bool{}
@@ -115,3 +130,63 @@ func giveContentsTo(r *declaration.Directory, before os.FileInfo, placed map[str
// ownDirectory gives a directory changed by path its owner (own); a variable so a test sees it without being root.
var ownDirectory = own
// ownerPassRuns is whether applying r runs the owner pass: the directory is found, a real directory the mesh made (or
// handed to the node-engine), with another owner than the one declared (design 47 H2, H-A-641). The same conditions
// applyDirectory judges before it gives the contents, read before any of them is applied so the module's units can be
// stopped first.
func ownerPassRuns(r *declaration.Directory, previous store.Applied, wasBefore bool) bool {
if r.Owner == "" {
return false
}
found, err := os.Lstat(r.Path)
if err != nil || found.Mode()&os.ModeSymlink != 0 || !found.IsDir() {
return false
}
if HandedOver()[handOverKey(r.ID, r.Path)] {
return false
}
if wasBefore {
ours := previous.Target != "" && filepath.Clean(previous.Target) == filepath.Clean(r.Path) && !previous.AsFound
if !ours && !madeInTheMeshsTree(r.Path, found) {
return false
}
}
owned, err := ownedBy(r.Path, r.Owner)
return err == nil && !owned
}
// stopForOwnerPass stops, once per module, the units of each module of d that declares a directory whose owner pass
// will run (H-A-641): before the first pass, so no process of the earlier account writes beneath a directory while it is
// given. The normal apply starts them again, as it starts any declared unit found stopped; a pass that fails gates the
// module (applyScoped), so its units stay stopped until the next apply's pass completes (H-A-701). The tool runner is
// never stopped (StopModule). A module whose units could not all be stopped fails at its directory, and is gated the same.
func stopForOwnerPass(ctx context.Context, sys system.System, d *declaration.Declaration, known store.State, in inputs,
run Runner, log func(string)) (failed map[string]error) {
stopped := map[string]bool{}
for _, res := range d.Resources {
dir, ok := res.(*declaration.Directory)
if !ok || in.refused[filepath.Clean(dir.Path)] != nil {
continue
}
module, ours := d.ModuleOfID(dir.ID)
if !ours || stopped[module] || failed[module] != nil {
continue
}
previous, _ := known.Find(dir.ID)
if !ownerPassRuns(dir, previous, in.dirsBefore[filepath.Clean(dir.Path)]) {
continue
}
stopped[module] = true
names, err := StopModule(ctx, sys, known, module, run)
if err != nil {
if failed == nil {
failed = map[string]error{}
}
failed[module] = fmt.Errorf("the units of %s could not be stopped for the owner of %s: %w", module, dir.Path, err)
continue
}
log(fmt.Sprintf(" stopped %s for the owner of %s: %s", module, dir.Path, strings.Join(names, ", ")))
}
return failed
}
+194 -6
View File
@@ -1,6 +1,7 @@
package apply
import (
"context"
"fmt"
"os"
"path/filepath"
@@ -25,6 +26,8 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) {
placed func(root string) []string
other string // a directory the stand-in deviceOf says is on another file system
group int // the group an entry keeps, when not to's
back bool // the pass back (H-A-602): the directory goes from to's account back to from's, the owner read stubbed
linked bool // token has a second name, token.again (H-A-579 (2))
want []string
}{
{name: "what the previous owner wrote is given", from: [2]int{me, myGroup},
@@ -37,6 +40,11 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) {
group: myGroup, want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link", "token"}},
{name: "another file system is not crossed", from: [2]int{me, myGroup}, other: "kept",
want: []string{"data", "data/repo", "link", "token"}},
{name: "an entry with two hard links is left with its owner, and said", from: [2]int{me, myGroup}, linked: true,
want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link"}},
{name: "given back to the earlier account it keeps the same three: a placed child, an entry of another user, a file with two links",
from: [2]int{me, myGroup}, back: true, linked: true,
placed: func(root string) []string { return []string{filepath.Join(root, "data")} }, want: []string{"link"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
@@ -59,16 +67,34 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) {
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {
t.Fatal(err)
}
var given []string
wasChown, wasDevice := lchownContent, deviceOf
t.Cleanup(func() { lchownContent, deviceOf = wasChown, wasDevice })
if c.linked {
if err := os.Link(filepath.Join(root, "token"), filepath.Join(root, "token.again")); err != nil {
t.Fatal(err)
}
}
var given, said []string
wasChown, wasDevice, wasJournal := lchownContent, deviceOf, journal
t.Cleanup(func() { lchownContent, deviceOf, journal = wasChown, wasDevice, wasJournal })
journal = func(line string) { said = append(said, line) }
wantGroup := to[1]
from, target := c.from, to
if c.back {
// What the pass gave is now owned by the new account: every entry but kept reads as to's, and goes back to c.from.
from, target, wantGroup = to, c.from, c.from[1]
ownerRead = func(info os.FileInfo) (int, int, bool) {
if info.Name() == "kept" { // another user's entry, and what lies below it
return to[0] + 1, to[1], true
}
return to[0], to[1], true
}
defer func() { ownerRead = statOwner }()
}
if c.group != 0 {
wantGroup = c.group
}
lchownContent = func(path string, uid, gid int) error {
if uid != to[0] || gid != wantGroup {
t.Errorf("%s given to %d:%d, want %d:%d", path, uid, gid, to[0], wantGroup)
if uid != target[0] || gid != wantGroup {
t.Errorf("%s given to %d:%d, want %d:%d", path, uid, gid, target[0], wantGroup)
}
rel, _ := filepath.Rel(root, path)
given = append(given, rel)
@@ -86,7 +112,7 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) {
placed[filepath.Clean(p)] = true
}
}
n, err := giveContents(root, c.from, to, placed)
n, err := giveContents(root, from, target, placed)
if err != nil {
t.Fatal(err)
}
@@ -94,6 +120,13 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) {
if n != len(c.want) || strings.Join(given, ",") != strings.Join(c.want, ",") {
t.Fatalf("gave %d: %v, want %v", n, given, c.want)
}
if c.linked {
if len(said) != 2 || !strings.Contains(said[0]+said[1], filepath.Join(root, "token")+" has 2 hard links") {
t.Errorf("said %q, want one line for each name of token naming its 2 hard links", said)
}
} else if len(said) != 0 {
t.Errorf("said %q, want nothing", said)
}
})
}
// The placed paths are every resource's target, cleaned.
@@ -153,3 +186,158 @@ func TestADirectoryWhoseOwnerChangedGivesItsContentsFirst(t *testing.T) {
}
}
}
// Design 47 H2 H-A-579 (1), H-A-641, H-A-701: the owner pass runs with the module's units stopped, and the apply starts
// them once it completes; a pass that fails leaves them stopped and fails the apply naming the entry, and the next apply
// runs the pass again and starts them. The units of another module are left as they are.
func TestAnOwnerPassRunsWithTheModulesUnitsStopped(t *testing.T) {
me, myGroup := os.Getuid(), os.Getgid()
for name, fails := range map[string]bool{"the pass completes": false, "the pass fails on an entry": true} {
t.Run(name, func(t *testing.T) {
dir := filepath.Join(t.TempDir(), "state")
if err := os.Mkdir(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "webhook.secret"), []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
raw := fmt.Sprintf(`{"declaration":1,"resources":[
{"id":"app.state","type":"directory","path":%q,"mode":"0700","owner":"%d:%d"},
{"id":"app.run","type":"service","unit":"app.service","state":"running"},
{"id":"other.run","type":"service","unit":"other.service","state":"running"}]}`, dir, me+4242, myGroup+4242)
m := unitsMachine(map[string]*fakeUnit{
"app.service": {active: "active", enabled: "enabled"},
"other.service": {active: "active", enabled: "enabled"},
})
var events []string
run := func(ctx context.Context, name string, args ...string) (string, error) {
out, err := m.run(ctx, name, args...)
if name == "systemctl" {
args = oldShape(name, args)
if args[0] == "stop" || args[0] == "start" {
events = append(events, args[0]+" "+args[len(args)-1])
}
}
return out, err
}
wasContent, wasOwn, wasF := lchownContent, ownDirectory, fchownDirectory
t.Cleanup(func() { lchownContent, ownDirectory, fchownDirectory = wasContent, wasOwn, wasF })
lchownContent = func(path string, uid, gid int) error {
if fails {
return syscall.EPERM
}
events = append(events, "give "+filepath.Base(path))
return nil
}
ownDirectory = func(path, o string) error { events = append(events, "own directory"); return nil }
fchownDirectory = func(fd, uid, gid int) error { events = append(events, "own directory"); return nil }
known := store.State{}
known.Record(store.Applied{ID: "app.run", Type: "service", Target: "app.service"})
known.Record(store.Applied{ID: "app.state", Type: "directory", Target: dir})
_, after, err := Apply(context.Background(), archHost(t), parse(t, raw), known, store.OriginDeclared, run, nil, nil)
if fails {
if err == nil || !strings.Contains(err.Error(), "webhook.secret") {
t.Fatalf("the apply answered %v, want a failure naming the entry", err)
}
if got := strings.Join(events, ","); got != "stop app.service" || m.units["app.service"].active != "inactive" {
t.Fatalf("events %q, app.service %s: want it stopped and left stopped", got, m.units["app.service"].active)
}
// The next apply runs the pass again from the start, and starts the unit once it completes.
events = nil
lchownContent = func(path string, uid, gid int) error {
events = append(events, "give "+filepath.Base(path))
return nil
}
if _, _, err = Apply(context.Background(), archHost(t), parse(t, raw), after, store.OriginDeclared, run, nil, nil); err != nil {
t.Fatal(err)
}
} else if err != nil {
t.Fatal(err)
}
want := "stop app.service,give webhook.secret,own directory,start app.service"
if fails {
want = "give webhook.secret,own directory,start app.service" // already stopped by the apply that failed
}
if strings.Join(events, ",") != want {
t.Fatalf("events %q, want %q", strings.Join(events, ","), want)
}
if m.units["app.service"].active != "active" || m.units["other.service"].active != "active" || m.did("systemctl stop other.service") {
t.Fatalf("units are %+v, asked %v", m.units, m.asked)
}
})
}
}
// Design 47 H2 H-A-641 (answered by H-A-735): the pass at the engine's start, where no apply follows, stops the module's
// units before it and starts them after it; one whose pass fails leaves them stopped.
func TestTheOwnerPassAtTheEnginesStartStopsAndStartsTheUnits(t *testing.T) {
me, myGroup := os.Getuid(), os.Getgid()
for name, fails := range map[string]bool{"the pass completes": false, "the pass fails": true} {
t.Run(name, func(t *testing.T) {
dir := filepath.Join(t.TempDir(), "state")
if err := os.Mkdir(dir, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "webhook.secret"), []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[
{"id":"app.state","type":"directory","path":%q,"mode":"0700","owner":"%d:%d"}]}`, dir, me+4242, myGroup+4242))
// H-A-752: only what the pass found running is stopped and started again, services before timers, then
// containers; a run-once step's service, a scheduled process's service off its timer, a service and a container
// found stopped stay stopped.
m := unitsMachine(map[string]*fakeUnit{
"app.service": {active: "active", enabled: "enabled"}, "app.timer": {active: "active", enabled: "enabled"},
"once.service": {active: "inactive", enabled: "disabled"},
"sched.timer": {active: "active", enabled: "enabled"},
"sched.service": {active: "inactive", enabled: "disabled"},
"idle.service": {active: "inactive", enabled: "enabled"},
})
m.containers = map[string]*fakeContainer{"app-box": {id: "a", running: true}, "app-off": {id: "b"}}
var events []string
run := func(ctx context.Context, name string, args ...string) (string, error) {
out, err := m.run(ctx, name, args...)
if name == "systemctl" {
args = oldShape(name, args)
if args[0] == "stop" || args[0] == "start" {
events = append(events, args[0]+" "+args[len(args)-1])
}
}
if name == "docker" && (args[0] == "stop" || args[0] == "start") {
events = append(events, "docker "+args[0]+" "+args[len(args)-1])
}
return out, err
}
wasContent, wasOwn, wasF := lchownContent, ownDirectory, fchownDirectory
t.Cleanup(func() { lchownContent, ownDirectory, fchownDirectory = wasContent, wasOwn, wasF })
lchownContent = func(path string, uid, gid int) error {
if fails {
return syscall.EPERM
}
events = append(events, "give "+filepath.Base(path))
return nil
}
ownDirectory = func(string, string) error { events = append(events, "own directory"); return nil }
fchownDirectory = func(int, int, int) error { events = append(events, "own directory"); return nil }
known := store.State{}
for _, r := range []store.Applied{
{ID: "app.run", Type: "service", Target: "app.service"}, {ID: "app.tick", Type: "service", Target: "app.timer"},
{ID: "app.once", Type: "service", Target: "once.service"}, {ID: "app.sched", Type: "process", Target: "sched"},
{ID: "app.idle", Type: "service", Target: "idle.service"},
{ID: "app.box", Type: "container", Target: "app-box"}, {ID: "app.off", Type: "container", Target: "app-off"},
{ID: "app.state", Type: "directory", Target: dir},
} {
known.Record(r)
}
ConvergeDirectories(context.Background(), archHost(t), d, known, run)
stops := "stop app.timer,stop sched.timer,stop app.service,docker stop app-box"
want := stops + ",give webhook.secret,own directory,start app.service,start app.timer,start sched.timer,docker start app-box"
if fails {
want = stops
}
if got := strings.Join(events, ","); got != want {
t.Fatalf("events %q, want %q", got, want)
}
})
}
}
+33 -1
View File
@@ -1,12 +1,14 @@
package apply
import (
"context"
"errors"
"fmt"
"os"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/store"
"github.com/novox/mesh-host/internal/system"
)
// ConvergeDirectories gives each directory entry of d whose record known holds, found on disk with another owner or mode
@@ -14,12 +16,15 @@ import (
// drift lasts at most until then, and with no apply of an unchanged composition. One the mesh never made (its record used
// as found, issue 339) is left as found and said. Answered as one line per directory set right or left; a directory
// declared that is missing, that has no record, or that is as declared, says nothing.
func ConvergeDirectories(d *declaration.Declaration, known store.State) []string {
func ConvergeDirectories(ctx context.Context, sys system.System, d *declaration.Declaration, known store.State, run Runner) []string {
if d == nil {
return nil
}
var lines []string
placed := placedPaths(d.Resources)
// H-A-641: the owner pass runs here with the module's units stopped, as in an apply, and with no apply after it they are
// started again once every directory of the module is through; one a pass failed on leaves them stopped (H-A-701).
stopped, failed := map[string][]string{}, map[string]bool{}
for _, r := range d.Resources {
dir, ok := r.(*declaration.Directory)
if !ok {
@@ -37,9 +42,28 @@ func ConvergeDirectories(d *declaration.Declaration, known store.State) []string
lines = append(lines, fmt.Sprintf("%s (%s) cannot be judged at this start: %v", dir.Path, dir.ID, err))
continue
}
module, ours := d.ModuleOfID(dir.ID)
if _, done := stopped[module]; ours && !done && ownerPassRuns(dir, rec, true) {
stopped[module] = nil
var err error
if sys == nil {
err = errors.New("this host is built for no system it knows")
} else {
stopped[module], err = StopModule(ctx, sys, known, module, run)
}
if err != nil {
failed[module] = true
lines = append(lines, fmt.Sprintf("%s (%s) is %s and is not set right at this start: the units of %s could not be stopped: %v", dir.Path, dir.ID, drift, module, err))
continue
}
}
if failed[module] {
continue
}
out, err := applyDirectory(dir, rec, true, placed)
switch {
case err != nil:
failed[module] = true
lines = append(lines, fmt.Sprintf("%s (%s) is %s and cannot be set right at this start: %v", dir.Path, dir.ID, drift, err))
case out.asFound:
lines = append(lines, fmt.Sprintf("%s (%s) is %s, and is left as found at this start: %s", dir.Path, dir.ID, drift, out.Detail))
@@ -47,6 +71,14 @@ func ConvergeDirectories(d *declaration.Declaration, known store.State) []string
lines = append(lines, fmt.Sprintf("%s (%s) was %s, and is set right at this start", dir.Path, dir.ID, drift))
}
}
for module, names := range stopped {
if failed[module] || sys == nil {
continue
}
if _, err := StartModule(ctx, sys, known, module, names, run); err != nil {
lines = append(lines, fmt.Sprintf("the units of %s stopped for its owner pass could not be started again: %v", module, err))
}
}
return lines
}
+7
View File
@@ -2,6 +2,7 @@ package apply
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
@@ -105,6 +106,8 @@ type fakeContainer struct {
// What a take compares (ADR 0163), answered in the long inspect form when set.
image, imageID string
networks, mounts, ports []string
// env is what the container's configuration holds, as `{{json .Config.Env}}` answers it.
env []string
}
// oldShape is a systemctl call as these fakes were written to read it: the verb, the unit, then the
@@ -171,6 +174,10 @@ func (m *machine) run(_ context.Context, name string, args ...string) (string, e
if c.running {
running = "true"
}
if strings.Contains(args[3], ".Config.Env") {
raw, _ := json.Marshal(c.env)
return string(raw) + "\n", nil
}
if strings.HasPrefix(args[3], "{{.Id}}") {
line := c.id + "\t" + running + "\t" + c.spec
if c.image != "" {
+3 -3
View File
@@ -56,13 +56,13 @@ func testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) {
if drifts := DirectoryDrifts(postgres, state); len(drifts) != 1 || drifts[0].Drift != "mode 0700, 0750 declared" {
t.Errorf("the drift read is %+v", drifts)
}
if lines := ConvergeDirectories(postgres, state); len(lines) != 1 || !strings.Contains(lines[0], "was mode 0700, 0750 declared, and is set right") {
if lines := ConvergeDirectories(context.Background(), archHost(t), postgres, state, noServices); len(lines) != 1 || !strings.Contains(lines[0], "was mode 0700, 0750 declared, and is set right") {
t.Errorf("a drifted directory the mesh made was converged as %q", lines)
}
if info, _ := os.Stat(made); info.Mode().Perm() != 0o750 {
t.Errorf("it was not set right at the start: %04o", info.Mode().Perm())
}
if lines := ConvergeDirectories(postgres, state); len(lines) != 0 {
if lines := ConvergeDirectories(context.Background(), archHost(t), postgres, state, noServices); len(lines) != 0 {
t.Errorf("a directory as declared was said at the start: %q", lines)
}
@@ -81,7 +81,7 @@ func testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) {
if !strings.Contains(strings.Join(said, "\n"), "WARNING notes.data") {
t.Errorf("a directory found outside the mesh's tree was not used as found: %q", said)
}
if lines := ConvergeDirectories(declare(t, decl), found); len(lines) != 1 || !strings.Contains(lines[0], "left as found") {
if lines := ConvergeDirectories(context.Background(), archHost(t), declare(t, decl), found, noServices); len(lines) != 1 || !strings.Contains(lines[0], "left as found") {
t.Errorf("a directory the mesh never made was converged as %q", lines)
}
if drifts := DirectoryDrifts(declare(t, decl), found); len(drifts) != 0 {
+40
View File
@@ -247,6 +247,45 @@ func testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *te
}
}
func testAContainerLabelledWithTheFingerprintItWasHandedIsAcceptedNotRecreated(t *testing.T) {
// Design 47 H2 H-A-710 (2): the node-engine before H2 handed every container MESH_FINGERPRINT, so a running container's
// label holds it and the composed spec does not. That difference alone recreates nothing, said once per container and
// process; a changed image still recreates, and its new label holds none.
declare := func(image string) *declaration.Declaration {
return parseTrusted(t, `{"declaration":1,"resources":[
{"id":"forge.server","type":"container","name":"forge","image":"`+image+`","env":{"A":"1"}}]}`)
}
was := declare(pinned).Resources[0].(*declaration.Container)
handed := *was
handed.Env = map[string]string{"A": "1", "MESH_FINGERPRINT": "src2:" + strings.Repeat("a", 64)}
known := store.State{}
known.Record(store.Applied{ID: "forge.server", Type: "container", Origin: store.OriginCarried, Target: "forge"})
m := &machine{containers: map[string]*fakeContainer{"forge": {id: "made-before", running: true, spec: containerSpecReading(&handed, nil, nil),
env: []string{"A=1", "MESH_FINGERPRINT=" + handed.Env["MESH_FINGERPRINT"]}}}}
var said []string
wasJournal := journal
t.Cleanup(func() { journal = wasJournal })
journal = func(line string) { said = append(said, line) }
keptFingerprintSaid.Clear()
for range 2 {
report, _ := applyCarried(t, declare(pinned), known, m, nil)
if m.did("docker rm") || m.did("docker run") || report.Changed() {
t.Fatalf("a container labelled with the fingerprint it was handed was recreated: %v %+v", m.asked, report.Outcomes)
}
}
if len(said) != 1 || !strings.Contains(said[0], "forge keeps MESH_FINGERPRINT src2:") || !strings.Contains(said[0], "a container is handed none, H-A-710") {
t.Errorf("said %q, want one line for the container", said)
}
// A changed image recreates it, and the label written holds no fingerprint.
m.asked = nil
other := "registry.example/other@sha256:" + strings.Repeat("9", 64)
applyCarried(t, declare(other), known, m, nil)
if !m.removed("forge") || !m.did("docker run") || strings.Contains(m.containers["forge"].spec, "MESH_FINGERPRINT") {
t.Fatalf("a changed image did not recreate the container with a clean label: %v", m.asked)
}
}
func testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) {
// The bundle's `store` becomes the postgres module's `postgres.server`: the same container by
// name, under a new id with no record of its own. A file change on that day is a real change,
@@ -322,6 +361,7 @@ func TestReads(t *testing.T) {
t.Run("AContainerIsRecreatedWhenAMountedSecretChanged", testAContainerIsRecreatedWhenAMountedSecretChanged)
t.Run("AMountedDirectoryIsNotLookedInside", testAMountedDirectoryIsNotLookedInside)
t.Run("AContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated", testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated)
t.Run("AContainerLabelledWithTheFingerprintItWasHandedIsAcceptedNotRecreated", testAContainerLabelledWithTheFingerprintItWasHandedIsAcceptedNotRecreated)
t.Run("AContainerAdoptedUnderANewIdStillSaysWhichFileChanged", testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged)
t.Run("AHeldContainerIsNotRecreatedByAChangedHeldFile", testAHeldContainerIsNotRecreatedByAChangedHeldFile)
}
+66 -6
View File
@@ -7,16 +7,14 @@ import (
"strings"
"git.novox.be/novox/mesh-sdk/go/declaration"
"github.com/novox/mesh-host/internal/compose/resolution"
"github.com/novox/mesh-host/internal/store"
"github.com/novox/mesh-host/internal/system"
)
// StopModule stops the units and containers the node's record holds for a module and removes nothing: no unit, file,
// container, data or record, so what the module kept survives and a later Apply starts the build it is given (design 47
// G A-98, §297). Units come first, a timer before the service it starts, then containers; a unit the mesh never held
// (Stateless) is left as it is. It answers what it stopped, and the first failure.
func StopModule(ctx context.Context, sys system.System, known store.State, module string, run Runner) ([]string, error) {
var timers, services, containers []store.Applied
// unitsOf is the timers, services and containers the node's record holds for a module, its processes' units among them but
// never the tool runner's own (H-A-641).
func unitsOf(known store.State, module string) (timers, services, containers []store.Applied) {
for _, r := range known.Resources {
if store.OwnerOf(r, declaration.ModuleGuess) != module {
continue
@@ -33,8 +31,66 @@ func StopModule(ctx context.Context, sys system.System, known store.State, modul
}
case string(declaration.TypeContainer):
containers = append(containers, r)
case string(declaration.TypeProcess):
// The tool runner is never stopped, whichever module's owner pass asks (H-A-641).
if strings.HasSuffix(r.ID, "."+resolution.RuntimeProcessID()) {
continue
}
timers = append(timers, store.Applied{ID: r.ID, Type: string(declaration.TypeService), Target: r.Target + ".timer"})
services = append(services, store.Applied{ID: r.ID, Type: string(declaration.TypeService), Target: r.Target + ".service"})
}
}
return timers, services, containers
}
// StartModule starts again exactly what StopModule found running and stopped, which is what it is given as stopped: the
// module's services, then its timers, then its containers, and nothing else (design 47 H2, H-A-752: a pass at the engine's
// start, with no apply after it, starts again the units it stopped, never a run-once step's service, a scheduled
// process's service off its timer or a unit found stopped before). It answers what it started, and the first failure.
func StartModule(ctx context.Context, sys system.System, known store.State, module string, stopped []string, run Runner) ([]string, error) {
timers, services, containers := unitsOf(known, module)
was := map[string]bool{}
for _, name := range stopped {
was[name] = true
}
var started []string
for _, r := range append(services, timers...) {
if !was[r.Target] {
continue
}
manager := managerFor(r.Scope, r.User, run)
if err := sys.SetServiceState(ctx, manager, r.Target, "running"); err != nil {
return started, fmt.Errorf("starting %s of %s: %w", r.Target, module, err)
}
started = append(started, r.Target)
}
var cri string
for _, r := range containers {
if !was[r.Target] {
continue
}
if cri == "" {
var err error
if cri, err = containerRuntime(ctx, run); err != nil {
return started, err
}
}
if _, err := run(ctx, cri, "start", r.Target); err != nil {
return started, fmt.Errorf("starting the container %s of %s: %w", r.Target, module, err)
}
started = append(started, r.Target)
}
return started, nil
}
// StopModule stops the units and containers the node's record holds for a module and removes nothing: no unit, file,
// container, data or record, so what the module kept survives and a later Apply starts the build it is given (design 47
// G A-98, §297). Units come first, a timer before the service it starts, then containers; a unit the mesh never held
// (Stateless) is left as it is. The module's processes are stopped with them (design 47 H2, H-A-641): the timer and the
// service of each, but never the tool runner's own process, which serves every other module's bundles. It answers what it
// stopped, and the first failure.
func StopModule(ctx context.Context, sys system.System, known store.State, module string, run Runner) ([]string, error) {
timers, services, containers := unitsOf(known, module)
var stopped []string
for _, r := range append(timers, services...) {
manager := managerFor(r.Scope, r.User, run)
@@ -60,6 +116,10 @@ func StopModule(ctx context.Context, sys system.System, known store.State, modul
}
sort.Slice(containers, func(i, j int) bool { return containers[i].Target < containers[j].Target })
for _, r := range containers {
// A container found stopped is not in the answer, so it is not started again (H-A-752).
if state, err := containerState(ctx, r.Target, run); err != nil || !state.Running {
continue
}
if _, err := run(ctx, cri, "stop", r.Target); err != nil {
return stopped, fmt.Errorf("stopping the container %s of %s: %w", r.Target, module, err)
}
+14 -5
View File
@@ -15,12 +15,20 @@ func TestStopModuleStopsAModulesUnitsAndContainersAndRemovesNothing(t *testing.T
"app.service": {active: "active", enabled: "enabled"},
"app.timer": {active: "active", enabled: "enabled"},
"other.service": {active: "active", enabled: "enabled"},
// A module's processes stop with it (H-A-641), but the tool runner's own never does.
"app-worker.service": {active: "active", enabled: "enabled"},
"app-rt.service": {active: "active", enabled: "enabled"},
})
// A container found stopped is not stopped and not in the answer, so it is not started again (H-A-752).
m.containers = map[string]*fakeContainer{"app-box": {id: "a", running: true}, "app-idle": {id: "b"}}
state := store.State{}
for _, r := range []store.Applied{
{ID: "app.run", Type: "service", Target: "app.service"},
{ID: "app.tick", Type: "service", Target: "app.timer"},
{ID: "app.c", Type: "container", Target: "app-box"},
{ID: "app.i", Type: "container", Target: "app-idle"},
{ID: "app.worker", Type: "process", Target: "app-worker"},
{ID: "app.runtime", Type: "process", Target: "app-rt"},
{ID: "other.run", Type: "service", Target: "other.service"},
{ID: "other.c", Type: "container", Target: "other-box"},
} {
@@ -30,16 +38,17 @@ func TestStopModuleStopsAModulesUnitsAndContainersAndRemovesNothing(t *testing.T
if err != nil {
t.Fatal(err)
}
if want := []string{"app.timer", "app.service", "app-box"}; !reflect.DeepEqual(got, want) {
if want := []string{"app.timer", "app.service", "app-worker.service", "app-box"}; !reflect.DeepEqual(got, want) {
t.Fatalf("stopped %v, want %v, the timer first", got, want)
}
if m.units["app.service"].active != "inactive" || m.units["app.timer"].active != "inactive" || m.units["other.service"].active != "active" {
if m.units["app.service"].active != "inactive" || m.units["app.timer"].active != "inactive" || m.units["other.service"].active != "active" ||
m.units["app-worker.service"].active != "inactive" || m.units["app-rt.service"].active != "active" {
t.Fatalf("units are %+v", m.units)
}
if !m.did("docker stop app-box") || m.did("docker stop other-box") || m.did("docker rm") {
if !m.did("docker stop app-box") || m.did("docker stop app-idle") || m.did("docker stop other-box") || m.did("docker rm") {
t.Fatalf("the machine was asked %v", m.asked)
}
if len(state.Resources) != 5 {
t.Fatalf("a record was removed: %d left", len(state.Resources))
if len(state.Resources) != 8 {
t.Fatalf("a record was removed: %d left of 8", len(state.Resources))
}
}
+8
View File
@@ -16,3 +16,11 @@ func statOwner(info os.FileInfo) (uid, gid int, ok bool) {
}
return int(stat.Uid), int(stat.Gid), true
}
// linkCount is how many names a file has (its hard links); 1 where the file system does not say.
func linkCount(info os.FileInfo) uint64 {
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
return uint64(stat.Nlink)
}
return 1
}
+25 -5
View File
@@ -167,12 +167,12 @@ func TestComparingCompositions(t *testing.T) {
t.Errorf("a composition not run is added: %+v", c)
}
// Design 47, *The fingerprint handover* (the composed resources are split here): a daemon or a container of a module
// Design 47, *The fingerprint handover* (the composed resources are split here), H2 H-A-710 (1): a daemon of a module
// is started with MESH_FINGERPRINT, the fingerprint of the want it applies, over any value its module declared of that
// name; a file, or a resource of no module, carries none.
// name; a container, a file, or a resource of no module, carries none.
split, err := Split("novox", []json.RawMessage{
json.RawMessage(`{"id":"d","type":"process","module":"nats","run":["x"],"env":{"A":"1","MESH_FINGERPRINT":"stale"}}`),
json.RawMessage(`{"id":"c","type":"container","module":"nats","image":"i"}`),
json.RawMessage(`{"id":"c","type":"container","module":"nats","image":"i","env":{"MESH_FINGERPRINT":"stale","B":"2"}}`),
file("conf", "a"),
json.RawMessage(`{"id":"own","type":"process","run":["x"]}`),
}, map[string]string{"nats": fp}, nil, NodeOwn{})
@@ -192,10 +192,10 @@ func TestComparingCompositions(t *testing.T) {
}
_ = json.Unmarshal(raw, &r)
want := fp
if r.ID == "conf" {
if r.ID == "conf" || r.ID == "c" {
want = ""
}
if r.Env[FingerprintVar] != want || (r.ID == "d" && r.Env["A"] != "1") {
if r.Env[FingerprintVar] != want || (r.ID == "d" && r.Env["A"] != "1") || (r.ID == "c" && r.Env["B"] != "2") {
t.Errorf("%s starts with %v, want %s=%q and its own words kept", r.ID, r.Env, FingerprintVar, want)
}
}
@@ -205,6 +205,26 @@ func TestComparingCompositions(t *testing.T) {
}
}
// H-A-710 (1): a daemon whose want names no fingerprint composes none, its declared value taken out and said once per
// module and node-engine process; a container's declared value likewise, and an env left empty goes.
var said []string
wasJournal := journal
t.Cleanup(func() { journal = wasJournal })
journal = func(line string) { said = append(said, line) }
takenOutSaid.Clear()
for range 2 {
for kind, in := range map[string]string{"process": `{"id":"d","type":"process","module":"nats","run":["x"],"env":{"A":"1","MESH_FINGERPRINT":"stale"}}`,
"container": `{"id":"c","type":"container","module":"nats","image":"i","env":{"MESH_FINGERPRINT":"stale"}}`} {
got, err := withFingerprint(json.RawMessage(in), kind, "nats", "")
if err != nil || strings.Contains(string(got), FingerprintVar) || (kind == "container" && strings.Contains(string(got), "env")) {
t.Errorf("a %s with no fingerprint composed %s, %v", kind, got, err)
}
}
}
if len(said) != 1 || !strings.Contains(said[0], "nats") {
t.Errorf("said %q, want one line for the module", said)
}
// §519, §618: the tool runner's process hands each bundle's module its own want's fingerprint in the words of its
// bundles, a module with bundles and no words included, and the runner's own fingerprint reaches no other module's.
fpLamp, fpBare := "src2:"+strings.Repeat("1", 64), "src2:"+strings.Repeat("2", 64)
+36 -10
View File
@@ -3,8 +3,10 @@ package compositions
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"sync"
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
@@ -239,7 +241,7 @@ func Split(node string, resources []json.RawMessage, fps map[string]string, fill
pathOf[head.Path] = key
}
if head.Module != "" {
if raw, err = withFingerprint(raw, head.Type, fps[head.Module]); err != nil {
if raw, err = withFingerprint(raw, head.Type, head.Module, fps[head.Module]); err != nil {
return nil, err
}
if raw, err = withBundleFingerprints(raw, head.Type, fps); err != nil {
@@ -262,16 +264,24 @@ func Split(node string, resources []json.RawMessage, fps map[string]string, fill
return out, nil
}
// FingerprintVar is the environment value every process the node-engine starts, a daemon or a container, holds: the
// fingerprint of the want it applies. mesh-sdk's runtime reads it once at the process's start as the process's own build
// (novox/hq ADR 0656 §1, design 47 *The fingerprint handover*).
// FingerprintVar is the environment value every daemon the node-engine starts holds: the fingerprint of the want it
// applies. mesh-sdk's runtime reads it once at the process's start as the process's own build (novox/hq ADR 0656 §1,
// design 47 *The fingerprint handover*). A container is handed none (H-A-710).
const FingerprintVar = "MESH_FINGERPRINT"
// withFingerprint is raw, when it is a daemon or a container, with FingerprintVar in its env set to fp. The value is
// the node-engine's to say, so one a module declared of that name is replaced. Another resource, or no fingerprint, is
// returned as it is.
func withFingerprint(raw json.RawMessage, kind, fp string) (json.RawMessage, error) {
if fp == "" || (kind != string(declaration.TypeProcess) && kind != string(declaration.TypeContainer)) {
// journal says one line in the node-engine's journal (its standard error); a variable so a test reads what was said.
var journal = func(line string) { fmt.Fprintf(os.Stderr, "mesh-host: %s\n", line) }
// takenOutSaid is each module a value of FingerprintVar taken out of an env was said for, once per node-engine process.
var takenOutSaid sync.Map
// withFingerprint is raw with FingerprintVar in its env set to fp when it is a daemon and the want names a fingerprint
// (design 47 H2, H-A-710 (1)). The value is the node-engine's to say, so one a module declared of that name is replaced.
// A container is handed none, and a daemon whose want names none no more, so no process reports a build it was never
// handed: a value of that name in such an env is taken out, said once per module and node-engine process. Another
// resource is returned as it is.
func withFingerprint(raw json.RawMessage, kind, module, fp string) (json.RawMessage, error) {
if kind != string(declaration.TypeProcess) && kind != string(declaration.TypeContainer) {
return raw, nil
}
var fields map[string]json.RawMessage
@@ -284,7 +294,23 @@ func withFingerprint(raw json.RawMessage, kind, fp string) (json.RawMessage, err
return nil, fmt.Errorf("compositions: the env of a %s resource is not words by name: %w", kind, err)
}
}
env[FingerprintVar] = fp
if kind == string(declaration.TypeProcess) && fp != "" {
env[FingerprintVar] = fp
} else {
declared, has := env[FingerprintVar]
if !has {
return raw, nil
}
delete(env, FingerprintVar)
if _, said := takenOutSaid.LoadOrStore(module, true); !said {
journal(fmt.Sprintf("%s: %s is taken out of the env of a %s it declares (%q): the node-engine hands it to a daemon whose want names a fingerprint, and to nothing else (H-A-710)",
module, FingerprintVar, kind, declared))
}
}
if len(env) == 0 {
delete(fields, "env")
return json.Marshal(fields)
}
body, err := json.Marshal(env)
if err != nil {
return nil, err
+29 -2
View File
@@ -9,6 +9,7 @@ import (
"strings"
"git.novox.be/novox/mesh-sdk/go/declaration"
engcomp "github.com/novox/mesh-host/internal/compositions"
)
// The judgement of a move (ADR 0377 §3), as a pure function over two compositions of one module, so the node agent that
@@ -269,7 +270,7 @@ func judgedResourcesByID(c Composed) map[string]*judgedResource {
if err := json.Unmarshal(raw, &head); err != nil {
continue
}
r := &judgedResource{kind: head.Type, path: head.Path, raw: compactResource(raw)}
r := &judgedResource{kind: head.Type, path: head.Path, raw: compactJudged(raw)}
for _, v := range head.Volumes {
source, _, _ := strings.Cut(v, ":")
r.mounts = append(r.mounts, source)
@@ -295,6 +296,32 @@ func compactResource(raw []byte) []byte {
return out
}
// compactJudged is a resource as the judgement compares it: compactResource, and for a container with the value
// MESH_FINGERPRINT taken out of its env on whichever side it stands, so two compositions whose containers differ by that
// value alone are no change and ask nothing (design 47 H2, H-A-710 (2)): a container is handed none now, and one composed
// by an earlier node-engine holds it.
func compactJudged(raw []byte) []byte {
var v map[string]any
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
if err := d.Decode(&v); err != nil || v["type"] != string(declaration.TypeContainer) {
return compactResource(raw)
}
if env, ok := v["env"].(map[string]any); ok {
if _, has := env[engcomp.FingerprintVar]; has {
delete(env, engcomp.FingerprintVar)
if len(env) == 0 {
delete(v, "env")
}
}
}
out, err := json.Marshal(v)
if err != nil {
return compactResource(raw)
}
return out
}
// changedOf are the ids of the resources of the kinds counted that are changed, added or removed, sorted.
func changedOf(before, after map[string]*judgedResource, counted func(kind string) bool) []string {
var out []string
@@ -357,7 +384,7 @@ func SameComposedResources(a, b Composed) bool {
return false
}
for i := range a.Resources {
if !bytes.Equal(compactResource(a.Resources[i]), compactResource(b.Resources[i])) {
if !bytes.Equal(compactJudged(a.Resources[i]), compactJudged(b.Resources[i])) {
return false
}
}
+7
View File
@@ -22,6 +22,10 @@ func TestJudgeMove(t *testing.T) {
const (
container = `{"id":"mesh-mail.server","type":"container","module":"mesh-mail","name":"mail","image":"mail@sha256:1111111111111111111111111111111111111111111111111111111111111111","volumes":["/var/lib/mesh-mail/spool:/spool"]}`
container2 = `{"id":"mesh-mail.server","type":"container","module":"mesh-mail","name":"mail","image":"mail@sha256:2222222222222222222222222222222222222222222222222222222222222222","volumes":["/var/lib/mesh-mail/spool:/spool"]}`
// H-A-710 (2): a container an earlier node-engine composed holds MESH_FINGERPRINT in its env, a new one none.
withFP = `{"id":"mesh-mail.server","type":"container","module":"mesh-mail","name":"mail","image":"mail@sha256:1111111111111111111111111111111111111111111111111111111111111111","volumes":["/var/lib/mesh-mail/spool:/spool"],"env":{"MESH_FINGERPRINT":"src2:aaaa"}}`
withFP2 = `{"id":"mesh-mail.server","type":"container","module":"mesh-mail","name":"mail","image":"mail@sha256:1111111111111111111111111111111111111111111111111111111111111111","volumes":["/var/lib/mesh-mail/spool:/spool"],"env":{"MESH_FINGERPRINT":"src2:bbbb"}}`
withFPAndA = `{"id":"mesh-mail.server","type":"container","module":"mesh-mail","name":"mail","image":"mail@sha256:1111111111111111111111111111111111111111111111111111111111111111","volumes":["/var/lib/mesh-mail/spool:/spool"],"env":{"A":"1","MESH_FINGERPRINT":"src2:bbbb"}}`
spool = `{"id":"mesh-mail.spool","type":"directory","module":"mesh-mail","path":"/var/lib/mesh-mail/spool"}`
spoolMoved = `{"id":"mesh-mail.spool","type":"directory","module":"mesh-mail","path":"/srv/mesh-mail/spool"}`
tools = `{"id":"mesh-mail.tools","type":"file","module":"mesh-mail","path":"/usr/lib/mesh-mail/tools.json","content":"a"}`
@@ -59,6 +63,9 @@ func TestJudgeMove(t *testing.T) {
"consumers join or leave: cloud on novox leaves smtp, wiki on ace joins smtp"},
{"a consumer leaves and a file moves", mail('a', true, container, spool, received, config), mail('b', true, container, spool, received2, config2), JudgedMovesData, false,
"it changes where its data is kept: mesh-mail.conf; consumers join or leave: cloud on novox leaves smtp, wiki on ace joins smtp"},
{"a container's fingerprint taken out", mail('a', true, withFP, spool), mail('b', true, container, spool), JudgedUnchanged, false, ""},
{"a container's fingerprint changes", mail('a', true, withFP, spool), mail('b', true, withFP2, spool), JudgedUnchanged, false, ""},
{"a container's fingerprint taken out and one more env", mail('a', true, withFP, spool), mail('b', true, withFPAndA, spool), JudgedRecreates, false, ""},
{"its data flag alone", mail('a', false, container, spool), mail('b', true, container, spool), JudgedNeither, false, ""},
{"its data flag and its spool", mail('a', false, container, spool), mail('b', true, container, spoolMoved), JudgedMovesData, false, ""},
{"a process of a module with data", mail('a', true, spool, process), mail('b', true, spool, process2), JudgedMovesData, false, ""},
+3 -3
View File
@@ -383,8 +383,8 @@ func testTheNodeKeyCarriesTheNodesFacts(t *testing.T) {
t.Errorf("the record states reads %v and capabilities %v, want the word want:version and no want-parts", got.Record.ManifestReads, got.Record.Capabilities)
}
// And that it gives a directory's contents the directory's new owner (H-A-556).
if !slices.Contains(got.Record.ManifestReads, catalogue.ReadDirectoryContentsOwner) {
t.Errorf("the record states reads %v, want %s", got.Record.ManifestReads, catalogue.ReadDirectoryContentsOwner)
if !slices.Contains(got.Record.ManifestReads, nodeengine.ManifestReadWordDirectoryContentsOwner) {
t.Errorf("the record states reads %v, want %s", got.Record.ManifestReads, nodeengine.ManifestReadWordDirectoryContentsOwner)
}
// Among them, that it fills a seat's reach from the seat holder's listen (ADR 0632 §1).
// And the words and forms it builds (design 42 zfs-owns-zfs §4, answer A-13).
@@ -1064,7 +1064,7 @@ func slicesIndex(rs []ResourceHealth, id string) int {
// that it gives a directory's contents its new owner (H-A-556).
func statedReads() []string {
return slices.Sorted(slices.Values(append(catalogue.ManifestReads(), nodeengine.ManifestReadWordWantVersion,
catalogue.ReadDirectoryContentsOwner)))
nodeengine.ManifestReadWordDirectoryContentsOwner)))
}
// TestHave runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
+1 -1
View File
@@ -60,7 +60,7 @@ func readsNow() []string {
set[nodeengine.ManifestReadWordWantVersion] = true
// And that it gives a directory's contents the directory's new owner (internal/apply giveContents; H-A-556): a module
// declaring runs-as needs it, so its move waits for this engine on its node.
set[catalogue.ReadDirectoryContentsOwner] = true
set[nodeengine.ManifestReadWordDirectoryContentsOwner] = true
for r := range set {
out = append(out, r)
}
+15 -11
View File
@@ -1,12 +1,12 @@
// Package processbuilds reads the build each process of this node was started with (design 47, *The fingerprint handover*):
// the value MESH_FINGERPRINT the node-engine handed a daemon or a container at its start, read from the running process
// itself, never from what the declaration would hand it now. A process started before the node-engine handed the value,
// or one whose value cannot be read, says why its build is unknown instead of a fingerprint.
// the value MESH_FINGERPRINT the node-engine handed a daemon at its start, read from the running process itself, never
// from what the declaration would hand it now; a container is handed none (design 47 H2, H-A-710 (4)), so its build is the
// one its module's have names. A process started before the node-engine handed the value, or one whose value cannot be
// read, says why its build is unknown instead of a fingerprint.
package processbuilds
import (
"context"
"encoding/json"
"fmt"
"os"
"sort"
@@ -30,6 +30,9 @@ type Reader struct {
Run Runner
// Environ reads a process's environment by its pid; nil reads /proc/<pid>/environ.
Environ func(pid int) ([]byte, error)
// Have answers the fingerprint the have of a module names, the want's build the node-engine applied it from; empty
// when the have names none. A container's build is that value (H-A-710 (4)); nil answers none.
Have func(ctx context.Context, module string) string
}
func (r Reader) environ(pid int) ([]byte, error) {
@@ -116,16 +119,17 @@ func (r Reader) container(ctx context.Context, module, name string) nodeengine.P
b.Unknown = "the container cannot be read: " + err.Error()
return b
}
env, started, _ := strings.Cut(strings.TrimSpace(said), "\t")
var vars []string
if err := json.Unmarshal([]byte(env), &vars); err != nil {
b.Unknown = "its environment cannot be read: " + err.Error()
return b
}
_, started, _ := strings.Cut(strings.TrimSpace(said), "\t")
if t, err := time.Parse(time.RFC3339Nano, started); err == nil {
b.Started = &t
}
b.Fingerprint, b.Unknown = fingerprintIn(vars)
// A container is handed none: its build is the one its module's have names, the composition it was applied from.
if r.Have != nil {
b.Fingerprint = r.Have(ctx, module)
}
if b.Fingerprint == "" {
b.Unknown = "the have of " + module + " names no build"
}
return b
}
+14 -4
View File
@@ -10,7 +10,7 @@ import (
)
// Design 47, *The fingerprint handover*: the build of a daemon is read from its running process's environment and of a
// container from its configuration, narrowed by module; one started without the value, one not running and one the
// container from the fingerprint its module's have names (it is handed none, H-A-710 (4)), narrowed by module; one started without the value, one not running and one the
// runtime cannot read each say why their build is unknown, never a guessed fingerprint.
func TestProcessBuildsAreReadFromTheRunningProcesses(t *testing.T) {
fp := "src2:" + strings.Repeat("a", 64)
@@ -19,6 +19,7 @@ func TestProcessBuildsAreReadFromTheRunningProcesses(t *testing.T) {
&declaration.Process{ID: "old.d", Type: declaration.TypeProcess, Module: "old", Name: "old-d"},
&declaration.Process{ID: "down.d", Type: declaration.TypeProcess, Module: "down", Name: "down-d"},
&declaration.Container{ID: "db.c", Type: declaration.TypeContainer, Module: "db", Name: "db-c"},
&declaration.Container{ID: "fresh.c", Type: declaration.TypeContainer, Module: "fresh", Name: "fresh-c"},
&declaration.Container{ID: "gone.c", Type: declaration.TypeContainer, Module: "gone", Name: "gone-c"},
&declaration.Directory{ID: "web.dir", Type: declaration.TypeDirectory, Module: "web"},
}}
@@ -31,7 +32,10 @@ func TestProcessBuildsAreReadFromTheRunningProcesses(t *testing.T) {
case name == "systemctl":
return "MainPID=0\nActiveEnterTimestamp=\n", nil
case name == "docker" && args[len(args)-1] == "db-c":
return `["A=1","MESH_FINGERPRINT=` + fp + `"]` + "\t2026-11-09T10:00:00.5Z\n", nil
// A container is handed no fingerprint (H-A-710): what its env holds, if anything, is no build.
return `["A=1","MESH_FINGERPRINT=src2:` + strings.Repeat("0", 64) + `"]` + "\t2026-11-09T10:00:00.5Z\n", nil
case name == "docker" && args[len(args)-1] == "fresh-c":
return `["A=1"]` + "\t2026-11-09T10:00:00.5Z\n", nil
}
return "", errors.New("no such container")
}
@@ -41,7 +45,13 @@ func TestProcessBuildsAreReadFromTheRunningProcesses(t *testing.T) {
}
return []byte("A=1\x00"), nil
}
r := Reader{Node: "n1", Run: run, Environ: environ}
have := func(_ context.Context, module string) string {
if module == "db" {
return fp
}
return ""
}
r := Reader{Node: "n1", Run: run, Environ: environ, Have: have}
got := r.Read(context.Background(), d, "")
by := map[string]string{}
for _, p := range got.Processes {
@@ -49,7 +59,7 @@ func TestProcessBuildsAreReadFromTheRunningProcesses(t *testing.T) {
}
want := map[string]string{"web": fp + "|", "db": fp + "|",
"old": "|started before the node-engine handed MESH_FINGERPRINT, or without it",
"down": "|the unit runs no process now", "gone": "|the container cannot be read: no such container"}
"down": "|the unit runs no process now", "fresh": "|the have of fresh names no build", "gone": "|the container cannot be read: no such container"}
if len(by) != len(want) || got.Node != "n1" {
t.Fatalf("read %v, want %v", by, want)
}
+6 -1
View File
@@ -766,7 +766,12 @@ func (c *Composer) entryHolds() map[string]string {
agent.EntryMissing, w.Fp, module)
default:
if _, missing := c.partsOf(module, e, w); missing != "" {
out[module] = fmt.Sprintf("the want of %s names no digest for %s, so the node composes nothing new of it", module, missing)
if w.Version == "" {
// H-A-673: a want naming no version has no digests to resolve; its writer is at fault, not the registry.
out[module] = fmt.Sprintf("the want of %s names no version, so the node composes nothing new of it", module)
} else {
out[module] = fmt.Sprintf("the want of %s names no digest for %s, so the node composes nothing new of it", module, missing)
}
}
}
}
+9 -2
View File
@@ -71,6 +71,7 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) {
parts map[string]string
missing string // a word the reason holds
said []string
holds string // the words the module's hold says (entryHolds), when it is held
// pkg names a package artifact the builder's done key carries with no reference beside what the build made: the key
// frombus hands takein.Manifest (H-A-466).
pkg string
@@ -88,7 +89,11 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) {
refs: map[string]string{"mail:server": "artifact-store://mail/server/blobs/" + d("9"),
"mail:files": "artifact-store://mail/files/blobs/" + d("1"), "mail:web": "container-image-registry/mail/web@" + d("3")}},
"a version a seat does not hold": {want: meshwants.WantsByWantNodeModuleValue{Fp: fp, Version: "2.0.0", Self: true},
missing: "2.0.0", said: []string{"mail at version 2.0.0", "oci-artifact-registry", "container-image-registry"}},
missing: "2.0.0", said: []string{"mail at version 2.0.0", "oci-artifact-registry", "container-image-registry"},
holds: "names no digest for"},
// Design 47 H2 H-A-673: a want with a fingerprint and no version is held as naming no version, not no digest.
"a want naming no version": {want: meshwants.WantsByWantNodeModuleValue{Fp: fp, Self: true},
missing: "mail:", holds: "the want of mail names no version, so the node composes nothing new of it"},
"a seat that does not answer": {want: meshwants.WantsByWantNodeModuleValue{Fp: fp, Version: "1.2.3", Self: true}, down: "container-image-registry",
missing: "mail:web", said: []string{"mail at version 1.2.3: the seat container-image-registry"}},
"a package artifact": {want: meshwants.WantsByWantNodeModuleValue{Fp: fpPkg, Version: "1.2.3", Self: true}, entry: &withPackage,
@@ -139,8 +144,10 @@ func aWantNamingItsVersionIsResolvedThroughTheRegistrySeats(t *testing.T) {
if parts != nil || b != nil || !strings.Contains(missing, row.missing) {
t.Errorf("%s: parts %v, build %v, missing %q: want the module held whole, naming %s", name, parts, b, missing, row.missing)
}
if c.entryHolds()["mail"] == "" {
if held := c.entryHolds()["mail"]; held == "" {
t.Errorf("%s: the module is not held", name)
} else if !strings.Contains(held, row.holds) {
t.Errorf("%s: held as %q, want words naming %q", name, held, row.holds)
}
for _, w := range row.said {
if !strings.Contains(strings.Join(said, "\n"), w) {
-9
View File
@@ -116,15 +116,6 @@ func testTheManifestConsumesTheBackupEvent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// ADR 0614 §4: the node-engine's own manifest uses only words every running engine reads (the baseline, what an engine
// stating none is read as), so its new build is never held for a word only it reads; but for its class and the
// declaration Version it reads, which an engine before them cannot state, so its build is held for a yes once at that
// delivery (H-A-388 and its addendum, H-A-394).
if needs, err := catalogue.ManifestNeeds(raw); err != nil || len(needs) == 0 {
t.Fatalf("the manifest's needs: %v, %v", needs, err)
} else if missing := catalogue.MissingManifestReads(needs, nil); !slices.Equal(missing, []string{"word:class", "word:declaration-reads", "word:declaration-writes"}) {
t.Errorf("the manifest needs %v, which an engine stating nothing does not read: its new build would be held", missing)
}
// Design 47 H2 §813 (12), H-A-388: it states the declaration Version it reads, the one its contract parses, so the
// delivery plan orders the composer that writes that Version after it.
// The claim of node-engine serves every verb the seat's contract defines, composition-diff among them (the H2 K row of