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)) } }