From 174cb9dcd87cc2300409228a54b3ddf6a6ed89b5 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:05:27 +0100 Subject: [PATCH 01/13] H4 operator-keys-row-goes: no test reads ManifestNeeds or MissingManifestReads Builds: design 47 H2 H-A-639 (hq 6b8373ce) --- packaging/operator_keys_test.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/packaging/operator_keys_test.go b/packaging/operator_keys_test.go index 95628fa0..ce01052d 100644 --- a/packaging/operator_keys_test.go +++ b/packaging/operator_keys_test.go @@ -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 From 3753d4d5dc6aa3e564d0b433f4f4ca7610d152c3 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:06:09 +0100 Subject: [PATCH 02/13] H5 names-no-version: a want naming no version is held as naming no version Builds: design 47 H2 H-A-673 (hq 6b8373ce) --- internal/selfcompose/entries.go | 7 ++++++- internal/selfcompose/versions_test.go | 11 +++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/internal/selfcompose/entries.go b/internal/selfcompose/entries.go index 0f964b9f..96a2ad72 100644 --- a/internal/selfcompose/entries.go +++ b/internal/selfcompose/entries.go @@ -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) + } } } } diff --git a/internal/selfcompose/versions_test.go b/internal/selfcompose/versions_test.go index e6741b33..131df219 100644 --- a/internal/selfcompose/versions_test.go +++ b/internal/selfcompose/versions_test.go @@ -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) { From 204cd51e4b553a73bdccdd470c747b23035eac2a Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:06:40 +0100 Subject: [PATCH 03/13] H1 the-word-from-the-contract: the engine states directory-contents-owner from the seat's contract Builds: design 47 H2 H-A-622, H-A-640 (hq 6b8373ce) --- internal/link/have_test.go | 6 +++--- internal/link/record.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/link/have_test.go b/internal/link/have_test.go index 508cfad9..1568b2fd 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -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). diff --git a/internal/link/record.go b/internal/link/record.go index 8cc45ee6..a575490d 100644 --- a/internal/link/record.go +++ b/internal/link/record.go @@ -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) } From 9c40b4a3fbcdaad579e9fa1fa7ebc70e379c1f02 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:09:52 +0100 Subject: [PATCH 04/13] H2 owner-pass-with-units-stopped: the module's units and processes stop before the owner pass and start after it Builds: design 47 H2 H-A-579 (1), H-A-602 (the pass back), H-A-641 (hq 6b8373ce), H-A-701 (hq 95cf2052) --- internal/apply/apply.go | 12 ++++ internal/apply/contents_owner.go | 64 +++++++++++++++++++++ internal/apply/contents_owner_test.go | 82 +++++++++++++++++++++++++++ internal/apply/stop.go | 12 +++- internal/apply/stop_test.go | 14 +++-- 5 files changed, 179 insertions(+), 5 deletions(-) diff --git a/internal/apply/apply.go b/internal/apply/apply.go index 42a471ab..0424d02a 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -18,9 +18,11 @@ import ( "encoding/json" "errors" "fmt" + "maps" "os" "os/exec" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -975,6 +977,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 diff --git a/internal/apply/contents_owner.go b/internal/apply/contents_owner.go index b99682c1..5d171d46 100644 --- a/internal/apply/contents_owner.go +++ b/internal/apply/contents_owner.go @@ -10,13 +10,17 @@ 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 @@ -115,3 +119,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 +} diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index 4526c562..d4d8fa91 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -1,6 +1,7 @@ package apply import ( + "context" "fmt" "os" "path/filepath" @@ -153,3 +154,84 @@ 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) + } + }) + } +} diff --git a/internal/apply/stop.go b/internal/apply/stop.go index 8a8b553e..e78b2ef4 100644 --- a/internal/apply/stop.go +++ b/internal/apply/stop.go @@ -7,6 +7,7 @@ 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" ) @@ -14,7 +15,9 @@ import ( // 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. +// (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) { var timers, services, containers []store.Applied for _, r := range known.Resources { @@ -33,6 +36,13 @@ 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"}) } } var stopped []string diff --git a/internal/apply/stop_test.go b/internal/apply/stop_test.go index 2febfb5d..cf5c219d 100644 --- a/internal/apply/stop_test.go +++ b/internal/apply/stop_test.go @@ -15,12 +15,17 @@ 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"}, }) 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.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 +35,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") { 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) != 7 { + t.Fatalf("a record was removed: %d left of 7", len(state.Resources)) } } From 894e2c89c2fb7d26b8f219e71566452fe9a2889b Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:10:27 +0100 Subject: [PATCH 05/13] H3 hard-links-left: an entry with more than one hard link keeps its owner in the owner pass, said in the journal Builds: design 47 H2 H-A-579 (2), H-A-583 (4), H-A-604 (4) --- internal/apply/contents_owner.go | 10 +++++++++- internal/apply/contents_owner_test.go | 22 +++++++++++++++++++--- internal/apply/user_unix.go | 8 ++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/internal/apply/contents_owner.go b/internal/apply/contents_owner.go index 5d171d46..09888dc8 100644 --- a/internal/apply/contents_owner.go +++ b/internal/apply/contents_owner.go @@ -26,7 +26,7 @@ import ( // 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) @@ -69,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] { @@ -86,6 +91,9 @@ 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 diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index d4d8fa91..4da31853 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -26,6 +26,7 @@ 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 + 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}, @@ -38,6 +39,8 @@ 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"}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -60,9 +63,15 @@ 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] if c.group != 0 { wantGroup = c.group @@ -95,6 +104,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. diff --git a/internal/apply/user_unix.go b/internal/apply/user_unix.go index fb6765df..d05399d8 100644 --- a/internal/apply/user_unix.go +++ b/internal/apply/user_unix.go @@ -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 +} From 4e520bffe413fca431ea6147b9d5441ea6eaa403 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:11:40 +0100 Subject: [PATCH 06/13] H6 fingerprint-for-daemons: only a daemon whose want names a fingerprint is handed MESH_FINGERPRINT Builds: design 47 H2 H-A-710 (1) (hq 27369077) --- internal/compositions/compare_test.go | 30 ++++++++++++++--- internal/compositions/composed.go | 46 +++++++++++++++++++++------ 2 files changed, 61 insertions(+), 15 deletions(-) diff --git a/internal/compositions/compare_test.go b/internal/compositions/compare_test.go index 434deff4..aedf8596 100644 --- a/internal/compositions/compare_test.go +++ b/internal/compositions/compare_test.go @@ -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) diff --git a/internal/compositions/composed.go b/internal/compositions/composed.go index 5d1d730b..a02a2f2a 100644 --- a/internal/compositions/composed.go +++ b/internal/compositions/composed.go @@ -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 From 915049a729f9b1e3571fb5f453e21127d0c76ae6 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:14:32 +0100 Subject: [PATCH 07/13] H7 fingerprint-no-change: a difference of MESH_FINGERPRINT alone in a container is no change, in the judgement and in the apply Builds: design 47 H2 H-A-710 (2), (3) (the node-engine's side) (hq 27369077) --- internal/agent/agent_test.go | 29 +++++++++++++++++++- internal/apply/apply.go | 51 ++++++++++++++++++++++++++++++++++++ internal/apply/hold_test.go | 7 +++++ internal/apply/reads_test.go | 40 ++++++++++++++++++++++++++++ internal/judge/judge.go | 31 ++++++++++++++++++++-- internal/judge/judge_test.go | 7 +++++ 6 files changed, 162 insertions(+), 3 deletions(-) diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 5c7412a4..4fd175a9 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -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 @@ -2209,6 +2209,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 diff --git a/internal/apply/apply.go b/internal/apply/apply.go index 0424d02a..15c40798 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -26,6 +26,7 @@ import ( "sort" "strconv" "strings" + "sync" "time" "git.novox.be/novox/mesh-sdk/go/declaration" @@ -2920,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 { @@ -3200,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 diff --git a/internal/apply/hold_test.go b/internal/apply/hold_test.go index 4b0a8fde..53dd615c 100644 --- a/internal/apply/hold_test.go +++ b/internal/apply/hold_test.go @@ -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 != "" { diff --git a/internal/apply/reads_test.go b/internal/apply/reads_test.go index b318c02a..32ead3de 100644 --- a/internal/apply/reads_test.go +++ b/internal/apply/reads_test.go @@ -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) } diff --git a/internal/judge/judge.go b/internal/judge/judge.go index 99ab051f..e1d623a2 100644 --- a/internal/judge/judge.go +++ b/internal/judge/judge.go @@ -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 } } diff --git a/internal/judge/judge_test.go b/internal/judge/judge_test.go index 9548f17d..c7b9f8fe 100644 --- a/internal/judge/judge_test.go +++ b/internal/judge/judge_test.go @@ -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, ""}, From 754f11a25850875e603f6794a14dce8197180f54 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:16:05 +0100 Subject: [PATCH 08/13] H8 fingerprint-readers: process-builds answers a container's build from its module's have, composition-diff names the value left from before H2 Builds: design 47 H2 H-A-710 (4) (hq 27369077) --- cmd/mesh-host/main.go | 8 +++++- internal/agent/agent.go | 14 +++++++++++ internal/agent/agent_test.go | 15 ++++++++--- internal/agent/composition.go | 7 ++++++ internal/processbuilds/processbuilds.go | 26 +++++++++++--------- internal/processbuilds/processbuilds_test.go | 18 +++++++++++--- 6 files changed, 68 insertions(+), 20 deletions(-) diff --git a/cmd/mesh-host/main.go b/cmd/mesh-host/main.go index 2ce4db11..42409919 100644 --- a/cmd/mesh-host/main.go +++ b/cmd/mesh-host/main.go @@ -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("", "") }) diff --git a/internal/agent/agent.go b/internal/agent/agent.go index ba9d4808..857d7d77 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -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() diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index 4fd175a9..ae48982b 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -2129,11 +2129,18 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( t.Error("composition-diff with neither a revision nor a digest was answered") } 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 (left from before H2, taken out at the container's next recreate)", 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 diff --git a/internal/agent/composition.go b/internal/agent/composition.go index 4eae9994..e8bf6f99 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -406,6 +406,9 @@ 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" + // 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.`, 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 +440,10 @@ 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. + e.Name = name + " (" + fingerprintLeft + ")" + } if w.secret[name] || n.secret[name] { e.Masked = true } else { diff --git a/internal/processbuilds/processbuilds.go b/internal/processbuilds/processbuilds.go index 9b39cf97..d778222f 100644 --- a/internal/processbuilds/processbuilds.go +++ b/internal/processbuilds/processbuilds.go @@ -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//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 } diff --git a/internal/processbuilds/processbuilds_test.go b/internal/processbuilds/processbuilds_test.go index fc31889b..59e30062 100644 --- a/internal/processbuilds/processbuilds_test.go +++ b/internal/processbuilds/processbuilds_test.go @@ -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) } From 39964d32d8f9eb1bce8d9844428f134b0c3806d9 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:18:12 +0100 Subject: [PATCH 09/13] H7 the bus server's integration test reads the container's env as the engine does Builds: design 47 H2 H-A-710 (2) (hq 27369077) --- cmd/mesh-host/nodeagent_integration_test.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/cmd/mesh-host/nodeagent_integration_test.go b/cmd/mesh-host/nodeagent_integration_test.go index 9ec999b9..6f4e0350 100644 --- a/cmd/mesh-host/nodeagent_integration_test.go +++ b/cmd/mesh-host/nodeagent_integration_test.go @@ -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) From 180d57fe16c40bf8e14fdb796839b0af779a0027 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 17:23:16 +0100 Subject: [PATCH 10/13] H2, H8 (H-A-735): the owner pass at the engine's start stops and starts the module's units; composition-diff keeps the entry's name, the words go to the journal Builds: design 47 H2 H-A-641, H-A-701, H-A-710 (4), H-A-735 --- cmd/mesh-host/nodeagent.go | 13 ++++-- internal/agent/agent_test.go | 12 +++++- internal/agent/composition.go | 12 +++++- internal/apply/contents_owner_test.go | 53 ++++++++++++++++++++++++ internal/apply/converge_dirs.go | 34 ++++++++++++++- internal/apply/mesh_tree_found_test.go | 6 +-- internal/apply/stop.go | 57 ++++++++++++++++++++++---- 7 files changed, 169 insertions(+), 18 deletions(-) diff --git a/cmd/mesh-host/nodeagent.go b/cmd/mesh-host/nodeagent.go index 0318ffe2..c3da4bbd 100644 --- a/cmd/mesh-host/nodeagent.go +++ b/cmd/mesh-host/nodeagent.go @@ -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 diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index ae48982b..f9d66faf 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -2128,6 +2128,16 @@ 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.box","type":"container","env":{"MESH_FINGERPRINT":"src2:a"}}`), @@ -2138,7 +2148,7 @@ func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes( 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 (left from before H2, taken out at the container's next recreate)", Running: "src2:a"}}) || + !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) diff --git a/internal/agent/composition.go b/internal/agent/composition.go index e8bf6f99..4c745b1a 100644 --- a/internal/agent/composition.go +++ b/internal/agent/composition.go @@ -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" @@ -409,6 +411,11 @@ func (a *Agent) CompositionDiff(ctx context.Context, module string, revision int // 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.`, 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 @@ -442,7 +449,10 @@ func DiffResources(running, other []json.RawMessage) []nodeengine.CompositionDif 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. - e.Name = name + " (" + fingerprintLeft + ")" + // 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 diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index 4da31853..41b7eead 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -251,3 +251,56 @@ func TestAnOwnerPassRunsWithTheModulesUnitsStopped(t *testing.T) { }) } } + +// 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)) + m := unitsMachine(map[string]*fakeUnit{"app.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(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{} + known.Record(store.Applied{ID: "app.run", Type: "service", Target: "app.service"}) + known.Record(store.Applied{ID: "app.state", Type: "directory", Target: dir}) + ConvergeDirectories(context.Background(), archHost(t), d, known, run) + want := "stop app.service,give webhook.secret,own directory,start app.service" + if fails { + want = "stop app.service" + } + if got := strings.Join(events, ","); got != want { + t.Fatalf("events %q, want %q", got, want) + } + }) + } +} diff --git a/internal/apply/converge_dirs.go b/internal/apply/converge_dirs.go index 2ba31001..deb07e3c 100644 --- a/internal/apply/converge_dirs.go +++ b/internal/apply/converge_dirs.go @@ -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]bool{}, 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 ours && !stopped[module] && ownerPassRuns(dir, rec, true) { + stopped[module] = true + var err error + if sys == nil { + err = errors.New("this host is built for no system it knows") + } else { + _, 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 := range stopped { + if failed[module] || sys == nil { + continue + } + if _, err := StartModule(ctx, sys, known, module, 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 } diff --git a/internal/apply/mesh_tree_found_test.go b/internal/apply/mesh_tree_found_test.go index cee31e7c..c549fedf 100644 --- a/internal/apply/mesh_tree_found_test.go +++ b/internal/apply/mesh_tree_found_test.go @@ -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 { diff --git a/internal/apply/stop.go b/internal/apply/stop.go index e78b2ef4..acdd3906 100644 --- a/internal/apply/stop.go +++ b/internal/apply/stop.go @@ -12,14 +12,9 @@ import ( "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. 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) { - 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 @@ -45,6 +40,52 @@ func StopModule(ctx context.Context, sys system.System, known store.State, modul services = append(services, store.Applied{ID: r.ID, Type: string(declaration.TypeService), Target: r.Target + ".service"}) } } + return timers, services, containers +} + +// StartModule starts again what StopModule stopped: the module's services and timers found stopped, services first, and its +// containers found stopped (design 47 H2, H-A-641: a pass at the engine's start, with no apply after it, starts the units +// it stopped). It answers what it started, and the first failure. +func StartModule(ctx context.Context, sys system.System, known store.State, module string, run Runner) ([]string, error) { + timers, services, containers := unitsOf(known, module) + var started []string + for _, r := range append(services, timers...) { + manager := managerFor(r.Scope, r.User, run) + if state, err := sys.ServiceState(ctx, manager, r.Target); err != nil || state != "stopped" { + continue + } + 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) + } + if len(containers) == 0 { + return started, nil + } + cri, err := containerRuntime(ctx, run) + if err != nil { + return started, err + } + for _, r := range containers { + if state, err := containerState(ctx, r.Target, run); err != nil || state.Running { + continue + } + 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) From d4fb8ef371c9c3581507ff33e0e608596c91b141 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 18:50:26 +0100 Subject: [PATCH 11/13] H2 owner-pass-with-units-stopped: a row gives the directory back to the earlier account, the owner read stubbed Builds: design 47 H2 H-A-602 (the pass back), AC-H2a, AC-H3 --- internal/apply/contents_owner.go | 5 ++++- internal/apply/contents_owner_test.go | 16 +++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/internal/apply/contents_owner.go b/internal/apply/contents_owner.go index 09888dc8..0034a6dc 100644 --- a/internal/apply/contents_owner.go +++ b/internal/apply/contents_owner.go @@ -61,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() } @@ -97,6 +97,9 @@ 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{} diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index 41b7eead..fa920a96 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -26,6 +26,7 @@ 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 }{ @@ -41,6 +42,8 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { 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: the user, the group only where it was the new one's, the rest left", + from: [2]int{me, myGroup}, back: true, want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link", "token"}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -73,12 +76,19 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { 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 reads as to's, and goes back to c.from. + from, target, wantGroup = to, c.from, c.from[1] + ownerRead = func(os.FileInfo) (int, int, bool) { 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) @@ -96,7 +106,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) } From 6d866665c2b34cf0493359bce8b99d42251c7eed Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 18:52:01 +0100 Subject: [PATCH 12/13] H2 owner-pass-with-units-stopped: the owner pass at the engine's start starts again exactly what its stop found running StopModule answers only what it found running (a container found stopped is not in it); StartModule starts that answer, services before timers, then containers. Builds: design 47 H2 H-A-752 (amends H-A-735 (1)), H-A-641 --- cmd/mesh-host/stop_test.go | 3 +++ internal/apply/contents_owner_test.go | 31 ++++++++++++++++++---- internal/apply/converge_dirs.go | 12 ++++----- internal/apply/stop.go | 37 +++++++++++++++++---------- internal/apply/stop_test.go | 9 ++++--- 5 files changed, 64 insertions(+), 28 deletions(-) diff --git a/cmd/mesh-host/stop_test.go b/cmd/mesh-host/stop_test.go index 4ca264a6..d18dd75a 100644 --- a/cmd/mesh-host/stop_test.go +++ b/cmd/mesh-host/stop_test.go @@ -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 { diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index fa920a96..ba688f5f 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -277,7 +277,17 @@ func TestTheOwnerPassAtTheEnginesStartStopsAndStartsTheUnits(t *testing.T) { } 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)) - m := unitsMachine(map[string]*fakeUnit{"app.service": {active: "active", enabled: "enabled"}}) + // 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...) @@ -287,6 +297,9 @@ func TestTheOwnerPassAtTheEnginesStartStopsAndStartsTheUnits(t *testing.T) { 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 @@ -301,12 +314,20 @@ func TestTheOwnerPassAtTheEnginesStartStopsAndStartsTheUnits(t *testing.T) { 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{} - known.Record(store.Applied{ID: "app.run", Type: "service", Target: "app.service"}) - known.Record(store.Applied{ID: "app.state", Type: "directory", Target: dir}) + 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) - want := "stop app.service,give webhook.secret,own directory,start app.service" + 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 = "stop app.service" + want = stops } if got := strings.Join(events, ","); got != want { t.Fatalf("events %q, want %q", got, want) diff --git a/internal/apply/converge_dirs.go b/internal/apply/converge_dirs.go index deb07e3c..ba25029e 100644 --- a/internal/apply/converge_dirs.go +++ b/internal/apply/converge_dirs.go @@ -24,7 +24,7 @@ func ConvergeDirectories(ctx context.Context, sys system.System, d *declaration. 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]bool{}, map[string]bool{} + stopped, failed := map[string][]string{}, map[string]bool{} for _, r := range d.Resources { dir, ok := r.(*declaration.Directory) if !ok { @@ -43,13 +43,13 @@ func ConvergeDirectories(ctx context.Context, sys system.System, d *declaration. continue } module, ours := d.ModuleOfID(dir.ID) - if ours && !stopped[module] && ownerPassRuns(dir, rec, true) { - stopped[module] = true + 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 { - _, err = StopModule(ctx, sys, known, module, run) + stopped[module], err = StopModule(ctx, sys, known, module, run) } if err != nil { failed[module] = true @@ -71,11 +71,11 @@ func ConvergeDirectories(ctx context.Context, sys system.System, d *declaration. lines = append(lines, fmt.Sprintf("%s (%s) was %s, and is set right at this start", dir.Path, dir.ID, drift)) } } - for module := range stopped { + for module, names := range stopped { if failed[module] || sys == nil { continue } - if _, err := StartModule(ctx, sys, known, module, run); err != nil { + 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)) } } diff --git a/internal/apply/stop.go b/internal/apply/stop.go index acdd3906..9d2aee45 100644 --- a/internal/apply/stop.go +++ b/internal/apply/stop.go @@ -43,33 +43,38 @@ func unitsOf(known store.State, module string) (timers, services, containers []s return timers, services, containers } -// StartModule starts again what StopModule stopped: the module's services and timers found stopped, services first, and its -// containers found stopped (design 47 H2, H-A-641: a pass at the engine's start, with no apply after it, starts the units -// it stopped). It answers what it started, and the first failure. -func StartModule(ctx context.Context, sys system.System, known store.State, module string, run Runner) ([]string, error) { +// 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...) { - manager := managerFor(r.Scope, r.User, run) - if state, err := sys.ServiceState(ctx, manager, r.Target); err != nil || state != "stopped" { + 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) } - if len(containers) == 0 { - return started, nil - } - cri, err := containerRuntime(ctx, run) - if err != nil { - return started, err - } + var cri string for _, r := range containers { - if state, err := containerState(ctx, r.Target, run); err != nil || state.Running { + 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) } @@ -111,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) } diff --git a/internal/apply/stop_test.go b/internal/apply/stop_test.go index cf5c219d..36cc6ec1 100644 --- a/internal/apply/stop_test.go +++ b/internal/apply/stop_test.go @@ -19,11 +19,14 @@ func TestStopModuleStopsAModulesUnitsAndContainersAndRemovesNothing(t *testing.T "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"}, @@ -42,10 +45,10 @@ func TestStopModuleStopsAModulesUnitsAndContainersAndRemovesNothing(t *testing.T 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) != 7 { - t.Fatalf("a record was removed: %d left of 7", len(state.Resources)) + if len(state.Resources) != 8 { + t.Fatalf("a record was removed: %d left of 8", len(state.Resources)) } } From 8e4ede6f96ed40c5026f5ae1327db24e3774a0d3 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 18:57:09 +0100 Subject: [PATCH 13/13] H2 owner-pass-with-units-stopped: the pass-back row keeps a placed child, another user's entry and a file with two links Builds: design 47 H2 H-A-602 (the pass back), AC-H2a, AC-H3 --- internal/apply/contents_owner_test.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index ba688f5f..a7f5cfc6 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -42,8 +42,9 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { 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: the user, the group only where it was the new one's, the rest left", - from: [2]int{me, myGroup}, back: true, want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link", "token"}}, + {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) { @@ -78,9 +79,14 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { wantGroup := to[1] from, target := c.from, to if c.back { - // What the pass gave is now owned by the new account: every entry reads as to's, and goes back to c.from. + // 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(os.FileInfo) (int, int, bool) { return to[0], to[1], true } + 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 {