package apply import ( "context" "fmt" "os" "path/filepath" "strings" "git.novox.be/novox/mesh-sdk/go/declaration" "github.com/novox/mesh-host/internal/store" ) // ConvergeProcessUnits writes again the unit of each process of d whose unit as composed (ProcessWrote, with d's node) // differs from the one its applied record says it wrote, for a module taken as running its want's composition at the // engine's start (design 47 G A-342, H-A-713): the process then has the node's name in its env. A service is restarted; a // run-once step's and a scheduled process's unit are written and neither run nor started, and take the name at their next // run. Nothing else is written or run (no backup, no other resource), and the record takes the new unit, so a second pass // finds nothing. A process with no record, or whose record holds another bundle than the composition's, is not touched: the // apply of its new form gives it the name. It answers the changed record state and one line per process. func ConvergeProcessUnits(ctx context.Context, d *declaration.Declaration, known store.State, run Runner) (store.State, []string) { var lines []string if d == nil { return known, nil } for _, res := range d.Resources { r, ok := res.(*declaration.Process) if !ok { continue } rec, held := known.Find(r.Identity()) if !held || rec.Type != string(declaration.TypeProcess) { continue } have, same := strings.CutPrefix(rec.Wrote, r.Digest+" ") want := ProcessWrote(r, d.For) if !same { // Another bundle than the composition's (or none) is what the record holds: the apply of the new form gives the // name (H-A-714). Said, so that the process left as it is can be read from the journal. named, _, _ := strings.Cut(rec.Wrote, " ") if named == "" { named = "none" } lines = append(lines, fmt.Sprintf("%s (%s) is left as it is at this start: its record names the bundle %s and the composition names %s", r.Name, r.ID, named, r.Digest)) continue } if have == strings.TrimPrefix(want, r.Digest+" ") { continue } unit := filepath.Join(unitDir, r.Name+".service") if err := os.WriteFile(unit, []byte(unitFor(withNode(r, d.For))), 0o644); err != nil { lines = append(lines, fmt.Sprintf("%s (%s) cannot be given its node's name at this start: %v", r.Name, r.ID, err)) continue } if _, err := run(ctx, "systemctl", "daemon-reload"); err != nil { lines = append(lines, fmt.Sprintf("%s (%s) was written with its node's name and the units could not be reloaded: %v", r.Name, r.ID, err)) continue } verb := "written again with its node's name at this start" if !r.RunOnce && r.Schedule == "" { if _, err := run(ctx, "systemctl", "restart", r.Name+".service"); err != nil { lines = append(lines, fmt.Sprintf("%s (%s) was written with its node's name and would not restart: %v", r.Name, r.ID, err)) continue } verb = "written again with its node's name and restarted at this start" } rec.Wrote = want known.Record(rec) lines = append(lines, fmt.Sprintf("%s (%s) %s", r.Name, r.ID, verb)) } return known, lines }