A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): keep generated files in .rexctl/generated (#3678)
Hampus9f612896dd1f
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdxindex 5423429e1..6091ae8c8 100644--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx@@ -174,6 +174,14 @@ rexctl branding set [flags]Read and change Fluxer's settings.+### rexctl config edit++Opens custom.compose.yml in $VISUAL or $EDITOR. rexctl checks the file, says which services restart and applies it once you agree. Your file stays as it was until it passes the check.++```sh+rexctl config edit+```+### rexctl config getShow one setting.diff --git a/fluxer_docs/src/content/docs/operator/running.mdx b/fluxer_docs/src/content/docs/operator/running.mdxindex 33afe1c48..0f06d30f6 100644--- a/fluxer_docs/src/content/docs/operator/running.mdx+++ b/fluxer_docs/src/content/docs/operator/running.mdx@@ -131,7 +131,17 @@ Each time rexctl starts Fluxer, it sizes memory limits, database connections andOn a machine with little memory, `rexctl config set FLUXER_API_EMBEDDED_WORKER true` runs background jobs inside the api service instead of a separate worker service. rexctl then removes the worker and adds half of its memory limit to the api.-To add your own Caddy directives, such as extra routes or headers, put them in a `.caddy` file in the `caddy.d` folder of your instance. Fluxer's Caddyfile loads every file there inside your site, and upgrades keep them. To use your own Caddyfile instead, mount it over `/etc/caddy/Caddyfile` on the `edge` service in a `custom.compose.yml` file in your instance folder.+## Change how Fluxer runs++rexctl writes Fluxer's Compose files and Caddyfile to `.rexctl/generated` in your instance folder and writes them again each time it changes the instance. If you edit one of them, rexctl keeps a copy of your version in `.rexctl/edited` and puts its own version back.++To change the Compose setup, such as labels, images, ports or volumes, run `rexctl config edit`. It opens `custom.compose.yml` in your instance folder, checks it, tells you which services restart and applies it. rexctl adds this file after its own Compose files, and upgrades keep it.++```sh+rexctl config edit+```++To add your own Caddy directives, such as extra routes or headers, put them in a `.caddy` file in the `caddy.d` folder of your instance. Fluxer's Caddyfile loads every file there inside your site, and upgrades keep them. To use your own Caddyfile instead, mount it over `/etc/caddy/Caddyfile` on the `edge` service in `custom.compose.yml`.## When something is wrong@@ -145,6 +155,6 @@ This checks your instance and the machine, and tells you how to fix each problem## Manage it without rexctl-To run your instance yourself with docker compose, run `rexctl eject`. Fluxer keeps running, and `rexctl takeover` hands it back to rexctl.+To run your instance yourself with docker compose, run `rexctl eject`. rexctl moves the Compose files and Caddyfile back into your instance folder and stops managing them. Fluxer keeps running, and `rexctl takeover` hands it back to rexctl.To upgrade Fluxer while you manage it yourself, run `rexctl takeover`, `rexctl upgrade` and `rexctl eject` one after the other. You can also [upgrade with the compose bundle](/operator/docker-compose/#upgrade) of the new version, the same way as an instance that never used rexctl.diff --git a/fluxer_rexctl/cmd/app.go b/fluxer_rexctl/cmd/app.goindex 7ef907b63..66abe03af 100644--- a/fluxer_rexctl/cmd/app.go+++ b/fluxer_rexctl/cmd/app.go@@ -18,13 +18,20 @@ import ("github.com/spf13/cobra""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/checks""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/deploy""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui")+const (+ docsURL = "https://docs.fluxer.app/operator/"+ changeHowFluxerRunsURL = docsURL + "running/#change-how-fluxer-runs"+)+type GlobalFlags struct {Dir stringYes bool@@ -40,9 +47,12 @@ type App struct {UI *ui.UIexit intoutcome string+ putBack []stringheld *instance.Instanceengine *engine.Enginewarned bool++ keepLayout bool}func (a *App) init(c *cobra.Command) {@@ -116,11 +126,15 @@ func (a *App) takeOverCommand() string {}func (a *App) Instance() (*instance.Instance, error) {+ return a.InstanceRepairing(nil)+}++func (a *App) InstanceRepairing(keys []string) (*instance.Instance, error) {dir, err := a.Dir()if err != nil {return nil, err}- inst, err := instance.Find(dir)+ inst, err := instance.FindRepairing(dir, keys)var se *instance.SettingErrorswitch {case err == nil:@@ -149,8 +163,10 @@ func (a *App) warnUnknown(inst *instance.Instance) {a.UI.Warn("This instance has settings this rexctl doesn't know: "+ui.JoinAnd(inst.State.Unknown)+".", "rexctl keeps them. Run rexctl upgrade if a newer rexctl wrote them.")}+var euid = os.Geteuid+func rootlessGuard(inst *instance.Instance) error {- if inst == nil || inst.State == nil || os.Geteuid() != 0 {+ if inst == nil || inst.State == nil || euid() != 0 {return nil}uid, ok := inst.OwnerUID()@@ -286,13 +302,17 @@ func (a *App) Locked(ctx context.Context, inst *instance.Instance, fn func() errif err != nil {return err}- return a.holding(inst, l, fn)+ return a.holding(ctx, inst, l, fn)}-func (a *App) holding(inst *instance.Instance, l *instance.Lock, fn func() error) error {+func (a *App) holding(ctx context.Context, inst *instance.Instance, l *instance.Lock, fn func() error) error {defer l.Release()+ if err := rootlessGuard(inst); err != nil {+ return err+ }a.held = instdefer func() { a.held = nil }()+ a.migrate(ctx, inst)if a.engine != nil {if err := a.pin(inst, a.engine); err != nil {return err@@ -301,6 +321,23 @@ func (a *App) holding(inst *instance.Instance, l *instance.Lock, fn func() errorreturn fn()}+var refreshUnitBinaries = func(ctx context.Context, inst *instance.Instance) error {+ bin, err := checks.RunningBinary()+ if err != nil {+ return err+ }+ return host.RefreshUnitBinaries(ctx, inst.Project(), bin)+}++func (a *App) migrate(ctx context.Context, inst *instance.Instance) {+ if a.keepLayout || !inst.OldLayout() {+ return+ }+ if err := inst.Migrate(func() error { return refreshUnitBinaries(ctx, inst) }); err != nil {+ a.UI.Detail("rexctl keeps Fluxer's files in %s for now: %v", inst.Dir, err)+ }+}+func (a *App) Change(ctx context.Context, inst *instance.Instance, fn func(e *engine.Engine) error) error {return a.change(ctx, inst, true, fn)}@@ -353,10 +390,27 @@ func managed(inst *instance.Instance) error {}func (a *App) drift(inst *instance.Instance, clean, withEnv bool) error {+ if clean {+ edits, err := instance.KeepEdits(inst)+ if err != nil {+ return ui.Wrap(err, "rexctl can't keep a copy of the files you changed.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ for _, ed := range edits {+ a.showEdit(ed)+ }+ if len(edits) > 0 && a.UI.Interactive() {+ instance.SeenEdits(inst)+ }+ }r, err := instance.Drift(inst)if err != nil {return ui.Wrap(err, "rexctl can't check Fluxer's files.", "Check that you can read "+inst.Dir+", then try again.")}+ if !clean {+ for _, name := range r.Changed {+ a.UI.Warn(name+" was changed by hand. rexctl puts its own version back and keeps a copy of yours.", editFix(name))+ }+ }if r.Env != nil && !r.Env.Same && !withEnv {r.Env = nil}@@ -382,6 +436,21 @@ func (a *App) drift(inst *instance.Instance, clean, withEnv bool) error {return nil}+func (a *App) showEdit(ed instance.Edit) {+ a.UI.Warn(fmt.Sprintf("%s was changed by hand. rexctl puts its own version back and keeps your copy in %s.", ed.Name, ed.Copy), editFix(ed.Name))+ for _, line := range ed.Diff {+ a.UI.Info(" %s", line)+ }+ a.putBack = append(a.putBack, fmt.Sprintf("rexctl put back its own %s. Your copy is in %s.", ed.Name, ed.Copy))+}++func editFix(name string) string {+ if name == stack.Caddyfile {+ return "Put extra Caddy directives in a .caddy file in " + instance.CaddyDropInDir + ", which rexctl keeps."+ }+ return "Put Compose changes in " + instance.CustomCompose + " with rexctl config edit, and change settings with rexctl config set."+}+func (a *App) replacePodmanCompose(ctx context.Context, inst *instance.Instance, e *engine.Engine) error {if e.Kind != engine.Podman {return nildiff --git a/fluxer_rexctl/cmd/autoupgrade.go b/fluxer_rexctl/cmd/autoupgrade.goindex 71e4f85e5..63c45825e 100644--- a/fluxer_rexctl/cmd/autoupgrade.go+++ b/fluxer_rexctl/cmd/autoupgrade.go@@ -323,6 +323,7 @@ func notifyUpgrade(ctx context.Context, app *App, runErr error) {default:return}+ n.Text = strings.Join(append([]string{n.Text}, app.putBack...), " ")if n.Instance != "" {n.Text = n.Instance + ": " + n.Text}diff --git a/fluxer_rexctl/cmd/config.go b/fluxer_rexctl/cmd/config.goindex a6040b352..40e214934 100644--- a/fluxer_rexctl/cmd/config.go+++ b/fluxer_rexctl/cmd/config.go@@ -93,8 +93,8 @@ type configView struct {schema []adminapi.ConfigKey}-func loadConfigView(app *App) (*configView, error) {- inst, err := app.Instance()+func loadConfigView(app *App, repairing []string) (*configView, error) {+ inst, err := app.InstanceRepairing(repairing)if err != nil {return nil, err}@@ -273,7 +273,7 @@ func (v *configView) deploymentKeys() []settings.Key {func newConfigCmd(app *App) *cobra.Command {c := &cobra.Command{Use: "config", Short: "Read and change Fluxer's settings", Args: noArgs}- c.AddCommand(newConfigListCmd(app), newConfigGetCmd(app), newConfigSetCmd(app), newConfigUnsetCmd(app), newConfigRenderCmd(app))+ c.AddCommand(newConfigListCmd(app), newConfigGetCmd(app), newConfigSetCmd(app), newConfigUnsetCmd(app), newConfigEditCmd(app), newConfigRenderCmd(app))return c}@@ -282,7 +282,7 @@ func newConfigListCmd(app *App) *cobra.Command {app.jsonFlag(list)list.RunE = func(c *cobra.Command, _ []string) error {ctx := c.Context()- v, err := loadConfigView(app)+ v, err := loadConfigView(app, nil)if err != nil {return err}@@ -333,7 +333,7 @@ func newConfigGetCmd(app *App) *cobra.Command {app.jsonFlag(get)get.Flags().BoolVar(&reveal, "reveal", false, "print a secret rexctl keeps")get.RunE = func(c *cobra.Command, args []string) error {- v, err := loadConfigView(app)+ v, err := loadConfigView(app, nil)if err != nil {return err}@@ -487,7 +487,11 @@ func newConfigUnsetCmd(app *App) *cobra.Command {}func runConfigChange(ctx context.Context, app *App, changes []configChange) error {- v, err := loadConfigView(app)+ typed := make([]string, 0, len(changes))+ for _, ch := range changes {+ typed = append(typed, ch.name)+ }+ v, err := loadConfigView(app, typed)if err != nil {return err}@@ -513,7 +517,7 @@ func runConfigChange(ctx context.Context, app *App, changes []configChange) erroif err != nil {return err}- reportConfigChange(app, change, deployment, sent)+ reportConfigChange(app, change, deployment, sent, v.inst.State.Upgrade != nil)names := slices.Collect(maps.Keys(deployment))for _, ac := range admin {names = append(names, ac.key.Key)@@ -539,7 +543,7 @@ func runConfigChange(ctx context.Context, app *App, changes []configChange) erro})}-func reportConfigChange(app *App, change *deploy.Change, values map[string]*string, admin []adminChange) {+func reportConfigChange(app *App, change *deploy.Change, values map[string]*string, admin []adminChange, upgrading bool) {var keys []stringif change != nil && !change.Unchanged {keys = change.Keys@@ -555,7 +559,10 @@ func reportConfigChange(app *App, change *deploy.Change, values map[string]*stridefault:app.UI.OK("%s", deploymentDone(keys[0], values[keys[0]]))}- if len(keys) > 0 && !change.Applied {+ switch {+ case len(keys) > 0 && upgrading:+ app.UI.Info("rexctl upgrade uses the new setting when it finishes.")+ case len(keys) > 0 && !change.Applied:app.UI.Info("Fluxer uses the new settings the next time it starts.")}}diff --git a/fluxer_rexctl/cmd/config_edit.go b/fluxer_rexctl/cmd/config_edit.gonew file mode 100644index 000000000..2d9bcfe5a--- /dev/null+++ b/fluxer_rexctl/cmd/config_edit.go@@ -0,0 +1,484 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io/fs"+ "maps"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "runtime"+ "slices"+ "strings"+ "time"++ "github.com/spf13/cobra"+ "go.yaml.in/yaml/v4"+ "golang.org/x/term"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/deploy"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++const (+ editDir = "edit"+ quickEditor = time.Second+)++var errNotAsked = errors.New("cmd: no one to ask")++var yamlLine = regexp.MustCompile(`\bL(\d+)\.C\d+`)++func newConfigEditCmd(app *App) *cobra.Command {+ return &cobra.Command{+ Use: "edit",+ Short: "Edit " + instance.CustomCompose + ", check it and apply it",+ Long: "Opens " + instance.CustomCompose + " in $VISUAL or $EDITOR. rexctl checks the file, says which services restart and applies it once you agree. " ++ "Your file stays as it was until it passes the check.",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runConfigEdit(c.Context(), app)+ },+ }+}++var openEditor = func(ctx context.Context, path string) error {+ if !term.IsTerminal(int(os.Stdin.Fd())) {+ return &ui.ExitError{Code: ui.ExitUsage, Msg: "rexctl config edit needs a terminal.",+ Fix: "Edit " + instance.CustomCompose + " in your instance folder yourself, then run rexctl restart."}+ }+ editor, ok := editorCommand()+ if !ok {+ return ui.Refused("rexctl can't find an editor.", "Set $EDITOR to the editor you use, then try again.")+ }+ c := editorCmd(ctx, editor, path)+ c.Stdin, c.Stdout, c.Stderr = os.Stdin, os.Stdout, os.Stderr+ if err := c.Run(); err != nil {+ var ee *exec.ExitError+ if errors.Is(err, exec.ErrNotFound) || errors.As(err, &ee) && ee.ExitCode() == 127 {+ return ui.Wrap(err, "rexctl can't find the editor "+editor+".", "Set $EDITOR to the editor you use, then try again.")+ }+ return ui.Wrap(err, "The editor "+editor+" didn't finish.", "Set $EDITOR to the editor you use, then try again.")+ }+ return nil+}++func editorCommand() (string, bool) {+ for _, name := range []string{"VISUAL", "EDITOR"} {+ if v := strings.TrimSpace(os.Getenv(name)); v != "" {+ return v, true+ }+ }+ if runtime.GOOS == "windows" {+ return "notepad", true+ }+ for _, name := range []string{"nano", "vi"} {+ if _, err := exec.LookPath(name); err == nil {+ return name, true+ }+ }+ return "", false+}++func editorCmd(ctx context.Context, editor, path string) *exec.Cmd {+ if runtime.GOOS == "windows" {+ args := splitCommand(editor)+ return exec.CommandContext(ctx, args[0], append(args[1:], path)...)+ }+ return exec.CommandContext(ctx, "sh", "-c", editor+` "$@"`, editor, path)+}++func splitCommand(s string) []string {+ var out []string+ var cur strings.Builder+ quoted, started := false, false+ for _, r := range s {+ switch {+ case r == '"':+ quoted, started = !quoted, true+ case (r == ' ' || r == '\t') && !quoted:+ if started {+ out = append(out, cur.String())+ cur.Reset()+ started = false+ }+ default:+ cur.WriteRune(r)+ started = true+ }+ }+ if started {+ out = append(out, cur.String())+ }+ return out+}++var askEdit = func(u *ui.UI, question string, def bool) (bool, error) {+ if u.Yes() || !u.Interactive() {+ return false, errNotAsked+ }+ return u.Confirm(question, def)+}++func runConfigEdit(ctx context.Context, app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ if err := managed(inst); err != nil {+ return err+ }+ if inst.State.Upgrade != nil {+ return ui.Refused("An upgrade of this instance hasn't finished.", "Run rexctl upgrade to finish it, then try again.")+ }+ return app.Locked(ctx, inst, func() error {+ e, err := app.guard(ctx, inst, true)+ if err != nil {+ return err+ }+ return editCustom(ctx, app, inst, e)+ })+}++func keptAsItWas() error {+ return ui.Refused(fmt.Sprintf("Kept %s as it was.", instance.CustomCompose), "")+}++func editCustom(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine) (err error) {+ path := inst.Path(instance.CustomCompose)+ start, rerr := os.ReadFile(path)+ existed := rerr == nil+ switch {+ case errors.Is(rerr, fs.ErrNotExist):+ start = []byte(instance.CustomTemplate)+ case rerr != nil:+ return ui.Wrap(rerr, fmt.Sprintf("rexctl can't read %s.", instance.CustomCompose), "Check that you can read it, then try again.")+ }+ draft, err := newDraft(inst, start)+ if err != nil {+ return ui.Wrap(err, "Couldn't make a copy to edit.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ after := start+ defer func() {+ if now, rerr := os.ReadFile(draft); rerr == nil {+ after = now+ }+ if err == nil || bytes.Equal(after, start) {+ os.Remove(draft)+ return+ }+ kept, kerr := keepDraft(inst, draft)+ if kerr != nil {+ kept = draft+ }+ instance.SeenEdits(inst)+ app.UI.Info("Your draft is in %s.", kept)+ }()+ failed := false+ for {+ began := time.Now()+ if err := openEditor(ctx, draft); err != nil {+ return err+ }+ next, err := os.ReadFile(draft)+ if err != nil {+ return err+ }+ same := bytes.Equal(next, after)+ after = next+ if bytes.Equal(after, start) {+ app.UI.OK("Nothing changed.")+ if time.Since(began) < quickEditor {+ app.UI.Info("If your editor opens a window, use code --wait.")+ }+ return nil+ }+ if failed && same {+ return keptAsItWas()+ }+ problem := checkCustom(ctx, inst, draft, after)+ if problem == "" {+ break+ }+ failed = true+ app.UI.Fail(fmt.Sprintf("Your change to %s doesn't work.", instance.CustomCompose), "")+ for _, line := range strings.Split(problem, "\n") {+ app.UI.Info(" %s", line)+ }+ again, err := askEdit(app.UI, "Edit it again? No keeps the file as it was.", true)+ if errors.Is(err, errNotAsked) || err == nil && !again {+ return keptAsItWas()+ }+ if err != nil {+ return err+ }+ }+ if err := confirmRisks(ctx, app, inst, draft); err != nil {+ return err+ }+ return applyCustom(ctx, app, inst, e, draft, start, existed, after)+}++func newDraft(inst *instance.Instance, data []byte) (string, error) {+ dir := inst.Path(instance.StateDirName, editDir)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return "", err+ }+ f, err := os.CreateTemp(dir, "custom.compose-*.yml")+ if err != nil {+ return "", err+ }+ if _, err := f.Write(data); err != nil {+ f.Close()+ os.Remove(f.Name())+ return "", err+ }+ if err := f.Close(); err != nil {+ os.Remove(f.Name())+ return "", err+ }+ return f.Name(), nil+}++func keepDraft(inst *instance.Instance, draft string) (string, error) {+ dir := inst.Path(instance.StateDirName, instance.EditedDir)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return "", err+ }+ kept := filepath.Join(dir, instance.CustomCompose+"."+time.Now().UTC().Format("20060102-150405"))+ return kept, os.Rename(draft, kept)+}++func checkCustom(ctx context.Context, inst *instance.Instance, draft string, data []byte) string {+ var doc map[string]any+ if err := yaml.Unmarshal(data, &doc); err != nil {+ lead := "The file isn't valid YAML."+ if m := yamlLine.FindStringSubmatch(err.Error()); m != nil {+ lead = fmt.Sprintf("Line %s isn't valid YAML.", m[1])+ }+ return lead + "\n" + err.Error()+ }+ s, err := customSpec(inst, draft)+ if err != nil {+ return err.Error()+ }+ var none engine.Engine+ if _, err := none.Load(ctx, s); err != nil {+ return composeProblem(err)+ }+ return ""+}++func customSpec(inst *instance.Instance, draft string) (engine.Spec, error) {+ s, err := deploy.Spec(inst)+ if err != nil {+ return s, err+ }+ s.Files = slices.DeleteFunc(s.Files, func(f string) bool { return f == inst.Path(instance.CustomCompose) })+ s.Files = append(s.Files, draft)+ return s, nil+}++type customRisks struct {+ removals []string+ changes []string+ env []string+}++func risksOf(ctx context.Context, inst *instance.Instance, draft string) (customRisks, error) {+ var r customRisks+ s, err := customSpec(inst, draft)+ if err != nil {+ return r, err+ }+ var none engine.Engine+ merged, err := none.Load(ctx, s)+ if err != nil {+ return r, err+ }+ s.Files = s.Files[:len(s.Files)-1]+ base, err := none.Load(ctx, s)+ if err != nil {+ return r, err+ }+ for _, m := range merged.DroppedMounts(base) {+ r.removals = append(r.removals, "loses the volume at "+m)+ }+ envs := map[string]bool{}+ for _, name := range stack.Services {+ b, ok := base.Model.Services[name]+ m, mok := merged.Model.Services[name]+ if !ok || !mok {+ continue+ }+ for _, n := range slices.Sorted(maps.Keys(b.Networks)) {+ if _, ok := m.Networks[n]; !ok {+ r.removals = append(r.removals, fmt.Sprintf("%s loses the network %s", name, n))+ }+ }+ if m.Image != b.Image {+ r.changes = append(r.changes, fmt.Sprintf("%s runs %s instead of %s", name, m.Image, b.Image))+ }+ if !slices.Equal(m.Command, b.Command) || !slices.Equal(m.Entrypoint, b.Entrypoint) {+ r.changes = append(r.changes, fmt.Sprintf("%s runs another command than the one Fluxer ships", name))+ }+ for k, v := range m.Environment {+ if !strings.HasPrefix(k, "FLUXER_") {+ continue+ }+ if was, ok := b.Environment[k]; !ok || (was == nil) != (v == nil) || was != nil && *was != *v {+ envs[k] = true+ }+ }+ }+ r.env = slices.Sorted(maps.Keys(envs))+ return r, nil+}++func confirmRisks(ctx context.Context, app *App, inst *instance.Instance, draft string) error {+ r, err := risksOf(ctx, inst, draft)+ if err != nil {+ return ui.Wrap(err, fmt.Sprintf("rexctl can't compare %s with Fluxer's own files.", instance.CustomCompose), "Run rexctl config edit --verbose to see why.")+ }+ for _, line := range r.changes {+ app.UI.Warn(fmt.Sprintf("With your change, %s.", line), "")+ }+ if len(r.env) > 0 {+ app.UI.Warn(fmt.Sprintf("Your change sets %s, which rexctl manages.", ui.JoinAnd(r.env)), "Change these with rexctl config set, so upgrades and checks know about them.")+ }+ if len(r.removals) > 0 {+ app.UI.Warn(fmt.Sprintf("With your change, %s.", ui.JoinAnd(r.removals)), "Fluxer may lose data or stop working without them.")+ ok, err := askEdit(app.UI, "Remove them anyway?", false)+ if errors.Is(err, errNotAsked) {+ return ui.Refused(fmt.Sprintf("rexctl doesn't remove volumes or networks of Fluxer's services without asking. Kept %s as it was.", instance.CustomCompose), "Run rexctl config edit in a terminal, without --yes, to confirm.")+ }+ if err != nil {+ return err+ }+ if !ok {+ return keptAsItWas()+ }+ return nil+ }+ if len(r.changes) > 0 || len(r.env) > 0 {+ ok, err := app.UI.Confirm("Keep these changes?", false)+ if err != nil {+ return err+ }+ if !ok {+ return keptAsItWas()+ }+ }+ return nil+}++func planLines(plan *engine.Plan) []string {+ var out []string+ if len(plan.Recreate) > 0 {+ out = append(out, fmt.Sprintf("This restarts %s.", ui.JoinAnd(slices.Sorted(slices.Values(plan.Recreate)))))+ }+ if len(plan.Create) > 0 {+ out = append(out, fmt.Sprintf("This starts %s.", ui.JoinAnd(slices.Sorted(slices.Values(plan.Create)))))+ }+ if len(plan.Remove) > 0 {+ out = append(out, fmt.Sprintf("This removes %s.", ui.JoinAnd(plan.Remove)))+ }+ if len(out) == 0 {+ out = append(out, "No service restarts.")+ }+ return out+}++func startFailure(existed bool) string {+ if existed {+ return fmt.Sprintf("Fluxer didn't start with your change. rexctl put the old %s back.", instance.CustomCompose)+ }+ return fmt.Sprintf("Fluxer didn't start with your change. rexctl removed the new %s.", instance.CustomCompose)+}++func unchangedSince(path string, start []byte, existed bool) error {+ now, err := os.ReadFile(path)+ if existed && err == nil && bytes.Equal(now, start) || !existed && errors.Is(err, fs.ErrNotExist) {+ return nil+ }+ return ui.Refused(fmt.Sprintf("%s changed while you were editing it.", instance.CustomCompose), "Run rexctl config edit again to start from the new file.")+}++func applyCustom(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, draft string, start []byte, existed bool, data []byte) error {+ path := inst.Path(instance.CustomCompose)+ var p *engine.Project+ if !inst.State.Stopped {+ s, err := customSpec(inst, draft)+ if err != nil {+ return err+ }+ if p, err = e.Load(ctx, s); err != nil {+ return engineFailure(err)+ }+ if plan, err := p.Plan(ctx); err == nil {+ for _, line := range planLines(plan) {+ app.UI.Info("%s", line)+ }+ } else {+ app.UI.Detail("%v", err)+ }+ }+ ok, err := app.UI.Confirm("Apply the change?", true)+ if err != nil {+ return err+ }+ if !ok {+ return keptAsItWas()+ }+ if err := unchangedSince(path, start, existed); err != nil {+ return err+ }+ if p != nil {+ err := app.UI.Step(ctx, "Downloading what your change needs", func(ctx context.Context, s *ui.Step) error {+ if err := p.Pull(ctx, app.progress(s, "Downloading")); err != nil {+ return err+ }+ s.Done("Downloaded what your change needs.")+ return nil+ })+ if err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't download the images your change needs. Fluxer still runs as it was, and %s didn't change.", instance.CustomCompose), "Check the image names and this machine's internet connection, then try again.")+ }+ }+ if err := envfile.WriteFileAtomic(path, data, false); err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't save %s.", instance.CustomCompose), "Check that you can write to "+inst.Dir+", then try again.")+ }+ if inst.State.Stopped {+ app.UI.OK("Saved %s. Fluxer uses it the next time it starts.", instance.CustomCompose)+ return nil+ }+ err = app.UI.Step(ctx, "Applying "+instance.CustomCompose, func(ctx context.Context, s *ui.Step) error {+ if _, err := deploy.Apply(ctx, inst, e, deploy.ApplyOptions{Wait: true, OnEvent: app.progress(s, "Starting")}); err != nil {+ return readyFailure(ctx, inst, e.Named(inst.Project(), inst.Dir), err)+ }+ s.Done("Applied %s.", instance.CustomCompose)+ return nil+ })+ if err == nil {+ return nil+ }+ restore := os.Remove(path)+ if existed {+ restore = envfile.WriteFileAtomic(path, start, false)+ }+ if restore != nil {+ return errors.Join(err, restore)+ }+ app.UI.Warn(startFailure(existed), "Run rexctl restart to start Fluxer with the file as it was.")+ return err+}diff --git a/fluxer_rexctl/cmd/config_edit_test.go b/fluxer_rexctl/cmd/config_edit_test.gonew file mode 100644index 000000000..0ce87824d--- /dev/null+++ b/fluxer_rexctl/cmd/config_edit_test.go@@ -0,0 +1,377 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++func editTest(t *testing.T, yes, stopped bool, edits ...func(path string) error) (*App, *instance.Instance, *bytes.Buffer, *int) {+ t.Helper()+ app, inst, out := testInstance(t, yes)+ if stopped {+ inst.State.Stopped = true+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ }+ opened := 0+ prev, prevAsk := openEditor, askEdit+ t.Cleanup(func() { openEditor, askEdit = prev, prevAsk })+ openEditor = func(_ context.Context, path string) error {+ opened+++ if opened > len(edits) {+ t.Errorf("opened the editor %d times", opened)+ return errors.New("too many edits")+ }+ return edits[opened-1](path)+ }+ return app, inst, out, &opened+}++func write(data string) func(string) error {+ return func(path string) error { return os.WriteFile(path, []byte(data), 0o644) }+}++func keep(string) error { return nil }++func editedCopies(t *testing.T, inst *instance.Instance) [][]byte {+ t.Helper()+ entries, _ := os.ReadDir(inst.Path(instance.StateDirName, instance.EditedDir))+ var out [][]byte+ for _, e := range entries {+ if strings.HasPrefix(e.Name(), instance.CustomCompose) {+ data, err := os.ReadFile(inst.Path(instance.StateDirName, instance.EditedDir, e.Name()))+ if err != nil {+ t.Fatal(err)+ }+ out = append(out, data)+ }+ }+ return out+}++func noCustom(t *testing.T, inst *instance.Instance) {+ t.Helper()+ if _, err := os.Stat(inst.Path(instance.CustomCompose)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("%s was written: %v", instance.CustomCompose, err)+ }+}++func TestConfigEditUnderYesStopsAtBrokenDraft(t *testing.T) {+ app, inst, out, opened := editTest(t, true, true, write("services: [\n"))+ err := runConfigEdit(context.Background(), app)+ if exitCode(err) != ui.ExitRefused || *opened != 1 {+ t.Fatalf("err %v after %d edits", err, *opened)+ }+ noCustom(t, inst)+ if copies := editedCopies(t, inst); len(copies) != 1 || string(copies[0]) != "services: [\n" {+ t.Fatalf("kept %q", copies)+ }+ if !strings.Contains(out.String(), "Your draft is in") {+ t.Fatalf("output doesn't say where the draft is:\n%s", out)+ }+}++func TestConfigEditStopsWhenDraftUnchanged(t *testing.T) {+ app, inst, _, opened := editTest(t, true, true, write("services: [\n"), keep)+ askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }+ err := runConfigEdit(context.Background(), app)+ if *opened != 2 || err == nil || !strings.Contains(err.Error(), "Kept "+instance.CustomCompose+" as it was.") {+ t.Fatalf("err %v after %d edits", err, *opened)+ }+ noCustom(t, inst)+}++func TestConfigEditTakesLockBeforeEditor(t *testing.T) {+ app, inst, _, opened := editTest(t, true, true, write("services: {}\n"))+ l, err := inst.Lock(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer l.Release()+ err = runConfigEdit(context.Background(), app)+ if *opened != 0 || exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "Another rexctl command") {+ t.Fatalf("err %v after %d edits", err, *opened)+ }+}++func TestConfigEditKeepsDraftWhenFileChangedMeanwhile(t *testing.T) {+ var inst *instance.Instance+ var draftPath string+ byHand := []byte("services: {}\n# by hand\n")+ app, inst, out, _ := editTest(t, true, true, func(path string) error {+ draftPath = path+ if err := os.WriteFile(inst.Path(instance.CustomCompose), byHand, 0o644); err != nil {+ return err+ }+ return os.WriteFile(path, []byte("services:\n edge:\n labels:\n team: chat\n"), 0o644)+ })+ swap := filepath.Join(inst.StateDir(), editDir, ".custom.compose.yml.swp")+ if err := os.MkdirAll(filepath.Dir(swap), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(swap, []byte("swap"), 0o600); err != nil {+ t.Fatal(err)+ }+ err := runConfigEdit(context.Background(), app)+ if exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "changed while you were editing") {+ t.Fatalf("err %v\n%s", err, out)+ }+ if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); !bytes.Equal(got, byHand) {+ t.Fatalf("overwrote the hand edit with %q", got)+ }+ if _, err := os.Stat(swap); err != nil {+ t.Fatalf("deleted a file rexctl didn't create: %v", err)+ }+ if draftPath == filepath.Join(inst.StateDir(), editDir, instance.CustomCompose) {+ t.Fatal("every run edits the same draft")+ }+ if copies := editedCopies(t, inst); len(copies) != 1 || !bytes.Contains(copies[0], []byte("team: chat")) {+ t.Fatalf("kept %q", copies)+ }+}++func TestConfigEditKeepsDraftWhenEditorFails(t *testing.T) {+ saved := "services:\n edge:\n labels:\n team: chat\n"+ app, inst, out, _ := editTest(t, true, true, func(path string) error {+ if err := os.WriteFile(path, []byte(saved), 0o644); err != nil {+ return err+ }+ return errors.New("the editor was killed")+ })+ if err := runConfigEdit(context.Background(), app); err == nil {+ t.Fatal("a failed editor counted as a change")+ }+ noCustom(t, inst)+ if copies := editedCopies(t, inst); len(copies) != 1 || string(copies[0]) != saved {+ t.Fatalf("lost what you saved before the editor failed, kept %q\n%s", copies, out)+ }+}++func TestConfigEditAsksBeforeDroppingFluxerVolumes(t *testing.T) {+ drop := "services:\n postgres:\n volumes: !reset []\n"+ app, inst, out, _ := editTest(t, true, true, write(drop))+ err := runConfigEdit(context.Background(), app)+ if exitCode(err) != ui.ExitRefused || !strings.Contains(out.String(), "loses the volume") {+ t.Fatalf("err %v\n%s", err, out)+ }+ noCustom(t, inst)++ app, inst, out, _ = editTest(t, true, true, write(drop))+ askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }+ if err := runConfigEdit(context.Background(), app); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); string(got) != drop {+ t.Fatalf("saved %q", got)+ }+}++func TestConfigEditWarnsAboutImagesAndManagedVariables(t *testing.T) {+ change := "services:\n api:\n image: example/api:1\n environment:\n FLUXER_DOMAIN: other.example.com\n"+ app, inst, out, _ := editTest(t, true, true, write(change))+ if err := runConfigEdit(context.Background(), app); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ for _, want := range []string{"api runs example/api:1", "FLUXER_DOMAIN", "rexctl config set"} {+ if !strings.Contains(out.String(), want) {+ t.Fatalf("output doesn't say %q:\n%s", want, out)+ }+ }+ if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); string(got) != change {+ t.Fatalf("saved %q", got)+ }+}++func TestConfigEditReportsDownloadFailureAccurately(t *testing.T) {+ app, inst, out, _ := editTest(t, true, false, write("services:\n edge:\n labels:\n team: chat\n"))+ err := runConfigEdit(context.Background(), app)+ if err == nil || !strings.Contains(err.Error(), "Couldn't download") || strings.Contains(out.String(), "didn't start") {+ t.Fatalf("err %v\n%s", err, out)+ }+ noCustom(t, inst)+}++func TestStartFailureSaysWhatHappenedToTheFile(t *testing.T) {+ if strings.Contains(startFailure(false), "put the old") || !strings.Contains(startFailure(true), "put the old") {+ t.Fatalf("%q / %q", startFailure(false), startFailure(true))+ }+}++func TestPlanLinesSayStartsForNewServices(t *testing.T) {+ got := planLines(&engine.Plan{Create: []string{"worker"}, Recreate: []string{"api"}})+ if want := []string{"This restarts api.", "This starts worker."}; !slices.Equal(got, want) {+ t.Fatalf("%q, want %q", got, want)+ }+}++func TestYAMLProblemNamesTheLine(t *testing.T) {+ _, inst, _ := testInstance(t, true)+ got := checkCustom(context.Background(), inst, "", []byte("services: [\n"))+ if !strings.HasPrefix(got, "Line 2 isn't valid YAML.\n") {+ t.Fatalf("%q", got)+ }+}++func TestQuickEditorGetsHint(t *testing.T) {+ app, _, out, _ := editTest(t, true, true, keep)+ if err := runConfigEdit(context.Background(), app); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(out.String(), "If your editor opens a window, use code --wait.") {+ t.Fatalf("no hint:\n%s", out)+ }+}++func TestEditorRunsThroughTheShell(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("uses sh")+ }+ dir := filepath.Join(t.TempDir(), "my editor")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ script := filepath.Join(dir, "edit.sh")+ if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf '%s' \"$1\" > \"$2\"\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ target := filepath.Join(t.TempDir(), "file")+ if err := editorCmd(context.Background(), "'"+script+"' edited", target).Run(); err != nil {+ t.Fatal(err)+ }+ if got, _ := os.ReadFile(target); string(got) != "edited" {+ t.Fatalf("editor wrote %q", got)+ }+}++func TestSplitCommandKeepsQuotedPaths(t *testing.T) {+ got := splitCommand(`"C:\Program Files\Notepad++\notepad++.exe" -multiInst`)+ if want := []string{`C:\Program Files\Notepad++\notepad++.exe`, "-multiInst"}; !slices.Equal(got, want) {+ t.Fatalf("%q", got)+ }+}++func TestNoEditorFound(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("notepad is always there")+ }+ t.Setenv("VISUAL", "")+ t.Setenv("EDITOR", "")+ t.Setenv("PATH", t.TempDir())+ if editor, ok := editorCommand(); ok {+ t.Fatalf("found %q", editor)+ }+}++func TestNotificationSaysWhichFilesWerePutBack(t *testing.T) {+ var body []byte+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ = io.ReadAll(r.Body)+ }))+ defer srv.Close()+ app, inst, _ := testInstance(t, true)+ inst.State.NotifyURL = srv.URL+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ path := inst.Generated(stack.ComposeFile)+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, append(data, "# mine\n"...), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := app.drift(inst, true, false); err != nil {+ t.Fatal(err)+ }+ app.outcome = "Upgraded to Fluxer 1."+ notifyUpgrade(context.Background(), app, nil)+ var n upgradeNotice+ if err := json.Unmarshal(body, &n); err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(n.Text, "rexctl put back its own "+stack.ComposeFile+". Your copy is in "+inst.Path(instance.StateDirName, instance.EditedDir)) {+ t.Fatalf("notice %q", n.Text)+ }+ if len(instance.UnseenEdits(inst)) != 1 {+ t.Fatal("an unattended put back isn't left for status and doctor to show")+ }+}++func TestConfigRepairsSettingAfterUpgradePulled(t *testing.T) {+ app, inst, out := testInstance(t, true)+ inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhasePulled}+ inst.State.Settings[settings.EdgeHTTPPort] = "not-a-port"+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort}}); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ found, err := instance.Find(inst.Dir)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := found.State.Settings[settings.EdgeHTTPPort]; ok {+ t.Fatal("the invalid setting is still there")+ }+ v := "8080"+ if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort, value: &v}}); exitCode(err) != ui.ExitRefused {+ t.Fatalf("changed a valid setting halfway through an upgrade: %v", err)+ }+}++func TestConfigSetDuringUpgradeChecksPorts(t *testing.T) {+ app, inst, out := testInstance(t, true)+ inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhaseSelfUpdated}+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ v := "7881"+ err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort, value: &v}})+ if exitCode(err) != ui.ExitRefused || !strings.Contains(err.Error(), "already uses") {+ t.Fatalf("err %v\n%s", err, out)+ }+}++func TestStatusPointsToCopiesUntilDoctorShowsThem(t *testing.T) {+ app, inst, out := testInstance(t, true)+ dir := inst.Path(instance.StateDirName, instance.EditedDir)+ if err := os.MkdirAll(dir, 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, stack.ComposeFile+".20260101-000000"), []byte("mine"), 0o600); err != nil {+ t.Fatal(err)+ }+ _ = runStatus(context.Background(), app)+ if !strings.Contains(out.String(), "Your copies are in "+dir) {+ t.Fatalf("status doesn't point to the copies:\n%s", out)+ }+ instance.SeenEdits(inst)+ out.Reset()+ _ = runStatus(context.Background(), app)+ if strings.Contains(out.String(), "Your copies are in") {+ t.Fatalf("status still points to copies you saw:\n%s", out)+ }+}diff --git a/fluxer_rexctl/cmd/doctor.go b/fluxer_rexctl/cmd/doctor.goindex c18428939..cb6b57235 100644--- a/fluxer_rexctl/cmd/doctor.go+++ b/fluxer_rexctl/cmd/doctor.go@@ -71,6 +71,12 @@ func runDoctor(ctx context.Context, app *App, fix bool) error {}run := func() error {results := diagnose(ctx, app, env, phase, fix)+ if env.Instance != nil {+ warnUnusedRootFiles(ctx, app, env.Instance)+ }+ if env.Instance != nil && app.UI.Interactive() {+ instance.SeenEdits(env.Instance)+ }var ej *instance.EjectedErrorif errors.As(env.Instance.Managed(), &ej) && !app.Flags.JSON {defer app.UI.Info("%s %s", ej.Error(), ej.Fix())diff --git a/fluxer_rexctl/cmd/eject.go b/fluxer_rexctl/cmd/eject.goindex 311b02aeb..088e00bd0 100644--- a/fluxer_rexctl/cmd/eject.go+++ b/fluxer_rexctl/cmd/eject.go@@ -44,14 +44,9 @@ func runEject(ctx context.Context, app *App) error {}e, engineErr := app.Engine(ctx, inst)tool := composeTool(inst, e)- u.Info("rexctl writes every setting for %s into %s and stops changing this instance. Fluxer keeps running.", tool, inst.Dir)- ok, err := u.Confirm("Manage this instance yourself?", false)- if err != nil {+ if ok, err := confirmEject(u, inst, tool); err != nil || !ok {return err}- if !ok {- return ui.Refused("Your instance was left as it was.", "")- }removed := falseerr = instance.Eject(inst, instance.EjectOptions{Rexctl: app.Version,@@ -85,6 +80,26 @@ func runEject(ctx context.Context, app *App) error {})}+func confirmEject(u *ui.UI, inst *instance.Instance, tool string) (bool, error) {+ u.Info("You probably don't need to eject. rexctl keeps these changes when it upgrades Fluxer.")+ u.Info(" rexctl config set changes settings, including the FLUXER_* variables, and rexctl config list shows them.")+ u.Info(" rexctl config edit changes %s for labels, images, ports and volumes.", instance.CustomCompose)+ u.Info(" A .caddy file in %s adds your own Caddy directives.", instance.CaddyDropInDir)+ u.Info(" See %s for more.", changeHowFluxerRunsURL)+ u.Info("If you eject, rexctl writes every setting for %s into %s and stops managing the instance. You start, stop and change Fluxer with %s yourself, and rexctl turns off automatic upgrades. To upgrade later, you run rexctl takeover, rexctl upgrade and rexctl eject one after the other. Fluxer keeps running.", tool, inst.Dir, tool)+ if !u.Interactive() && !u.Yes() {+ return false, &ui.ExitError{Code: ui.ExitUsage, Msg: "rexctl eject asks before it hands the instance over.", Fix: "Pass --yes to eject without the question."}+ }+ ok, err := u.Confirm("Manage this instance yourself?", false)+ if err != nil {+ return false, err+ }+ if !ok {+ return false, ui.Refused("Your instance was left as it was.", "")+ }+ return true, nil+}+func sendAdminImport(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine) {client := app.adminClient(inst, e.Named(inst.Project(), inst.Dir))client.OnSkew = nildiff --git a/fluxer_rexctl/cmd/install.go b/fluxer_rexctl/cmd/install.goindex 0642488b1..977b0d4c2 100644--- a/fluxer_rexctl/cmd/install.go+++ b/fluxer_rexctl/cmd/install.go@@ -685,7 +685,7 @@ func (in *installer) proxyNote() {return}in.app.UI.Info("Set up your proxy to forward https://%s to http://%s.", normaliseDomain(in.f.Domain), in.f.Bind)- in.app.UI.Info("See https://docs.fluxer.app/operator/reverse-proxy/ for what your proxy needs to do.")+ in.app.UI.Info("See %sreverse-proxy/ for what your proxy needs to do.", docsURL)}func (in *installer) installDocker(ctx context.Context) error {@@ -1010,7 +1010,7 @@ func (in *installer) findLegacy(ctx context.Context) *instance.Legacy {continue}first := strings.Split(p.ConfigFiles, ",")[0]- if l, err := instance.DetectLegacy(filepath.Dir(first)); err == nil && l != nil {+ if l, err := instance.DetectLegacy(stack.ProjectDir(first)); err == nil && l != nil {return l}}@@ -1110,10 +1110,13 @@ func (in *installer) write(ctx context.Context, inst *instance.Instance, deleteOif err := release.WriteRelease(inst, set); err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't write Fluxer's files to %s.", inst.Dir), "Check the free disk space, then run rexctl install again.")}- r, err := stack.Render(set, stack.OverlaysFor(st.Settings), st.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(st.Settings), st.Images.Refs)if err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't write Fluxer's files to %s.", inst.Dir), "Check the free disk space, then run rexctl install again.")}+ if err := inst.WriteCustomTemplate(); err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't write %s to %s.", instance.CustomCompose, inst.Dir), "Check the free disk space, then run rexctl install again.")+ }st.Rendered = r.Hashesif err := inst.Save(); err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't save your settings in %s.", inst.Dir), "Check that you can write to it, then run rexctl install again.")diff --git a/fluxer_rexctl/cmd/layout_test.go b/fluxer_rexctl/cmd/layout_test.gonew file mode 100644index 000000000..da0375a0a--- /dev/null+++ b/fluxer_rexctl/cmd/layout_test.go@@ -0,0 +1,168 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++func testInstance(t *testing.T, yes bool) (*App, *instance.Instance, *bytes.Buffer) {+ t.Helper()+ inst, err := instance.Create(t.TempDir(), "fluxer")+ if err != nil {+ t.Fatal(err)+ }+ set := stack.Embedded()+ inst.State.Release = set.Release+ inst.State.Settings[settings.Domain] = "chat.example.com"+ if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {+ t.Fatal(err)+ }+ r, err := stack.Render(set, nil, inst.State.Images.Refs, inst.Project(), inst.Dir)+ if err != nil {+ t.Fatal(err)+ }+ inst.State.Rendered = r.Hashes+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ out := &bytes.Buffer{}+ app := &App{+ Flags: GlobalFlags{Dir: inst.Dir, Yes: yes},+ UI: ui.New(ui.Options{Yes: yes, Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),+ engine: &engine.Engine{Kind: engine.Docker},+ }+ return app, inst, out+}++func exitCode(err error) int {+ var ee *ui.ExitError+ if errors.As(err, &ee) {+ return ee.Code+ }+ return -1+}++func TestEjectExplainsAndRefusesWithoutYes(t *testing.T) {+ app, inst, out := testInstance(t, false)+ err := runEject(context.Background(), app)+ if code := exitCode(err); code != ui.ExitUsage {+ t.Fatalf("exit code %d (%v), want %d", code, err, ui.ExitUsage)+ }+ for _, want := range []string{"You probably don't need to eject.", "rexctl config set changes settings", "rexctl config list shows them", "FLUXER_*", "run rexctl takeover, rexctl upgrade and rexctl eject", "rexctl config edit", instance.CaddyDropInDir, changeHowFluxerRunsURL, "stops managing the instance"} {+ if !strings.Contains(out.String(), want) {+ t.Fatalf("output doesn't say %q:\n%s", want, out)+ }+ }+ if strings.Contains(out.String(), "config list and") || strings.Contains(out.String(), "upgrade Fluxer with") {+ t.Fatalf("output says config list changes settings or that you upgrade with compose yourself:\n%s", out)+ }+ found, err := instance.Find(inst.Dir)+ if err != nil || found.State.Ejected != nil {+ t.Fatalf("ejected without asking: %v", err)+ }+ if _, err := os.Stat(inst.Path(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("eject wrote files before asking")+ }+}++func TestConfigUnsetRepairsSettingDuringUnfinishedUpgrade(t *testing.T) {+ app, inst, out := testInstance(t, true)+ inst.State.Upgrade = &instance.Upgrade{From: inst.State.Release, To: "2099.1.0", Phase: release.PhaseSelfUpdated}+ inst.State.Settings[settings.EdgeHTTPPort] = "not-a-port"+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ if _, err := app.Instance(); exitCode(err) != ui.ExitRefused {+ t.Fatalf("loaded an invalid setting: %v", err)+ }+ if err := runConfigChange(context.Background(), app, []configChange{{name: settings.EdgeHTTPPort}}); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ found, err := instance.Find(inst.Dir)+ if err != nil {+ t.Fatal(err)+ }+ if _, ok := found.State.Settings[settings.EdgeHTTPPort]; ok {+ t.Fatal("the invalid setting is still there")+ }+ if found.State.Upgrade == nil || found.State.Upgrade.Phase != release.PhaseSelfUpdated {+ t.Fatal("the repair changed the upgrade")+ }+ if !strings.Contains(out.String(), "rexctl upgrade uses the new setting when it finishes.") || strings.Contains(out.String(), "the next time it starts") {+ t.Fatalf("output doesn't say once that the upgrade uses it:\n%s", out)+ }+}++func TestConfigEditKeepsFileUntilItWorks(t *testing.T) {+ app, inst, out := testInstance(t, true)+ inst.State.Stopped = true+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ edits := []string{"services: [\n", "services:\n edge:\n build: .\n", "services:\n edge:\n labels:\n team: chat\n"}+ var opened int+ prev, prevAsk := openEditor, askEdit+ t.Cleanup(func() { openEditor, askEdit = prev, prevAsk })+ askEdit = func(*ui.UI, string, bool) (bool, error) { return true, nil }+ openEditor = func(_ context.Context, path string) error {+ before, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if opened == 0 && string(before) != instance.CustomTemplate {+ t.Errorf("first edit started from %q", before)+ }+ if _, err := os.Stat(inst.Path(instance.CustomCompose)); !errors.Is(err, os.ErrNotExist) {+ t.Errorf("the file changed before it passed the check")+ }+ opened+++ return os.WriteFile(path, []byte(edits[opened-1]), 0o644)+ }+ if err := runConfigEdit(context.Background(), app); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ if opened != len(edits) {+ t.Fatalf("opened the editor %d times, want %d", opened, len(edits))+ }+ got, err := os.ReadFile(inst.Path(instance.CustomCompose))+ if err != nil || string(got) != edits[len(edits)-1] {+ t.Fatalf("saved %q, %v", got, err)+ }+ if left, _ := os.ReadDir(filepath.Join(inst.StateDir(), editDir)); len(left) > 0 {+ t.Fatalf("left the draft behind: %v", left)+ }+}++func TestConfigEditWithoutAnswerKeepsFile(t *testing.T) {+ app, inst, _ := testInstance(t, false)+ mine := []byte("services: {}\n")+ if err := os.WriteFile(inst.Path(instance.CustomCompose), mine, 0o644); err != nil {+ t.Fatal(err)+ }+ prev := openEditor+ t.Cleanup(func() { openEditor = prev })+ openEditor = func(_ context.Context, path string) error {+ return os.WriteFile(path, []byte("services: [\n"), 0o644)+ }+ if err := runConfigEdit(context.Background(), app); err == nil {+ t.Fatal("applied a broken file")+ }+ if got, _ := os.ReadFile(inst.Path(instance.CustomCompose)); !bytes.Equal(got, mine) {+ t.Fatalf("file changed to %q", got)+ }+}diff --git a/fluxer_rexctl/cmd/lifecycle.go b/fluxer_rexctl/cmd/lifecycle.goindex f6f5db6cb..984aa1837 100644--- a/fluxer_rexctl/cmd/lifecycle.go+++ b/fluxer_rexctl/cmd/lifecycle.go@@ -587,7 +587,10 @@ func runBootStart(ctx context.Context, app *App) error {if err != nil {return engineFailure(err)}- return readyFailure(ctx, inst, p, p.Up(context.WithoutCancel(ctx), engine.UpOptions{RemoveOrphans: true, Wait: true, WaitTimeout: engine.DefaultReadyTimeout}))+ if err := p.Up(context.WithoutCancel(ctx), engine.UpOptions{RemoveOrphans: true, Wait: true, WaitTimeout: engine.DefaultReadyTimeout}); err != nil {+ return readyFailure(ctx, inst, p, err)+ }+ return inst.DropRootCopies(ctx, true)}if p, err := deploy.Load(ctx, inst, e); err == nil && stackRunning(ctx, p) {app.sendAdminImport(ctx, inst, p)@@ -636,7 +639,7 @@ func bootLocked(ctx context.Context, app *App, inst *instance.Instance, fn func(for {l, err := inst.Lock(ctx)if err == nil {- return app.holding(inst, l, fn)+ return app.holding(ctx, inst, l, fn)}if !errors.Is(err, instance.ErrLocked) || time.Now().After(deadline) {return app.Locked(ctx, inst, fn)diff --git a/fluxer_rexctl/cmd/migrate_test.go b/fluxer_rexctl/cmd/migrate_test.gonew file mode 100644index 000000000..d71da2bb5--- /dev/null+++ b/fluxer_rexctl/cmd/migrate_test.go@@ -0,0 +1,238 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++func oldInstance(t *testing.T, yes bool) (*App, *instance.Instance, *bytes.Buffer) {+ t.Helper()+ app, inst, out := testInstance(t, yes)+ for name := range inst.State.Rendered {+ plain := stack.Plain(name, readFile(t, inst.Generated(name)))+ if err := os.WriteFile(inst.Path(name), plain, 0o644); err != nil {+ t.Fatal(err)+ }+ inst.State.Rendered[name] = stack.Hash(plain)+ }+ if err := os.RemoveAll(stack.GeneratedPath(inst.Dir)); err != nil {+ t.Fatal(err)+ }+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ data := bytes.Replace(readFile(t, inst.StatePath()), []byte(`"schema": 3`), []byte(`"schema": 2`), 1)+ if err := os.WriteFile(inst.StatePath(), data, 0o600); err != nil {+ t.Fatal(err)+ }+ old, err := instance.Find(inst.Dir)+ if err != nil || !old.OldLayout() {+ t.Fatalf("the fixture isn't on the old layout: %v", err)+ }+ stubUnits(t, func() error { return nil })+ return app, old, out+}++func stubUnits(t *testing.T, fn func() error) {+ t.Helper()+ prev := refreshUnitBinaries+ t.Cleanup(func() { refreshUnitBinaries = prev })+ refreshUnitBinaries = func(context.Context, *instance.Instance) error { return fn() }+}++func readFile(t *testing.T, path string) []byte {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ return data+}++func schemaOnDisk(t *testing.T, inst *instance.Instance) int {+ t.Helper()+ var head struct{ Schema int }+ if err := json.Unmarshal(readFile(t, inst.StatePath()), &head); err != nil {+ t.Fatal(err)+ }+ return head.Schema+}++func requireOldLayout(t *testing.T, inst *instance.Instance) {+ t.Helper()+ if s := schemaOnDisk(t, inst); s != 2 {+ t.Fatalf("schema on disk %d, want 2", s)+ }+ if _, err := os.Stat(inst.Path(stack.ComposeFile)); err != nil {+ t.Fatalf("the compose file left the instance folder: %v", err)+ }+ if _, err := os.Stat(stack.GeneratedPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("a read made the generated folder")+ }+}++func serveRelease(t *testing.T, rel release.Release) {+ t.Helper()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _ = json.NewEncoder(w).Encode(rel)+ }))+ t.Cleanup(srv.Close)+ t.Setenv(release.ResolverURLEnv, srv.URL)+}++func TestReadsLeaveTheOldLayout(t *testing.T) {+ app, inst, out := oldInstance(t, true)+ serveRelease(t, release.Release{Version: "2099.101.0", StateSchema: instance.StateSchema, Assets: []release.Asset{{OS: runtime.GOOS, Arch: runtime.GOARCH}}})+ ctx := context.Background()+ for name, run := range map[string]func() error{+ "instance": func() error { _, err := app.Instance(); return err },+ "config get": func() error { _, err := loadConfigView(app, nil); return err },+ "upgrade --check": func() error { return runUpgrade(ctx, app, &upgradeFlags{Check: true}) },+ "upgrade --dry-run": func() error { return runUpgrade(ctx, app, &upgradeFlags{DryRun: true}) },+ "declined upgrade": func() error {+ app.UI = ui.New(ui.Options{Stdin: strings.NewReader("n\n"), Stdout: out, Stderr: out})+ return runUpgrade(ctx, app, &upgradeFlags{})+ },+ } {+ if err := run(); err != nil && exitCode(err) == -1 {+ t.Fatalf("%s: %v\n%s", name, err, out)+ }+ requireOldLayout(t, inst)+ }+}++func TestOldLayoutLoadsWhileAnotherCommandHoldsIt(t *testing.T) {+ app, inst, _ := oldInstance(t, true)+ l, err := inst.Lock(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer l.Release()+ if _, err := app.Instance(); err != nil {+ t.Fatalf("status refused while another command holds the instance: %v", err)+ }+ found, err := bootInstance(app)+ if err != nil || found == nil {+ t.Fatalf("boot start gave up before waiting for the lock: %v", err)+ }+ requireOldLayout(t, inst)+}++func TestChangeMovesAfterRefreshingUnitCopies(t *testing.T) {+ app, inst, _ := oldInstance(t, true)+ var schemaThen int+ stubUnits(t, func() error {+ schemaThen = schemaOnDisk(t, inst)+ return nil+ })+ if err := app.Locked(context.Background(), inst, func() error { return nil }); err != nil {+ t.Fatal(err)+ }+ if schemaThen != 2 {+ t.Fatalf("refreshed the unit copies with schema %d on disk, want 2", schemaThen)+ }+ if s := schemaOnDisk(t, inst); s != instance.StateSchema {+ t.Fatalf("schema on disk %d after a change, want %d", s, instance.StateSchema)+ }+ if _, err := os.Stat(inst.Generated(stack.ComposeFile)); err != nil || inst.OldLayout() {+ t.Fatalf("the compose file didn't move: %v", err)+ }+}++func TestChangeKeepsOldLayoutWhenUnitCopiesCantBeRefreshed(t *testing.T) {+ app, inst, _ := oldInstance(t, true)+ stubUnits(t, func() error { return errors.New("sudo: a password is required") })+ ran := false+ if err := app.Locked(context.Background(), inst, func() error { ran = true; return nil }); err != nil {+ t.Fatal(err)+ }+ if !ran {+ t.Fatal("the command didn't run")+ }+ requireOldLayout(t, inst)+}++func TestRootGuardRunsBeforeMoving(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("no root on Windows")+ }+ app, inst, _ := oldInstance(t, true)+ if uid, ok := inst.OwnerUID(); !ok || uid == 0 {+ t.Skip("the test folder belongs to root")+ }+ inst.State.Engine = instance.EngineRef{Kind: string(engine.Podman)}+ prev := euid+ t.Cleanup(func() { euid = prev })+ euid = func() int { return 0 }+ stubUnits(t, func() error { t.Error("refreshed unit copies as root"); return nil })+ if err := app.Locked(context.Background(), inst, func() error { return nil }); exitCode(err) != ui.ExitRefused {+ t.Fatalf("got %v, want the rootless refusal", err)+ }+ requireOldLayout(t, inst)+}++func TestUpgradeToAnOlderSchemaReleaseKeepsTheOldLayout(t *testing.T) {+ app, inst, out := oldInstance(t, true)+ app.Version = "2099.100.0"+ serveRelease(t, release.Release{Version: "2099.101.0", StateSchema: 2, Assets: []release.Asset{{OS: runtime.GOOS, Arch: runtime.GOARCH, URL: "https://example.invalid/rexctl.tar.gz", SHA256: strings.Repeat("0", 64)}}})+ prevUpdate, prevReexec := selfUpdate, reexec+ t.Cleanup(func() { selfUpdate, reexec = prevUpdate, prevReexec })+ updated := false+ selfUpdate = func(context.Context, release.Asset) error {+ updated = true+ requireOldLayout(t, inst)+ return nil+ }+ reexec = func([]string) error { return nil }+ if err := runUpgrade(context.Background(), app, &upgradeFlags{}); err != nil {+ t.Fatalf("%v\n%s", err, out)+ }+ if !updated {+ t.Fatalf("rexctl didn't switch to the release:\n%s", out)+ }+ requireOldLayout(t, inst)+ if _, err := os.Stat(filepath.Join(inst.Dir, stack.Caddyfile)); err != nil {+ t.Fatal(err)+ }+}++func TestStatusAndDoctorSayAnEditedRootCaddyfileIsUnused(t *testing.T) {+ app, inst, out := oldInstance(t, true)+ ctx := context.Background()+ if err := app.Locked(ctx, inst, func() error { return nil }); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ compose := inst.Generated(stack.ComposeFile)+ if err := os.WriteFile(compose, stack.Managed(stack.ComposeFile, stack.Plain(stack.ComposeFile, readFile(t, compose))), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := inst.DropRootCopies(ctx, true); err != nil {+ t.Fatal(err)+ }+ warnUnusedRootFiles(ctx, app, inst)+ lines := strings.Split(strings.TrimSpace(out.String()), "\n")+ last := lines[len(lines)-1]+ if len(lines) == 0 || !strings.Contains(last, "no longer uses "+inst.Path(stack.Caddyfile)) || !strings.Contains(last, instance.CaddyDropInDir+"/") {+ t.Fatalf("output:\n%s", out)+ }+}diff --git a/fluxer_rexctl/cmd/status.go b/fluxer_rexctl/cmd/status.goindex d0acf20e4..7623e8b71 100644--- a/fluxer_rexctl/cmd/status.go+++ b/fluxer_rexctl/cmd/status.go@@ -175,6 +175,10 @@ func runStatus(ctx context.Context, app *App) error {if free, err := host.FreeDisk(inst.Dir); err == nil && free < statusLowDisk {app.UI.Warn(fmt.Sprintf("This machine has only %s of free disk space left.", diskGB(free)), "Free up space on this machine before you upgrade.")}+ warnUnusedRootFiles(ctx, app, inst)+ if len(instance.UnseenEdits(inst)) > 0 {+ app.UI.Warn(fmt.Sprintf("rexctl put back its own version of files you changed. Your copies are in %s.", inst.Path(instance.StateDirName, instance.EditedDir)), "Run rexctl doctor to see them.")+ }for _, s := range out.Services {health := s.Healthif health == "" {@@ -205,3 +209,12 @@ func withMissing(expected []string, containers []engine.Container) []engine.Contfunc diskGB(b uint64) string {return fmt.Sprintf("%d GB", (b+(1<<29))>>30)}++func warnUnusedRootFiles(ctx context.Context, app *App, inst *instance.Instance) {+ if app.Flags.JSON {+ return+ }+ for _, name := range inst.UnusedRootFiles(ctx) {+ app.UI.Warn(fmt.Sprintf("Fluxer no longer uses %s, which you changed after rexctl moved its files. Put your Caddy directives in a .caddy file in %s/ instead.", inst.Path(name), instance.CaddyDropInDir), "")+ }+}diff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.goindex 5eeea1fa5..e456eae06 100644--- a/fluxer_rexctl/cmd/upgrade.go+++ b/fluxer_rexctl/cmd/upgrade.go@@ -104,6 +104,7 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {if f.Resume != "" && f.Resume != release.ResumeRecovery {return resumeUpgrade(ctx, app, f)}+ app.keepLayout = trueinst, tookOver, err := upgradeInstance(ctx, app, f.DryRun)if err != nil || inst == nil {return err@@ -146,10 +147,8 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {case cmp < 0:return ui.Refused(fmt.Sprintf("Fluxer %s is older than the release you run, %s.", to, from), "Run rexctl rollback to go back to the release you ran before.")}- if e != nil {- if err := release.CheckTarget(e, rel); err != nil {- return floorRefusal(err, to)- }+ if err := release.CheckTarget(e, rel, inst.State.Schema); err != nil {+ return floorRefusal(err, to)}if release.Valid(cur) {app.UI.Info("Fluxer %s is available. You're on %s.", to, from)@@ -157,6 +156,7 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {app.UI.Info("Fluxer %s is available.", to)}needSelf := release.Compare(rel.Version, app.Version) != 0+ app.keepLayout = needSelf && rel.StateSchema > 0 && rel.StateSchema < instance.StateSchemaif f.DryRun {for _, k := range keptCopies(inst) {warnKeptCopy(app.UI, k.Name, k.Copy, true)@@ -581,7 +581,7 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *engif err := setPhase(inst, from, to, release.PhaseMigrated); err != nil {return abortUpgrade(ctx, app, inst, e, err, ui.Wrap(err, "Couldn't save your settings.", "Run rexctl upgrade --verbose to see why."))}- r, err := stack.Render(set, stack.OverlaysFor(next.Settings), next.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(next.Settings), next.Images.Refs)if err != nil {return abortUpgrade(ctx, app, inst, e, err, ui.Wrap(err, fmt.Sprintf("Couldn't write the files for Fluxer %s.", toShort), "Run rexctl upgrade --verbose to see why."))}@@ -602,6 +602,9 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *eng}return abortUpgrade(ctx, app, inst, e, err, ctx.Err())}+ if err := inst.DropRootCopies(ctx, true); err != nil {+ app.UI.Detail("%v", err)+ }if err := setPhase(inst, from, to, release.PhaseVerified); err != nil {return err}@@ -655,7 +658,7 @@ func retryUpgrade(ctx context.Context, app *App, inst *instance.Instance, e *engif err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't read the files for Fluxer %s.", toShort), "Run rexctl doctor to see what's wrong.")}- r, err := stack.Render(set, stack.OverlaysFor(next.Settings), next.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(next.Settings), next.Images.Refs)if err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't write the files for Fluxer %s.", toShort), "Run rexctl upgrade --verbose to see why.")}@@ -683,6 +686,9 @@ func retryUpgrade(ctx context.Context, app *App, inst *instance.Instance, e *eng}return ui.Wrap(err, fmt.Sprintf("Fluxer %s didn't start either.", toShort), fix)}+ if err := inst.DropRootCopies(ctx, true); err != nil {+ app.UI.Detail("%v", err)+ }if err := setPhase(inst, pend.From, pend.To, release.PhaseVerified); err != nil {return err}@@ -778,7 +784,7 @@ func refList(refs map[string]string) []string {func pullRelease(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, set *stack.Set, next *instance.State, toShort string) error {scratch := filepath.Join(release.Dir(inst, next.Release), scratchDir)defer os.RemoveAll(scratch)- r, err := stack.Render(set, stack.OverlaysFor(next.Settings), next.Images.Refs, inst.Project(), scratch)+ r, err := stack.RenderAt(set, stack.OverlaysFor(next.Settings), next.Images.Refs, inst.Project(), scratch, inst.OldLayout())if err != nil {return ui.Wrap(err, fmt.Sprintf("Couldn't prepare the files for Fluxer %s.", toShort), "Run rexctl upgrade --verbose to see why.")}diff --git a/fluxer_rexctl/internal/backup/create.go b/fluxer_rexctl/internal/backup/create.goindex a47419bd7..20267232d 100644--- a/fluxer_rexctl/internal/backup/create.go+++ b/fluxer_rexctl/internal/backup/create.go@@ -511,8 +511,8 @@ func addInstanceFiles(w *archiveWriter, inst *instance.Instance) error {return err}}- for _, sub := range []string{instance.CertsDir, instance.CaddyDropInDir} {- if err := addTree(w, filepath.Join(dir, sub), FilesPrefix+sub, 0); err != nil {+ for _, sub := range []string{instance.CertsDir, instance.CaddyDropInDir, stack.GeneratedDir} {+ if err := addTree(w, filepath.Join(dir, filepath.FromSlash(sub)), FilesPrefix+sub, 0); err != nil {return err}}diff --git a/fluxer_rexctl/internal/backup/layout_test.go b/fluxer_rexctl/internal/backup/layout_test.gonew file mode 100644index 000000000..c2080c30d--- /dev/null+++ b/fluxer_rexctl/internal/backup/layout_test.go@@ -0,0 +1,130 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package backup++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+)++const oldState = `{"schema": 2, "project": "fluxer", "release": "", "settings": {}, "rendered": {}}`++func oldLayoutDir(t *testing.T) (string, map[string][]byte) {+ t.Helper()+ dir := t.TempDir()+ files := map[string][]byte{+ stack.ComposeFile: []byte("name: fluxer\nservices: {}\n"),+ stack.Caddyfile: []byte(":80 {\n}\n"),+ instance.CustomCompose: []byte("services: {}\n"),+ filepath.Join(instance.CaddyDropInDir, "x.caddy"): []byte("header X-Mine yes\n"),+ filepath.Join(instance.StateDirName, instance.StateFileName): []byte(oldState),+ }+ for name, data := range files {+ if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, name), data, 0o644); err != nil {+ t.Fatal(err)+ }+ }+ return dir, files+}++func archiveOf(t *testing.T, inst *instance.Instance) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "backup.tar.zst")+ w, err := createArchive(path)+ if err != nil {+ t.Fatal(err)+ }+ if err := addInstanceFiles(w, inst); err != nil {+ w.abort()+ t.Fatal(err)+ }+ if err := w.finish(&Manifest{Project: "fluxer"}); err != nil {+ t.Fatal(err)+ }+ return path+}++func restoredFrom(t *testing.T, archive string) *instance.Instance {+ t.Helper()+ dir := t.TempDir()+ if err := extractFiles(archive, dir); err != nil {+ t.Fatal(err)+ }+ inst, err := instance.Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ return inst+}++func movedInstance(t *testing.T, dir string) *instance.Instance {+ t.Helper()+ inst, err := instance.Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if err := inst.Migrate(nil); err != nil {+ t.Fatal(err)+ }+ return inst+}++func TestOldBackupRestoresOnTheOldLayout(t *testing.T) {+ dir, files := oldLayoutDir(t)+ inst := restoredFrom(t, archiveOf(t, &instance.Instance{Dir: dir}))+ if !inst.OldLayout() {+ t.Fatal("an old backup restored as the new layout")+ }+ for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {+ if inst.Generated(name) != inst.Path(name) {+ t.Fatalf("%s resolves to %s", name, inst.Generated(name))+ }+ got, err := os.ReadFile(inst.Path(name))+ if err != nil || !bytes.Equal(got, files[name]) {+ t.Fatalf("%s: %q, %v", name, got, err)+ }+ }+ moved := movedInstance(t, inst.Dir)+ for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {+ got, err := os.ReadFile(moved.Generated(name))+ if err != nil || !bytes.Equal(got, files[name]) {+ t.Fatalf("%s after moving: %q, %v", name, got, err)+ }+ }+ for _, name := range []string{instance.CustomCompose, filepath.Join(instance.CaddyDropInDir, "x.caddy")} {+ if got, err := os.ReadFile(inst.Path(name)); err != nil || !bytes.Equal(got, files[name]) {+ t.Fatalf("%s: %q, %v", name, got, err)+ }+ }+}++func TestNewBackupKeepsGeneratedFolder(t *testing.T) {+ dir, files := oldLayoutDir(t)+ inst := restoredFrom(t, archiveOf(t, movedInstance(t, dir)))+ if got, err := os.ReadFile(inst.Generated(stack.ComposeFile)); err != nil || !bytes.Equal(got, files[stack.ComposeFile]) {+ t.Fatalf("compose file: %q, %v", got, err)+ }+ if _, err := os.Stat(inst.Path(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("a compose file showed up in the instance folder")+ }+}++func TestClearingAnInstanceRemovesGeneratedFolder(t *testing.T) {+ dir, _ := oldLayoutDir(t)+ movedInstance(t, dir)+ if err := clearInstanceFiles(dir); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("generated files stayed behind before the restore")+ }+}diff --git a/fluxer_rexctl/internal/backup/restore.go b/fluxer_rexctl/internal/backup/restore.goindex cb0c918f5..0a735d21c 100644--- a/fluxer_rexctl/internal/backup/restore.go+++ b/fluxer_rexctl/internal/backup/restore.go@@ -199,7 +199,7 @@ func renderRestored(inst *instance.Instance) (map[string]string, error) {st := inst.Stateif st.Release != stack.LegacyRelease {if set, err := release.LoadSet(inst, st.Release); err == nil {- r, err := stack.Render(set, stack.OverlaysFor(st.Settings), st.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(st.Settings), st.Images.Refs)if err != nil {return nil, err}@@ -208,7 +208,7 @@ func renderRestored(inst *instance.Instance) (map[string]string, error) {}out := map[string]string{}for name := range st.Rendered {- data, err := os.ReadFile(filepath.Join(inst.Dir, filepath.FromSlash(name)))+ data, err := os.ReadFile(inst.Generated(name))if err != nil {continue}@@ -263,7 +263,7 @@ func checkProjectFree(ctx context.Context, e *engine.Engine, project, dir stringcontinue}first, _, _ := strings.Cut(pr.ConfigFiles, ",")- other := filepath.Dir(strings.TrimSpace(first))+ other := stack.ProjectDir(strings.TrimSpace(first))if !samePath(other, dir) {return &ProjectInUseError{Project: project, Dir: other}}@@ -293,6 +293,7 @@ func clearInstanceFiles(dir string) error {for _, p := range []string{filepath.Join(dir, instance.CertsDir),filepath.Join(dir, instance.CaddyDropInDir),+ stack.GeneratedPath(dir),filepath.Join(dir, instance.StateDirName, instance.ReleasesDir),filepath.Join(dir, instance.StateDirName, instance.StateFileName),} {diff --git a/fluxer_rexctl/internal/checks/env_file.go b/fluxer_rexctl/internal/checks/env_file.goindex 6684d009c..215f1d8a8 100644--- a/fluxer_rexctl/internal/checks/env_file.go+++ b/fluxer_rexctl/internal/checks/env_file.go@@ -11,6 +11,7 @@ import ("github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui")func init() {@@ -81,30 +82,33 @@ func runStackEdits(ctx context.Context, e *Env) Result {if err == nil && len(r.Changed) == 0 && len(e.keptEdits) > 0 {return keptEditsResult(e.keptEdits)}+ if err == nil && len(r.Changed) == 0 {+ if copies := instance.UnseenEdits(e.Instance); len(copies) > 0 {+ res := warn("rexctl put back its own version of files you changed. Your copies are in "+filepath.Dir(copies[0])+".", "Put Compose changes in "+instance.CustomCompose+" with rexctl config edit, and Caddy directives in "+instance.CaddyDropInDir+".")+ res.Details = copies+ return res+ }+ }if err != nil || len(r.Changed) == 0 {return skip("")}- var de *instance.DriftError- if !errors.As(r.Err(), &de) {- return skip("")+ msg := fmt.Sprintf("%s was changed by hand. rexctl writes this file and puts its own version back on the next change.", r.Changed[0])+ if len(r.Changed) > 1 {+ msg = fmt.Sprintf("%s were changed by hand. rexctl writes these files and puts its own versions back on the next change.", ui.JoinAnd(r.Changed))}- res := fixable(fail(de.Msg, "Run rexctl doctor --fix to put rexctl's version back and keep yours next to it, or rexctl eject to manage the files yourself."))+ res := fixable(warn(msg, "Run rexctl doctor --fix to put rexctl's version back now and keep a copy of yours. Put Compose changes in "+instance.CustomCompose+" with rexctl config edit, and Caddy directives in "+instance.CaddyDropInDir+"."))res.Details = r.Changedreturn res}func fixStackEdits(ctx context.Context, e *Env) error {- r, err := e.drift()+ edits, err := instance.KeepEdits(e.Instance)if err != nil {return err}- for _, name := range r.Changed {- kept, err := instance.KeepEdited(e.Instance, name)- if err != nil {- return err- }- e.keptEdits = append(e.keptEdits, [2]string{name, kept})- if err := os.Remove(filepath.Join(e.Instance.Dir, filepath.FromSlash(name))); err != nil && !errors.Is(err, os.ErrNotExist) {+ for _, ed := range edits {+ e.keptEdits = append(e.keptEdits, [2]string{ed.Name, ed.Copy})+ if err := os.Remove(e.Instance.Generated(ed.Name)); err != nil && !errors.Is(err, os.ErrNotExist) {return err}}@@ -124,7 +128,7 @@ func keptEditsResult(kept [][2]string) Result {if len(kept) == 1 {return pass(fmt.Sprintf("Put rexctl's %s back. Your edited copy is in %s.", kept[0][0], kept[0][1]))}- r := pass("Put rexctl's versions of your edited files back. Your copies are next to them.")+ r := pass("Put rexctl's versions of your edited files back. Your copies are in " + filepath.Dir(kept[0][1]) + ".")for _, k := range kept {r.Details = append(r.Details, k[0]+" is in "+k[1])}diff --git a/fluxer_rexctl/internal/deploy/apply.go b/fluxer_rexctl/internal/deploy/apply.goindex 1cdd76a03..5a4d4fe7b 100644--- a/fluxer_rexctl/internal/deploy/apply.go+++ b/fluxer_rexctl/internal/deploy/apply.go@@ -57,6 +57,9 @@ func Apply(ctx context.Context, inst *instance.Instance, e *engine.Engine, o Appif err := up(ctx, p, o.Wait, o.OnEvent); err != nil {return nil, err}+ if err := inst.DropRootCopies(ctx, true); err != nil {+ return nil, err+ }change := &Change{Restarted: restarted(plan), Removed: slices.Clone(plan.Remove), Applied: true}if restartEdge && slices.Contains(p.Services(), edgeService) && !slices.Contains(change.Restarted, edgeService) {if err := p.Restart(context.WithoutCancel(ctx), edgeService); err != nil {diff --git a/fluxer_rexctl/internal/deploy/set.go b/fluxer_rexctl/internal/deploy/set.goindex f9b2aa8b9..057208750 100644--- a/fluxer_rexctl/internal/deploy/set.go+++ b/fluxer_rexctl/internal/deploy/set.go@@ -68,9 +68,6 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesif err := refuseEjected(inst); err != nil {return nil, err}- if err := refuseUpgrade(inst); err != nil {- return nil, err- }if inst.State.Pending != nil {return nil, ui.Refused("An earlier settings change didn't finish.", "Run rexctl doctor --fix to put the old values back, then try again.")}@@ -78,6 +75,9 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesif len(changes) > 1 {return nil, ui.Usage("Change engine.host on its own, without other settings.")}+ if err := refuseUpgrade(inst); err != nil {+ return nil, err+ }return setEngineHost(ctx, inst, e, changes[settings.EngineHost])}if err := checkDrift(inst, false); err != nil {@@ -94,6 +94,7 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesst := inst.Statenext := maps.Clone(st.Settings)var promised, changed []string+ repairs := truefor _, name := range keys {k, err := Lookup(rs, custom, name)if err != nil {@@ -104,6 +105,7 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changes}v := changes[name]current, had := st.Settings[name]+ repairs = repairs && had && validate(k, current) != nilif v == nil {delete(next, name)} else {@@ -133,11 +135,32 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesif next[settings.StorageSecret] != st.Settings[settings.StorageSecret] && next[settings.StorageEndpoint] == "" && next[settings.StorageSecret] != "" {return nil, ui.Refused("storage.secret_key only applies to your own object store.", "Set storage.endpoint in the same command, for example rexctl config set storage.endpoint=https://s3.example.com storage.secret_key=-.")}- oldEnv, err := Environment(rs, st, st.Settings)+ if st.Upgrade != nil && !repairs {+ if err := refuseUpgrade(inst); err != nil {+ return nil, err+ }+ }+ slices.Sort(promised)+ preview := Preview{Keys: changed, Promised: slices.Compact(promised)}+ newEnv, err := Environment(rs, st, next)if err != nil {return nil, err}- newEnv, err := Environment(rs, st, next)+ if st.Upgrade != nil {+ oldEnv, _ := Environment(rs, st, st.Settings)+ if err := checkPorts(ctx, e, inst.Project(), oldEnv, newEnv, changed, next[settings.EdgeMode]); err != nil {+ return nil, err+ }+ if o.Confirm != nil && !o.Confirm(preview) {+ return nil, ErrDeclined+ }+ st.Settings = next+ if err := save(inst); err != nil {+ return nil, err+ }+ return &Change{Keys: changed}, nil+ }+ oldEnv, err := Environment(rs, st, st.Settings)if err != nil {return nil, err}@@ -171,8 +194,6 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesreturn nil, err}ipv6 := parseBool(st.Settings[settings.IPv6]) != parseBool(next[settings.IPv6])- slices.Sort(promised)- preview := Preview{Keys: changed, Promised: slices.Compact(promised)}if live {if err := oldP.Pull(ctx, o.OnEvent); err != nil {return nil, err@@ -186,15 +207,9 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changespreview.Restarts = newP.Services()}}- added, _ := portDiff(oldEnv, newEnv)- if err := checkPortsFree(ctx, e, inst.Project(), added); err != nil {+ if err := checkPorts(ctx, e, inst.Project(), oldEnv, newEnv, changed, next[settings.EdgeMode]); err != nil {return nil, err}- if portKeyChanged(changed) {- if err := checkPortsDistinct(effectivePorts(newEnv, next[settings.EdgeMode])); err != nil {- return nil, err- }- }if o.Confirm != nil && !o.Confirm(preview) {return nil, ErrDeclined}@@ -247,6 +262,17 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changesreturn &Change{Keys: changed, Restarted: preview.Restarts, Removed: preview.Removes, Applied: true}, nil}+func checkPorts(ctx context.Context, e *engine.Engine, project string, oldEnv, newEnv map[string]string, changed []string, mode string) error {+ added, _ := portDiff(oldEnv, newEnv)+ if err := checkPortsFree(ctx, e, project, added); err != nil {+ return err+ }+ if portKeyChanged(changed) {+ return checkPortsDistinct(effectivePorts(newEnv, mode))+ }+ return nil+}+func bringUp(ctx context.Context, oldP, newP *engine.Project, ipv6 bool, onEvent func(engine.Event)) error {bg := context.WithoutCancel(ctx)if ipv6 {@@ -291,12 +317,15 @@ func stageOverlays(inst *instance.Instance, rs *stack.Set, chosen map[string]strvar created []stringfor _, o := range stack.OverlaysFor(chosen) {name := stack.OverlayFiles[o]- target := inst.Path(name)+ target := inst.Generated(name)if _, err := os.Stat(target); err == nil {continue}data, err := stack.ReadFile(rs, name)if err == nil {+ if !inst.OldLayout() {+ data = stack.Managed(name, data)+ }err = os.WriteFile(target, data, 0o644)}if err != nil {diff --git a/fluxer_rexctl/internal/deploy/spec.go b/fluxer_rexctl/internal/deploy/spec.goindex 130babff8..49b26ba48 100644--- a/fluxer_rexctl/internal/deploy/spec.go+++ b/fluxer_rexctl/internal/deploy/spec.go@@ -11,11 +11,13 @@ import ("io/fs""os""path/filepath"+ "slices""strings""time""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"@@ -64,7 +66,7 @@ func Environment(set *stack.Set, s *instance.State, chosen map[string]string) (m}func composeFiles(inst *instance.Instance, chosen map[string]string) []string {- files := stack.ComposeFiles(inst.Dir, stack.OverlaysFor(chosen))+ files := inst.StackFiles(stack.OverlaysFor(chosen))if _, err := os.Stat(inst.Path(instance.CustomCompose)); err == nil {files = append(files, inst.Path(instance.CustomCompose))}@@ -96,7 +98,7 @@ func Load(ctx context.Context, inst *instance.Instance, e *engine.Engine) (*engi}func render(inst *instance.Instance, set *stack.Set, chosen map[string]string) (*stack.Rendered, error) {- r, err := stack.Render(set, stack.OverlaysFor(chosen), inst.State.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(chosen), inst.State.Images.Refs)if err != nil {return nil, ui.Wrap(err, "Couldn't write Fluxer's files.", "Check that you can write to "+inst.Dir+", then try again.")}@@ -144,6 +146,9 @@ func mountedHashes(inst *instance.Instance) (map[string]string, error) {}func checkDrift(inst *instance.Instance, withEnv bool) error {+ if _, err := instance.KeepEdits(inst); err != nil {+ return ui.Wrap(err, "rexctl can't keep a copy of the files you changed.", "Check that you can write to "+inst.Dir+", then try again.")+ }r, err := instance.Drift(inst)if err != nil {return ui.Wrap(err, "rexctl can't check Fluxer's files.", "Check that you can read "+inst.Dir+", then try again.")@@ -173,10 +178,16 @@ func refuseEjected(inst *instance.Instance) error {}func refuseUpgrade(inst *instance.Instance) error {- if inst.State.Upgrade == nil {+ if inst.State.Upgrade == nil || upgradeNotPulled(inst) {return nil}return ui.Refused("An upgrade of this instance hasn't finished.", "Run rexctl upgrade to finish it, then try again.")}+func upgradeNotPulled(inst *instance.Instance) bool {+ u := inst.State.Upgrade+ i := slices.Index(release.Phases, u.Phase)+ return i >= 0 && i < slices.Index(release.Phases, release.PhasePulled)+}+func now() time.Time { return time.Now().UTC().Truncate(time.Second) }diff --git a/fluxer_rexctl/internal/engine/binds.go b/fluxer_rexctl/internal/engine/binds.gonew file mode 100644index 000000000..b98a6dde8--- /dev/null+++ b/fluxer_rexctl/internal/engine/binds.go@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package engine++import (+ "context"+ "path/filepath"+ "sort"++ "github.com/compose-spec/compose-go/v2/cli"+ "github.com/compose-spec/compose-go/v2/loader"+ "github.com/compose-spec/compose-go/v2/types"+)++func BindSources(ctx context.Context, dir, name string, files []string, env map[string]string) ([]string, error) {+ vars := make([]string, 0, len(env))+ for k, v := range env {+ vars = append(vars, k+"="+v)+ }+ sort.Strings(vars)+ opts, err := cli.NewProjectOptions(files,+ cli.WithWorkingDirectory(dir),+ cli.WithEnv(vars),+ cli.WithName(name),+ cli.WithDefaultProfiles(),+ cli.WithResolvedPaths(true),+ cli.WithLoadOptions(func(o *loader.Options) {+ o.SkipValidation = true+ o.SkipConsistencyCheck = true+ }),+ )+ if err != nil {+ return nil, err+ }+ model, err := opts.LoadProject(ctx)+ if err != nil {+ return nil, err+ }+ var out []string+ for _, svc := range model.AllServices() {+ for _, v := range svc.Volumes {+ if v.Type == types.VolumeTypeBind && v.Source != "" {+ src := v.Source+ if !filepath.IsAbs(src) {+ src = filepath.Join(dir, src)+ }+ out = append(out, filepath.Clean(src))+ }+ }+ }+ return out, nil+}diff --git a/fluxer_rexctl/internal/host/bootunit.go b/fluxer_rexctl/internal/host/bootunit.goindex 5835eade6..d272689c8 100644--- a/fluxer_rexctl/internal/host/bootunit.go+++ b/fluxer_rexctl/internal/host/bootunit.go@@ -12,6 +12,8 @@ import ("os/exec""path/filepath""runtime"+ "slices"+ "strconv""strings""time"@@ -290,13 +292,10 @@ func writeBootUnit(ctx context.Context, u BootUnit) error {if err != nil {return err}- if !u.Rootless && !sameFile(u.Binary, LibexecBinary) {- if _, err := output(ctx, false, "install", "-D", "-m", "0755", u.Binary, LibexecBinary); err != nil {+ if !u.Rootless {+ if err := installBinary(ctx, true, u.Binary, LibexecBinary); err != nil {return err}- if has("restorecon") {- _, _ = output(ctx, false, "restorecon", LibexecBinary)- }}changed, err := writeHostFile(ctx, u.Rootless, path, []byte(u.content(ctx)))if err != nil || !changed {@@ -305,6 +304,140 @@ func writeBootUnit(ctx context.Context, u BootUnit) error {return systemctlRun(ctx, u.Rootless, "daemon-reload")}+func installBinary(ctx context.Context, system bool, src, dst string) error {+ if sameFile(src, dst) {+ return nil+ }+ if !system {+ if out, err := exec.CommandContext(ctx, "install", "-D", "-m", "0755", src, dst).CombinedOutput(); err != nil {+ return &CommandError{Command: "install " + dst, Output: string(out), Err: err}+ }+ return nil+ }+ if _, err := output(ctx, false, "install", installArgs(src, dst)...); err != nil {+ return err+ }+ if has("restorecon") {+ _, _ = output(ctx, false, "restorecon", dst)+ }+ return nil+}++func installArgs(src, dst string) []string {+ args := []string{"-D", "-m", "0755"}+ if uid, gid, ok := fileOwner(dst); ok {+ args = append(args, "-o", strconv.Itoa(uid), "-g", strconv.Itoa(gid))+ }+ return append(args, src, dst)+}++var asRoot = isRoot++func unitFiles(project string) (map[string]bool, error) {+ boot, upgrade := BootUnit{Project: project}.Name(), AutoUpgrade{Project: project}.ServiceName()+ units := map[string]bool{+ filepath.Join("/etc/systemd/system", boot): true,+ filepath.Join("/etc/systemd/system", upgrade): true,+ filepath.Join(cronDir, project+"-upgrade"): true,+ }+ if asRoot() {+ return units, nil+ }+ userDir, err := unitDir(true)+ if err != nil {+ return nil, err+ }+ units[filepath.Join(userDir, boot)] = false+ units[filepath.Join(userDir, upgrade)] = false+ return units, nil+}++func RefreshUnitBinaries(ctx context.Context, project, bin string) error {+ if runtime.GOOS != "linux" {+ return nil+ }+ units, err := unitFiles(project)+ if err != nil {+ return err+ }+ for path, system := range units {+ data, err := os.ReadFile(path)+ if os.IsNotExist(err) {+ continue+ }+ if err != nil {+ return err+ }+ for _, b := range unitBinaries(data) {+ if err := installBinary(ctx, system, bin, b); err != nil {+ return err+ }+ }+ }+ return nil+}++func unitBinaries(data []byte) []string {+ var out []string+ for _, line := range strings.Split(string(data), "\n") {+ var bin string+ if v, ok := strings.CutPrefix(line, "ExecStart="); ok {+ bin = systemdWord(v)+ } else {+ bin = cronBinary(line)+ }+ if filepath.IsAbs(bin) && !slices.Contains(out, bin) {+ out = append(out, bin)+ }+ }+ return out+}++func systemdWord(v string) string {+ var word string+ if rest, ok := strings.CutPrefix(v, `"`); ok {+ var b strings.Builder+ for i := 0; i < len(rest) && rest[i] != '"'; i++ {+ if rest[i] == '\\' && i+1 < len(rest) {+ i+++ }+ b.WriteByte(rest[i])+ }+ word = b.String()+ } else {+ word, _, _ = strings.Cut(v, " ")+ }+ return strings.NewReplacer("%%", "%", "$$", "$").Replace(word)+}++func cronBinary(line string) string {+ f := strings.Fields(line)+ if len(f) < 7 || strings.Contains(f[0], "=") || strings.HasPrefix(f[0], "#") {+ return ""+ }+ i := strings.Index(line, " '")+ if i < 0 {+ return ""+ }+ var b strings.Builder+ rest := line[i+2:]+ for {+ end := strings.IndexByte(rest, '\'')+ if end < 0 {+ return ""+ }+ b.WriteString(rest[:end])+ rest = rest[end+1:]+ next, ok := strings.CutPrefix(rest, `\''`)+ if !ok {+ break+ }+ b.WriteByte('\'')+ rest = next+ }+ return strings.ReplaceAll(b.String(), `\%`, "%")+}+func writeHostFile(ctx context.Context, user bool, path string, data []byte) (bool, error) {if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, data) {return false, nildiff --git a/fluxer_rexctl/internal/host/bootunit_test.go b/fluxer_rexctl/internal/host/bootunit_test.gonew file mode 100644index 000000000..a2c2f81ae--- /dev/null+++ b/fluxer_rexctl/internal/host/bootunit_test.go@@ -0,0 +1,78 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strconv"+ "strings"+ "testing"+)++func TestUnitBinariesReadWhatRexctlWrites(t *testing.T) {+ const bin = `/home/a b/it's 100%/$rexctl`+ a := AutoUpgrade{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin, At: "04:00", Log: "/srv/fluxer/.rexctl/upgrade.log"}+ for name, c := range map[string]struct {+ unit string+ want string+ }{+ "rootful boot unit": {BootUnit{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin}.render(false, "fluxer"), LibexecBinary},+ "rootless boot unit": {BootUnit{Project: "fluxer", Dir: "/srv/fluxer", Binary: bin, Rootless: true}.render(false, ""), bin},+ "upgrade service": {a.service("fluxer"), bin},+ "cron job": {a.cron(4, 0, "fluxer"), bin},+ } {+ if got := unitBinaries([]byte(c.unit)); !slices.Equal(got, []string{c.want}) {+ t.Errorf("%s runs %q, want %q", name, got, c.want)+ }+ }+}++func TestRootRefreshesOnlyUnitsRootOwns(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("XDG_CONFIG_HOME", "")+ prev := asRoot+ t.Cleanup(func() { asRoot = prev })+ for _, root := range []bool{false, true} {+ asRoot = func() bool { return root }+ units, err := unitFiles("fluxer")+ if err != nil {+ t.Fatal(err)+ }+ inHome := 0+ for path := range units {+ if strings.HasPrefix(path, home) {+ inHome+++ }+ }+ if root && inHome > 0 {+ t.Errorf("as root, rexctl reads units from $HOME, which sudo may keep: %v", units)+ }+ if !root && inHome != 2 {+ t.Errorf("without root, rexctl skips your own units: %v", units)+ }+ }+}++func TestInstallKeepsTheBinarysOwner(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("no owners on Windows")+ }+ dir := t.TempDir()+ dst := filepath.Join(dir, "rexctl")+ if got := installArgs("/tmp/new", dst); slices.Contains(got, "-o") {+ t.Fatalf("a new binary got an owner: %q", got)+ }+ if err := os.WriteFile(dst, []byte("old"), 0o755); err != nil {+ t.Fatal(err)+ }+ uid, gid := strconv.Itoa(os.Getuid()), strconv.Itoa(os.Getgid())+ got := installArgs("/tmp/new", dst)+ want := []string{"-D", "-m", "0755", "-o", uid, "-g", gid, "/tmp/new", dst}+ if !slices.Equal(got, want) {+ t.Fatalf("install %q, want %q", got, want)+ }+}diff --git a/fluxer_rexctl/internal/host/owner_unix.go b/fluxer_rexctl/internal/host/owner_unix.goindex ca1620084..51c4bc839 100644--- a/fluxer_rexctl/internal/host/owner_unix.go+++ b/fluxer_rexctl/internal/host/owner_unix.go@@ -26,3 +26,15 @@ func dirOwner(dir string) string {}return u.Username}++func fileOwner(path string) (int, int, bool) {+ info, err := os.Stat(path)+ if err != nil {+ return 0, 0, false+ }+ st, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return 0, 0, false+ }+ return int(st.Uid), int(st.Gid), true+}diff --git a/fluxer_rexctl/internal/host/owner_windows.go b/fluxer_rexctl/internal/host/owner_windows.goindex a692bce7f..827cfe903 100644--- a/fluxer_rexctl/internal/host/owner_windows.go+++ b/fluxer_rexctl/internal/host/owner_windows.go@@ -3,3 +3,5 @@package hostfunc dirOwner(string) string { return "" }++func fileOwner(string) (int, int, bool) { return 0, 0, false }diff --git a/fluxer_rexctl/internal/instance/custom.go b/fluxer_rexctl/internal/instance/custom.gonew file mode 100644index 000000000..43b5f20a4--- /dev/null+++ b/fluxer_rexctl/internal/instance/custom.go@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package instance++import (+ "errors"+ "io/fs"+ "os"+)++const CustomTemplate = `# This is the file to edit when you want to change how Fluxer runs.+# rexctl adds it after its own Compose files and keeps it on upgrades.+# Run rexctl config edit to change it. rexctl checks the file and applies it.+# Change settings with rexctl config set, not here.+# To use an example, remove the # at the start of its lines.+#+# services:+# edge:+# labels:+# com.example.team: chat+# image: caddy:2.11-alpine+# ports:+# - "8443:8443"+# api:+# volumes:+# - ./extra:/extra:ro+`++func (i *Instance) WriteCustomTemplate() error {+ f, err := os.OpenFile(i.Path(CustomCompose), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)+ if errors.Is(err, fs.ErrExist) {+ return nil+ }+ if err != nil {+ return err+ }+ if _, err := f.WriteString(CustomTemplate); err != nil {+ f.Close()+ return err+ }+ return f.Close()+}diff --git a/fluxer_rexctl/internal/instance/drift.go b/fluxer_rexctl/internal/instance/drift.goindex 9c0200513..3ccf5de3b 100644--- a/fluxer_rexctl/internal/instance/drift.go+++ b/fluxer_rexctl/internal/instance/drift.go@@ -11,6 +11,8 @@ import ("os""path/filepath""slices"+ "strings"+ "time""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"@@ -44,7 +46,7 @@ func Drift(inst *Instance) (*DriftReport, error) {return r, nil}for _, name := range slices.Sorted(maps.Keys(inst.State.Rendered)) {- data, err := os.ReadFile(inst.Path(name))+ data, err := os.ReadFile(inst.Generated(name))switch {case errors.Is(err, fs.ErrNotExist):r.Missing = append(r.Missing, name)@@ -91,29 +93,18 @@ func envDrift(inst *Instance) (*EnvDrift, error) {}func (r *DriftReport) Err() error {- if r == nil {+ if r == nil || r.Env == nil || r.Env.Same {return nil}- if len(r.Changed) > 0 {- name := r.Changed[0]- msg := fmt.Sprintf("%s was changed by hand. rexctl writes this file and would undo your change.", name)- if len(r.Changed) > 1 {- msg = fmt.Sprintf("%s were changed by hand. rexctl writes these files and would undo your changes.", ui.JoinAnd(r.Changed))- }- return &DriftError{Msg: msg, Fix: "Run rexctl doctor --fix to put rexctl's version back, or rexctl eject to manage the files yourself."}+ lines := make([]string, 0, len(r.Env.Changes))+ for _, c := range r.Env.Changes {+ lines = append(lines, c.Command())}- if r.Env != nil && !r.Env.Same {- lines := make([]string, 0, len(r.Env.Changes))- for _, c := range r.Env.Changes {- lines = append(lines, c.Command())- }- return &DriftError{- Msg: "Your instance has a .env file, and rexctl doesn't read it.",- Fix: r.Env.Fix(),- Lines: lines,- }+ return &DriftError{+ Msg: "Your instance has a .env file, and rexctl doesn't read it.",+ Fix: r.Env.Fix(),+ Lines: lines,}- return nil}func (r *EnvDrift) Fix() string {@@ -200,3 +191,141 @@ func copyPrivate(src, dst string) error {}return envfile.WriteFileAtomic(dst, data, true)}++const (+ EditedDir = "edited"+ diffLines = 12+ editedFormat = "20060102-150405"+)++type Edit struct {+ Name string+ Copy string+ Diff []string+}++func KeepEdits(inst *Instance) ([]Edit, error) {+ r, err := Drift(inst)+ if err != nil || len(r.Changed) == 0 {+ return nil, err+ }+ set, err := inst.Set()+ if err != nil {+ return nil, err+ }+ want, err := stack.Files(set, inst.Overlays(), inst.State.Images.Refs, inst.Project())+ if err != nil {+ return nil, err+ }+ var out []Edit+ for _, name := range r.Changed {+ data, err := os.ReadFile(inst.Generated(name))+ if err != nil {+ return nil, err+ }+ kept, err := keepEdit(inst, name, data)+ if err != nil {+ return nil, err+ }+ w := want[name]+ if inst.OldLayout() {+ w = stack.Plain(name, w)+ }+ out = append(out, Edit{Name: name, Copy: kept, Diff: ShortDiff(w, data)})+ }+ return out, nil+}++func keepEdit(inst *Instance, name string, data []byte) (string, error) {+ dir := inst.Path(StateDirName, EditedDir)+ if entries, err := os.ReadDir(dir); err == nil {+ for _, e := range entries {+ if !strings.HasPrefix(e.Name(), name+".") {+ continue+ }+ if old, err := os.ReadFile(filepath.Join(dir, e.Name())); err == nil && bytes.Equal(old, data) {+ return filepath.Join(dir, e.Name()), nil+ }+ }+ }+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return "", err+ }+ path := filepath.Join(dir, name+"."+time.Now().UTC().Format(editedFormat))+ return path, envfile.WriteFileAtomic(path, data, false)+}++func ShortDiff(from, to []byte) []string {+ a, b := splitLines(from), splitLines(to)+ lcs := make([][]int, len(a)+1)+ for i := range lcs {+ lcs[i] = make([]int, len(b)+1)+ }+ for i := len(a) - 1; i >= 0; i-- {+ for j := len(b) - 1; j >= 0; j-- {+ if a[i] == b[j] {+ lcs[i][j] = lcs[i+1][j+1] + 1+ } else {+ lcs[i][j] = max(lcs[i+1][j], lcs[i][j+1])+ }+ }+ }+ var out []string+ i, j := 0, 0+ for i < len(a) || j < len(b) {+ switch {+ case i < len(a) && j < len(b) && a[i] == b[j]:+ i, j = i+1, j+1+ case i < len(a) && (j == len(b) || lcs[i+1][j] >= lcs[i][j+1]):+ out = append(out, "- "+a[i])+ i+++ default:+ out = append(out, "+ "+b[j])+ j+++ }+ }+ if len(out) > diffLines {+ out = append(out[:diffLines], fmt.Sprintf("and %d more changed lines", len(out)-diffLines))+ }+ return out+}++func splitLines(data []byte) []string {+ text := strings.TrimSuffix(string(data), "\n")+ if text == "" {+ return nil+ }+ return strings.Split(text, "\n")+}++const seenMarker = ".seen"++func UnseenEdits(inst *Instance) []string {+ dir := inst.Path(StateDirName, EditedDir)+ entries, err := os.ReadDir(dir)+ if err != nil {+ return nil+ }+ var seen time.Time+ if info, err := os.Stat(filepath.Join(dir, seenMarker)); err == nil {+ seen = info.ModTime()+ }+ var out []string+ for _, e := range entries {+ if e.Name() == seenMarker || e.IsDir() {+ continue+ }+ if info, err := e.Info(); err == nil && info.ModTime().After(seen) {+ out = append(out, filepath.Join(dir, e.Name()))+ }+ }+ return out+}++func SeenEdits(inst *Instance) {+ path := inst.Path(StateDirName, EditedDir, seenMarker)+ now := time.Now()+ if os.Chtimes(path, now, now) != nil {+ _ = os.WriteFile(path, nil, 0o600)+ }+}diff --git a/fluxer_rexctl/internal/instance/eject.go b/fluxer_rexctl/internal/instance/eject.goindex d758b8635..f82a8ee0d 100644--- a/fluxer_rexctl/internal/instance/eject.go+++ b/fluxer_rexctl/internal/instance/eject.go@@ -52,6 +52,10 @@ func Eject(inst *Instance, o EjectOptions) error {if err != nil {return err}+ rendered, err := writePlain(inst)+ if err != nil {+ return err+ }f := envfile.New(inst.Path(EnvFileName))for _, k := range slices.Sorted(maps.Keys(env)) {f.Set(k, env[k])@@ -66,20 +70,50 @@ func Eject(inst *Instance, o EjectOptions) error {return err}}+ s.Rendered = rendereds.Ejected = &Ejected{At: time.Now().UTC().Truncate(time.Second), Rexctl: o.Rexctl}s.UpdatedAt = time.Now().UTC().Truncate(time.Second)- return s.Save(inst.StatePath())+ if err := s.Save(inst.StatePath()); err != nil {+ return err+ }+ for name := range rendered {+ if _, mounted := stack.MountedFiles[name]; !mounted && !inst.OldLayout() {+ if err := removeIfExists(inst.Generated(name)); err != nil {+ return err+ }+ }+ }+ return nil}-func composeFileList(inst *Instance) string {- var rel []string- for _, f := range inst.ComposeFiles() {- if r, err := filepath.Rel(inst.Dir, f); err == nil && !strings.HasPrefix(r, "..") {- f = r+func writePlain(inst *Instance) (map[string]string, error) {+ out := map[string]string{}+ for _, name := range stack.FileNames() {+ data, err := os.ReadFile(inst.Generated(name))+ if errors.Is(err, fs.ErrNotExist) {+ continue+ }+ if err != nil {+ return nil, err}- rel = append(rel, f)+ data = stack.Plain(name, data)+ if err := envfile.WriteFileAtomic(inst.Path(name), data, false); err != nil {+ return nil, err+ }+ out[name] = stack.Hash(data)+ }+ return out, nil+}++func composeFileList(inst *Instance) string {+ names := []string{stack.ComposeFile}+ for _, o := range inst.Overlays() {+ names = append(names, stack.OverlayFiles[o])+ }+ if exists(inst.Path(CustomCompose)) {+ names = append(names, CustomCompose)}- return strings.Join(rel, string(os.PathListSeparator))+ return strings.Join(names, string(os.PathListSeparator))}func importEjected(ctx context.Context, dir string, e *engine.Engine, s *State, dry bool) (*State, *ImportReport, error) {diff --git a/fluxer_rexctl/internal/instance/eject_test.go b/fluxer_rexctl/internal/instance/eject_test.goindex 85e6cdd00..ed9bffc21 100644--- a/fluxer_rexctl/internal/instance/eject_test.go+++ b/fluxer_rexctl/internal/instance/eject_test.go@@ -56,7 +56,10 @@ func ejectedInstance(t *testing.T, declared *stack.Set, refs map[string]string)if err := stack.WriteSet(filepath.Join(dir, StateDirName, ReleasesDir, ejectedAt, StackDir), old); err != nil {t.Fatal(err)}- r, err := stack.Render(old, nil, fluxerRefs("a"), "fluxer", dir)+ if _, err := stack.Render(old, nil, fluxerRefs("a"), "fluxer", dir); err != nil {+ t.Fatal(err)+ }+ rendered, err := writePlain(&Instance{Dir: dir})if err != nil {t.Fatal(err)}@@ -73,7 +76,7 @@ func ejectedInstance(t *testing.T, declared *stack.Set, refs map[string]string)Images: Images{Release: ejectedAt, Refs: fluxerRefs("a")},Settings: map[string]string{},Secrets: map[string]string{},- Rendered: r.Hashes,+ Rendered: rendered,SetupDone: true,Ejected: &Ejected{At: time.Now().UTC().Truncate(time.Second)},}diff --git a/fluxer_rexctl/internal/instance/import.go b/fluxer_rexctl/internal/instance/import.goindex 717ef0f69..19c3575d6 100644--- a/fluxer_rexctl/internal/instance/import.go+++ b/fluxer_rexctl/internal/instance/import.go@@ -277,6 +277,7 @@ func finishImport(dir string, s *State) error {return err}s.UpdatedAt = time.Now().UTC().Truncate(time.Second)+ s.rootLayout = trueif err := s.Save(filepath.Join(dir, StateDirName, StateFileName)); err != nil {return err}@@ -448,13 +449,8 @@ func newSet(release string, files fs.FS, profiles map[string]map[string]string)}func renderedNames(dir string) []string {- names := []string{stack.ComposeFile}- for _, o := range slices.Sorted(maps.Keys(stack.OverlayFiles)) {- names = append(names, stack.OverlayFiles[o])- }- names = append(names, stack.Caddyfile)var out []string- for _, n := range names {+ for _, n := range stack.FileNames() {if isFile(filepath.Join(dir, n)) {out = append(out, n)}diff --git a/fluxer_rexctl/internal/instance/instance.go b/fluxer_rexctl/internal/instance/instance.goindex 93c7bf857..8189f20e7 100644--- a/fluxer_rexctl/internal/instance/instance.go+++ b/fluxer_rexctl/internal/instance/instance.go@@ -85,12 +85,16 @@ func present(dir string) bool {}func Find(dir string) (*Instance, error) {+ return FindRepairing(dir, nil)+}++func FindRepairing(dir string, keys []string) (*Instance, error) {dir, err := filepath.Abs(dir)if err != nil {return nil, err}i := &Instance{Dir: dir}- state, err := LoadState(i.StatePath())+ state, err := loadState(i.StatePath(), keys)if errors.Is(err, fs.ErrNotExist) {if isLegacy(dir) {return nil, ErrLegacy@@ -323,7 +327,7 @@ func (i *Instance) Overlays() []stack.Overlay {}func (i *Instance) ComposeFiles() []string {- files := stack.ComposeFiles(i.Dir, i.Overlays())+ files := i.StackFiles(i.Overlays())if exists(i.Path(CustomCompose)) {files = append(files, i.Path(CustomCompose))}@@ -331,9 +335,9 @@ func (i *Instance) ComposeFiles() []string {}func (i *Instance) MissingFiles() []string {- files := stack.ComposeFiles(i.Dir, i.Overlays())+ files := i.StackFiles(i.Overlays())for name := range stack.MountedFiles {- files = append(files, i.Path(name))+ files = append(files, i.Generated(name))}var out []stringfor _, f := range files {diff --git a/fluxer_rexctl/internal/instance/layout.go b/fluxer_rexctl/internal/instance/layout.gonew file mode 100644index 000000000..8485202a3--- /dev/null+++ b/fluxer_rexctl/internal/instance/layout.go@@ -0,0 +1,184 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package instance++import (+ "context"+ "encoding/json"+ "errors"+ "io/fs"+ "maps"+ "os"+ "path/filepath"+ "slices"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+)++const generatedSchema = 3++var (+ euid = os.Geteuid+ chown = os.Lchown+)++func (i *Instance) OldLayout() bool {+ return i.State != nil && i.State.rootLayout+}++func (i *Instance) Generated(name string) string {+ return filepath.Join(stack.FilesDir(i.Dir, i.OldLayout()), filepath.FromSlash(name))+}++func (i *Instance) StackFiles(overlays []stack.Overlay) []string {+ return stack.ComposeFilesAt(i.Dir, overlays, i.OldLayout())+}++func (i *Instance) Render(set *stack.Set, overlays []stack.Overlay, images map[string]string) (*stack.Rendered, error) {+ return stack.RenderAt(set, overlays, images, i.Project(), i.Dir, i.OldLayout())+}++func (i *Instance) Migrate(prepare func() error) error {+ if !i.OldLayout() || i.State.Ejected != nil {+ return nil+ }+ schema, err := savedSchema(i.StatePath())+ if err != nil {+ return err+ }+ if schema >= generatedSchema {+ i.State.rootLayout = false+ return nil+ }+ if prepare != nil {+ if err := prepare(); err != nil {+ return err+ }+ }+ left, err := copyGenerated(i)+ if err != nil {+ return err+ }+ i.State.rootLayout = false+ i.State.LeftInRoot = left+ if err := i.Save(); err != nil {+ i.State.rootLayout, i.State.LeftInRoot = true, nil+ return err+ }+ return i.DropRootCopies(context.Background(), false)+}++func savedSchema(path string) (int, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return 0, err+ }+ var head struct {+ Schema int `json:"schema"`+ }+ return head.Schema, json.Unmarshal(data, &head)+}++func copyGenerated(i *Instance) (map[string]string, error) {+ gen := stack.GeneratedPath(i.Dir)+ if err := os.MkdirAll(gen, 0o755); err != nil {+ return nil, err+ }+ if err := i.giveToOwner(gen); err != nil {+ return nil, err+ }+ left := map[string]string{}+ for _, name := range stack.FileNames() {+ src := filepath.Join(i.Dir, name)+ info, err := os.Lstat(src)+ if errors.Is(err, fs.ErrNotExist) {+ continue+ }+ if err != nil {+ return nil, err+ }+ if !info.Mode().IsRegular() {+ continue+ }+ data, err := os.ReadFile(src)+ if err != nil {+ return nil, err+ }+ dst := filepath.Join(gen, name)+ if err := envfile.WriteFileAtomic(dst, data, false); err != nil {+ return nil, err+ }+ if err := i.giveToOwner(dst); err != nil {+ return nil, err+ }+ left[name] = stack.Hash(data)+ }+ return left, nil+}++func (i *Instance) DropRootCopies(ctx context.Context, started bool) error {+ if i.State == nil || i.OldLayout() || i.State.Ejected != nil || len(i.State.LeftInRoot) == 0 {+ return nil+ }+ changed := false+ for name, hash := range i.State.LeftInRoot {+ _, mounted := stack.MountedFiles[name]+ if mounted && (!started || i.rootMounted(ctx, name)) {+ continue+ }+ data, err := os.ReadFile(i.Path(name))+ switch {+ case errors.Is(err, fs.ErrNotExist):+ case err != nil:+ return err+ case stack.Hash(data) == hash:+ if err := os.Remove(i.Path(name)); err != nil {+ return err+ }+ case mounted:+ continue+ }+ delete(i.State.LeftInRoot, name)+ changed = true+ }+ if !changed {+ return nil+ }+ return i.Save()+}++func (i *Instance) UnusedRootFiles(ctx context.Context) []string {+ if i.State == nil || i.OldLayout() || i.State.Ejected != nil {+ return nil+ }+ var out []string+ for _, name := range slices.Sorted(maps.Keys(i.State.LeftInRoot)) {+ if _, mounted := stack.MountedFiles[name]; !mounted {+ continue+ }+ data, err := os.ReadFile(i.Path(name))+ if err != nil || stack.Hash(data) == i.State.LeftInRoot[name] || i.rootMounted(ctx, name) {+ continue+ }+ out = append(out, name)+ }+ return out+}++func (i *Instance) rootMounted(ctx context.Context, name string) bool {+ compose, err := os.ReadFile(i.Generated(stack.ComposeFile))+ if err != nil || !stack.MountsGenerated(compose, name) {+ return true+ }+ custom := i.Path(CustomCompose)+ if _, err := os.Stat(custom); errors.Is(err, fs.ErrNotExist) {+ return false+ }+ sources, err := engine.BindSources(ctx, i.Dir, i.Project(), []string{custom}, map[string]string{"PWD": i.Dir})+ if err != nil {+ return true+ }+ return slices.Contains(sources, filepath.Clean(i.Path(name)))+}diff --git a/fluxer_rexctl/internal/instance/layout_test.go b/fluxer_rexctl/internal/instance/layout_test.gonew file mode 100644index 000000000..e1d01099b--- /dev/null+++ b/fluxer_rexctl/internal/instance/layout_test.go@@ -0,0 +1,604 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package instance++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "maps"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+)++var userFiles = map[string]string{+ CustomCompose: "services:\n edge:\n labels:\n team: chat\n",+ filepath.Join(CaddyDropInDir, "x.caddy"): "header X-Mine yes\n",+ filepath.Join(CertsDir, "site.pem"): "pem\n",+}++func oldLayout(t *testing.T) (string, map[string][]byte) {+ t.Helper()+ dir := t.TempDir()+ set := stack.Embedded()+ refs := fluxerRefs("a")+ s := &State{+ Project: "fluxer",+ Release: set.Release,+ Images: Images{Release: set.Release, Refs: refs},+ Settings: map[string]string{settings.Domain: "chat.example.com"},+ Secrets: map[string]string{},+ }+ if _, err := secrets.Mint(s.Secrets, false); err != nil {+ t.Fatal(err)+ }+ managed, err := stack.Files(set, nil, refs, "fluxer")+ if err != nil {+ t.Fatal(err)+ }+ if s.Rendered, err = stack.Hashes(set, nil, refs, "fluxer"); err != nil {+ t.Fatal(err)+ }+ files := map[string][]byte{}+ for name, data := range managed {+ files[name] = stack.Plain(name, data)+ if stack.Hash(files[name]) != s.Rendered[name] {+ t.Fatalf("the old layout fixture of %s doesn't match what older rexctl wrote", name)+ }+ }+ for name, data := range userFiles {+ files[name] = []byte(data)+ }+ for name, data := range files {+ writeTestFile(t, filepath.Join(dir, name), data)+ }+ if err := os.MkdirAll(filepath.Join(dir, StateDirName), 0o700); err != nil {+ t.Fatal(err)+ }+ s.rootLayout = true+ if err := s.Save(filepath.Join(dir, StateDirName, StateFileName)); err != nil {+ t.Fatal(err)+ }+ return dir, files+}++func writeTestFile(t *testing.T, path string, data []byte) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, data, 0o644); err != nil {+ t.Fatal(err)+ }+}++func readTestFile(t *testing.T, path string) []byte {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ return data+}++func diskSchema(t *testing.T, dir string) int {+ t.Helper()+ var head struct{ Schema int }+ if err := json.Unmarshal(readTestFile(t, filepath.Join(dir, StateDirName, StateFileName)), &head); err != nil {+ t.Fatal(err)+ }+ return head.Schema+}++func migrated(t *testing.T, dir string, old map[string][]byte) *Instance {+ t.Helper()+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if err := inst.Migrate(nil); err != nil {+ t.Fatal(err)+ }+ return checkMigrated(t, dir, old)+}++func checkMigrated(t *testing.T, dir string, old map[string][]byte) *Instance {+ t.Helper()+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if inst.OldLayout() {+ t.Fatal("the instance is still on the old layout")+ }+ for _, name := range stack.FileNames() {+ want, ok := old[name]+ if !ok {+ continue+ }+ if got := readTestFile(t, inst.Generated(name)); !bytes.Equal(got, want) {+ t.Fatalf("%s changed while moving", name)+ }+ _, err := os.Lstat(inst.Path(name))+ if _, mounted := stack.MountedFiles[name]; !mounted && !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("%s is still in the instance folder: %v", name, err)+ }+ }+ for name, data := range userFiles {+ if got := readTestFile(t, inst.Path(name)); string(got) != data {+ t.Fatalf("%s changed", name)+ }+ }+ if s := diskSchema(t, dir); s != StateSchema {+ t.Fatalf("schema on disk %d, want %d", s, StateSchema)+ }+ r, err := Drift(inst)+ if err != nil || len(r.Changed) > 0 || len(r.Missing) > 0 {+ t.Fatalf("drift after moving: %+v %v", r, err)+ }+ for _, f := range inst.ComposeFiles() {+ if f != inst.Path(CustomCompose) && !strings.HasPrefix(f, stack.GeneratedPath(dir)) {+ t.Fatalf("compose file %s isn't in %s", f, stack.GeneratedDir)+ }+ }+ return inst+}++func checkOldLayout(t *testing.T, dir string, old map[string][]byte) {+ t.Helper()+ if s := diskSchema(t, dir); s != 2 {+ t.Fatalf("schema on disk %d, want 2", s)+ }+ for name, want := range old {+ if got := readTestFile(t, filepath.Join(dir, name)); !bytes.Equal(got, want) {+ t.Fatalf("%s changed", name)+ }+ }+}++func TestFindLeavesOldLayout(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if !inst.OldLayout() {+ t.Fatal("an older rexctl's instance loaded as the new layout")+ }+ checkOldLayout(t, dir, old)+ if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("loading the instance made the generated folder")+ }+ r, err := Drift(inst)+ if err != nil || len(r.Changed) > 0 || len(r.Missing) > 0 || len(inst.MissingFiles()) > 0 {+ t.Fatalf("drift on the old layout: %+v %v %v", r, err, inst.MissingFiles())+ }+ for _, f := range inst.ComposeFiles() {+ if filepath.Dir(f) != dir {+ t.Fatalf("compose file %s isn't in the instance folder", f)+ }+ }+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ checkOldLayout(t, dir, old)+}++func TestFindWorksWhileLockedAndReadOnly(t *testing.T) {+ dir, old := oldLayout(t)+ l, err := (&Instance{Dir: dir}).Lock(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer l.Release()+ if runtime.GOOS != "windows" && os.Geteuid() != 0 {+ if err := os.Chmod(filepath.Join(dir, StateDirName), 0o500); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { os.Chmod(filepath.Join(dir, StateDirName), 0o700) })+ }+ if _, err := Find(dir); err != nil {+ t.Fatalf("Find on an old layout another command holds: %v", err)+ }+ checkOldLayout(t, dir, old)+}++func TestOldLayoutRendersInPlace(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ inst.State.Settings[settings.EdgeMode] = settings.EdgeProxy+ r, err := inst.Render(stack.Embedded(), inst.Overlays(), inst.State.Images.Refs)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(stack.GeneratedPath(dir)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("rendering the old layout wrote the generated folder")+ }+ for name, hash := range r.Hashes {+ data := readTestFile(t, filepath.Join(dir, name))+ if stack.Hash(data) != hash || bytes.HasPrefix(data, []byte("# rexctl writes this file")) {+ t.Fatalf("%s isn't what an older rexctl writes", name)+ }+ }+ if !bytes.Equal(readTestFile(t, filepath.Join(dir, stack.ComposeFile)), old[stack.ComposeFile]) {+ t.Fatal("the compose file changed")+ }+}++func TestMigrateMovesOldLayout(t *testing.T) {+ dir, old := oldLayout(t)+ migrated(t, dir, old)+ if got := readTestFile(t, filepath.Join(dir, stack.Caddyfile)); !bytes.Equal(got, old[stack.Caddyfile]) {+ t.Fatal("the Caddyfile the running edge mounts went away before the next start")+ }+}++func TestMigrateOnce(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ before := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName))+ if err := inst.Migrate(func() error { return errors.New("ran again") }); err != nil {+ t.Fatal(err)+ }+ if after := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName)); !bytes.Equal(before, after) {+ t.Fatal("a second migration changed the state again")+ }+}++func TestMigrateNoticesAnotherProcessMoved(t *testing.T) {+ dir, old := oldLayout(t)+ stale, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ migrated(t, dir, old)+ if err := stale.Migrate(func() error { return errors.New("ran again") }); err != nil {+ t.Fatal(err)+ }+ if err := stale.Save(); err != nil {+ t.Fatal(err)+ }+ checkMigrated(t, dir, old)+}++func TestMigrateStopsBeforeSavingWhenPrepareFails(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ var schemaThen int+ err = inst.Migrate(func() error {+ schemaThen = diskSchema(t, dir)+ return errors.New("no copy of rexctl")+ })+ if err == nil || schemaThen != 2 {+ t.Fatalf("got %v with schema %d while preparing", err, schemaThen)+ }+ if !inst.OldLayout() {+ t.Fatal("the instance switched layouts without its files")+ }+ checkOldLayout(t, dir, old)+}++func TestMigrateAfterCrashBeforeSave(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := copyGenerated(inst); err != nil {+ t.Fatal(err)+ }+ checkOldLayout(t, dir, old)+ again, err := Find(dir)+ if err != nil || !again.OldLayout() {+ t.Fatalf("after the crash: %v", err)+ }+ migrated(t, dir, old)+}++func TestMigrateAsRootGivesFilesToOwner(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("no owners on Windows")+ }+ dir, _ := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ owner, _ := inst.OwnerUID()+ prevUID, prevChown := euid, chown+ t.Cleanup(func() { euid, chown = prevUID, prevChown })+ euid = func() int { return 0 }+ given := map[string]int{}+ chown = func(path string, uid, _ int) error {+ given[path] = uid+ return nil+ }+ if owner == 0 {+ t.Skip("the test folder belongs to root")+ }+ if err := inst.Migrate(nil); err != nil {+ t.Fatal(err)+ }+ for _, path := range []string{stack.GeneratedPath(dir), inst.Generated(stack.ComposeFile), inst.Generated(stack.Caddyfile)} {+ if uid, ok := given[path]; !ok || uid != owner {+ t.Fatalf("%s wasn't given to the folder's owner: %v", path, given)+ }+ }+}++func startedWithGenerated(t *testing.T, inst *Instance) {+ t.Helper()+ compose := inst.Generated(stack.ComposeFile)+ writeTestFile(t, compose, stack.Managed(stack.ComposeFile, stack.Plain(stack.ComposeFile, readTestFile(t, compose))))+ if err := inst.DropRootCopies(context.Background(), true); err != nil {+ t.Fatal(err)+ }+}++func TestDropRootCopiesRemovesOnlyWhatMigrationLeft(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ root := inst.Path(stack.Caddyfile)+ if err := inst.DropRootCopies(context.Background(), true); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(root); err != nil {+ t.Fatal("removed the Caddyfile an older compose file still mounts")+ }+ startedWithGenerated(t, inst)+ if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("kept the Caddyfile the migration left after edge moved to the generated one")+ }+ again, err := Find(dir)+ if err != nil || len(again.State.LeftInRoot) != 0 {+ t.Fatalf("the state still lists %v, %v", again.State.LeftInRoot, err)+ }+}++func TestDropRootCopiesKeepsYourCaddyfile(t *testing.T) {+ for name, change := range map[string]func(t *testing.T, inst *Instance){+ "mounted from custom.compose.yml": func(t *testing.T, inst *Instance) {+ writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ./Caddyfile:/etc/caddy/Caddyfile:ro\n"))+ },+ "mounted from ${PWD}": func(t *testing.T, inst *Instance) {+ writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ${PWD}/Caddyfile:/etc/caddy/Caddyfile:ro\n"))+ },+ "mounted with the long syntax": func(t *testing.T, inst *Instance) {+ writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - type: bind\n source: Caddyfile\n target: /etc/caddy/Caddyfile\n"))+ },+ "custom.compose.yml that doesn't load": func(t *testing.T, inst *Instance) {+ writeTestFile(t, inst.Path(CustomCompose), []byte("services: [\n"))+ },+ "changed by you": func(t *testing.T, inst *Instance) {+ writeTestFile(t, inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"))+ },+ "never left by rexctl": func(t *testing.T, inst *Instance) {+ inst.State.LeftInRoot = nil+ },+ } {+ t.Run(name, func(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ change(t, inst)+ startedWithGenerated(t, inst)+ if _, err := os.Stat(inst.Path(stack.Caddyfile)); err != nil {+ t.Fatalf("removed your Caddyfile: %v", err)+ }+ })+ }+}++func TestDropRootCopiesLooksAtWhatCustomComposeMounts(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - ${PWD}/caddy.d/x.caddy:/etc/caddy/x.caddy:ro\n - ./Caddyfile.mine:/etc/caddy/mine:ro\n"))+ startedWithGenerated(t, inst)+ if _, err := os.Stat(inst.Path(stack.Caddyfile)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("kept the Caddyfile though custom.compose.yml mounts other files")+ }+}++func TestUnusedRootFilesNamesAnEditedCaddyfile(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ ctx := context.Background()+ writeTestFile(t, inst.Path(stack.Caddyfile), []byte(":443 {\n}\n"))+ if got := inst.UnusedRootFiles(ctx); len(got) != 0 {+ t.Fatalf("the edge still mounts the root Caddyfile, but got %v", got)+ }+ startedWithGenerated(t, inst)+ if got := inst.UnusedRootFiles(ctx); !slices.Equal(got, []string{stack.Caddyfile}) {+ t.Fatalf("UnusedRootFiles = %v", got)+ }+ writeTestFile(t, inst.Path(CustomCompose), []byte("services:\n edge:\n volumes:\n - type: bind\n source: Caddyfile\n target: /etc/caddy/Caddyfile\n"))+ if got := inst.UnusedRootFiles(ctx); len(got) != 0 {+ t.Fatalf("custom.compose.yml mounts it, but got %v", got)+ }+}++func TestDropRootCopiesLeavesTheOldLayoutAlone(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ inst.State.LeftInRoot = map[string]string{}+ for _, name := range []string{stack.ComposeFile, stack.Caddyfile} {+ inst.State.LeftInRoot[name] = stack.Hash(old[name])+ }+ if err := inst.DropRootCopies(context.Background(), true); err != nil {+ t.Fatal(err)+ }+ checkOldLayout(t, dir, old)+}++func TestEjectAfterMoveGivesTheOldFiles(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ if err := Eject(inst, EjectOptions{Rexctl: "test"}); err != nil {+ t.Fatal(err)+ }+ for _, name := range stack.FileNames() {+ want, ok := old[name]+ if !ok {+ continue+ }+ if got := readTestFile(t, inst.Path(name)); !bytes.Equal(got, want) {+ t.Fatalf("ejected %s differs from the file older rexctl left", name)+ }+ _, err := os.Stat(inst.Generated(name))+ if _, mounted := stack.MountedFiles[name]; !mounted && !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("%s stayed in %s after eject", name, stack.GeneratedDir)+ }+ }+ env, err := envfile.Load(inst.Path(EnvFileName))+ if err != nil {+ t.Fatal(err)+ }+ if got, want := env.Value("COMPOSE_FILE"), stack.ComposeFile+string(os.PathListSeparator)+CustomCompose; got != want {+ t.Fatalf("COMPOSE_FILE = %q, want %q", got, want)+ }+ again, err := Find(dir)+ if err != nil || again.State.Ejected == nil {+ t.Fatalf("not ejected: %v", err)+ }+ if _, err := os.Stat(inst.Generated(stack.ComposeFile)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("loading an ejected instance moved its files")+ }++ s, r, err := Import(dir, nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(r.KeepAsMine) > 0 || s.Ejected != nil {+ t.Fatalf("takeover kept %v", r.KeepAsMine)+ }+ checkOldLayout(t, dir, old)+ migrated(t, dir, old)+}++func TestFreshLayoutLoadsWithTemplate(t *testing.T) {+ inst, err := Create(t.TempDir(), "fluxer")+ if err != nil {+ t.Fatal(err)+ }+ set := stack.Embedded()+ inst.State.Release = set.Release+ inst.State.Images = Images{Release: set.Release, Refs: fluxerRefs("a")}+ inst.State.Settings[settings.Domain] = "chat.example.com"+ if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {+ t.Fatal(err)+ }+ r, err := stack.Render(set, nil, inst.State.Images.Refs, "fluxer", inst.Dir)+ if err != nil {+ t.Fatal(err)+ }+ inst.State.Rendered = r.Hashes+ if err := inst.WriteCustomTemplate(); err != nil {+ t.Fatal(err)+ }+ if got := string(readTestFile(t, inst.Path(CustomCompose))); got != CustomTemplate {+ t.Fatalf("template %q", got)+ }+ mine := []byte("services: {}\n")+ writeTestFile(t, inst.Path(CustomCompose), mine)+ if err := inst.WriteCustomTemplate(); err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(readTestFile(t, inst.Path(CustomCompose)), mine) {+ t.Fatal("the template replaced the file you wrote")+ }+ writeTestFile(t, inst.Path(CustomCompose), []byte(CustomTemplate))+ for _, name := range slices.Sorted(maps.Keys(r.Hashes)) {+ if !bytes.HasPrefix(readTestFile(t, inst.Generated(name)), []byte("# rexctl writes this file and puts its own version back")) {+ t.Fatalf("%s has no header", name)+ }+ if _, err := os.Stat(inst.Path(name)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("%s is in the instance folder", name)+ }+ }+ env, err := inst.Environment()+ if err != nil {+ t.Fatal(err)+ }+ var none engine.Engine+ p, err := none.Load(context.Background(), engine.Spec{Name: "fluxer", Dir: inst.Dir, Files: inst.ComposeFiles(), Env: env})+ if err != nil {+ t.Fatal(err)+ }+ if p.Model.WorkingDir != inst.Dir {+ t.Fatalf("project folder %s, want %s", p.Model.WorkingDir, inst.Dir)+ }+ var sources []string+ for _, v := range p.Model.Services["edge"].Volumes {+ sources = append(sources, v.Source)+ }+ for _, want := range []string{inst.Generated(stack.Caddyfile), inst.Path(CertsDir), inst.Path(CaddyDropInDir)} {+ if !slices.Contains(sources, want) {+ t.Fatalf("edge mounts %v, want %s", sources, want)+ }+ }+}++func TestOlderRexctlRefusesMovedState(t *testing.T) {+ dir, old := oldLayout(t)+ migrated(t, dir, old)+ data := readTestFile(t, filepath.Join(dir, StateDirName, StateFileName))+ older := strings.Replace(string(data), `"schema": 3`, `"schema": 4`, 1)+ if _, err := ParseState([]byte(older), dir); !errors.Is(err, ErrNewerState) {+ t.Fatalf("got %v, want ErrNewerState", err)+ }+ if !bytes.Contains(data, []byte(`"schema": 3`)) {+ t.Fatal("the moved state isn't schema 3, so rexctl with schema 2 would read it")+ }+}++func TestKeepEditsKeepsOneCopyWithDiff(t *testing.T) {+ dir, old := oldLayout(t)+ inst := migrated(t, dir, old)+ path := inst.Generated(stack.ComposeFile)+ writeTestFile(t, path, append(readTestFile(t, path), []byte("# my change\n")...))+ edits, err := KeepEdits(inst)+ if err != nil || len(edits) != 1 {+ t.Fatalf("edits %v, %v", edits, err)+ }+ if !slices.Contains(edits[0].Diff, "+ # my change") {+ t.Fatalf("diff %q", edits[0].Diff)+ }+ if !strings.HasPrefix(edits[0].Copy, inst.Path(StateDirName, EditedDir)) || !bytes.Equal(readTestFile(t, edits[0].Copy), readTestFile(t, path)) {+ t.Fatalf("copy %s", edits[0].Copy)+ }+ again, err := KeepEdits(inst)+ if err != nil || len(again) != 1 || again[0].Copy != edits[0].Copy {+ t.Fatalf("second copy %v, %v", again, err)+ }+}++func TestEjectOnTheOldLayoutKeepsTheFiles(t *testing.T) {+ dir, old := oldLayout(t)+ inst, err := Find(dir)+ if err != nil {+ t.Fatal(err)+ }+ if err := Eject(inst, EjectOptions{Rexctl: "test"}); err != nil {+ t.Fatal(err)+ }+ checkOldLayout(t, dir, old)+}diff --git a/fluxer_rexctl/internal/instance/owner_unix.go b/fluxer_rexctl/internal/instance/owner_unix.goindex 5ed942960..af8b91335 100644--- a/fluxer_rexctl/internal/instance/owner_unix.go+++ b/fluxer_rexctl/internal/instance/owner_unix.go@@ -20,3 +20,18 @@ func (i *Instance) OwnerUID() (int, bool) {}return int(st.Uid), true}++func (i *Instance) giveToOwner(path string) error {+ if euid() != 0 {+ return nil+ }+ info, err := os.Stat(i.Dir)+ if err != nil {+ return err+ }+ st, ok := info.Sys().(*syscall.Stat_t)+ if !ok || st.Uid == 0 {+ return nil+ }+ return chown(path, int(st.Uid), int(st.Gid))+}diff --git a/fluxer_rexctl/internal/instance/owner_windows.go b/fluxer_rexctl/internal/instance/owner_windows.goindex 9568c367e..2e317dc49 100644--- a/fluxer_rexctl/internal/instance/owner_windows.go+++ b/fluxer_rexctl/internal/instance/owner_windows.go@@ -5,3 +5,5 @@package instancefunc (i *Instance) OwnerUID() (int, bool) { return 0, false }++func (i *Instance) giveToOwner(string) error { return nil }diff --git a/fluxer_rexctl/internal/instance/state.go b/fluxer_rexctl/internal/instance/state.goindex 5fc12b56a..f56ccf9e9 100644--- a/fluxer_rexctl/internal/instance/state.go+++ b/fluxer_rexctl/internal/instance/state.go@@ -18,7 +18,7 @@ import ("github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings")-const StateSchema = 2+const StateSchema = generatedSchemavar ErrNewerState = errors.New("instance: state was written by a newer rexctl")@@ -40,6 +40,7 @@ type State struct {Stopped bool `json:"stopped"`Rendered map[string]string `json:"rendered"`Mounted map[string]string `json:"mounted"`+ LeftInRoot map[string]string `json:"left_in_root,omitempty"`Ejected *Ejected `json:"ejected"`BackupDir string `json:"backup_dir,omitempty"`KeepBackups int `json:"keep_backups,omitempty"`@@ -47,7 +48,8 @@ type State struct {InstalledAt time.Time `json:"installed_at"`UpdatedAt time.Time `json:"updated_at"`- Unknown []string `json:"-"`+ Unknown []string `json:"-"`+ rootLayout bool}type EngineRef struct {@@ -98,19 +100,27 @@ func (e *SettingError) Error() string {}func (e *SettingError) Fix() string {- return "Run rexctl config unset " + e.Key + "."+ return "Run rexctl config set " + e.Key + " <value>, or rexctl config unset " + e.Key + " to go back to the default."}func LoadState(path string) (*State, error) {+ return loadState(path, nil)+}++func loadState(path string, repairing []string) (*State, error) {data, err := os.ReadFile(path)if err != nil {return nil, err}dir := filepath.Dir(filepath.Dir(path))- return ParseState(data, dir)+ return parseStateRepairing(data, dir, repairing)}func ParseState(data []byte, dir string) (*State, error) {+ return parseStateRepairing(data, dir, nil)+}++func parseStateRepairing(data []byte, dir string, repairing []string) (*State, error) {var head struct {Schema int `json:"schema"`Project string `json:"project"`@@ -124,10 +134,11 @@ func ParseState(data []byte, dir string) (*State, error) {if head.Project == "" {return nil, fmt.Errorf("instance: the state in %s names no project", dir)}- s, err := parseState(data, dir)+ s, err := parseState(data, dir, repairing)if err != nil {return nil, err}+ s.rootLayout = head.Schema < generatedSchemas.normalize()return s, nil}@@ -135,11 +146,11 @@ func ParseState(data []byte, dir string) (*State, error) {var stateFields = map[string]bool{"schema": true, "project": true, "engine": true, "release": true, "previous_release": true, "failed_release": true,"upgrade": true, "pending": true, "images": true, "settings": true, "secrets": true, "admin_import": true,- "setup_done": true, "installing": true, "stopped": true, "rendered": true, "mounted": true, "ejected": true,+ "setup_done": true, "installing": true, "stopped": true, "rendered": true, "mounted": true, "left_in_root": true, "ejected": true,"installed_at": true, "updated_at": true, "backup_dir": true, "keep_backups": true, "notify_url": true,}-func parseState(data []byte, dir string) (*State, error) {+func parseState(data []byte, dir string, repairing []string) (*State, error) {var raw map[string]json.RawMessageif err := json.Unmarshal(data, &raw); err != nil {return nil, fmt.Errorf("instance: reading state in %s: %w", dir, err)@@ -150,7 +161,7 @@ func parseState(data []byte, dir string) (*State, error) {unknown = append(unknown, k)}}- values, more, err := checkSettings(raw["settings"], dir)+ values, more, err := checkSettings(raw["settings"], dir, repairing)if err != nil {return nil, err}@@ -170,7 +181,7 @@ func parseState(data []byte, dir string) (*State, error) {return &s, nil}-func checkSettings(data json.RawMessage, dir string) (map[string]string, []string, error) {+func checkSettings(data json.RawMessage, dir string, repairing []string) (map[string]string, []string, error) {out := map[string]string{}if len(data) == 0 || string(data) == "null" {return out, nil, nil@@ -196,6 +207,7 @@ func checkSettings(data json.RawMessage, dir string) (map[string]string, []strincontinue}switch {+ case isNamed && slices.Contains(repairing, name):case isNamed:if k.Validate != nil {if err := k.Validate(v); err != nil {@@ -218,6 +230,9 @@ func (s *State) InstallUnfinished() bool { return s.Installing }func (s *State) normalize() {s.Schema = StateSchema+ if s.rootLayout {+ s.Schema = generatedSchema - 1+ }if s.Settings == nil {s.Settings = map[string]string{}}@@ -237,13 +252,16 @@ func (s *State) normalize() {func (s *State) Save(path string) error {c := *s- c.Schema = StateSchemac.normalize()data, err := json.MarshalIndent(&c, "", " ")if err != nil {return err}- return writePrivate(path, append(data, '\n'))+ if err := writePrivate(path, append(data, '\n')); err != nil {+ return err+ }+ s.Schema = c.Schema+ return nil}func writePrivate(path string, data []byte) error {diff --git a/fluxer_rexctl/internal/release/files.go b/fluxer_rexctl/internal/release/files.goindex 73ca52f0a..c0e12f030 100644--- a/fluxer_rexctl/internal/release/files.go+++ b/fluxer_rexctl/internal/release/files.go@@ -154,7 +154,7 @@ func Restore(inst *instance.Instance, version string) (*Restored, error) {if len(saved.Images.Refs) == 0 && Valid(version) {return nil, fmt.Errorf("release: the snapshot of %s records no images", version)}- r, err := stack.Render(set, stack.OverlaysFor(saved.Settings), saved.Images.Refs, inst.Project(), inst.Dir)+ r, err := inst.Render(set, stack.OverlaysFor(saved.Settings), saved.Images.Refs)if err != nil {return nil, err}@@ -212,7 +212,7 @@ func MissingFiles(inst *instance.Instance) []string {}var out []stringfor _, name := range expectedFiles(inst) {- if _, err := os.Lstat(filepath.Join(inst.Dir, name)); errors.Is(err, fs.ErrNotExist) {+ if _, err := os.Lstat(inst.Generated(name)); errors.Is(err, fs.ErrNotExist) {out = append(out, name)}}@@ -269,10 +269,10 @@ func RestoreMissing(inst *instance.Instance) ([]string, error) {return nil, err}defer os.RemoveAll(tmp)- if _, err := stack.Render(set, stack.OverlaysFor(inst.State.Settings), inst.State.Images.Refs, inst.Project(), tmp); err != nil {+ if _, err := stack.RenderAt(set, stack.OverlaysFor(inst.State.Settings), inst.State.Images.Refs, inst.Project(), tmp, inst.OldLayout()); err != nil {return nil, err}- source = os.DirFS(tmp)+ source = os.DirFS(stack.FilesDir(tmp, inst.OldLayout()))}var restored []stringfor _, name := range missing {@@ -280,7 +280,10 @@ func RestoreMissing(inst *instance.Instance) ([]string, error) {if err != nil || len(data) == 0 {continue}- if err := writeFile(filepath.Join(inst.Dir, name), data, false); err != nil {+ if set.Release == stack.LegacyRelease && !inst.OldLayout() {+ data = stack.Managed(name, data)+ }+ if err := writeFile(inst.Generated(name), data, false); err != nil {return restored, err}if inst.State.Rendered == nil {diff --git a/fluxer_rexctl/internal/release/floor.go b/fluxer_rexctl/internal/release/floor.goindex 89cac54bb..c754f8e42 100644--- a/fluxer_rexctl/internal/release/floor.go+++ b/fluxer_rexctl/internal/release/floor.go@@ -9,7 +9,6 @@ import ("strings""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"- "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance")var (@@ -42,12 +41,12 @@ func (e *OlderSchemaError) Error() string {func (e *OlderSchemaError) Is(target error) bool { return target == ErrOlderSchema }-func CheckTarget(e *engine.Engine, to *Release) error {+func CheckTarget(e *engine.Engine, to *Release, have int) error {if to == nil {return nil}- if to.StateSchema > 0 && to.StateSchema < instance.StateSchema {- return &OlderSchemaError{Have: instance.StateSchema, Reads: to.StateSchema, Release: to.Version}+ if to.StateSchema > 0 && to.StateSchema < have {+ return &OlderSchemaError{Have: have, Reads: to.StateSchema, Release: to.Version}}if e == nil {return nildiff --git a/fluxer_rexctl/internal/stack/generated_test.go b/fluxer_rexctl/internal/stack/generated_test.gonew file mode 100644index 000000000..b53ccf29e--- /dev/null+++ b/fluxer_rexctl/internal/stack/generated_test.go@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package stack++import (+ "bytes"+ "path/filepath"+ "testing"+)++func TestManagedFilesRoundTrip(t *testing.T) {+ set := Embedded()+ for _, name := range FileNames() {+ plain, err := ReadFile(set, name)+ if err != nil {+ t.Fatal(err)+ }+ managed := Managed(name, plain)+ if !bytes.HasPrefix(managed, header(name)) {+ t.Fatalf("%s has no header", name)+ }+ if !bytes.Equal(Plain(name, managed), plain) {+ t.Fatalf("%s doesn't come back the same after eject", name)+ }+ }+ compose, err := ReadFile(set, ComposeFile)+ if err != nil {+ t.Fatal(err)+ }+ plain, managed := mountRefs(Caddyfile)+ if !bytes.Contains(compose, plain) || bytes.Contains(Managed(ComposeFile, compose), plain) || !bytes.Contains(Managed(ComposeFile, compose), managed) {+ t.Fatal("the edge service doesn't mount the generated Caddyfile")+ }+}++func TestProjectDirOfGeneratedComposeFile(t *testing.T) {+ dir := filepath.Join(t.TempDir(), "fluxer")+ for _, f := range []string{filepath.Join(dir, ComposeFile), GeneratedPath(dir, ComposeFile)} {+ if got := ProjectDir(f); got != dir {+ t.Fatalf("ProjectDir(%s) = %s, want %s", f, got, dir)+ }+ }+}++func TestHeaderSaysHowToChangeTheFile(t *testing.T) {+ for name, want := range map[string]string{+ ComposeFile: "# rexctl writes this file and puts its own version back when it changes Fluxer.\n# To change it, run rexctl config edit.\n\n",+ Caddyfile: "# rexctl writes this file and puts its own version back when it changes Fluxer.\n# To add Caddy directives, put a .caddy file in caddy.d in your instance folder.\n\n",+ } {+ if got := string(header(name)); got != want {+ t.Errorf("%s header %q, want %q", name, got, want)+ }+ }+}diff --git a/fluxer_rexctl/internal/stack/stack.go b/fluxer_rexctl/internal/stack/stack.goindex 0e0dbc606..89d07a5fe 100644--- a/fluxer_rexctl/internal/stack/stack.go+++ b/fluxer_rexctl/internal/stack/stack.go@@ -22,8 +22,9 @@ const defaultProject = "fluxer"var defaultName = regexp.MustCompile(`(?m)^name: ` + defaultProject + `$`)const (- ComposeFile = "docker-compose.yml"- Caddyfile = "Caddyfile"+ ComposeFile = "docker-compose.yml"+ Caddyfile = "Caddyfile"+ GeneratedDir = ".rexctl/generated")type Overlay string@@ -101,17 +102,87 @@ func OverlaysFor(settings map[string]string) []Overlay {return out}-func ComposeFiles(dir string, overlays []Overlay) []string {+func FileNames() []string {+ names := []string{ComposeFile, Caddyfile}+ for _, o := range overlayOrder {+ names = append(names, OverlayFiles[o])+ }+ return names+}++func GeneratedPath(dir string, name ...string) string {+ return filepath.Join(append([]string{dir, filepath.FromSlash(GeneratedDir)}, name...)...)+}++func ProjectDir(composeFile string) string {+ dir := filepath.Dir(composeFile)+ if trimmed, ok := strings.CutSuffix(dir, string(filepath.Separator)+filepath.FromSlash(GeneratedDir)); ok {+ return trimmed+ }+ return dir+}++func FilesDir(dir string, root bool) string {if abs, err := filepath.Abs(dir); err == nil {dir = abs}- files := []string{filepath.Join(dir, ComposeFile)}+ if root {+ return dir+ }+ return GeneratedPath(dir)+}++func ComposeFiles(dir string, overlays []Overlay) []string {+ return ComposeFilesAt(dir, overlays, false)+}++func ComposeFilesAt(dir string, overlays []Overlay, root bool) []string {+ files := FilesDir(dir, root)+ out := []string{filepath.Join(files, ComposeFile)}for _, o := range overlayOrder {if slices.Contains(overlays, o) {- files = append(files, filepath.Join(dir, OverlayFiles[o]))+ out = append(out, filepath.Join(files, OverlayFiles[o]))}}- return files+ return out+}++func header(name string) []byte {+ how := "To change it, run rexctl config edit."+ if name == Caddyfile {+ how = "To add Caddy directives, put a .caddy file in caddy.d in your instance folder."+ }+ return []byte("# rexctl writes this file and puts its own version back when it changes Fluxer.\n# " + how + "\n\n")+}++func mountRefs(name string) (plain, managed []byte) {+ return []byte("./" + name + ":"), []byte("./" + GeneratedDir + "/" + name + ":")+}++func Managed(name string, data []byte) []byte {+ if name != Caddyfile {+ for mounted := range MountedFiles {+ plain, managed := mountRefs(mounted)+ data = bytes.ReplaceAll(data, plain, managed)+ }+ }+ return append(header(name), data...)+}++func Plain(name string, data []byte) []byte {+ data = bytes.TrimPrefix(data, header(name))+ if name != Caddyfile {+ for mounted := range MountedFiles {+ plain, managed := mountRefs(mounted)+ data = bytes.ReplaceAll(data, managed, plain)+ }+ }+ return data+}++func MountsGenerated(compose []byte, name string) bool {+ _, managed := mountRefs(name)+ return bytes.Contains(compose, managed)}type renderedFile struct {@@ -221,12 +292,25 @@ func nameProject(compose []byte, project string) []byte {return bytes.ReplaceAll(compose, []byte("compose -p "+defaultProject+" "), []byte("compose -p "+project+" "))}-func Render(set *Set, selected []Overlay, images map[string]string, project, dir string) (*Rendered, error) {- files, overlays, err := renderFiles(set, selected, images, project)+func Files(set *Set, selected []Overlay, images map[string]string, project string) (map[string][]byte, error) {+ files, _, err := renderFiles(set, selected, images, project)if err != nil {return nil, err}- if err := os.MkdirAll(dir, 0o755); err != nil {+ out := make(map[string][]byte, len(files))+ for _, f := range files {+ out[f.name] = Managed(f.name, f.data)+ }+ return out, nil+}++func Render(set *Set, selected []Overlay, images map[string]string, project, dir string) (*Rendered, error) {+ return RenderAt(set, selected, images, project, dir, false)+}++func RenderAt(set *Set, selected []Overlay, images map[string]string, project, dir string, root bool) (*Rendered, error) {+ files, overlays, err := renderFiles(set, selected, images, project)+ if err != nil {return nil, err}for _, d := range MountedDirs {@@ -234,7 +318,16 @@ func Render(set *Set, selected []Overlay, images map[string]string, project, dirreturn nil, err}}- changed, stale, err := plan(dir, files, overlays)+ if !root {+ for i, f := range files {+ files[i].data = Managed(f.name, f.data)+ }+ }+ gen := FilesDir(dir, root)+ if err := os.MkdirAll(gen, 0o755); err != nil {+ return nil, err+ }+ changed, stale, err := plan(gen, files, overlays)if err != nil {return nil, err}@@ -244,15 +337,15 @@ func Render(set *Set, selected []Overlay, images map[string]string, project, dirwrite = append(write, f)}}- if err := writeAll(dir, write); err != nil {+ if err := writeAll(gen, write); err != nil {return nil, err}for _, name := range stale {- if err := os.Remove(filepath.Join(dir, name)); err != nil && !errors.Is(err, fs.ErrNotExist) {+ if err := os.Remove(filepath.Join(gen, name)); err != nil && !errors.Is(err, fs.ErrNotExist) {return nil, err}}- r := &Rendered{Dir: dir, Hashes: make(map[string]string, len(files)), ComposeFiles: ComposeFiles(dir, overlays)}+ r := &Rendered{Dir: dir, Hashes: make(map[string]string, len(files)), ComposeFiles: ComposeFilesAt(dir, overlays, root)}for _, f := range files {r.Hashes[f.name] = Hash(f.data)}