A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): add unattended daily upgrades (#3666)
Hampus5afcaa87efa0
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdxindex 6f6bc31c5..6ec3319e2 100644--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx@@ -52,6 +52,44 @@ Print a link that signs an admin in once.rexctl admins sign-in-link <user>```+## rexctl auto-upgrade++Show whether rexctl upgrades Fluxer by itself every day, when it runs next and how the last run went. The daily run is rexctl upgrade --yes, so it works like an upgrade you run yourself.++```sh+rexctl auto-upgrade [flags]+```++- `--json`++ Print JSON.++### rexctl auto-upgrade off++Stop upgrading Fluxer by itself.++```sh+rexctl auto-upgrade off+```++### rexctl auto-upgrade on++Run rexctl upgrade --yes every day with a systemd timer, or with cron on machines without systemd. Each run backs up your instance first, goes back to the release you had if the new one doesn't start, and waits for the next day if another rexctl command is changing the instance. Run it again to change the time or the address, and leave out --notify to stop the notifications.++With --notify, rexctl posts JSON to the address when an upgrade installs a new release or fails: instance, status (upgraded or failed), release, and the message as both text and content, which Slack and Discord webhooks show as they are. For ntfy, add ?tpl=1&m=\{\{.text\}\} to the topic address.++```sh+rexctl auto-upgrade on [flags]+```++- `--at string`++ Time of day to upgrade, as HH:MM in this machine's time zone. The default is `04:00`.++- `--notify string`++ Web address rexctl posts to when an upgrade installs a new release or fails.+## rexctl backupBack up your instance. Fluxer pauses while uploads are copied.diff --git a/fluxer_rexctl/cmd/app.go b/fluxer_rexctl/cmd/app.goindex 217fea8e4..7ef907b63 100644--- a/fluxer_rexctl/cmd/app.go+++ b/fluxer_rexctl/cmd/app.go@@ -39,6 +39,7 @@ type App struct {Flags GlobalFlagsUI *ui.UIexit int+ outcome stringheld *instance.Instanceengine *engine.Enginewarned booldiff --git a/fluxer_rexctl/cmd/autoupgrade.go b/fluxer_rexctl/cmd/autoupgrade.gonew file mode 100644index 000000000..f15c1508f--- /dev/null+++ b/fluxer_rexctl/cmd/autoupgrade.go@@ -0,0 +1,362 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/checks"+ "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/ui"+)++const (+ autoUpgradeLog = "auto-upgrade.log"+ autoUpgradeDefault = "04:00"+ autoUpgradeWindow = 30 * time.Minute+ notifyTimeout = 15 * time.Second+)++type autoUpgradeJSON struct {+ On bool `json:"on"`+ Scheduler string `json:"scheduler,omitempty"`+ At string `json:"at,omitempty"`+ NextRun string `json:"next_run,omitempty"`+ LastRun string `json:"last_run,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+ Running bool `json:"running"`+ Notify string `json:"notify,omitempty"`+ Log string `json:"log,omitempty"`+}++type upgradeNotice struct {+ Instance string `json:"instance"`+ Status string `json:"status"`+ Release string `json:"release"`+ Text string `json:"text"`+ Content string `json:"content"`+}++func newAutoUpgradeCmd(app *App) *cobra.Command {+ c := &cobra.Command{+ Use: "auto-upgrade",+ Short: "Show whether rexctl upgrades Fluxer by itself every day",+ Long: "Show whether rexctl upgrades Fluxer by itself every day, when it runs next and how the last run went. The daily run is rexctl upgrade --yes, so it works like an upgrade you run yourself.",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runAutoUpgradeShow(c.Context(), app)+ },+ }+ app.jsonFlag(c)+ var at, notify string+ on := &cobra.Command{+ Use: "on",+ Short: "Upgrade Fluxer by itself every day",+ Long: "Run rexctl upgrade --yes every day with a systemd timer, or with cron on machines without systemd. Each run backs up your instance first, goes back to the release you had if the new one doesn't start, and waits for the next day if another rexctl command is changing the instance. Run it again to change the time or the address, and leave out --notify to stop the notifications.\n\n" ++ "With --notify, rexctl posts JSON to the address when an upgrade installs a new release or fails: instance, status (upgraded or failed), release, and the message as both text and content, which Slack and Discord webhooks show as they are. For ntfy, add ?tpl=1&m={{.text}} to the topic address.",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runAutoUpgradeOn(c.Context(), app, at, notify)+ },+ }+ on.Flags().StringVar(&at, "at", autoUpgradeDefault, "time of day to upgrade, as HH:MM in this machine's time zone")+ on.Flags().StringVar(¬ify, "notify", "", "web address rexctl posts to when an upgrade installs a new release or fails")+ off := &cobra.Command{+ Use: "off",+ Short: "Stop upgrading Fluxer by itself",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runAutoUpgradeOff(c.Context(), app)+ },+ }+ c.AddCommand(on, off)+ return c+}++func autoUpgradeFor(inst *instance.Instance, e *engine.Engine) (host.AutoUpgrade, error) {+ bin, err := checks.RunningBinary()+ if err != nil {+ return host.AutoUpgrade{}, err+ }+ dir, err := filepath.Abs(inst.Dir)+ if err != nil {+ return host.AutoUpgrade{}, err+ }+ a := host.AutoUpgrade{+ Scheduler: host.UpgradeScheduler(),+ Project: inst.Project(),+ Dir: dir,+ Binary: bin,+ Rootless: runtime.GOOS == "linux" && os.Geteuid() != 0,+ Log: filepath.Join(dir, instance.StateDirName, autoUpgradeLog),+ }+ if e != nil {+ a.Podman, a.Rootless = e.Kind == engine.Podman, e.Rootless+ }+ return a, nil+}++func noScheduler() error {+ return ui.Refused("rexctl can upgrade Fluxer by itself only on Linux with systemd or cron.", "Run rexctl upgrade --yes every day from your own scheduler.")+}++func runAutoUpgradeOn(ctx context.Context, app *App, at, notify string) error {+ t, err := time.Parse("15:04", at)+ if err != nil {+ return ui.Usage("Pass --at as a time of day like 04:00.")+ }+ at = t.Format("15:04")+ if notify != "" {+ if u, err := url.Parse(notify); err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {+ return ui.Usage("Pass --notify as a web address like https://ntfy.sh/your-topic.")+ }+ }+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ if err := managed(inst); err != nil {+ return err+ }+ e, err := app.Engine(ctx, inst)+ if err != nil {+ return err+ }+ a, err := autoUpgradeFor(inst, e)+ if err != nil {+ return err+ }+ if a.Scheduler == "" {+ return noScheduler()+ }+ a.At = at+ return app.Locked(ctx, inst, func() error {+ if err := host.InstallAutoUpgrade(ctx, a); err != nil {+ return schedulerError(err, "Couldn't turn on automatic upgrades.", "rexctl auto-upgrade on")+ }+ if inst.State.NotifyURL != notify {+ inst.State.NotifyURL = notify+ if err := inst.Save(); err != nil {+ return ui.Wrap(err, "Couldn't save your instance's state.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ }+ app.UI.OK("rexctl upgrades Fluxer every day %s.", autoUpgradeWhen(a.Scheduler, at))+ if notify != "" {+ app.UI.Info("rexctl tells %s when an upgrade installs a new release or fails.", maskURL(notify))+ }+ app.UI.Info("Run rexctl auto-upgrade to see when it runs next and how the last run went.")+ return nil+ })+}++func runAutoUpgradeOff(ctx context.Context, app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ e, err := app.Engine(ctx, inst)+ if err != nil {+ return err+ }+ return app.Locked(ctx, inst, func() error {+ removed, err := removeAutoUpgrade(ctx, inst, e)+ if err != nil {+ return schedulerError(err, "Couldn't turn off automatic upgrades.", "rexctl auto-upgrade off")+ }+ if inst.State.NotifyURL != "" {+ inst.State.NotifyURL = ""+ if err := inst.Save(); err != nil {+ return ui.Wrap(err, "Couldn't save your instance's state.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ }+ if !removed {+ app.UI.OK("Automatic upgrades are already off.")+ return nil+ }+ app.UI.OK("Turned off automatic upgrades. Run rexctl upgrade when you want a new release.")+ return nil+ })+}++func removeAutoUpgrade(ctx context.Context, inst *instance.Instance, e *engine.Engine) (bool, error) {+ a, err := autoUpgradeFor(inst, e)+ if err != nil || a.Scheduler == "" {+ return false, err+ }+ return host.RemoveAutoUpgrade(ctx, a)+}++func schedulerError(err error, msg, command string) error {+ if errors.Is(err, host.ErrNeedsRoot) {+ return ui.Refused(msg+" This needs root.", "Run sudo "+command+".")+ }+ return ui.Wrap(err, msg, "Run "+command+" --verbose to see why.")+}++func runAutoUpgradeShow(ctx context.Context, app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ e, err := app.Engine(ctx, inst)+ if err != nil {+ return err+ }+ a, err := autoUpgradeFor(inst, e)+ if err != nil {+ return err+ }+ if a.Scheduler == "" {+ if app.Flags.JSON {+ return app.UI.JSON(autoUpgradeJSON{})+ }+ return noScheduler()+ }+ s, err := host.CheckAutoUpgrade(ctx, a, time.Now())+ if err != nil {+ return ui.Wrap(err, "Couldn't read the automatic upgrade schedule.", "Run rexctl auto-upgrade --verbose to see why.")+ }+ out := autoUpgradeJSON{On: s.On}+ if s.On {+ out.Scheduler, out.At, out.NextRun, out.LastRun, out.Running = string(a.Scheduler), s.At, s.Next, s.Last, s.Running+ out.Log = autoUpgradeLogs(a)+ if inst.State.NotifyURL != "" {+ out.Notify = maskURL(inst.State.NotifyURL)+ }+ if s.Ran {+ code := s.ExitCode+ out.ExitCode = &code+ }+ }+ if app.Flags.JSON {+ return app.UI.JSON(out)+ }+ if !s.On {+ app.UI.Info("Automatic upgrades are off. Run rexctl auto-upgrade on to upgrade Fluxer every day.")+ return nil+ }+ app.UI.OK("rexctl upgrades Fluxer every day %s.", autoUpgradeWhen(a.Scheduler, s.At))+ switch {+ case s.Running:+ app.UI.Info("An automatic upgrade is running now.")+ case s.Ran && s.ExitCode != 0:+ app.UI.Warn(fmt.Sprintf("The last automatic upgrade stopped with exit code %d.", s.ExitCode), "Read its log to see why.")+ }+ rows := [][]string{{"Next run", s.Next}, {"Last run", s.Last}, {"Notify", out.Notify}, {"Log", out.Log}}+ for _, r := range rows {+ if r[1] != "" {+ app.UI.Result(fmt.Sprintf("%-9s %s", r[0], r[1]))+ }+ }+ return nil+}++func autoUpgradeWhen(s host.Scheduler, at string) string {+ t, err := time.Parse("15:04", at)+ if err != nil || s != host.Systemd {+ return "at " + at+ }+ return fmt.Sprintf("between %s and %s", at, t.Add(autoUpgradeWindow).Format("15:04"))+}++func autoUpgradeLogs(a host.AutoUpgrade) string {+ if a.Scheduler == host.Cron {+ return a.Log+ }+ if a.Rootless {+ return "journalctl --user -u " + a.ServiceName()+ }+ return "journalctl -u " + a.ServiceName()+}++func maskURL(raw string) string {+ u, err := url.Parse(raw)+ if err != nil || u.Host == "" {+ return "your notification address"+ }+ masked := u.Scheme + "://" + u.Host+ if strings.Trim(u.Path, "/") != "" || u.RawQuery != "" {+ masked += "/…"+ }+ return masked+}++func notifyUpgrade(ctx context.Context, app *App, runErr error) {+ if ctx.Err() != nil || errors.Is(runErr, context.Canceled) {+ return+ }+ dir, err := app.Dir()+ if err != nil {+ return+ }+ inst, err := instance.Find(dir)+ if err != nil || inst.State.NotifyURL == "" {+ return+ }+ n := upgradeNotice{Instance: inst.Domain(), Release: inst.State.Release}+ switch {+ case runErr != nil:+ n.Status, n.Text = "failed", noticeText(runErr)+ case app.exit != 0:+ n.Status, n.Text = "failed", app.outcome+ case app.outcome != "":+ n.Status, n.Text = "upgraded", app.outcome+ default:+ return+ }+ if n.Instance != "" {+ n.Text = n.Instance + ": " + n.Text+ }+ n.Content = n.Text+ if err := postNotice(ctx, inst.State.NotifyURL, n); err != nil {+ app.UI.Warn(fmt.Sprintf("Couldn't tell %s how the upgrade went.", maskURL(inst.State.NotifyURL)), "")+ app.UI.Detail("%v", err)+ }+}++func noticeText(err error) string {+ var ee *ui.ExitError+ if errors.As(err, &ee) && ee.Msg != "" {+ return strings.TrimSpace(ee.Msg + " " + ee.Fix)+ }+ return capitalise(err.Error())+}++func postNotice(ctx context.Context, rawURL string, n upgradeNotice) error {+ body, err := json.Marshal(n)+ if err != nil {+ return err+ }+ ctx, cancel := context.WithTimeout(ctx, notifyTimeout)+ defer cancel()+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(body))+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("User-Agent", "rexctl")+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return fmt.Errorf("notify: status %d", resp.StatusCode)+ }+ return nil+}diff --git a/fluxer_rexctl/cmd/autoupgrade_test.go b/fluxer_rexctl/cmd/autoupgrade_test.gonew file mode 100644index 000000000..6a6969126--- /dev/null+++ b/fluxer_rexctl/cmd/autoupgrade_test.go@@ -0,0 +1,109 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++func notifyRun(t *testing.T, notify bool) (*App, chan upgradeNotice) {+ t.Helper()+ got := make(chan upgradeNotice, 1)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var n upgradeNotice+ if r.Method != http.MethodPost || r.Header.Get("Content-Type") != "application/json" || json.NewDecoder(r.Body).Decode(&n) != nil {+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ got <- n+ }))+ t.Cleanup(srv.Close)+ inst, err := instance.Create(t.TempDir(), "fluxer")+ if err != nil {+ t.Fatal(err)+ }+ inst.State.Release = "2026.1027.120000"+ if notify {+ inst.State.NotifyURL = srv.URL + "/hooks/secret"+ }+ if err := inst.Save(); err != nil {+ t.Fatal(err)+ }+ out := &bytes.Buffer{}+ app := &App{+ Flags: GlobalFlags{Dir: inst.Dir},+ UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),+ }+ return app, got+}++func TestNotifyUpgrade(t *testing.T) {+ ctx := context.Background()++ app, got := notifyRun(t, true)+ app.outcome = "Upgraded to Fluxer 2026.1027.120000."+ notifyUpgrade(ctx, app, nil)+ n := <-got+ if n.Status != "upgraded" || n.Release != "2026.1027.120000" || n.Text != n.Content || !strings.HasSuffix(n.Text, "Upgraded to Fluxer 2026.1027.120000.") {+ t.Errorf("upgraded notice = %+v", n)+ }++ app, got = notifyRun(t, true)+ notifyUpgrade(ctx, app, ui.Refused("Another rexctl command is changing this instance.", "Wait for it to finish, then try again."))+ n = <-got+ if n.Status != "failed" || !strings.HasSuffix(n.Text, "Another rexctl command is changing this instance. Wait for it to finish, then try again.") {+ t.Errorf("failed notice = %+v", n)+ }++ app, got = notifyRun(t, true)+ app.outcome = "Fluxer 2026.1027.120000 didn't start. Went back to Fluxer 2026.1020.100000."+ app.SetExit(ui.ExitFailed)+ notifyUpgrade(ctx, app, nil)+ if n = <-got; n.Status != "failed" {+ t.Errorf("went-back notice = %+v", n)+ }++ app, got = notifyRun(t, true)+ notifyUpgrade(ctx, app, nil)+ notifyUpgrade(ctx, app, context.Canceled)+ app, _ = notifyRun(t, false)+ app.outcome = "Upgraded to Fluxer 2026.1027.120000."+ notifyUpgrade(ctx, app, nil)+ select {+ case n := <-got:+ t.Errorf("sent %+v for a run with nothing to tell", n)+ default:+ }+}++func TestMaskURL(t *testing.T) {+ cases := map[string]string{+ "https://discord.com/api/webhooks/1/secret": "https://discord.com/…",+ "https://ntfy.sh/topic?tpl=1": "https://ntfy.sh/…",+ "https://hooks.example.com": "https://hooks.example.com",+ }+ for in, want := range cases {+ if got := maskURL(in); got != want {+ t.Errorf("maskURL(%s) = %s, want %s", in, got, want)+ }+ }+}++func TestAutoUpgradeWhen(t *testing.T) {+ if got := autoUpgradeWhen(host.Systemd, "23:45"); got != "between 23:45 and 00:15" {+ t.Errorf("systemd: %s", got)+ }+ if got := autoUpgradeWhen(host.Cron, "04:00"); got != "at 04:00" {+ t.Errorf("cron: %s", got)+ }+}diff --git a/fluxer_rexctl/cmd/eject.go b/fluxer_rexctl/cmd/eject.goindex ee9462779..311b02aeb 100644--- a/fluxer_rexctl/cmd/eject.go+++ b/fluxer_rexctl/cmd/eject.go@@ -63,6 +63,9 @@ func runEject(ctx context.Context, app *App) error {},RemoveBootUnit: func() error {removed = true+ if _, err := removeAutoUpgrade(ctx, inst, e); err != nil {+ return fmt.Errorf("removing automatic upgrades: %w", err)+ }return removeBootUnit(ctx, inst, e)},})diff --git a/fluxer_rexctl/cmd/root.go b/fluxer_rexctl/cmd/root.goindex 64cc14aa1..a4d748099 100644--- a/fluxer_rexctl/cmd/root.go+++ b/fluxer_rexctl/cmd/root.go@@ -110,6 +110,7 @@ func newRoot(app *App) *cobra.Command {newStopCmd(app),newRestartCmd(app),newUpgradeCmd(app),+ newAutoUpgradeCmd(app),newRollbackCmd(app),newBackupCmd(app),newRestoreCmd(app),@@ -158,7 +159,7 @@ const ()var commandGroups = map[string][]string{- "run": {"install", "setup", "status", "doctor", "logs", "start", "stop", "restart", "upgrade", "rollback", "backup", "restore", "proxy", "takeover", "eject", "uninstall"},+ "run": {"install", "setup", "status", "doctor", "logs", "start", "stop", "restart", "upgrade", "auto-upgrade", "rollback", "backup", "restore", "proxy", "takeover", "eject", "uninstall"},"manage": {"users", "admins", "invites", "registration", "email", "branding", "search", "config"},"other": {"version", "docs"},}diff --git a/fluxer_rexctl/cmd/uninstall.go b/fluxer_rexctl/cmd/uninstall.goindex fa4b488dc..787313e9a 100644--- a/fluxer_rexctl/cmd/uninstall.go+++ b/fluxer_rexctl/cmd/uninstall.go@@ -70,6 +70,9 @@ func runUninstall(ctx context.Context, app *App, keepData bool, confirm string)if err := removeBootUnit(ctx, inst, p.Engine); err != nil {app.UI.Detail("%v", err)}+ if _, err := removeAutoUpgrade(ctx, inst, p.Engine); err != nil {+ app.UI.Detail("removing automatic upgrades: %v", err)+ }s.Done("Removed Fluxer.")return nil})diff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.goindex 04b1e283f..5eeea1fa5 100644--- a/fluxer_rexctl/cmd/upgrade.go+++ b/fluxer_rexctl/cmd/upgrade.go@@ -69,7 +69,11 @@ func newUpgradeCmd(app *App) *cobra.Command {Short: "Upgrade rexctl and Fluxer to the latest release",Args: noArgs,RunE: func(c *cobra.Command, _ []string) error {- return runUpgrade(c.Context(), app, &f)+ err := runUpgrade(c.Context(), app, &f)+ if !f.Check && !f.DryRun {+ notifyUpgrade(c.Context(), app, err)+ }+ return err},}fl := c.Flags()@@ -896,6 +900,7 @@ func failedStart(ctx context.Context, app *App, inst *instance.Instance, e *engi}inst.State.FailedRelease = pend.To_ = inst.Save()+ app.outcome = fmt.Sprintf("%s Went back to %s.", msg, fluxerName(fromShort))app.UI.OK("Went back to %s. Your instance is running.", fluxerName(fromShort))if logPath != "" {fixLine(app, fmt.Sprintf("Read %s to see why.", logPath))@@ -1099,6 +1104,7 @@ func finishUpgrade(ctx context.Context, app *App, inst *instance.Instance, e *enapp.UI.Detail("%v", err)}_, toShort := versionPair(pend.From, pend.To)+ app.outcome = fmt.Sprintf("Upgraded to Fluxer %s.", toShort)app.UI.OK("Your instance is on Fluxer %s.", toShort)return nil}diff --git a/fluxer_rexctl/internal/host/autoupgrade.go b/fluxer_rexctl/internal/host/autoupgrade.gonew file mode 100644index 000000000..42f6cebc7--- /dev/null+++ b/fluxer_rexctl/internal/host/autoupgrade.go@@ -0,0 +1,362 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "bufio"+ "bytes"+ "context"+ "fmt"+ "os"+ "os/exec"+ "os/user"+ "path/filepath"+ "runtime"+ "strconv"+ "strings"+ "time"+)++type Scheduler string++const (+ Systemd Scheduler = "systemd"+ Cron Scheduler = "cron"+)++const (+ cronDir = "/etc/cron.d"+ upgradeDelay = "30min"+ cronPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"+ cronExitPrefix = "rexctl exited with "+ systemdTimeLayout = "Mon 2006-01-02 15:04:05 MST"+)++func UpgradeScheduler() Scheduler {+ if BootUnitSupported() {+ return Systemd+ }+ if runtime.GOOS != "linux" {+ return ""+ }+ if info, err := os.Stat(cronDir); err == nil && info.IsDir() {+ return Cron+ }+ return ""+}++type AutoUpgrade struct {+ Scheduler Scheduler+ Project string+ Dir string+ Binary string+ Podman bool+ Rootless bool+ At string+ Log string+}++type AutoUpgradeState struct {+ On bool+ At string+ Next string+ Last string+ Ran bool+ ExitCode int+ Running bool+}++func (a AutoUpgrade) name() string { return a.Project + "-upgrade" }++func (a AutoUpgrade) ServiceName() string { return a.name() + ".service" }++func (a AutoUpgrade) TimerName() string { return a.name() + ".timer" }++func (a AutoUpgrade) Paths() ([]string, error) {+ if a.Scheduler == Cron {+ return []string{filepath.Join(cronDir, a.name())}, nil+ }+ dir, err := unitDir(a.Rootless)+ if err != nil {+ return nil, err+ }+ return []string{filepath.Join(dir, a.ServiceName()), filepath.Join(dir, a.TimerName())}, nil+}++func (a AutoUpgrade) runAs() string {+ if a.Rootless {+ if u, err := user.Current(); err == nil {+ return u.Username+ }+ return strconv.Itoa(os.Geteuid())+ }+ if a.Podman {+ return ""+ }+ return dirOwner(a.Dir)+}++func (a AutoUpgrade) clock() (int, int, error) {+ t, err := time.Parse("15:04", a.At)+ if err != nil {+ return 0, 0, fmt.Errorf("host: %q is not a time of day", a.At)+ }+ return t.Hour(), t.Minute(), nil+}++func (a AutoUpgrade) service(runAs string) string {+ after := []string{a.Project + ".service"}+ var b strings.Builder+ b.WriteString("[Unit]\n")+ fmt.Fprintf(&b, "Description=Upgrade Fluxer in %s\n", strings.ReplaceAll(a.Dir, "%", "%%"))+ if !a.Rootless {+ after = append([]string{"network-online.target"}, after...)+ b.WriteString("Wants=network-online.target\n")+ }+ fmt.Fprintf(&b, "After=%s\n", strings.Join(after, " "))+ b.WriteString("\n[Service]\n")+ b.WriteString("Type=oneshot\n")+ if runAs != "" {+ fmt.Fprintf(&b, "User=%s\n", runAs)+ }+ fmt.Fprintf(&b, "ExecStart=%s upgrade --yes --dir %s\n", systemdQuote(a.Binary), systemdQuote(a.Dir))+ if runAs != "" {+ fmt.Fprintf(&b, "ExecStopPost=-+/usr/bin/install -D -m 0755 %s %s\n", systemdQuote(a.Binary), LibexecBinary)+ }+ return b.String()+}++func (a AutoUpgrade) timer(hour, minute int) string {+ var b strings.Builder+ b.WriteString("[Unit]\n")+ fmt.Fprintf(&b, "Description=Upgrade Fluxer in %s every day\n", strings.ReplaceAll(a.Dir, "%", "%%"))+ b.WriteString("\n[Timer]\n")+ fmt.Fprintf(&b, "OnCalendar=*-*-* %02d:%02d:00\n", hour, minute)+ fmt.Fprintf(&b, "RandomizedDelaySec=%s\n", upgradeDelay)+ b.WriteString("Persistent=true\n")+ b.WriteString("\n[Install]\n")+ b.WriteString("WantedBy=timers.target\n")+ return b.String()+}++func (a AutoUpgrade) cron(hour, minute int, runAs string) string {+ if runAs == "" {+ runAs = "root"+ }+ log := cronQuote(a.Log)+ var b strings.Builder+ b.WriteString("SHELL=/bin/sh\n")+ fmt.Fprintf(&b, "PATH=%s\n", cronPath)+ fmt.Fprintf(&b, "%d %d * * * %s %s upgrade --yes --dir %s >%s 2>&1; echo \"%s$?\" >>%s\n", minute, hour, runAs, cronQuote(a.Binary), cronQuote(a.Dir), log, cronExitPrefix, log)+ return b.String()+}++func cronQuote(s string) string {+ s = "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"+ return strings.ReplaceAll(s, "%", `\%`)+}++func (a AutoUpgrade) files() ([][]byte, error) {+ if !filepath.IsAbs(a.Binary) || !filepath.IsAbs(a.Dir) {+ return nil, fmt.Errorf("host: automatic upgrades need absolute paths, got %q and %q", a.Binary, a.Dir)+ }+ hour, minute, err := a.clock()+ if err != nil {+ return nil, err+ }+ runAs := a.runAs()+ switch a.Scheduler {+ case Systemd:+ if a.Rootless {+ runAs = ""+ }+ return [][]byte{[]byte(a.service(runAs)), []byte(a.timer(hour, minute))}, nil+ case Cron:+ if !filepath.IsAbs(a.Log) {+ return nil, fmt.Errorf("host: automatic upgrades need an absolute log path, got %q", a.Log)+ }+ return [][]byte{[]byte(a.cron(hour, minute, runAs))}, nil+ }+ return nil, fmt.Errorf("host: no scheduler for automatic upgrades")+}++func InstallAutoUpgrade(ctx context.Context, a AutoUpgrade) error {+ data, err := a.files()+ if err != nil {+ return err+ }+ paths, err := a.Paths()+ if err != nil {+ return err+ }+ userScope := a.Scheduler == Systemd && a.Rootless+ changed := false+ for i, p := range paths {+ c, err := writeHostFile(ctx, userScope, p, data[i])+ if err != nil {+ return err+ }+ changed = changed || c+ }+ if a.Scheduler != Systemd {+ return nil+ }+ if changed {+ if err := systemctlRun(ctx, a.Rootless, "daemon-reload"); err != nil {+ return err+ }+ }+ if !unitIs(ctx, a.Rootless, a.TimerName(), "enabled") {+ if err := systemctlRun(ctx, a.Rootless, "enable", a.TimerName()); err != nil {+ return err+ }+ }+ if changed || !unitIs(ctx, a.Rootless, a.TimerName(), "active") {+ if err := systemctlRun(ctx, a.Rootless, "restart", a.TimerName()); err != nil {+ return err+ }+ }+ if a.Rootless && !lingering(ctx) {+ return enableLinger(ctx)+ }+ return nil+}++func RemoveAutoUpgrade(ctx context.Context, a AutoUpgrade) (bool, error) {+ paths, err := a.Paths()+ if err != nil {+ return false, err+ }+ var found []string+ for _, p := range paths {+ if _, err := os.Stat(p); err == nil {+ found = append(found, p)+ }+ }+ if len(found) == 0 {+ return false, nil+ }+ if a.Scheduler == Cron {+ return true, removeHostFiles(ctx, false, found...)+ }+ if unitIs(ctx, a.Rootless, a.TimerName(), "enabled") || unitIs(ctx, a.Rootless, a.TimerName(), "active") {+ if err := systemctlRun(ctx, a.Rootless, "disable", "--now", a.TimerName()); err != nil {+ return false, err+ }+ }+ if err := removeHostFiles(ctx, a.Rootless, found...); err != nil {+ return false, err+ }+ return true, systemctlRun(ctx, a.Rootless, "daemon-reload")+}++func CheckAutoUpgrade(ctx context.Context, a AutoUpgrade, now time.Time) (AutoUpgradeState, error) {+ paths, err := a.Paths()+ if err != nil {+ return AutoUpgradeState{}, err+ }+ data, err := os.ReadFile(paths[len(paths)-1])+ if os.IsNotExist(err) {+ return AutoUpgradeState{}, nil+ }+ if err != nil {+ return AutoUpgradeState{}, err+ }+ s := AutoUpgradeState{On: true}+ if a.Scheduler == Cron {+ s.At = cronAt(data)+ if hour, minute, err := (AutoUpgrade{At: s.At}).clock(); err == nil {+ s.Next = nextDaily(now, hour, minute).Format(systemdTimeLayout)+ }+ if info, err := os.Stat(a.Log); err == nil {+ s.Last = info.ModTime().Format(systemdTimeLayout)+ s.Ran, s.ExitCode = cronExit(a.Log)+ }+ return s, nil+ }+ s.At = timerAt(data)+ t := systemctlShow(ctx, a.Rootless, a.TimerName(), "NextElapseUSecRealtime", "LastTriggerUSec")+ s.Next, s.Last = t["NextElapseUSecRealtime"], t["LastTriggerUSec"]+ svc := systemctlShow(ctx, a.Rootless, a.ServiceName(), "ActiveState", "ExecMainExitTimestamp", "ExecMainStatus")+ s.Running = svc["ActiveState"] == "activating"+ if svc["ExecMainExitTimestamp"] != "" {+ s.Ran = true+ s.ExitCode, _ = strconv.Atoi(svc["ExecMainStatus"])+ }+ return s, nil+}++func systemctlShow(ctx context.Context, rootless bool, unit string, props ...string) map[string]string {+ args := []string{"show", unit}+ if rootless {+ args = append([]string{"--user"}, args...)+ }+ for _, p := range props {+ args = append(args, "-p", p)+ }+ out, _ := exec.CommandContext(ctx, "systemctl", args...).Output()+ return parseShow(out)+}++func parseShow(out []byte) map[string]string {+ m := map[string]string{}+ s := bufio.NewScanner(bytes.NewReader(out))+ for s.Scan() {+ k, v, ok := strings.Cut(s.Text(), "=")+ if !ok {+ continue+ }+ v = strings.TrimSpace(v)+ if v == "n/a" || v == "0" && k != "ExecMainStatus" {+ v = ""+ }+ m[k] = v+ }+ return m+}++func timerAt(data []byte) string {+ for _, line := range strings.Split(string(data), "\n") {+ if v, ok := strings.CutPrefix(line, "OnCalendar=*-*-* "); ok && len(v) >= 5 {+ return v[:5]+ }+ }+ return ""+}++func cronAt(data []byte) string {+ for _, line := range strings.Split(string(data), "\n") {+ f := strings.Fields(line)+ if len(f) < 2 || strings.Contains(f[0], "=") {+ continue+ }+ minute, merr := strconv.Atoi(f[0])+ hour, herr := strconv.Atoi(f[1])+ if merr == nil && herr == nil {+ return fmt.Sprintf("%02d:%02d", hour, minute)+ }+ }+ return ""+}++func cronExit(log string) (bool, int) {+ data, err := os.ReadFile(log)+ if err != nil {+ return false, 0+ }+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")+ v, ok := strings.CutPrefix(lines[len(lines)-1], cronExitPrefix)+ if !ok {+ return false, 0+ }+ code, err := strconv.Atoi(strings.TrimSpace(v))+ return err == nil, code+}++func nextDaily(now time.Time, hour, minute int) time.Time {+ next := time.Date(now.Year(), now.Month(), now.Day(), hour, minute, 0, 0, now.Location())+ if !next.After(now) {+ next = next.AddDate(0, 0, 1)+ }+ return next+}diff --git a/fluxer_rexctl/internal/host/autoupgrade_test.go b/fluxer_rexctl/internal/host/autoupgrade_test.gonew file mode 100644index 000000000..dc4af181e--- /dev/null+++ b/fluxer_rexctl/internal/host/autoupgrade_test.go@@ -0,0 +1,244 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package host++import (+ "context"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestAutoUpgradeService(t *testing.T) {+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}+ want := `[Unit]+Description=Upgrade Fluxer in /opt/fluxer+Wants=network-online.target+After=network-online.target fluxer.service++[Service]+Type=oneshot+ExecStart=/usr/local/bin/rexctl upgrade --yes --dir /opt/fluxer+`+ if got := a.service(""); got != want {+ t.Errorf("service as root:\n%s\nwant:\n%s", got, want)+ }+ a.Dir, a.Binary = "/home/alice/my fluxer", "/home/alice/.local/bin/rexctl"+ want = `[Unit]+Description=Upgrade Fluxer in /home/alice/my fluxer+Wants=network-online.target+After=network-online.target fluxer.service++[Service]+Type=oneshot+User=alice+ExecStart=/home/alice/.local/bin/rexctl upgrade --yes --dir "/home/alice/my fluxer"+ExecStopPost=-+/usr/bin/install -D -m 0755 /home/alice/.local/bin/rexctl /usr/local/libexec/rexctl/rexctl+`+ if got := a.service("alice"); got != want {+ t.Errorf("service as owner:\n%s\nwant:\n%s", got, want)+ }+ a.Rootless = true+ if got := a.service(""); strings.Contains(got, "network-online") || !strings.Contains(got, "After=fluxer.service\n") {+ t.Errorf("rootless service waits for the wrong units:\n%s", got)+ }+}++func TestAutoUpgradeTimer(t *testing.T) {+ a := AutoUpgrade{Scheduler: Systemd, Project: "blue", Dir: "/srv/blue", Binary: "/usr/local/bin/rexctl", At: "23:05"}+ hour, minute, err := a.clock()+ if err != nil {+ t.Fatal(err)+ }+ want := `[Unit]+Description=Upgrade Fluxer in /srv/blue every day++[Timer]+OnCalendar=*-*-* 23:05:00+RandomizedDelaySec=30min+Persistent=true++[Install]+WantedBy=timers.target+`+ got := a.timer(hour, minute)+ if got != want {+ t.Errorf("timer:\n%s\nwant:\n%s", got, want)+ }+ if at := timerAt([]byte(got)); at != "23:05" {+ t.Errorf("timerAt = %q, want 23:05", at)+ }+ if a.TimerName() != "blue-upgrade.timer" || a.ServiceName() != "blue-upgrade.service" {+ t.Errorf("unit names are %s and %s", a.TimerName(), a.ServiceName())+ }+}++func TestAutoUpgradeCron(t *testing.T) {+ a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/it's 100%", Binary: "/usr/local/bin/rexctl", At: "04:07", Log: "/srv/it's 100%/.rexctl/auto-upgrade.log"}+ want := `SHELL=/bin/sh+PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin+7 4 * * * root '/usr/local/bin/rexctl' upgrade --yes --dir '/srv/it'\''s 100\%' >'/srv/it'\''s 100\%/.rexctl/auto-upgrade.log' 2>&1; echo "rexctl exited with $?" >>'/srv/it'\''s 100\%/.rexctl/auto-upgrade.log'+`+ got := a.cron(4, 7, "")+ if got != want {+ t.Errorf("cron:\n%s\nwant:\n%s", got, want)+ }+ if at := cronAt([]byte(got)); at != "04:07" {+ t.Errorf("cronAt = %q, want 04:07", at)+ }+ if !strings.Contains(a.cron(4, 7, "alice"), " * * * alice ") {+ t.Error("cron doesn't run as the instance owner")+ }+ paths, err := a.Paths()+ if err != nil || len(paths) != 1 || paths[0] != "/etc/cron.d/fluxer-upgrade" {+ t.Errorf("Paths() = %v, %v", paths, err)+ }+}++func TestAutoUpgradeRefusesBadInput(t *testing.T) {+ for _, a := range []AutoUpgrade{+ {Scheduler: Systemd, Project: "fluxer", Dir: "fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},+ {Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "4am"},+ {Scheduler: Cron, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},+ {Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"},+ } {+ if _, err := a.files(); err == nil {+ t.Errorf("files() accepted %+v", a)+ }+ }+}++func TestCronExit(t *testing.T) {+ log := filepath.Join(t.TempDir(), "auto-upgrade.log")+ if ran, _ := cronExit(log); ran {+ t.Error("a missing log counts as a run")+ }+ if err := os.WriteFile(log, []byte("✓ Fluxer is up to date.\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if ran, _ := cronExit(log); ran {+ t.Error("a log without an exit line counts as a finished run")+ }+ if err := os.WriteFile(log, []byte("✗ Another rexctl command is changing this instance.\nrexctl exited with 3\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if ran, code := cronExit(log); !ran || code != 3 {+ t.Errorf("cronExit = %v, %d, want true, 3", ran, code)+ }+}++func TestNextDaily(t *testing.T) {+ loc := time.FixedZone("CET", 3600)+ now := time.Date(2026, 10, 27, 5, 0, 0, 0, loc)+ if got := nextDaily(now, 4, 0); !got.Equal(time.Date(2026, 10, 28, 4, 0, 0, 0, loc)) {+ t.Errorf("after the time: %v", got)+ }+ if got := nextDaily(now, 6, 30); !got.Equal(time.Date(2026, 10, 27, 6, 30, 0, 0, loc)) {+ t.Errorf("before the time: %v", got)+ }+}++func TestParseShow(t *testing.T) {+ m := parseShow([]byte("NextElapseUSecRealtime=Wed 2026-10-28 04:12:09 CET\nLastTriggerUSec=n/a\nExecMainStatus=0\nExecMainExitTimestamp=\n"))+ if m["NextElapseUSecRealtime"] != "Wed 2026-10-28 04:12:09 CET" || m["LastTriggerUSec"] != "" || m["ExecMainStatus"] != "0" || m["ExecMainExitTimestamp"] != "" {+ t.Errorf("parseShow = %v", m)+ }+}++const fakeSystemctl = `#!/bin/sh+echo "$*" >> "$SYSTEMCTL_LOG"+case "$2" in+enable) echo 1 > "$SYSTEMCTL_STATE.enabled" ;;+restart) echo 1 > "$SYSTEMCTL_STATE.active" ;;+disable) : > "$SYSTEMCTL_STATE.enabled"; : > "$SYSTEMCTL_STATE.active" ;;+is-enabled) v=""; read -r v < "$SYSTEMCTL_STATE.enabled"; [ "$v" = 1 ] && echo enabled ;;+is-active) v=""; read -r v < "$SYSTEMCTL_STATE.active"; [ "$v" = 1 ] && echo active ;;+esac+exit 0+`++func TestAutoUpgradeInstallAndRemove(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("needs a shell to fake systemctl")+ }+ root := t.TempDir()+ bin := filepath.Join(root, "bin")+ if err := os.MkdirAll(bin, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte(fakeSystemctl), 0o755); err != nil {+ t.Fatal(err)+ }+ state := filepath.Join(root, "unit")+ for _, s := range []string{".enabled", ".active"} {+ if err := os.WriteFile(state+s, nil, 0o600); err != nil {+ t.Fatal(err)+ }+ }+ log := filepath.Join(root, "systemctl.log")+ t.Setenv("PATH", bin)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))+ t.Setenv("SYSTEMCTL_LOG", log)+ t.Setenv("SYSTEMCTL_STATE", state)+ calls := func() []string {+ data, _ := os.ReadFile(log)+ _ = os.Remove(log)+ return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(data)), " ", "_"))+ }+ ctx := context.Background()+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(bin, "rexctl"), Rootless: true, At: "04:00"}+ if err := InstallAutoUpgrade(ctx, a); err != nil {+ t.Fatal(err)+ }+ want := []string{"--user_daemon-reload", "--user_is-enabled_fluxer-upgrade.timer", "--user_enable_fluxer-upgrade.timer", "--user_restart_fluxer-upgrade.timer"}+ if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("first install ran %v, want %v", got, want)+ }+ unitDir := filepath.Join(root, "config", "systemd", "user")+ for _, name := range []string{"fluxer-upgrade.service", "fluxer-upgrade.timer"} {+ if _, err := os.Stat(filepath.Join(unitDir, name)); err != nil {+ t.Errorf("%s wasn't written: %v", name, err)+ }+ }+ if err := InstallAutoUpgrade(ctx, a); err != nil {+ t.Fatal(err)+ }+ want = []string{"--user_is-enabled_fluxer-upgrade.timer", "--user_is-active_fluxer-upgrade.timer"}+ if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("second install ran %v, want only %v", got, want)+ }+ a.At = "05:30"+ if err := InstallAutoUpgrade(ctx, a); err != nil {+ t.Fatal(err)+ }+ want = []string{"--user_daemon-reload", "--user_is-enabled_fluxer-upgrade.timer", "--user_restart_fluxer-upgrade.timer"}+ if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("changing the time ran %v, want %v", got, want)+ }+ timer, err := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer"))+ if err != nil || timerAt(timer) != "05:30" {+ t.Errorf("the timer doesn't run at 05:30: %v", err)+ }+ removed, err := RemoveAutoUpgrade(ctx, a)+ if err != nil || !removed {+ t.Fatalf("RemoveAutoUpgrade = %v, %v", removed, err)+ }+ want = []string{"--user_is-enabled_fluxer-upgrade.timer", "--user_disable_--now_fluxer-upgrade.timer", "--user_daemon-reload"}+ if got := calls(); strings.Join(got, " ") != strings.Join(want, " ") {+ t.Errorf("remove ran %v, want %v", got, want)+ }+ entries, _ := os.ReadDir(unitDir)+ if len(entries) != 0 {+ t.Errorf("remove left %d files", len(entries))+ }+ removed, err = RemoveAutoUpgrade(ctx, a)+ if err != nil || removed {+ t.Errorf("second RemoveAutoUpgrade = %v, %v, want false, nil", removed, err)+ }+ if got := calls(); len(got) != 0 {+ t.Errorf("second remove ran %v", got)+ }+}diff --git a/fluxer_rexctl/internal/host/bootunit.go b/fluxer_rexctl/internal/host/bootunit.goindex 7ab17d85a..5835eade6 100644--- a/fluxer_rexctl/internal/host/bootunit.go+++ b/fluxer_rexctl/internal/host/bootunit.go@@ -56,8 +56,16 @@ func BootUnitSupported() bool {func (u BootUnit) Name() string { return u.Project + ".service" }func (u BootUnit) Path() (string, error) {- if !u.Rootless {- return filepath.Join("/etc/systemd/system", u.Name()), nil+ dir, err := unitDir(u.Rootless)+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, u.Name()), nil+}++func unitDir(rootless bool) (string, error) {+ if !rootless {+ return "/etc/systemd/system", nil}dir := os.Getenv("XDG_CONFIG_HOME")if dir == "" {@@ -67,7 +75,7 @@ func (u BootUnit) Path() (string, error) {}dir = filepath.Join(home, ".config")}- return filepath.Join(dir, "systemd", "user", u.Name()), nil+ return filepath.Join(dir, "systemd", "user"), nil}func (u BootUnit) execPath() string {@@ -255,16 +263,25 @@ func RemoveBootUnit(ctx context.Context, u BootUnit) error {return err}}- if u.Rootless {- if err := os.Remove(path); err != nil && !os.IsNotExist(err) {- return err- }- } else if _, err := output(ctx, false, "rm", "-f", path); err != nil {+ if err := removeHostFiles(ctx, u.Rootless, path); err != nil {return err}return systemctlRun(ctx, u.Rootless, "daemon-reload")}+func removeHostFiles(ctx context.Context, user bool, paths ...string) error {+ if !user {+ _, err := output(ctx, false, "rm", append([]string{"-f"}, paths...)...)+ return err+ }+ for _, p := range paths {+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ return err+ }+ }+ return nil+}+func writeBootUnit(ctx context.Context, u BootUnit) error {if !filepath.IsAbs(u.Binary) || !filepath.IsAbs(u.Dir) {return fmt.Errorf("host: boot unit needs absolute paths, got %q and %q", u.Binary, u.Dir)@@ -281,35 +298,39 @@ func writeBootUnit(ctx context.Context, u BootUnit) error {_, _ = output(ctx, false, "restorecon", LibexecBinary)}}- data := []byte(u.content(ctx))+ changed, err := writeHostFile(ctx, u.Rootless, path, []byte(u.content(ctx)))+ if err != nil || !changed {+ return err+ }+ return systemctlRun(ctx, u.Rootless, "daemon-reload")+}++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 nil+ return false, nil}- if u.Rootless {+ if user {if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {- return err- }- if err := envfile.WriteFileAtomic(path, data, false); err != nil {- return err- }- } else {- tmp, err := os.CreateTemp("", "rexctl-unit-")- if err != nil {- return err- }- defer os.Remove(tmp.Name())- _, werr := tmp.Write(data)- if cerr := tmp.Close(); werr == nil {- werr = cerr- }- if werr != nil {- return werr- }- if _, err := output(ctx, false, "install", "-D", "-m", "0644", tmp.Name(), path); err != nil {- return err+ return false, err}+ return true, envfile.WriteFileAtomic(path, data, false)}- return systemctlRun(ctx, u.Rootless, "daemon-reload")+ tmp, err := os.CreateTemp("", "rexctl-unit-")+ if err != nil {+ return false, err+ }+ defer os.Remove(tmp.Name())+ _, werr := tmp.Write(data)+ if cerr := tmp.Close(); werr == nil {+ werr = cerr+ }+ if werr != nil {+ return false, werr+ }+ if _, err := output(ctx, false, "install", "-D", "-m", "0644", tmp.Name(), path); err != nil {+ return false, err+ }+ return true, nil}func systemctlRun(ctx context.Context, rootless bool, args ...string) error {diff --git a/fluxer_rexctl/internal/instance/state.go b/fluxer_rexctl/internal/instance/state.goindex fd5da7296..5fc12b56a 100644--- a/fluxer_rexctl/internal/instance/state.go+++ b/fluxer_rexctl/internal/instance/state.go@@ -43,6 +43,7 @@ type State struct {Ejected *Ejected `json:"ejected"`BackupDir string `json:"backup_dir,omitempty"`KeepBackups int `json:"keep_backups,omitempty"`+ NotifyURL string `json:"notify_url,omitempty"`InstalledAt time.Time `json:"installed_at"`UpdatedAt time.Time `json:"updated_at"`@@ -135,7 +136,7 @@ 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,- "installed_at": true, "updated_at": true, "backup_dir": true, "keep_backups": true,+ "installed_at": true, "updated_at": true, "backup_dir": true, "keep_backups": true, "notify_url": true,}func parseState(data []byte, dir string) (*State, error) {