Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): weekly auto-upgrades and lighter upgrade backups (#3693)

Hampus662bbfc1b545
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdx
index 724b4f787..26b829fe1 100644
--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx
+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx
@@ -54,7 +54,7 @@ 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.
+Show whether rexctl upgrades Fluxer by itself, when it runs next and how the last run went. Each run is rexctl upgrade --yes and works like an upgrade you run yourself.
```sh
rexctl auto-upgrade [flags]
@@ -66,7 +66,7 @@ rexctl auto-upgrade [flags]
### rexctl auto-upgrade off
-Stop upgrading Fluxer by itself.
+Stop upgrading Fluxer by itself. This also stops the monthly full backup that --full-backup turned on.
```sh
rexctl auto-upgrade off
@@ -74,7 +74,7 @@ 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.
+Run rexctl upgrade --yes by itself with a systemd timer, or with cron on machines without systemd. It runs every day, or once a week on the day you pass to --day. Each run backs up your instance first and goes back to the release you had if the new one doesn't start. It skips that run if another rexctl command is changing the instance, and tries again at the next one. A weekly run that is skipped or fails waits a week, and you can run rexctl upgrade yourself at any time. With --full-backup monthly it also makes a full backup with uploads on the 1st of every month, 3 hours before the upgrade time. Run it again to change the day, the time, the backups or the address. Leaving out a flag sets it back to its default, and leaving out --notify stops 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.
@@ -86,13 +86,25 @@ rexctl auto-upgrade on [flags]
Time of day to upgrade, as HH:MM in this machine's time zone. The default is `04:00`.
+- `--backup string`
+
+ What the backup before each upgrade holds, full or without-uploads. When an upgrade changes how uploads are stored, the backup includes them anyway. The default is `full`.
+
+- `--day string`
+
+ Run once a week on this day, like sun. Leave it out to run every day.
+
+- `--full-backup string`
+
+ Pass monthly to also make a full backup with uploads on the 1st of every month.
+
- `--notify string`
Web address rexctl posts to when an upgrade installs a new release or fails.
## rexctl backup
-Back up your instance. Fluxer pauses while uploads are copied.
+Back up your instance in one file that restores on this machine or a new one. It holds the database, search data and uploads that Fluxer stores itself. Fluxer pauses while uploads are copied.
```sh
rexctl backup
@@ -100,7 +112,7 @@ rexctl backup
### rexctl backup keep
-Show or change how many backups rexctl keeps. After each backup, rexctl deletes the oldest ones beyond this number, except the backup that rexctl rollback needs. Pass all to keep every backup.
+Show or change how many backups rexctl keeps. After each backup, rexctl deletes the oldest ones beyond this number, except the backup that rexctl rollback needs and the newest backup with uploads. Pass all to keep every backup.
```sh
rexctl backup keep [count|all] [flags]
@@ -607,7 +619,7 @@ rexctl restart
## rexctl restore
-Restore your instance from a backup. This works on a new machine too. Copy the backup file there and run this command.
+Restore your instance from a backup. This works on a new machine too. Copy the backup file there and run this command. A backup without uploads restores only on the instance it was made for, and the uploads there stay as they are.
```sh
rexctl restore <file> [flags]
@@ -789,6 +801,10 @@ Upgrade rexctl and Fluxer to the latest release.
rexctl upgrade [flags]
```
+- `--backup string`
+
+ What the backup before this upgrade holds, full or without-uploads. When the upgrade changes how uploads are stored, the backup includes them anyway. The default is `full`.
+
- `--check`
Show whether an upgrade is available without changing anything.
diff --git a/fluxer_docs/src/content/docs/operator/running.mdx b/fluxer_docs/src/content/docs/operator/running.mdx
index 3280562d5..3342bc335 100644
--- a/fluxer_docs/src/content/docs/operator/running.mdx
+++ b/fluxer_docs/src/content/docs/operator/running.mdx
@@ -22,6 +22,34 @@ If you installed Fluxer before rexctl existed, upgrade it with the current insta
curl -fsSL https://fluxer.dev/install.sh | sh -s -- --update --dir /path/to/your/instance
```
+### Upgrade by itself
+
+```sh
+rexctl auto-upgrade on
+```
+
+This runs `rexctl upgrade --yes` every day at about 04:00 with a systemd timer, or with cron on machines without systemd. Each run backs up your instance first and goes back to the version you had if the new one doesn't start. Run `rexctl auto-upgrade` to see when it runs next and how the last run went, and `rexctl auto-upgrade off` to stop it.
+
+- `--at 03:30` picks the time of day, in this machine's time zone. A systemd timer starts within 30 minutes after it, and cron starts at a fixed minute in that window.
+- `--day sun` upgrades once a week on that day. A weekly run that is skipped or fails waits a week, and you can run `rexctl upgrade` yourself at any time.
+- `--notify https://ntfy.sh/your-topic` posts to that address when an upgrade installs a new release or fails.
+- `--backup without-uploads` leaves uploads out of the backup before each upgrade.
+- `--full-backup monthly` also makes a full backup with uploads on the 1st of every month.
+
+Run `rexctl auto-upgrade on` again to change any of these. A flag you leave out goes back to its default.
+
+Uploads are often the largest part of an instance, and they stay on this machine while Fluxer upgrades. A backup without them is enough to go back to the version you had, and it takes less time and disk space. When a new version changes how uploads are stored, rexctl includes them in that backup anyway and says so.
+
+A backup without uploads doesn't help if you lose the machine. Keep a full backup on a schedule as well.
+
+```sh
+rexctl auto-upgrade on --day sun --backup without-uploads --full-backup monthly
+```
+
+This upgrades every Sunday with backups that leave out uploads, and makes a full backup with `rexctl backup` on the 1st of every month. The full backup has its own systemd timer or cron entry and starts 3 hours before the upgrade time. With systemd, an upgrade waits until a running full backup has finished, and a backup missed while the machine was off runs once the machine starts again. With cron, an upgrade that starts while the full backup is still running skips that run, and a missed backup waits for the next month. `rexctl auto-upgrade off` stops both.
+
+With `--backup without-uploads`, `rexctl auto-upgrade` warns when no backup from the last 5 weeks has your uploads.
+
## Roll back
```sh
@@ -30,6 +58,8 @@ rexctl rollback
This goes back to the version you had before your last upgrade and keeps your database as it is. To also restore the backup rexctl made before the upgrade, add `--restore-database`.
+If that backup leaves out uploads, the uploads stay as they are. Files uploaded since the upgrade stay on disk, and attachments deleted since the upgrade don't come back. For backups before upgrades that also hold uploads, run `rexctl auto-upgrade on` again with your other flags and `--backup full`, or pass `--backup full` to `rexctl upgrade`. This applies from the next upgrade.
+
## Back up and restore
```sh
@@ -40,7 +70,9 @@ This saves your settings, database and uploads in one file in the `backups` fold
rexctl keeps the newest 3 backups and deletes older ones after each backup, but it always keeps the one `rexctl rollback` needs. To keep more, run `rexctl backup keep 10`, or `rexctl backup keep all` to keep every backup. To save backups on another drive, run `rexctl backup location /mnt/backups/fluxer`.
-To put your instance back the way it was when a backup was made, find the file with `rexctl backup list` and pass its path to `rexctl restore`.
+To put your instance back the way it was when a backup was made, find the file with `rexctl backup list` and pass its path to `rexctl restore`. `rexctl backup list` marks the backups without uploads.
+
+A backup without uploads only restores on the instance it was made for, where it leaves the uploads as they are. If that restore stops partway, run the same `rexctl restore` again. Anywhere else rexctl refuses before it changes anything. In the folder of the instance the backup was made for, it also suggests that instance's newest backup with uploads. rexctl never deletes the newest backup with uploads to keep the number of backups down.
```sh
rexctl restore /opt/fluxer/backups/fluxer-chat.example.com-20261105-120000.tar.zst
@@ -48,7 +80,7 @@ rexctl restore /opt/fluxer/backups/fluxer-chat.example.com-20261105-120000.tar.z
## Move to a new machine
-Back up your instance on the old machine and copy the backup file to the new one. On the new machine, install rexctl and restore the backup with one command, run from the folder you copied the backup to.
+Back up your instance on the old machine with `rexctl backup` and copy the backup file to the new one. A backup without uploads can't move an instance. On the new machine, install rexctl and restore the backup with one command, run from the folder you copied the backup to.
```sh
curl -fsSL https://fluxer.dev/install.sh | sh -s -- restore fluxer-chat.example.com-20261105-120000.tar.zst
diff --git a/fluxer_rexctl/cmd/autoupgrade.go b/fluxer_rexctl/cmd/autoupgrade.go
index 63c45825e..236c486f7 100644
--- a/fluxer_rexctl/cmd/autoupgrade.go
+++ b/fluxer_rexctl/cmd/autoupgrade.go
@@ -18,6 +18,7 @@ import (
"github.com/spf13/cobra"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/checks"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
@@ -29,18 +30,22 @@ const (
autoUpgradeLog = "auto-upgrade.log"
autoUpgradeDefault = "04:00"
notifyTimeout = 15 * time.Second
+ uploadsBackupAge = 35 * 24 * time.Hour
)
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"`
+ On bool `json:"on"`
+ Scheduler string `json:"scheduler,omitempty"`
+ At string `json:"at,omitempty"`
+ Day string `json:"day,omitempty"`
+ Backup string `json:"backup,omitempty"`
+ FullBackup string `json:"full_backup,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 {
@@ -54,30 +59,34 @@ type upgradeNotice struct {
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.",
+ Short: "Show whether rexctl upgrades Fluxer by itself",
+ Long: "Show whether rexctl upgrades Fluxer by itself, when it runs next and how the last run went. Each run is rexctl upgrade --yes and 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
+ var o autoUpgradeOptions
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" +
+ Short: "Upgrade Fluxer by itself every day or once a week",
+ Long: "Run rexctl upgrade --yes by itself with a systemd timer, or with cron on machines without systemd. It runs every day, or once a week on the day you pass to --day. Each run backs up your instance first and goes back to the release you had if the new one doesn't start. It skips that run if another rexctl command is changing the instance, and tries again at the next one. A weekly run that is skipped or fails waits a week, and you can run rexctl upgrade yourself at any time. With --full-backup monthly it also makes a full backup with uploads on the 1st of every month, 3 hours before the upgrade time. Run it again to change the day, the time, the backups or the address. Leaving out a flag sets it back to its default, and leaving out --notify stops 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)
+ return runAutoUpgradeOn(c.Context(), app, o)
},
}
- on.Flags().StringVar(&at, "at", autoUpgradeDefault, "time of day to upgrade, as HH:MM in this machine's time zone")
- on.Flags().StringVar(&notify, "notify", "", "web address rexctl posts to when an upgrade installs a new release or fails")
+ on.Flags().StringVar(&o.At, "at", autoUpgradeDefault, "time of day to upgrade, as HH:MM in this machine's time zone")
+ on.Flags().StringVar(&o.Day, "day", "", "run once a week on this day, like sun. Leave it out to run every day.")
+ on.Flags().StringVar(&o.Backup, "backup", backup.ScopeFull, "what the backup before each upgrade holds, full or without-uploads. When an upgrade changes how uploads are stored, the backup includes them anyway.")
+ on.Flags().StringVar(&o.FullBackup, "full-backup", "", "pass monthly to also make a full backup with uploads on the 1st of every month")
+ on.Flags().StringVar(&o.Notify, "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",
+ Long: "Stop upgrading Fluxer by itself. This also stops the monthly full backup that --full-backup turned on.",
Args: noArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runAutoUpgradeOff(c.Context(), app)
@@ -115,12 +124,63 @@ 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)
+type autoUpgradeOptions struct {
+ At string
+ Day string
+ Backup string
+ FullBackup string
+ Notify string
+}
+
+func parseFullBackup(s string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "":
+ return "", nil
+ case host.FullBackupMonthly:
+ return host.FullBackupMonthly, nil
+ }
+ return "", ui.Usage("Pass --full-backup as monthly, or leave it out.")
+}
+
+func parseDay(s string) (string, error) {
+ if s == "" {
+ return "", nil
+ }
+ d, ok := host.Weekday(s)
+ if !ok {
+ return "", ui.Usage("Pass --day as a day of the week like sun or sunday.")
+ }
+ return time.Weekday(d).String()[:3], nil
+}
+
+func parseBackupScope(s string) (string, error) {
+ switch s {
+ case "", backup.ScopeFull:
+ return backup.ScopeFull, nil
+ case backup.ScopeWithoutUploads:
+ return s, nil
+ }
+ return "", ui.Usage("Pass --backup as full or without-uploads.")
+}
+
+func runAutoUpgradeOn(ctx context.Context, app *App, o autoUpgradeOptions) error {
+ t, err := time.Parse("15:04", o.At)
if err != nil {
return ui.Usage("Pass --at as a time of day like 04:00.")
}
- at = t.Format("15:04")
+ at, notify := t.Format("15:04"), o.Notify
+ day, err := parseDay(o.Day)
+ if err != nil {
+ return err
+ }
+ scope, err := parseBackupScope(o.Backup)
+ if err != nil {
+ return err
+ }
+ fullBackup, err := parseFullBackup(o.FullBackup)
+ if err != nil {
+ return err
+ }
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.")
@@ -144,7 +204,7 @@ func runAutoUpgradeOn(ctx context.Context, app *App, at, notify string) error {
if a.Scheduler == "" {
return noScheduler()
}
- a.At = at
+ a.At, a.Day, a.Backup, a.FullBackup = at, day, scope, fullBackup
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")
@@ -155,11 +215,18 @@ func runAutoUpgradeOn(ctx context.Context, app *App, at, notify string) error {
return ui.Wrap(err, "Couldn't save your instance's state.", "Check that you can write to "+inst.Dir+", then try again.")
}
}
- start, err := a.Start()
+ startDay, start, err := a.Start()
if err != nil {
return ui.Usage("Pass --at as a time of day like 04:00.")
}
- app.UI.OK("rexctl upgrades Fluxer every day %s.", autoUpgradeWhen(a.Scheduler, start))
+ app.UI.OK("rexctl upgrades Fluxer %s.", autoUpgradeWhen(a.Scheduler, startDay, start))
+ if fullBackup != "" {
+ backupAt, _ := a.BackupStart()
+ app.UI.Info("%s", fullBackupWhen(backupAt))
+ }
+ if scope == backup.ScopeWithoutUploads && fullBackup == "" {
+ leanBackupNote(app, host.AutoUpgradeState{Day: day, At: at, Backup: scope}, notify)
+ }
if notify != "" {
app.UI.Info("rexctl tells %s when an upgrade installs a new release or fails.", maskURL(notify))
}
@@ -235,9 +302,14 @@ func runAutoUpgradeShow(ctx context.Context, app *App) error {
if err != nil {
return ui.Wrap(err, "Couldn't read the automatic upgrade schedule.", "Run rexctl auto-upgrade --verbose to see why.")
}
+ return showAutoUpgrade(app, inst, a, s, time.Now())
+}
+
+func showAutoUpgrade(app *App, inst *instance.Instance, a host.AutoUpgrade, s host.AutoUpgradeState, now time.Time) error {
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.Day, out.Backup, out.FullBackup = strings.ToLower(s.Day), s.Backup, s.FullBackup
out.Log = autoUpgradeLogs(a)
if inst.State.NotifyURL != "" {
out.Notify = maskURL(inst.State.NotifyURL)
@@ -251,10 +323,16 @@ func runAutoUpgradeShow(ctx context.Context, app *App) error {
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.")
+ app.UI.Info("Automatic upgrades are off. Run rexctl auto-upgrade on to upgrade Fluxer every day or once a week.")
return nil
}
- app.UI.OK("rexctl upgrades Fluxer every day %s.", autoUpgradeWhen(a.Scheduler, s.At))
+ app.UI.OK("rexctl upgrades Fluxer %s.", autoUpgradeWhen(a.Scheduler, s.Day, s.At))
+ if s.FullBackup != "" {
+ app.UI.Info("%s", fullBackupWhen(s.FullBackupAt))
+ }
+ if s.Backup == backup.ScopeWithoutUploads {
+ uploadsBackupNote(app, inst, a, s, now)
+ }
switch {
case s.Running:
app.UI.Info("An automatic upgrade is running now.")
@@ -270,12 +348,69 @@ func runAutoUpgradeShow(ctx context.Context, app *App) error {
return nil
}
-func autoUpgradeWhen(s host.Scheduler, at string) string {
+func autoUpgradeWhen(s host.Scheduler, day, at string) string {
+ every := "every day"
+ if long := host.DayLong(day); long != "" {
+ every = "every " + long
+ }
t, err := time.Parse("15:04", at)
if err != nil || s != host.Systemd {
- return "at " + at
+ return every + " at " + at
+ }
+ return fmt.Sprintf("%s between %s and %s", every, at, t.Add(host.UpgradeWindow).Format("15:04"))
+}
+
+func leanBackupNote(app *App, s host.AutoUpgradeState, notify string) {
+ s.FullBackup = host.FullBackupMonthly
+ app.UI.Info("Backups before upgrades leave out uploads. Run %s to keep a full backup as well, or run rexctl backup yourself now and then.", scheduleCommand(s))
+ if notify != "" {
+ app.UI.Info("Add --notify with your address to that command to keep the notifications.")
+ }
+}
+
+func uploadsBackupNote(app *App, inst *instance.Instance, a host.AutoUpgrade, s host.AutoUpgradeState, now time.Time) {
+ list, err := backup.List(inst.BackupDir())
+ if err != nil {
+ app.UI.Detail("%v", err)
+ return
+ }
+ b := backup.NewestWithUploads(list)
+ if b != nil {
+ app.UI.Info("The newest backup with uploads is from %s.", b.CreatedAt.In(now.Location()).Format("2 January 2006 at 15:04 MST"))
+ }
+ if b == nil || now.Sub(b.CreatedAt) > uploadsBackupAge {
+ full := s
+ full.Day, full.At = a.Requested(s.Day, s.At)
+ full.FullBackup = host.FullBackupMonthly
+ fix := fmt.Sprintf("Run rexctl backup now, and run %s.", scheduleCommand(full))
+ if inst.State != nil && inst.State.NotifyURL != "" {
+ fix += " Add --notify with your address to that command to keep the notifications."
+ }
+ switch {
+ case s.FullBackup != "" && s.FullBackupRan:
+ fix = fmt.Sprintf("Run rexctl backup now, and read %s to see why the monthly backup failed.", fullBackupLogs(a))
+ case s.FullBackup != "":
+ fix = "Run rexctl backup now. The monthly backup hasn't run yet."
+ }
+ app.UI.Warn("No backup from the last 5 weeks has your uploads.", fix)
+ }
+}
+
+func fullBackupWhen(at string) string {
+ if at == "" {
+ return "rexctl makes a full backup with uploads once a month."
+ }
+ return fmt.Sprintf("rexctl makes a full backup with uploads on the 1st of every month at %s.", at)
+}
+
+func fullBackupLogs(a host.AutoUpgrade) string {
+ if a.Scheduler == host.Cron {
+ return a.BackupLog()
+ }
+ if a.Rootless {
+ return "journalctl --user -u " + a.BackupServiceName()
}
- return fmt.Sprintf("between %s and %s", at, t.Add(host.UpgradeWindow).Format("15:04"))
+ return "journalctl -u " + a.BackupServiceName()
}
func autoUpgradeLogs(a host.AutoUpgrade) string {
diff --git a/fluxer_rexctl/cmd/autoupgrade_test.go b/fluxer_rexctl/cmd/autoupgrade_test.go
index 6a6969126..cbca7e47b 100644
--- a/fluxer_rexctl/cmd/autoupgrade_test.go
+++ b/fluxer_rexctl/cmd/autoupgrade_test.go
@@ -6,11 +6,17 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
"strings"
"testing"
+ "time"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
@@ -100,10 +106,230 @@ func TestMaskURL(t *testing.T) {
}
func TestAutoUpgradeWhen(t *testing.T) {
- if got := autoUpgradeWhen(host.Systemd, "23:45"); got != "between 23:45 and 00:15" {
+ if got := autoUpgradeWhen(host.Systemd, "", "23:45"); got != "every day between 23:45 and 00:15" {
t.Errorf("systemd: %s", got)
}
- if got := autoUpgradeWhen(host.Cron, "04:00"); got != "at 04:00" {
+ if got := autoUpgradeWhen(host.Cron, "", "04:00"); got != "every day at 04:00" {
t.Errorf("cron: %s", got)
}
+ if got := autoUpgradeWhen(host.Systemd, "Sun", "04:00"); got != "every Sunday between 04:00 and 04:30" {
+ t.Errorf("weekly systemd gives %q", got)
+ }
+ if got := autoUpgradeWhen(host.Cron, "Mon", "00:10"); got != "every Monday at 00:10" {
+ t.Errorf("weekly cron gives %q", got)
+ }
+}
+
+func TestUnknownDayIsRefused(t *testing.T) {
+ app, _ := notifyRun(t, false)
+ for _, day := range []string{"funday", "su", "8", "sundays"} {
+ err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", Day: day})
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--day") {
+ t.Errorf("--day %s returned %v, want a usage error about --day", day, err)
+ }
+ }
+ err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", Backup: "some"})
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--backup") {
+ t.Errorf("--backup some returned %v, want a usage error about --backup", err)
+ }
+}
+
+func TestDayAcceptsFullNames(t *testing.T) {
+ for in, want := range map[string]string{"sun": "Sun", "Sunday": "Sun", "MONDAY": "Mon", "thu": "Thu", "saturday": "Sat", "": ""} {
+ got, err := parseDay(in)
+ if err != nil || got != want {
+ t.Errorf("parseDay(%q) = %q, %v, want %q", in, got, err, want)
+ }
+ }
+}
+
+func scheduledStatus(t *testing.T, a host.AutoUpgrade) host.AutoUpgradeState {
+ t.Helper()
+ 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("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", bin)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
+ if err := host.InstallAutoUpgrade(context.Background(), a); err != nil {
+ t.Fatal(err)
+ }
+ s, err := host.CheckAutoUpgrade(context.Background(), a, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+
+func autoUpgradeStatus(t *testing.T, a host.AutoUpgrade) map[string]any {
+ t.Helper()
+ app, _ := notifyRun(t, false)
+ app.Flags.JSON = true
+ out := app.UI.Stdout().(*bytes.Buffer)
+ inst, err := instance.Find(app.Flags.Dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.Dir, a.Binary = inst.Dir, filepath.Join(inst.Dir, "rexctl")
+ s := scheduledStatus(t, a)
+ if err := showAutoUpgrade(app, inst, a, s, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var got map[string]any
+ if err := json.Unmarshal(out.Bytes(), &got); err != nil {
+ t.Fatalf("status JSON %q doesn't decode (%v)", out.String(), err)
+ }
+ return got
+}
+
+func TestStatusJSONShowsDayAndBackup(t *testing.T) {
+ a := host.AutoUpgrade{Scheduler: host.Systemd, Project: "fluxer", Rootless: true, At: "04:00", Day: "Sun", Backup: backup.ScopeWithoutUploads}
+ got := autoUpgradeStatus(t, a)
+ if got["day"] != "sun" || got["backup"] != "without-uploads" || got["at"] != "04:00" || got["on"] != true {
+ t.Errorf("weekly status JSON = %v", got)
+ }
+ if _, ok := got["full_backup"]; ok {
+ t.Errorf("status JSON without a monthly backup = %v", got)
+ }
+ a.Day, a.Backup = "", backup.ScopeFull
+ got = autoUpgradeStatus(t, a)
+ if _, ok := got["day"]; ok || got["backup"] != "full" {
+ t.Errorf("daily status JSON = %v", got)
+ }
+ a.FullBackup = host.FullBackupMonthly
+ if got = autoUpgradeStatus(t, a); got["full_backup"] != "monthly" {
+ t.Errorf("status JSON with a monthly backup = %v", got)
+ }
+}
+
+func TestFullBackupAcceptsOnlyMonthly(t *testing.T) {
+ for in, want := range map[string]string{"": "", "monthly": "monthly", "Monthly": "monthly"} {
+ if got, err := parseFullBackup(in); err != nil || got != want {
+ t.Errorf("parseFullBackup(%q) = %q, %v, want %q", in, got, err, want)
+ }
+ }
+ app, _ := notifyRun(t, false)
+ err := runAutoUpgradeOn(context.Background(), app, autoUpgradeOptions{At: "04:00", FullBackup: "weekly"})
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitUsage || !strings.Contains(ee.Msg, "--full-backup") {
+ t.Errorf("--full-backup weekly returned %v, want a usage error about --full-backup", err)
+ }
+}
+
+func TestStatusWarnsWithoutRecentUploadsBackup(t *testing.T) {
+ now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC)
+ app, _ := notifyRun(t, false)
+ out := app.UI.Stdout().(*bytes.Buffer)
+ inst, err := instance.Find(app.Flags.Dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := host.AutoUpgrade{Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", Podman: true}
+ const warning = "No backup from the last 5 weeks has your uploads."
+ weekly := host.AutoUpgradeState{On: true, Day: "Sun", At: "04:00", Backup: backup.ScopeWithoutUploads}
+ uploadsBackupNote(app, inst, a, weekly, now)
+ if s := out.String(); !strings.Contains(s, warning) || !strings.Contains(s, "Run rexctl backup now, and run rexctl auto-upgrade on --day sun --backup without-uploads --full-backup monthly.") || strings.Contains(s, "cron") || strings.Contains(s, "--notify") {
+ t.Errorf("with no backups the status says %q", s)
+ }
+ out.Reset()
+ cron := a
+ cron.Scheduler, cron.Domain = host.Cron, "chat.example.com"
+ cron.At, cron.Day = "03:30", "Sat"
+ day, at, err := cron.Start()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
+ uploadsBackupNote(app, inst, cron, host.AutoUpgradeState{On: true, Day: day, At: at, Backup: backup.ScopeWithoutUploads}, now)
+ inst.State.NotifyURL = ""
+ if s := out.String(); !strings.Contains(s, "run rexctl auto-upgrade on --day sat --at 03:30 --backup without-uploads --full-backup monthly. Add --notify with your address to that command to keep the notifications.") {
+ t.Errorf("with a cron schedule and notifications the status says %q", s)
+ }
+ out.Reset()
+ for _, tc := range []struct {
+ scheduler host.Scheduler
+ rootless bool
+ want string
+ }{
+ {host.Systemd, false, "read journalctl -u fluxer-backup.service to see why the monthly backup failed"},
+ {host.Systemd, true, "read journalctl --user -u fluxer-backup.service to see why"},
+ {host.Cron, false, "read /opt/fluxer/.rexctl/full-backup.log to see why"},
+ } {
+ out.Reset()
+ scheduled := a
+ scheduled.Scheduler, scheduled.Rootless, scheduled.FullBackup, scheduled.Log = tc.scheduler, tc.rootless, host.FullBackupMonthly, "/opt/fluxer/.rexctl/auto-upgrade.log"
+ uploadsBackupNote(app, inst, scheduled, host.AutoUpgradeState{FullBackup: host.FullBackupMonthly}, now)
+ if s := out.String(); !strings.Contains(s, "Run rexctl backup now. The monthly backup hasn't run yet.") {
+ t.Errorf("with a monthly %s backup that never ran the status says %q", tc.scheduler, s)
+ }
+ out.Reset()
+ uploadsBackupNote(app, inst, scheduled, host.AutoUpgradeState{FullBackup: host.FullBackupMonthly, FullBackupRan: true}, now)
+ if s := out.String(); !strings.Contains(s, warning) || !strings.Contains(s, tc.want) {
+ t.Errorf("with a monthly %s backup and none recent the status says %q", tc.scheduler, s)
+ }
+ }
+ out.Reset()
+ writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 12, 4, 0, 0, 0, time.UTC), "")
+ writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 11, 15, 4, 0, 0, 0, time.UTC), backup.ScopeWithoutUploads)
+ out.Reset()
+ uploadsBackupNote(app, inst, a, host.AutoUpgradeState{}, now)
+ if !strings.Contains(out.String(), "The newest backup with uploads is from 12 October 2026 at 04:00 UTC.") || !strings.Contains(out.String(), warning) {
+ t.Errorf("with an old full backup the status says %q", out.String())
+ }
+ out.Reset()
+ uploadsBackupNote(app, inst, a, host.AutoUpgradeState{}, time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC))
+ if strings.Contains(out.String(), warning) || !strings.Contains(out.String(), "12 October 2026") {
+ t.Errorf("with a recent full backup the status says %q", out.String())
+ }
+}
+
+func TestLeanBackupNoteKeepsTheSchedule(t *testing.T) {
+ app, _ := notifyRun(t, false)
+ out := app.UI.Stdout().(*bytes.Buffer)
+ leanBackupNote(app, host.AutoUpgradeState{Day: "Sun", At: "04:00", Backup: backup.ScopeWithoutUploads}, "")
+ if s := out.String(); !strings.Contains(s, "Run rexctl auto-upgrade on --day sun --backup without-uploads --full-backup monthly to keep a full backup as well") || strings.Contains(s, "--notify") {
+ t.Errorf("auto-upgrade on --day sun --backup without-uploads says %q", s)
+ }
+ out.Reset()
+ leanBackupNote(app, host.AutoUpgradeState{At: "02:15", Backup: backup.ScopeWithoutUploads}, "https://ntfy.sh/fluxer-upgrades")
+ if s := out.String(); !strings.Contains(s, "Run rexctl auto-upgrade on --at 02:15 --backup without-uploads --full-backup monthly to keep") || !strings.Contains(s, "Add --notify with your address to that command to keep the notifications.") {
+ t.Errorf("auto-upgrade on --at 02:15 with --notify says %q", s)
+ }
+}
+
+func TestMonthlyBackupOnTheFirstIsRecentAllMonth(t *testing.T) {
+ app, _ := notifyRun(t, false)
+ out := app.UI.Stdout().(*bytes.Buffer)
+ inst, err := instance.Find(app.Flags.Dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stockholm, err := time.LoadLocation("Europe/Stockholm")
+ if err != nil {
+ t.Skip(err)
+ }
+ writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 1, 3, 0, 0, 0, stockholm), "")
+ uploadsBackupNote(app, inst, host.AutoUpgrade{Project: "fluxer"}, host.AutoUpgradeState{}, time.Date(2026, 11, 1, 2, 59, 0, 0, stockholm))
+ if strings.Contains(out.String(), "No backup from the last") {
+ t.Errorf("a backup from 1 October counts as too old on 1 November before 03:00, output %q", out.String())
+ }
+ app, _ = notifyRun(t, false)
+ out = app.UI.Stdout().(*bytes.Buffer)
+ if inst, err = instance.Find(app.Flags.Dir); err != nil {
+ t.Fatal(err)
+ }
+ writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 1, 1, 0, 0, 0, stockholm), "")
+ uploadsBackupNote(app, inst, host.AutoUpgrade{Project: "fluxer"}, host.AutoUpgradeState{}, time.Date(2026, 10, 2, 12, 0, 0, 0, stockholm))
+ if want := "The newest backup with uploads is from 1 October 2026 at 01:00 CEST."; !strings.Contains(out.String(), want) {
+ t.Errorf("a monthly backup at 01:00 on the 1st shows as %q, want %q", out.String(), want)
+ }
}
diff --git a/fluxer_rexctl/cmd/backup.go b/fluxer_rexctl/cmd/backup.go
index c6956bbbb..f84828ea8 100644
--- a/fluxer_rexctl/cmd/backup.go
+++ b/fluxer_rexctl/cmd/backup.go
@@ -26,7 +26,7 @@ func newBackupCmd(app *App) *cobra.Command {
c := &cobra.Command{
Use: "backup",
Short: "Back up your instance",
- Long: "Back up your instance. Fluxer pauses while uploads are copied.",
+ Long: "Back up your instance in one file that restores on this machine or a new one. It holds the database, search data and uploads that Fluxer stores itself. Fluxer pauses while uploads are copied.",
Args: noArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runBackup(c.Context(), app)
@@ -64,7 +64,7 @@ func newBackupCmd(app *App) *cobra.Command {
keep := &cobra.Command{
Use: "keep [count|all]",
Short: "Show or change how many backups rexctl keeps",
- Long: "Show or change how many backups rexctl keeps. After each backup, rexctl deletes the oldest ones beyond this number, except the backup that rexctl rollback needs. Pass all to keep every backup.",
+ Long: "Show or change how many backups rexctl keeps. After each backup, rexctl deletes the oldest ones beyond this number, except the backup that rexctl rollback needs and the newest backup with uploads. Pass all to keep every backup.",
Args: maxArgs(1),
RunE: func(c *cobra.Command, args []string) error {
if len(args) == 0 {
@@ -252,12 +252,22 @@ func runBackupList(app *App) error {
}
rows := make([][]string, 0, len(list))
for _, b := range list {
- rows = append(rows, []string{b.File, backupTime(b.CreatedAt), b.Release, ui.Bytes(b.SizeBytes)})
+ rows = append(rows, []string{b.File, backupTime(b.CreatedAt), b.Release, backupReason(b), ui.Bytes(b.SizeBytes)})
}
- app.UI.Table([]string{"File", "Made", "Version", "Size"}, rows)
+ app.UI.Table([]string{"File", "Made", "Version", "Reason", "Size"}, rows)
return nil
}
+func backupReason(b backup.Info) string {
+ if !b.WithoutUploads() {
+ return b.Reason
+ }
+ if b.Reason == "" {
+ return "without uploads"
+ }
+ return b.Reason + ", without uploads"
+}
+
func runBackupVerify(ctx context.Context, app *App, arg string) error {
path := resolveBackupPath(app, arg)
return app.UI.Step(ctx, "Checking the backup", func(ctx context.Context, s *ui.Step) error {
@@ -265,6 +275,10 @@ func runBackupVerify(ctx context.Context, app *App, arg string) error {
if err != nil {
return backupFileErr(path, err)
}
+ if m.WithoutUploads() {
+ s.Done("The backup is complete. It has %s on %s without uploads, made %s.", m.Domain, fluxerName(m.Release), backupTime(m.CreatedAt))
+ return nil
+ }
s.Done("The backup is complete. It has %s on %s, made %s.", m.Domain, fluxerName(m.Release), backupTime(m.CreatedAt))
return nil
})
@@ -316,22 +330,35 @@ func pruneBackups(app *App, inst *instance.Instance) {
return
}
dir := inst.BackupDir()
+ removed, err := backup.Prune(dir, keep, protectedBackups(inst, dir)...)
+ if len(removed) > 0 {
+ msg := fmt.Sprintf("Deleted %s to keep the newest %d.", plural(len(removed), "older backup", "older backups"), keep)
+ if left, lerr := backup.List(dir); lerr == nil && len(left) > keep {
+ msg += " rexctl also keeps the newest backup with uploads and the one rexctl rollback needs."
+ }
+ app.UI.Info("%s Run rexctl backup keep to change how many rexctl keeps.", msg)
+ }
+ if err != nil {
+ app.UI.Warn(fmt.Sprintf("Couldn't delete older backups in %s.", dir), "Check that you can change files in that folder.")
+ }
+}
+
+func protectedBackups(inst *instance.Instance, dir string) []string {
var protect []string
if u := inst.State.Upgrade; u != nil {
protect = append(protect, u.Backup)
}
- if list, err := backup.List(dir); err == nil {
- if b := backup.NewestOf(list, inst.State.PreviousRelease); b != nil {
- protect = append(protect, b.Path)
- }
+ list, err := backup.List(dir)
+ if err != nil {
+ return protect
}
- removed, err := backup.Prune(dir, keep, protect...)
- if len(removed) > 0 {
- app.UI.Info("Deleted %s to keep the newest %d. Run rexctl backup keep to change how many rexctl keeps.", plural(len(removed), "older backup", "older backups"), keep)
+ if b := rollbackTarget(inst, list, inst.State.PreviousRelease); b != nil {
+ protect = append(protect, b.Path)
}
- if err != nil {
- app.UI.Warn(fmt.Sprintf("Couldn't delete older backups in %s.", dir), "Check that you can change files in that folder.")
+ if b := backup.NewestWithUploads(list); b != nil {
+ protect = append(protect, b.Path)
}
+ return protect
}
func runBackupLocationShow(app *App) error {
diff --git a/fluxer_rexctl/cmd/backup_test.go b/fluxer_rexctl/cmd/backup_test.go
index ecebeca9d..e22c8b36a 100644
--- a/fluxer_rexctl/cmd/backup_test.go
+++ b/fluxer_rexctl/cmd/backup_test.go
@@ -3,11 +3,20 @@
package cmd
import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "encoding/json"
"errors"
+ "os"
+ "path/filepath"
+ "slices"
"strings"
"testing"
+ "time"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
)
@@ -30,3 +39,179 @@ func TestBackupCompressingStageHasTitle(t *testing.T) {
t.Fatal("the compressing stage has no progress title")
}
}
+
+func writeTestBackup(t *testing.T, inst *instance.Instance, release string, at time.Time, scope string) string {
+ t.Helper()
+ m := backup.Manifest{Format: 1, Release: release, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: at, Reason: "upgrade", Scope: scope, Volumes: []string{}}
+ if scope != "" {
+ m.Format = backup.FormatVersion
+ }
+ return writeManifestBackup(t, inst, m)
+}
+
+func writeManifestBackup(t *testing.T, inst *instance.Instance, m backup.Manifest) string {
+ t.Helper()
+ at := m.CreatedAt
+ data, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var b bytes.Buffer
+ b.Write(binary.LittleEndian.AppendUint32(nil, 0x184D2A5E))
+ b.Write(binary.LittleEndian.AppendUint32(nil, uint32(len(data)+16)))
+ b.Write(data)
+ b.Write(binary.LittleEndian.AppendUint64(nil, uint64(len(data))))
+ b.WriteString("RXBKMAN1")
+ dir := inst.BackupDir()
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "fluxer-test-"+at.UTC().Format("20060102-150405")+backup.Extension)
+ if err := os.WriteFile(path, b.Bytes(), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func backupApp(t *testing.T) (*App, *instance.Instance, *bytes.Buffer) {
+ t.Helper()
+ app, _ := notifyRun(t, false)
+ inst, err := instance.Find(app.Flags.Dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return app, inst, app.UI.Stdout().(*bytes.Buffer)
+}
+
+func remaining(t *testing.T, inst *instance.Instance) []string {
+ t.Helper()
+ list, err := backup.List(inst.BackupDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, b := range list {
+ out = append(out, b.Path)
+ }
+ return out
+}
+
+func TestPruneKeepsNewestBackupWithUploads(t *testing.T) {
+ app, inst, out := backupApp(t)
+ inst.State.KeepBackups = 2
+ day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
+ full := writeTestBackup(t, inst, "2026.1001.100000", day, "")
+ older := writeTestBackup(t, inst, "2026.1001.100000", day.Add(-24*time.Hour), "")
+ var lean []string
+ for i := 1; i <= 4; i++ {
+ lean = append(lean, writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Duration(i)*7*24*time.Hour), backup.ScopeWithoutUploads))
+ }
+ pruneBackups(app, inst)
+ got := remaining(t, inst)
+ if !slices.Contains(got, full) {
+ t.Errorf("the newest backup with uploads was deleted, left %v", got)
+ }
+ if slices.Contains(got, older) || slices.Contains(got, lean[0]) || slices.Contains(got, lean[1]) {
+ t.Errorf("older backups were kept, left %v", got)
+ }
+ if !slices.Contains(got, lean[3]) || !slices.Contains(got, lean[2]) {
+ t.Errorf("the newest backups were deleted, left %v", got)
+ }
+ want := "Deleted 3 older backups to keep the newest 2. rexctl also keeps the newest backup with uploads and the one rexctl rollback needs."
+ if !strings.Contains(out.String(), want) {
+ t.Errorf("prune says %q, want %q", out.String(), want)
+ }
+ out.Reset()
+ writeTestBackup(t, inst, "2026.1001.100000", day.Add(5*7*24*time.Hour), "")
+ pruneBackups(app, inst)
+ if s := out.String(); !strings.Contains(s, "Deleted 2 older backups to keep the newest 2.") || strings.Contains(s, "also keeps") {
+ t.Errorf("with nothing kept beyond the count, prune says %q", s)
+ }
+}
+
+func TestPruneKeepsBackupForRealPreviousRelease(t *testing.T) {
+ app, inst, _ := backupApp(t)
+ inst.State.KeepBackups = 1
+ day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
+ stale := writeTestBackup(t, inst, "2026.1001.100000", day, "")
+ forB := writeTestBackup(t, inst, "2026.1008.100000", day.Add(7*24*time.Hour), backup.ScopeWithoutUploads)
+ writeTestBackup(t, inst, "2026.1015.100000", day.Add(14*24*time.Hour), backup.ScopeWithoutUploads)
+ inst.State.PreviousRelease, inst.State.PreviousBackup = "2026.1008.100000", stale
+ pruneBackups(app, inst)
+ got := remaining(t, inst)
+ if !slices.Contains(got, forB) {
+ t.Errorf("the backup for the previous release was deleted, left %v", got)
+ }
+ list, err := backup.List(inst.BackupDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b := backupFor(inst, list, inst.State.PreviousRelease); b == nil || b.Path != forB {
+ t.Errorf("rollback would restore %v, want %s", b, forB)
+ }
+}
+
+func TestPruneKeepsPreviousBackup(t *testing.T) {
+ app, inst, _ := backupApp(t)
+ inst.State.KeepBackups = 1
+ inst.State.PreviousRelease = "2026.1001.100000"
+ day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
+ recorded := writeTestBackup(t, inst, "2026.1001.100000", day, backup.ScopeWithoutUploads)
+ later := writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Hour), backup.ScopeWithoutUploads)
+ writeTestBackup(t, inst, "2026.1008.100000", day.Add(48*time.Hour), backup.ScopeWithoutUploads)
+ inst.State.PreviousBackup = recorded
+ pruneBackups(app, inst)
+ got := remaining(t, inst)
+ if !slices.Contains(got, recorded) {
+ t.Errorf("the backup rollback needs was deleted, left %v", got)
+ }
+ if slices.Contains(got, later) {
+ t.Errorf("a newer backup on the same release was kept over the recorded one, left %v", got)
+ }
+}
+
+func TestBackupListMarksWithoutUploads(t *testing.T) {
+ app, inst, out := backupApp(t)
+ day := time.Date(2026, 10, 1, 4, 0, 0, 0, time.UTC)
+ writeTestBackup(t, inst, "2026.1001.100000", day, "")
+ writeTestBackup(t, inst, "2026.1001.100000", day.Add(time.Hour), backup.ScopeWithoutUploads)
+ if err := runBackupList(app); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(out.String(), "upgrade, without uploads") || strings.Count(out.String(), "without uploads") != 1 {
+ t.Errorf("backup list:\n%s", out.String())
+ }
+ out.Reset()
+ app.Flags.JSON = true
+ app.UI = ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out, JSON: true})
+ if err := runBackupList(app); err != nil {
+ t.Fatal(err)
+ }
+ var list []map[string]any
+ if err := json.Unmarshal(out.Bytes(), &list); err != nil {
+ t.Fatalf("%v in %s", err, out.String())
+ }
+ if len(list) != 2 || list[0]["scope"] != "without-uploads" {
+ t.Errorf("JSON list = %s", out.String())
+ }
+ if _, ok := list[1]["scope"]; ok {
+ t.Errorf("a full backup has a scope in %s", out.String())
+ }
+}
+
+func TestUploadsRefusalSuggestsOnlyThisInstancesBackup(t *testing.T) {
+ _, inst, _ := backupApp(t)
+ own := writeTestBackup(t, inst, "2026.1020.100000", time.Date(2026, 10, 12, 4, 0, 0, 0, time.UTC), "")
+ other := writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: "2026.1020.100000", Project: inst.Project(), Domain: "chat-a.example.com", CreatedAt: time.Date(2026, 10, 20, 4, 0, 0, 0, time.UTC), Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Volumes: []string{}})
+ err := checkUploadsInPlace(context.Background(), inst.Dir, inst, nil, other)
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !errors.Is(err, backup.ErrUploadsNotHere) {
+ t.Fatalf("restoring another instance's backup without uploads returned %v", err)
+ }
+ if strings.Contains(ee.Fix, own) || ee.Fix != "Restore a backup made with rexctl backup." {
+ t.Errorf("the refusal for chat-a.example.com says %q", ee.Fix)
+ }
+ if err := uploadsNotHere(inst, inst.Domain(), inst.Project(), backup.ErrUploadsNotHere); !errors.As(err, &ee) || !strings.Contains(ee.Fix, own) {
+ t.Errorf("the refusal for this instance's own backup says %v", err)
+ }
+}
diff --git a/fluxer_rexctl/cmd/fileid_unix_test.go b/fluxer_rexctl/cmd/fileid_unix_test.go
new file mode 100644
index 000000000..542a5e523
--- /dev/null
+++ b/fluxer_rexctl/cmd/fileid_unix_test.go
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+//go:build !windows
+
+package cmd
+
+import (
+ "os"
+ "syscall"
+ "testing"
+)
+
+func uploadsInode(t *testing.T, path string) uint64 {
+ t.Helper()
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return uint64(info.Sys().(*syscall.Stat_t).Ino)
+}
diff --git a/fluxer_rexctl/cmd/fileid_windows_test.go b/fluxer_rexctl/cmd/fileid_windows_test.go
new file mode 100644
index 000000000..9488ff42f
--- /dev/null
+++ b/fluxer_rexctl/cmd/fileid_windows_test.go
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package cmd
+
+import "testing"
+
+func uploadsInode(t *testing.T, path string) uint64 {
+ t.Helper()
+ return 0
+}
diff --git a/fluxer_rexctl/cmd/restore.go b/fluxer_rexctl/cmd/restore.go
index 8ceab67f1..ed7ff4354 100644
--- a/fluxer_rexctl/cmd/restore.go
+++ b/fluxer_rexctl/cmd/restore.go
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"runtime"
+ "slices"
"strings"
"time"
@@ -28,7 +29,7 @@ func newRestoreCmd(app *App) *cobra.Command {
c := &cobra.Command{
Use: "restore <file>",
Short: "Restore your instance from a backup",
- Long: "Restore your instance from a backup. This works on a new machine too. Copy the backup file there and run this command.",
+ Long: "Restore your instance from a backup. This works on a new machine too. Copy the backup file there and run this command. A backup without uploads restores only on the instance it was made for, and the uploads there stay as they are.",
Args: exactArgs("the backup file"),
RunE: func(c *cobra.Command, args []string) error {
return runRestore(c.Context(), app, args[0], confirm, engineFlag)
@@ -75,14 +76,36 @@ func runRestore(ctx context.Context, app *App, arg, confirm, engineFlag string)
}
}
+ old := oldEngineRef(existing)
+ if m.WithoutUploads() {
+ if existing == nil && !backup.ResumesRestore(dir, m) || toDocker && existing != nil && old.Kind != string(engine.Docker) {
+ return uploadsNotHere(existing, m.Domain, m.Project, backup.ErrUploadsNotHere)
+ }
+ e, err := app.Engine(ctx, existing)
+ if err != nil {
+ return err
+ }
+ if toDocker && e.Kind != engine.Docker {
+ return uploadsNotHere(existing, m.Domain, m.Project, backup.ErrUploadsNotHere)
+ }
+ if err := checkUploadsInPlace(ctx, dir, existing, e, path); err != nil {
+ return err
+ }
+ }
+
made := backupTime(m.CreatedAt)
domain := m.Domain
what := fmt.Sprintf("This restores %s in %s from the backup made on %s.", m.Domain, dir, made)
- if existing != nil {
+ switch {
+ case existing != nil && m.WithoutUploads():
+ domain = existing.Domain()
+ what = fmt.Sprintf("This replaces everything on %s except uploads with the backup made on %s. Uploads stay as they are.", domain, made)
+ case existing != nil:
domain = existing.Domain()
what = fmt.Sprintf("This replaces everything on %s with the backup made on %s.", domain, made)
+ case m.WithoutUploads():
+ what = fmt.Sprintf("This finishes restoring %s in %s from the backup made on %s. Uploads stay as they are.", m.Domain, dir, made)
}
- old := oldEngineRef(existing)
if toDocker && old.Kind == string(engine.Podman) {
what += " Fluxer stops on Podman and starts on Docker. Podman keeps its copy of your data."
}
@@ -106,6 +129,34 @@ func runRestore(ctx context.Context, app *App, arg, confirm, engineFlag string)
return run()
}
+func checkUploadsInPlace(ctx context.Context, dir string, existing *instance.Instance, e *engine.Engine, path string) error {
+ m, err := backup.ReadManifest(path)
+ if err != nil {
+ return backupFileErr(path, err)
+ }
+ err = backup.CheckUploadsInPlace(ctx, dir, existing, e, m)
+ switch {
+ case errors.Is(err, backup.ErrUploadsNotHere):
+ return uploadsNotHere(existing, m.Domain, m.Project, err)
+ case err != nil:
+ return engineFailure(err)
+ }
+ return nil
+}
+
+func uploadsNotHere(existing *instance.Instance, domain, project string, err error) error {
+ fix := "Restore a backup made with rexctl backup."
+ if existing != nil {
+ if list, lerr := backup.List(existing.BackupDir()); lerr == nil {
+ same := slices.DeleteFunc(list, func(b backup.Info) bool { return b.Domain != domain || b.Project != project })
+ if b := backup.NewestWithUploads(same); b != nil {
+ fix = fmt.Sprintf("Restore %s, the newest backup with uploads.", b.Path)
+ }
+ }
+ }
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: "This backup leaves out uploads, and this machine doesn't have the uploads it belongs with.", Fix: fix, Err: err}
+}
+
func oldEngineRef(inst *instance.Instance) instance.EngineRef {
if inst == nil || inst.State == nil {
return instance.EngineRef{}
@@ -318,6 +369,8 @@ func restoreErr(path string, err error, logPath string) error {
return engineFailure(pull.Err)
}
return ui.Wrap(pull.Err, "Couldn't download Fluxer.", "Run rexctl restore again with --verbose to see why.")
+ case errors.Is(err, backup.ErrUploadsNotHere):
+ return uploadsNotHere(nil, "", "", err)
case errors.As(err, &inUse):
return ui.Refused(
fmt.Sprintf("Another Fluxer instance on this machine is in %s.", inUse.Dir),
diff --git a/fluxer_rexctl/cmd/rollback.go b/fluxer_rexctl/cmd/rollback.go
index 2c99052c4..9a408b31c 100644
--- a/fluxer_rexctl/cmd/rollback.go
+++ b/fluxer_rexctl/cmd/rollback.go
@@ -157,6 +157,7 @@ func runRollback(ctx context.Context, app *App, f *rollbackFlags) error {
app.UI.Info("Nothing changed.")
return nil
}
+ prevBackup := inst.State.PreviousBackup
if err := release.Snapshot(inst, cur, refList(inst.State.Images.Refs)); err != nil {
return ui.Wrap(err, fmt.Sprintf("Couldn't save the files of Fluxer %s.", curShort), "Check that the disk isn't full, then run rexctl rollback again.")
}
@@ -168,9 +169,9 @@ func runRollback(ctx context.Context, app *App, f *rollbackFlags) error {
return err
})
if err != nil {
- return rollbackFailed(ctx, app, inst, e, cur, prev, err)
+ return rollbackFailed(ctx, app, inst, e, cur, prev, prevBackup, err)
}
- inst.State.PreviousRelease = ""
+ inst.State.PreviousRelease, inst.State.PreviousBackup = "", ""
if err := inst.Save(); err != nil {
return ui.Wrap(err, "Couldn't save your instance's state.", "Run rexctl doctor to see what's wrong.")
}
@@ -181,7 +182,7 @@ func runRollback(ctx context.Context, app *App, f *rollbackFlags) error {
})
}
-func rollbackFailed(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, cur, prev string, cause error) error {
+func rollbackFailed(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, cur, prev, prevBackup string, cause error) error {
curShort, prevShort := versionPair(cur, prev)
logPath := writeFailureLog(ctx, inst, e.Named(inst.Project(), inst.Dir), "rollback-"+release.DirName(prev)+".log", cause, nil)
app.UI.Fail(fmt.Sprintf("Fluxer %s didn't start.", prevShort), "")
@@ -190,7 +191,7 @@ func rollbackFailed(ctx context.Context, app *App, inst *instance.Instance, e *e
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recoveryTimeout)
defer cancel()
_, err := restoreRelease(cctx, app, inst, e, cur)
- inst.State.Release, inst.State.PreviousRelease = cur, prev
+ inst.State.Release, inst.State.PreviousRelease, inst.State.PreviousBackup = cur, prev, prevBackup
_ = inst.Save()
if err == nil {
app.UI.OK("Went back to %s. Your instance is running.", curShort)
@@ -215,13 +216,30 @@ func rollbackWithBackup(ctx context.Context, app *App, inst *instance.Instance,
return err
}
when := backupTime(info.CreatedAt)
+ if info.WithoutUploads() {
+ if e == nil {
+ if e, err = app.Engine(ctx, inst); err != nil {
+ return err
+ }
+ }
+ if err := checkUploadsInPlace(ctx, inst.Dir, inst, e, info.Path); err != nil {
+ return err
+ }
+ }
if f.DryRun {
app.UI.Info("Your instance goes back to the backup from %s, on Fluxer %s.", when, prevShort)
- app.UI.Info("Anything that changed since then is lost.")
+ if info.WithoutUploads() {
+ app.UI.Info("Messages and changes since then are lost. Uploads stay as they are.")
+ } else {
+ app.UI.Info("Messages, uploads and changes since then are lost.")
+ }
app.UI.Info("Dry run. Nothing changed.")
return nil
}
what := fmt.Sprintf("This restores the backup from %s. Messages, uploads and changes since then will be lost.", when)
+ if info.WithoutUploads() {
+ what = fmt.Sprintf("This restores the backup from %s. Messages and changes since then will be lost. Uploads stay as they are.", when)
+ }
if err := app.UI.ConfirmDestructive(what, inst.Domain(), f.Confirm); err != nil {
return err
}
@@ -232,6 +250,9 @@ func rollbackWithBackup(ctx context.Context, app *App, inst *instance.Instance,
}
}})
if err != nil {
+ if errors.Is(err, backup.ErrUploadsNotHere) {
+ return uploadsNotHere(inst, info.Domain, info.Project, err)
+ }
return err
}
if err := e.Named(restored.Project(), restored.Dir).WaitReady(ctx, readyTimeout, showReadiness(s, "Starting Fluxer "+prevShort)); err != nil {
@@ -247,9 +268,41 @@ func upgradeBackup(inst *instance.Instance, prev string) (*backup.Info, error) {
if err != nil {
return nil, ui.Wrap(err, "Couldn't read your backups.", "Run rexctl backup list to see why.")
}
- best := backup.NewestOf(list, prev)
+ best := backupFor(inst, list, prev)
if best == nil {
return nil, ui.Refused(fmt.Sprintf("There's no backup from Fluxer %s on this machine.", prev), "Run rexctl restore with a backup file you kept somewhere else.")
}
return best, nil
}
+
+func backupFor(inst *instance.Instance, list []backup.Info, version string) *backup.Info {
+ if inst.State == nil {
+ return backup.NewestOf(list, version)
+ }
+ if u := inst.State.Upgrade; u != nil && u.Backup != "" {
+ if b := knownBackup(list, u.Backup); b != nil {
+ return b
+ }
+ }
+ return rollbackTarget(inst, list, version)
+}
+
+func rollbackTarget(inst *instance.Instance, list []backup.Info, version string) *backup.Info {
+ if inst.State != nil && inst.State.PreviousBackup != "" {
+ if b := knownBackup(list, inst.State.PreviousBackup); b != nil && b.Release == version {
+ return b
+ }
+ }
+ return backup.NewestOf(list, version)
+}
+
+func knownBackup(list []backup.Info, path string) *backup.Info {
+ if b := backup.Find(list, path); b != nil {
+ return b
+ }
+ b, err := backup.Stat(path)
+ if err != nil {
+ return nil
+ }
+ return b
+}
diff --git a/fluxer_rexctl/cmd/search.go b/fluxer_rexctl/cmd/search.go
index 0d67776fc..980e3c7f1 100644
--- a/fluxer_rexctl/cmd/search.go
+++ b/fluxer_rexctl/cmd/search.go
@@ -48,7 +48,7 @@ func keepSearchReadable(ctx context.Context, app *App, inst *instance.Instance,
}
name := capitalise(fluxerName(release.Short(version)))
list, _ := backup.List(inst.BackupDir())
- if b := backup.NewestOf(list, version); b != nil {
+ if b := backupFor(inst, list, version); b != nil {
err := backup.RestoreVolume(ctx, b.Path, inst, p, searchVolume)
if err == nil {
app.UI.Info("%s can't read the search index that a newer Meilisearch wrote, so rexctl put back the copy from the backup from %s. Messages sent since then don't show up in search.", name, backupTime(b.CreatedAt))
diff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.go
index 3641a266b..c97be1aa7 100644
--- a/fluxer_rexctl/cmd/upgrade.go
+++ b/fluxer_rexctl/cmd/upgrade.go
@@ -40,8 +40,10 @@ const (
var fatalChecks = map[string]bool{"services": true, "health": true}
var (
- selfUpdate = release.SelfUpdate
- reexec = release.Reexec
+ selfUpdate = release.SelfUpdate
+ reexec = release.Reexec
+ createBackup = backup.Create
+ estimateBackup = backup.Estimate
)
type upgradeFlags struct {
@@ -49,6 +51,7 @@ type upgradeFlags struct {
To string
Prefetch bool
NoBackup bool
+ Backup string
DryRun bool
Resume string
}
@@ -69,6 +72,9 @@ func newUpgradeCmd(app *App) *cobra.Command {
Short: "Upgrade rexctl and Fluxer to the latest release",
Args: noArgs,
RunE: func(c *cobra.Command, _ []string) error {
+ if !c.Flags().Changed("backup") {
+ f.Backup = ""
+ }
err := runUpgrade(c.Context(), app, &f)
if !f.Check && !f.DryRun {
notifyUpgrade(c.Context(), app, err)
@@ -81,6 +87,7 @@ func newUpgradeCmd(app *App) *cobra.Command {
fl.StringVar(&f.To, "to", "", "upgrade to this version, not the latest")
fl.BoolVar(&f.Prefetch, "prefetch", false, "download the new version and upgrade later")
fl.BoolVar(&f.NoBackup, "no-backup", false, "skip the backup before upgrading")
+ fl.StringVar(&f.Backup, "backup", backup.ScopeFull, "what the backup before this upgrade holds, full or without-uploads. When the upgrade changes how uploads are stored, the backup includes them anyway.")
fl.BoolVar(&f.DryRun, "dry-run", false, "show what would happen without changing anything")
fl.StringVar(&f.Resume, release.ResumeFlag, "", "")
_ = fl.MarkHidden(release.ResumeFlag)
@@ -90,7 +97,7 @@ func newUpgradeCmd(app *App) *cobra.Command {
func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
if f.Check {
- if f.Prefetch || f.NoBackup || f.DryRun {
+ if f.Prefetch || f.NoBackup || f.DryRun || f.Backup != "" {
return ui.Usage("Use --check on its own, or with --to and --json.")
}
return runUpgradeCheck(ctx, app, f)
@@ -101,6 +108,15 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
if f.Prefetch && f.NoBackup {
return ui.Usage("Use --no-backup when you upgrade, not with --prefetch.")
}
+ if f.Prefetch && f.Backup != "" {
+ return ui.Usage("Use --backup when you upgrade, not with --prefetch.")
+ }
+ if f.Backup != "" && f.NoBackup {
+ return ui.Usage("Use --backup or --no-backup, not both.")
+ }
+ if _, err := parseBackupScope(f.Backup); err != nil {
+ return err
+ }
if f.Resume != "" && f.Resume != release.ResumeRecovery {
return resumeUpgrade(ctx, app, f)
}
@@ -161,7 +177,7 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
for _, k := range keptCopies(inst) {
warnKeptCopy(app.UI, k.Name, k.Copy, true)
}
- printUpgradePlan(ctx, app, inst, f, needSelf, to)
+ printUpgradePlan(ctx, app, inst, f, needSelf, cur, rel.Version)
return nil
}
if f.Prefetch {
@@ -199,6 +215,12 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
if err != nil {
return ui.Failed(fmt.Sprintf("There's no rexctl %s for this machine.", to), "")
}
+ args := os.Args[1:]
+ if release.Valid(app.Version) && release.Compare(rel.Version, app.Version) < 0 {
+ if args, err = switchBack(ctx, app, inst, e, args, to); err != nil {
+ return err
+ }
+ }
err = app.Change(ctx, inst, func(*engine.Engine) error {
if err := setPhase(inst, cur, rel.Version, release.PhaseResolved); err != nil {
return err
@@ -220,12 +242,99 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
if err != nil {
return err
}
- if err := reexec(resumeArgs(os.Args[1:], release.PhaseSelfUpdated, app.pickedDir())); err != nil {
+ if err := reexec(resumeArgs(args, release.PhaseSelfUpdated, app.pickedDir())); err != nil {
return ui.Wrap(err, "Updated rexctl but couldn't start it again.", "Run rexctl upgrade again.")
}
return nil
}
+var dropScheduledBackup = func(ctx context.Context, inst *instance.Instance, e *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ a, err := autoUpgradeFor(inst, e)
+ if err != nil || a.Scheduler == "" {
+ return host.AutoUpgradeState{}, false, err
+ }
+ s, err := host.CheckAutoUpgrade(ctx, a, time.Now())
+ if err != nil {
+ return s, false, err
+ }
+ s.Day, s.At = a.Requested(s.Day, s.At)
+ changed, err := host.DropBackupFlag(ctx, a)
+ return s, changed, err
+}
+
+func switchBack(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, args []string, to string) ([]string, error) {
+ kept, dropped := withoutFlag(args, "--backup")
+ lean := dropped != "" && dropped != backup.ScopeFull
+ if lean {
+ app.UI.Info("rexctl %s may not know --backup. This upgrade makes a full backup.", to)
+ }
+ s, changed, err := dropScheduledBackup(ctx, inst, e)
+ if err != nil {
+ if errors.Is(err, host.ErrNeedsRoot) {
+ return nil, ui.Refused(fmt.Sprintf("Automatic upgrades pass --backup without-uploads, which rexctl %s may not know. Changing that needs root.", to), "Run sudo rexctl upgrade with the same flags.")
+ }
+ return nil, ui.Wrap(err, fmt.Sprintf("Couldn't change automatic upgrades for rexctl %s.", to), "Run rexctl auto-upgrade on again without --backup and with your other flags, then run this upgrade again.")
+ }
+ again := scheduleCommand(s)
+ offered := changed
+ switch {
+ case changed && lean:
+ app.UI.Info("Automatic upgrades make full backups from now on as well. Once rexctl is newer than %s, run %s again.", to, again)
+ case changed:
+ app.UI.Info("rexctl %s may not know --backup. Automatic upgrades make full backups from now on. Once rexctl is newer than %s, run %s again.", to, to, again)
+ }
+ if long := host.DayLong(s.Day); long != "" {
+ app.UI.Info("rexctl %s shows this weekly schedule as every day, and it keeps running every %s. Once rexctl is newer than %s, run rexctl auto-upgrade to see it again.", to, long, to)
+ if !changed {
+ app.UI.Info("rexctl auto-upgrade on from rexctl %s makes the schedule daily. Once rexctl is newer than %s, run %s to make it weekly again.", to, to, again)
+ offered = true
+ }
+ }
+ if offered && inst != nil && inst.State != nil && inst.State.NotifyURL != "" {
+ app.UI.Info("Add --notify with your address to that command to keep the notifications.")
+ }
+ if s.FullBackup != "" {
+ app.UI.Info("The monthly full backup keeps running. rexctl %s doesn't know about it, and rexctl auto-upgrade off from rexctl %s leaves it on.", to, to)
+ }
+ return kept, nil
+}
+
+func scheduleCommand(s host.AutoUpgradeState) string {
+ cmd := "rexctl auto-upgrade on"
+ if s.Day != "" {
+ cmd += " --day " + strings.ToLower(s.Day)
+ }
+ if s.At != "" && s.At != autoUpgradeDefault {
+ cmd += " --at " + s.At
+ }
+ if s.Backup == backup.ScopeWithoutUploads {
+ cmd += " --backup " + backup.ScopeWithoutUploads
+ }
+ if s.FullBackup != "" {
+ cmd += " --full-backup " + s.FullBackup
+ }
+ return cmd
+}
+
+func withoutFlag(args []string, flag string) ([]string, string) {
+ out := make([]string, 0, len(args))
+ value := ""
+ for i := 0; i < len(args); i++ {
+ a := args[i]
+ if a == flag && i+1 < len(args) {
+ value = args[i+1]
+ i++
+ continue
+ }
+ if v, ok := strings.CutPrefix(a, flag+"="); ok {
+ value = v
+ continue
+ }
+ out = append(out, a)
+ }
+ return out, value
+}
+
func updateBeforeRecovery(ctx context.Context, app *App, resume, to, command string) (bool, error) {
if resume == release.ResumeRecovery || !release.Valid(app.Version) {
return false, nil
@@ -396,25 +505,48 @@ func resumeUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
})
}
-func printUpgradePlan(ctx context.Context, app *App, inst *instance.Instance, f *upgradeFlags, needSelf bool, to string) {
+func printUpgradePlan(ctx context.Context, app *App, inst *instance.Instance, f *upgradeFlags, needSelf bool, from, version string) {
+ _, to := versionPair(from, version)
if needSelf {
app.UI.Info("rexctl updates itself to %s.", to)
}
app.UI.Info("Fluxer %s downloads while your instance keeps running.", to)
+ lean := !f.Prefetch && !f.NoBackup && upgradeScope(f) == backup.ScopeWithoutUploads
+ planned, known := f, !needSelf
+ if lean && known {
+ changed, ok := plannedUploadsChange(inst, from, version)
+ known = ok
+ if changed {
+ app.UI.Info("Fluxer %s changes how uploads are stored. The backup before it includes them.", to)
+ full := *f
+ full.Backup = backup.ScopeFull
+ planned, lean = &full, false
+ }
+ }
if e, err := app.Engine(ctx, inst); err != nil {
app.UI.Detail("%v", err)
- } else if needSelf {
- printSpace(ctx, app, inst, e, nil, f, to)
} else {
- printSpace(ctx, app, inst, e, embeddedRefs(), f, to)
+ var refs map[string]string
+ if !needSelf {
+ refs = embeddedRefs()
+ }
+ printSpace(ctx, app, inst, e, refs, planned, to)
+ if lean && !known {
+ printFullBackupSpace(ctx, app, inst, e, refs, planned, to)
+ }
}
if f.Prefetch {
app.UI.Info("Dry run. Nothing changed.")
return
}
- if f.NoBackup {
+ switch {
+ case f.NoBackup:
app.UI.Info("Your instance isn't backed up first.")
- } else {
+ case lean && !known:
+ app.UI.Info("Your instance is backed up first, without uploads unless Fluxer %s changes how uploads are stored.", to)
+ case lean:
+ app.UI.Info("Your instance is backed up first, without uploads.")
+ default:
app.UI.Info("Your instance is backed up first.")
}
app.UI.Info("Fluxer stops for about 2 minutes while it moves to %s.", to)
@@ -422,6 +554,31 @@ func printUpgradePlan(ctx context.Context, app *App, inst *instance.Instance, f
app.UI.Info("Dry run. Nothing changed.")
}
+func plannedUploadsChange(inst *instance.Instance, from, version string) (bool, bool) {
+ set := stack.Embedded()
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ return false, false
+ }
+ next, _, err := nextState(inst, set, images, version)
+ if err != nil {
+ return false, false
+ }
+ return uploadsChange(inst, from, set, next), true
+}
+
+func printFullBackupSpace(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, refs map[string]string, f *upgradeFlags, to string) {
+ full := *f
+ full.Backup = backup.ScopeFull
+ lean := upgradeSpace(ctx, app, inst, e, refs, f)
+ for i, sp := range upgradeSpace(ctx, app, inst, e, refs, &full) {
+ if i < len(lean) && ui.Bytes(int64(lean[i].Need)) == ui.Bytes(int64(sp.Need)) {
+ continue
+ }
+ app.UI.Info("If Fluxer %s changes how uploads are stored, the backup includes them and Fluxer %s needs about %s of free disk space in %s.", to, to, ui.Bytes(int64(sp.Need)), sp.Path)
+ }
+}
+
func printSpace(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, next map[string]string, f *upgradeFlags, to string) {
for _, sp := range upgradeSpace(ctx, app, inst, e, next, f) {
if sp.Short() {
@@ -448,7 +605,7 @@ func upgradeSpace(ctx context.Context, app *App, inst *instance.Instance, e *eng
}
var saved uint64
if !f.Prefetch && !f.NoBackup {
- if saved, err = backup.Estimate(ctx, inst, old); err != nil {
+ if saved, err = estimateBackup(ctx, inst, old, upgradeScope(f)); err != nil {
app.UI.Detail("%v", err)
}
}
@@ -517,6 +674,7 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *eng
clearUpgrade(inst)
return ui.Wrap(err, fmt.Sprintf("Couldn't save the settings for Fluxer %s.", toShort), "Check that the disk isn't full, then run rexctl upgrade again.")
}
+ f = backupFlagsFor(app, inst, from, set, next, f, toShort)
old := e.Named(inst.Project(), inst.Dir)
for _, sp := range upgradeSpace(ctx, app, inst, e, next.Images.Refs, f) {
if sp.Short() {
@@ -543,23 +701,7 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *eng
if f.NoBackup {
app.UI.Warn("Skipped the backup.", "")
} else {
- err := app.UI.Step(ctx, "Backing up your instance", func(ctx context.Context, s *ui.Step) error {
- info, err := backup.Create(ctx, inst, old, backup.CreateOptions{Reason: "upgrade", OnEvent: app.progress(s, "Starting"), Progress: func(stage string) {
- if t := backupStageTitle(stage); t != "" {
- s.Title(t)
- }
- }})
- if errors.Is(err, backup.ErrNeverStarted) {
- s.Done("There was nothing to back up yet.")
- return nil
- }
- if err != nil {
- return err
- }
- inst.State.Upgrade.Backup = info.Path
- s.Done("Backed up your instance.")
- return nil
- })
+ err := backUpForUpgrade(ctx, app, inst, old, upgradeScope(f))
if err != nil {
fix := "Run rexctl backup to see why, then run rexctl upgrade again."
if logPath := writeBackupLog(inst, "upgrade-"+release.DirName(to)+".log", err); logPath != "" {
@@ -614,6 +756,62 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *eng
return finishUpgrade(ctx, app, inst, e)
}
+func upgradeScope(f *upgradeFlags) string {
+ if f.Backup == backup.ScopeWithoutUploads {
+ return backup.ScopeWithoutUploads
+ }
+ return backup.ScopeFull
+}
+
+func backUpForUpgrade(ctx context.Context, app *App, inst *instance.Instance, old *engine.Project, scope string) error {
+ return app.UI.Step(ctx, "Backing up your instance", func(ctx context.Context, s *ui.Step) error {
+ info, err := createBackup(ctx, inst, old, backup.CreateOptions{Reason: "upgrade", Scope: scope, OnEvent: app.progress(s, "Starting"), Progress: func(stage string) {
+ if t := backupStageTitle(stage); t != "" {
+ s.Title(t)
+ }
+ }})
+ if errors.Is(err, backup.ErrNeverStarted) {
+ s.Done("There was nothing to back up yet.")
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if info.WithoutUploads() {
+ s.Title("Checking the backup")
+ if _, err := backup.Verify(info.Path); err != nil {
+ os.Remove(info.Path)
+ return err
+ }
+ inst.State.Upgrade.Backup = info.Path
+ s.Done("Backed up your instance without uploads.")
+ return nil
+ }
+ inst.State.Upgrade.Backup = info.Path
+ s.Done("Backed up your instance.")
+ return nil
+ })
+}
+
+func backupFlagsFor(app *App, inst *instance.Instance, from string, set *stack.Set, next *instance.State, f *upgradeFlags, toShort string) *upgradeFlags {
+ if f.NoBackup || f.Prefetch || upgradeScope(f) != backup.ScopeWithoutUploads || !uploadsChange(inst, from, set, next) {
+ return f
+ }
+ app.UI.Info("Fluxer %s changes how uploads are stored. This backup includes them.", toShort)
+ full := *f
+ full.Backup = backup.ScopeFull
+ return &full
+}
+
+func uploadsChange(inst *instance.Instance, from string, set *stack.Set, next *instance.State) bool {
+ old, err := release.LoadSet(inst, from)
+ if err != nil {
+ return true
+ }
+ was, now := backup.UploadsDefinition(old, inst.State), backup.UploadsDefinition(set, next)
+ return was == "" || now == "" || was != now
+}
+
func startRelease(ctx context.Context, app *App, target *instance.Instance, e *engine.Engine, p *engine.Project, toShort string) ([]string, error) {
var waiting []string
err := app.UI.Step(ctx, "Starting Fluxer "+toShort, func(ctx context.Context, s *ui.Step) error {
@@ -769,12 +967,7 @@ func nextState(inst *instance.Instance, set *stack.Set, images stack.ImageSet, t
}
func postgresRef(s *instance.State) string {
- for _, v := range []string{s.Settings[settings.ImagesPrefix+"postgres"], s.Settings[settings.ImageVars["postgres"]], s.Images.Refs["postgres"]} {
- if v != "" {
- return v
- }
- }
- return ""
+ return settings.ImageRef(s.Settings, s.Images.Refs, "postgres")
}
func refList(refs map[string]string) []string {
@@ -1089,6 +1282,7 @@ func finishUpgrade(ctx context.Context, app *App, inst *instance.Instance, e *en
inst.State.SetupDone = done
}
inst.State.PreviousRelease = pend.From
+ inst.State.PreviousBackup = pend.Backup
inst.State.Release = pend.To
inst.State.Images = next.Images
inst.State.Settings = next.Settings
diff --git a/fluxer_rexctl/cmd/upgrade_recovery_test.go b/fluxer_rexctl/cmd/upgrade_recovery_test.go
index 9011a9408..7d018f677 100644
--- a/fluxer_rexctl/cmd/upgrade_recovery_test.go
+++ b/fluxer_rexctl/cmd/upgrade_recovery_test.go
@@ -6,17 +6,28 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
+ "io/fs"
+ "maps"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"runtime"
"slices"
"strings"
"testing"
+ "testing/fstest"
+ "time"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
"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/release"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/secrets"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
)
@@ -151,3 +162,520 @@ func TestPendingUpgradeRecoversWithCurrentRexctlWhenItIsLatest(t *testing.T) {
t.Fatal("the upgrade wasn't recovered")
}
}
+
+func recoveryInstance(t *testing.T, r *recoveryRun) *instance.Instance {
+ t.Helper()
+ inst, err := instance.Find(r.dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return inst
+}
+
+func TestFinishUpgradeRecordsPreviousBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ made := writeTestBackup(t, inst, recoveryFrom, time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC), backup.ScopeWithoutUploads)
+ inst.State.Upgrade = &instance.Upgrade{From: recoveryFrom, To: recoveryRexctl, Phase: release.PhaseVerified, Backup: made}
+ next := *inst.State
+ next.Release, next.Upgrade = recoveryRexctl, nil
+ if err := release.Snapshot(&instance.Instance{Dir: inst.Dir, State: &next}, recoveryRexctl, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := finishUpgrade(context.Background(), r.app, inst, r.app.engine); err != nil {
+ t.Fatal(err)
+ }
+ saved := recoveryInstance(t, r)
+ if saved.State.PreviousBackup != made || saved.State.PreviousRelease != recoveryFrom || saved.State.Release != recoveryRexctl {
+ t.Errorf("after the upgrade the release is %s, the previous one %s and the previous backup %q", saved.State.Release, saved.State.PreviousRelease, saved.State.PreviousBackup)
+ }
+}
+
+func TestRollbackUsesRecordedBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ inst.State.Upgrade = nil
+ day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
+ recorded := writeTestBackup(t, inst, recoveryFrom, day, backup.ScopeWithoutUploads)
+ manual := writeTestBackup(t, inst, recoveryFrom, day.Add(2*time.Hour), "")
+ inst.State.PreviousRelease, inst.State.PreviousBackup = recoveryFrom, recorded
+ b, err := upgradeBackup(inst, recoveryFrom)
+ if err != nil || b.Path != recorded {
+ t.Fatalf("upgradeBackup = %v, %v, want the recorded backup %s", b, err, recorded)
+ }
+ inst.State.PreviousBackup = filepath.Join(inst.BackupDir(), "gone"+backup.Extension)
+ if b, _ := upgradeBackup(inst, recoveryFrom); b == nil || b.Path != manual {
+ t.Errorf("with the recorded backup gone, upgradeBackup = %v, want the newest backup %s", b, manual)
+ }
+ inst.State.PreviousBackup = recorded
+ if b, _ := upgradeBackup(inst, "2026.1001.100000"); b != nil {
+ t.Errorf("upgradeBackup for another release = %v, want none", b)
+ }
+}
+
+func TestSearchGoBackUsesUpgradeBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
+ made := writeTestBackup(t, inst, recoveryFrom, day, backup.ScopeWithoutUploads)
+ writeTestBackup(t, inst, recoveryFrom, day.Add(time.Hour), "")
+ inst.State.Upgrade.Backup = made
+ list, err := backup.List(inst.BackupDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b := backupFor(inst, list, recoveryFrom); b == nil || b.Path != made {
+ t.Errorf("backupFor = %v, want the backup made for this upgrade %s", b, made)
+ }
+ inst.State.Upgrade.Backup = ""
+ if b := backupFor(inst, list, recoveryFrom); b == nil || b.Path == made {
+ t.Errorf("without an upgrade backup, backupFor = %v, want the newest one", b)
+ }
+}
+
+func testSet(t *testing.T, name string, edit func(string) string) *stack.Set {
+ t.Helper()
+ src := stack.Embedded()
+ files := fstest.MapFS{}
+ err := fs.WalkDir(src.Files, ".", func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return err
+ }
+ data, err := fs.ReadFile(src.Files, p)
+ if err != nil {
+ return err
+ }
+ if p == stack.ComposeFile && edit != nil {
+ data = []byte(edit(string(data)))
+ }
+ files[p] = &fstest.MapFile{Data: data, Mode: 0o644}
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return &stack.Set{Release: name, Files: files, Profiles: src.Profiles, Vars: src.Vars}
+}
+
+func TestUploadsChangeForcesFullBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Images = instance.Images{Release: recoveryFrom, Refs: images.Images}
+ if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
+ t.Fatal(err)
+ }
+ next := *inst.State
+ if uploadsChange(inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &next) {
+ t.Error("the same uploads services count as a change")
+ }
+ api := testSet(t, recoveryRexctl, func(c string) string {
+ return strings.Replace(c, "FLUXER_API_HEADERS_TIMEOUT_MS:-}", "FLUXER_API_HEADERS_TIMEOUT_MS:-5}", 1)
+ })
+ if uploadsChange(inst, recoveryFrom, api, &next) {
+ t.Error("a change to another service counts as an uploads change")
+ }
+ changed := testSet(t, recoveryRexctl, func(c string) string {
+ return strings.Replace(c, "-volume.max=${FLUXER_SEAWEEDFS_VOLUME_MAX:-10000}", "-volume.max=${FLUXER_SEAWEEDFS_VOLUME_MAX:-20000}", 1)
+ })
+ if !uploadsChange(inst, recoveryFrom, changed, &next) {
+ t.Error("a new seaweedfs command doesn't count as an uploads change")
+ }
+ init := testSet(t, recoveryRexctl, func(c string) string {
+ return strings.Replace(c, "FLUXER_SEAWEEDFS_UPLOADS_TTL:-1d", "FLUXER_SEAWEEDFS_UPLOADS_TTL:-2d", 1)
+ })
+ if !uploadsChange(inst, recoveryFrom, init, &next) {
+ t.Error("a new seaweedfs-init definition doesn't count as an uploads change")
+ }
+ bumped := next
+ bumped.Images.Refs = map[string]string{}
+ for k, v := range next.Images.Refs {
+ bumped.Images.Refs[k] = v
+ }
+ bumped.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
+ if !uploadsChange(inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &bumped) {
+ t.Error("a new seaweedfs image doesn't count as an uploads change")
+ }
+ if !uploadsChange(inst, "2026.0101.000000", testSet(t, recoveryRexctl, nil), &next) {
+ t.Error("a release without saved files doesn't fall back to a full backup")
+ }
+
+ lean := &upgradeFlags{Backup: backup.ScopeWithoutUploads}
+ if f := backupFlagsFor(r.app, inst, recoveryFrom, testSet(t, recoveryRexctl, nil), &next, lean, "2026.1025"); f != lean || strings.Contains(r.out.String(), "changes how uploads are stored") {
+ t.Errorf("an upgrade that keeps the uploads services got %+v and printed %q", f, r.out.String())
+ }
+ f := backupFlagsFor(r.app, inst, recoveryFrom, changed, &next, lean, "2026.1025")
+ if upgradeScope(f) != backup.ScopeFull || upgradeScope(lean) != backup.ScopeWithoutUploads {
+ t.Fatalf("an upgrade that changes uploads backs up with %s", upgradeScope(f))
+ }
+ if !strings.Contains(r.out.String(), "Fluxer 2026.1025 changes how uploads are stored. This backup includes them.") {
+ t.Errorf("the forced full backup printed %q", r.out.String())
+ }
+ var scopes []string
+ prevCreate, prevEstimate := createBackup, estimateBackup
+ t.Cleanup(func() { createBackup, estimateBackup = prevCreate, prevEstimate })
+ estimateBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, scope string) (uint64, error) {
+ scopes = append(scopes, "estimate "+scope)
+ return 0, nil
+ }
+ createBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, o backup.CreateOptions) (*backup.Info, error) {
+ scopes = append(scopes, "create "+o.Scope)
+ return nil, backup.ErrNeverStarted
+ }
+ upgradeSpace(context.Background(), r.app, inst, r.app.engine, next.Images.Refs, f)
+ if err := backUpForUpgrade(context.Background(), r.app, inst, r.app.engine.Named(inst.Project(), inst.Dir), upgradeScope(f)); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{"estimate full", "create full"}; !slices.Equal(scopes, want) {
+ t.Errorf("the forced full backup ran %q, want %q", scopes, want)
+ }
+ scopes = nil
+ upgradeSpace(context.Background(), r.app, inst, r.app.engine, next.Images.Refs, lean)
+ if want := []string{"estimate without-uploads"}; !slices.Equal(scopes, want) {
+ t.Errorf("a lean upgrade estimates %q, want %q", scopes, want)
+ }
+}
+
+func TestLeanBackupVerifyFailureAbortsUpgrade(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ inst.State.Upgrade.Phase = release.PhasePulled
+ bad := filepath.Join(t.TempDir(), "broken"+backup.Extension)
+ prev := createBackup
+ t.Cleanup(func() { createBackup = prev })
+ var got backup.CreateOptions
+ createBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, o backup.CreateOptions) (*backup.Info, error) {
+ got = o
+ if err := os.WriteFile(bad, []byte("not a backup"), 0o600); err != nil {
+ return nil, err
+ }
+ return &backup.Info{Path: bad, Release: recoveryFrom, Scope: backup.ScopeWithoutUploads}, nil
+ }
+ err := backUpForUpgrade(context.Background(), r.app, inst, r.app.engine.Named(inst.Project(), inst.Dir), backup.ScopeWithoutUploads)
+ if err == nil {
+ t.Fatal("a backup that fails its check let the upgrade go on")
+ }
+ if got.Scope != backup.ScopeWithoutUploads || got.Reason != "upgrade" {
+ t.Errorf("Create got %+v", got)
+ }
+ if inst.State.Upgrade.Backup != "" {
+ t.Errorf("the broken backup was recorded as %s", inst.State.Upgrade.Backup)
+ }
+ if fileExists(bad) {
+ t.Error("the broken backup was left on disk")
+ }
+ if inst.State.Upgrade.Phase != release.PhasePulled {
+ t.Errorf("phase = %s, want %s", inst.State.Upgrade.Phase, release.PhasePulled)
+ }
+}
+
+func TestReexecKeepsBackupFlag(t *testing.T) {
+ args := resumeArgs([]string{"upgrade", "--yes", "--backup", "without-uploads", "--dir", "/opt/fluxer"}, release.PhaseSelfUpdated, "")
+ if i := slices.Index(args, "--backup"); i < 0 || i+1 >= len(args) || args[i+1] != "without-uploads" {
+ t.Errorf("resume args = %q", args)
+ }
+ r := newRecoveryRun(t, recoveryLatest)
+ prevArgs := os.Args
+ t.Cleanup(func() { os.Args = prevArgs })
+ os.Args = []string{"rexctl", "upgrade", "--yes", "--backup=without-uploads"}
+ var handed []string
+ reexec = func(args []string) error {
+ handed = args
+ return nil
+ }
+ if err := runUpgrade(context.Background(), r.app, &upgradeFlags{Backup: backup.ScopeWithoutUploads}); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(handed, "--backup=without-uploads") || !slices.Contains(handed, release.ResumeRecovery) {
+ t.Errorf("rexctl started again with %q", handed)
+ }
+}
+
+func TestBackupFlagConflictsWithNoBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ for _, f := range []upgradeFlags{
+ {Backup: backup.ScopeWithoutUploads, NoBackup: true},
+ {Backup: backup.ScopeFull, NoBackup: true},
+ {Backup: backup.ScopeWithoutUploads, Check: true},
+ {Backup: backup.ScopeWithoutUploads, Prefetch: true},
+ {Backup: backup.ScopeFull, Prefetch: true},
+ {Backup: "uploads"},
+ } {
+ err := runUpgrade(context.Background(), r.app, &f)
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitUsage {
+ t.Errorf("runUpgrade(%+v) = %v, want a usage error", f, err)
+ }
+ }
+}
+
+func TestSwitchingRexctlBackDropsBackupFlag(t *testing.T) {
+ r := newRecoveryRun(t, "2026.1022.100000")
+ r.app.UI = ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: r.out, Stderr: r.out, Yes: true})
+ inst, err := instance.Find(r.dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Upgrade = nil
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ scheduled := 0
+ prevDrop := dropScheduledBackup
+ t.Cleanup(func() { dropScheduledBackup = prevDrop })
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ scheduled++
+ return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
+ }
+ prevArgs := os.Args
+ t.Cleanup(func() { os.Args = prevArgs })
+ for _, args := range [][]string{
+ {"rexctl", "upgrade", "--to", "2026.1022.100000", "--backup", "without-uploads", "--yes"},
+ {"rexctl", "upgrade", "--to", "2026.1022.100000", "--backup=without-uploads", "--yes"},
+ } {
+ os.Args = args
+ var handed []string
+ reexec = func(args []string) error {
+ handed = args
+ return nil
+ }
+ r.out.Reset()
+ if err := runUpgrade(context.Background(), r.app, &upgradeFlags{To: "2026.1022.100000", Backup: backup.ScopeWithoutUploads}); err != nil {
+ t.Fatalf("%q: %v", args, err)
+ }
+ if handed == nil || slices.ContainsFunc(handed, func(a string) bool { return strings.HasPrefix(a, "--backup") }) || slices.Contains(handed, "without-uploads") {
+ t.Errorf("%q started the older rexctl with %q", args, handed)
+ }
+ if !slices.Contains(handed, "--to") || !slices.Contains(handed, release.PhaseSelfUpdated) {
+ t.Errorf("%q lost other flags, started with %q", args, handed)
+ }
+ for _, want := range []string{"This upgrade makes a full backup.", "Automatic upgrades make full backups from now on as well.", "Switched rexctl back to"} {
+ if !strings.Contains(r.out.String(), want) {
+ t.Errorf("%q printed %q, want %q", args, r.out.String(), want)
+ }
+ }
+ inst, err := instance.Find(r.dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Upgrade = nil
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if scheduled != 2 {
+ t.Errorf("the schedule was checked %d times, want 2", scheduled)
+ }
+}
+
+func TestSwitchBackRefusesWhenScheduleCantChange(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ prevDrop := dropScheduledBackup
+ t.Cleanup(func() { dropScheduledBackup = prevDrop })
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{}, false, host.ErrNeedsRoot
+ }
+ _, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022")
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !strings.Contains(ee.Fix, "sudo") {
+ t.Errorf("switchBack = %v, want a refusal that asks for root", err)
+ }
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{}, false, nil
+ }
+ r.out.Reset()
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
+ }
+ if _, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil || !strings.Contains(r.out.String(), "rexctl 2026.1022 may not know --backup. Automatic upgrades make full backups from now on.") {
+ t.Errorf("switchBack without --backup = %v, printed %q", err, r.out.String())
+ }
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{}, false, nil
+ }
+ r.out.Reset()
+ args, err := switchBack(context.Background(), r.app, nil, nil, []string{"upgrade", "--backup", "full", "--to", "2026.1022.100000"}, "2026.1022")
+ if err != nil || slices.Contains(args, "--backup") || strings.Contains(r.out.String(), "full backup") {
+ t.Errorf("switchBack with --backup full = %q, %v, printed %q", args, err, r.out.String())
+ }
+}
+
+func TestSwitchBackKeepsTheWholeSchedule(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
+ prevDrop := dropScheduledBackup
+ t.Cleanup(func() { dropScheduledBackup = prevDrop })
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, Day: "Sun", At: "03:30", Backup: backup.ScopeWithoutUploads, FullBackup: host.FullBackupMonthly}, true, nil
+ }
+ if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--backup", "without-uploads", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
+ t.Fatal(err)
+ }
+ out := r.out.String()
+ for _, want := range []string{
+ "run rexctl auto-upgrade on --day sun --at 03:30 --backup without-uploads --full-backup monthly again.",
+ "Add --notify with your address to that command to keep the notifications.",
+ "The monthly full backup keeps running. rexctl 2026.1022 doesn't know about it, and rexctl auto-upgrade off from rexctl 2026.1022 leaves it on.",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("switchBack printed %q, want %q", out, want)
+ }
+ }
+ r.out.Reset()
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeFull, FullBackup: host.FullBackupMonthly}, false, nil
+ }
+ if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
+ t.Fatal(err)
+ }
+ if out := r.out.String(); !strings.Contains(out, "The monthly full backup keeps running.") || strings.Contains(out, "--notify") {
+ t.Errorf("switchBack with full backups before upgrades printed %q", out)
+ }
+ r.out.Reset()
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, At: autoUpgradeDefault, Backup: backup.ScopeWithoutUploads}, true, nil
+ }
+ inst.State.NotifyURL = ""
+ if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--backup", "without-uploads", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
+ t.Fatal(err)
+ }
+ if out := r.out.String(); !strings.Contains(out, "run rexctl auto-upgrade on --backup without-uploads again.") || strings.Contains(out, "monthly") || strings.Contains(out, "weekly") {
+ t.Errorf("switchBack with a daily schedule printed %q", out)
+ }
+}
+
+func TestSwitchBackWarnsAboutWeeklySchedule(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ inst.State.NotifyURL = "https://ntfy.sh/fluxer-upgrades"
+ prevDrop := dropScheduledBackup
+ t.Cleanup(func() { dropScheduledBackup = prevDrop })
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, Day: "Sun", At: autoUpgradeDefault, Backup: backup.ScopeFull, FullBackup: host.FullBackupMonthly}, false, nil
+ }
+ if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
+ t.Fatal(err)
+ }
+ out := r.out.String()
+ for _, want := range []string{
+ "rexctl 2026.1022 shows this weekly schedule as every day, and it keeps running every Sunday. Once rexctl is newer than 2026.1022, run rexctl auto-upgrade to see it again.",
+ "rexctl auto-upgrade on from rexctl 2026.1022 makes the schedule daily. Once rexctl is newer than 2026.1022, run rexctl auto-upgrade on --day sun --full-backup monthly to make it weekly again.",
+ "Add --notify with your address to that command to keep the notifications.",
+ "The monthly full backup keeps running.",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("switchBack with a weekly schedule and full backups printed %q, want %q", out, want)
+ }
+ }
+ r.out.Reset()
+ dropScheduledBackup = func(context.Context, *instance.Instance, *engine.Engine) (host.AutoUpgradeState, bool, error) {
+ return host.AutoUpgradeState{On: true, Day: "Sun", At: "03:30", Backup: backup.ScopeWithoutUploads}, true, nil
+ }
+ if _, err := switchBack(context.Background(), r.app, inst, nil, []string{"upgrade", "--to", "2026.1022.100000"}, "2026.1022"); err != nil {
+ t.Fatal(err)
+ }
+ out = r.out.String()
+ if !strings.Contains(out, "run rexctl auto-upgrade on --day sun --at 03:30 --backup without-uploads again.") || !strings.Contains(out, "it keeps running every Sunday") || strings.Contains(out, "makes the schedule daily") || strings.Count(out, "--notify") != 1 {
+ t.Errorf("switchBack with a weekly lean schedule printed %q", out)
+ }
+}
+
+func TestDryRunShowsForcedFullBackup(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Images = instance.Images{Release: recoveryFrom, Refs: maps.Clone(images.Images)}
+ if _, err := secrets.Mint(inst.State.Secrets, false); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
+ t.Fatal(err)
+ }
+ var scopes []string
+ prevEstimate := estimateBackup
+ t.Cleanup(func() { estimateBackup = prevEstimate })
+ estimateBackup = func(_ context.Context, _ *instance.Instance, _ *engine.Project, scope string) (uint64, error) {
+ scopes = append(scopes, scope)
+ return 0, nil
+ }
+ lean := &upgradeFlags{Backup: backup.ScopeWithoutUploads, DryRun: true}
+ version := stack.Embedded().Release
+ printUpgradePlan(context.Background(), r.app, inst, lean, false, recoveryFrom, version)
+ if out := r.out.String(); !strings.Contains(out, "backed up first, without uploads") || strings.Contains(out, "changes how uploads are stored") || !slices.Equal(scopes, []string{backup.ScopeWithoutUploads}) {
+ t.Errorf("a dry run that keeps seaweedfs estimated %q and printed %q", scopes, out)
+ }
+ r.out.Reset()
+ scopes = nil
+ inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:3.1"
+ printUpgradePlan(context.Background(), r.app, inst, lean, false, recoveryFrom, version)
+ out := r.out.String()
+ if !strings.Contains(out, "changes how uploads are stored. The backup before it includes them.") || strings.Contains(out, "without uploads") || !strings.Contains(out, "Your instance is backed up first.") {
+ t.Errorf("a dry run with a new seaweedfs printed %q", out)
+ }
+ if !slices.Equal(scopes, []string{backup.ScopeFull}) {
+ t.Errorf("a dry run with a new seaweedfs estimated %q, want a full backup", scopes)
+ }
+ r.out.Reset()
+ scopes = nil
+ printUpgradePlan(context.Background(), r.app, inst, lean, true, recoveryFrom, recoveryLatest)
+ if !slices.Equal(scopes, []string{backup.ScopeWithoutUploads, backup.ScopeWithoutUploads, backup.ScopeFull}) {
+ t.Errorf("a dry run that updates rexctl first estimated %q, want both scopes", scopes)
+ }
+ if out := r.out.String(); !strings.Contains(out, "without uploads unless Fluxer") {
+ t.Errorf("a dry run that updates rexctl first printed %q", out)
+ }
+}
+
+func TestRollbackDryRunChecksUploads(t *testing.T) {
+ r := newRecoveryRun(t, "")
+ inst := recoveryInstance(t, r)
+ inst.State.Upgrade = nil
+ uploads := t.TempDir()
+ if err := os.WriteFile(filepath.Join(uploads, backup.UploadsIDFile), []byte("made-again\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.WriteRelease(inst, testSet(t, recoveryFrom, nil)); err != nil {
+ t.Fatal(err)
+ }
+ set, err := release.LoadSet(inst, recoveryFrom)
+ if err != nil {
+ t.Fatal(err)
+ }
+ day := time.Date(2026, 10, 25, 4, 0, 0, 0, time.UTC)
+ ref := &backup.UploadsRef{Bind: uploads, ID: "made-before", Definition: backup.UploadsDefinition(set, inst.State)}
+ if ref.Definition == "" {
+ t.Fatal("no uploads definition for the test release")
+ }
+ made := writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: recoveryFrom, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: day, Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Uploads: ref, Volumes: []string{}})
+ inst.State.PreviousRelease, inst.State.PreviousBackup = recoveryFrom, made
+ err = rollbackWithBackup(context.Background(), r.app, inst, nil, &rollbackFlags{DryRun: true, RestoreDB: true}, recoveryFrom, "2026.1020")
+ var ee *ui.ExitError
+ var why *backup.UploadsNotHereError
+ if !errors.As(err, &ee) || ee.Code != ui.ExitRefused || !errors.As(err, &why) || !strings.Contains(why.Why, "made again") {
+ t.Errorf("a dry run with uploads made again returned %v (%v)", err, why)
+ }
+ if strings.Contains(r.out.String(), "Uploads stay as they are") {
+ t.Errorf("the dry run promised a restore without uploads: %q", r.out.String())
+ }
+ if err := os.WriteFile(filepath.Join(uploads, backup.UploadsIDFile), []byte("made-before\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ ref.Inode = uploadsInode(t, uploads)
+ made = writeManifestBackup(t, inst, backup.Manifest{Format: backup.FormatVersion, Release: recoveryFrom, Project: inst.Project(), Domain: inst.Domain(), CreatedAt: day.Add(time.Minute), Reason: "upgrade", Scope: backup.ScopeWithoutUploads, Uploads: ref, Volumes: []string{}})
+ inst.State.PreviousBackup = made
+ r.out.Reset()
+ if err := rollbackWithBackup(context.Background(), r.app, inst, nil, &rollbackFlags{DryRun: true, RestoreDB: true}, recoveryFrom, "2026.1020"); err != nil {
+ t.Fatalf("a dry run with the uploads in place returned %v", err)
+ }
+ out := r.out.String()
+ if !strings.Contains(out, "Messages and changes since then are lost. Uploads stay as they are.") || strings.Contains(out, "Anything that changed") {
+ t.Errorf("the dry run of a restore without uploads says %q", out)
+ }
+}
diff --git a/fluxer_rexctl/internal/backup/archive.go b/fluxer_rexctl/internal/backup/archive.go
index c0862e93a..70171fd32 100644
--- a/fluxer_rexctl/internal/backup/archive.go
+++ b/fluxer_rexctl/internal/backup/archive.go
@@ -85,7 +85,10 @@ func (w *archiveWriter) addBytes(name string, mode int64, data []byte) error {
}
func (w *archiveWriter) finish(m *Manifest) error {
- m.Format = FormatVersion
+ m.Format = formatFull
+ if m.WithoutUploads() {
+ m.Format = FormatVersion
+ }
m.Entries = append([]Entry{}, w.entries...)
if m.Volumes == nil {
m.Volumes = []string{}
diff --git a/fluxer_rexctl/internal/backup/backup.go b/fluxer_rexctl/internal/backup/backup.go
index c2f1361a6..1c5b9671f 100644
--- a/fluxer_rexctl/internal/backup/backup.go
+++ b/fluxer_rexctl/internal/backup/backup.go
@@ -14,7 +14,8 @@ import (
)
const (
- FormatVersion = 1
+ FormatVersion = 2
+ formatFull = 1
Extension = ".tar.zst"
ManifestName = "manifest.json"
SumsName = "SHA256SUMS"
@@ -41,6 +42,12 @@ const (
SkippedUploads = "uploads"
)
+const (
+ ScopeFull = "full"
+ ScopeWithoutUploads = "without-uploads"
+ UploadsVolume = "seaweedfs-data"
+)
+
var (
ErrNotBackup = errors.New("backup: not a rexctl backup")
ErrDamaged = errors.New("backup: damaged")
@@ -54,16 +61,31 @@ type Entry struct {
}
type Manifest struct {
- Format int `json:"format"`
- Release string `json:"release"`
- Project string `json:"project"`
- Domain string `json:"domain"`
- CreatedAt time.Time `json:"created_at"`
- Reason string `json:"reason,omitempty"`
- Database string `json:"database"`
- Volumes []string `json:"volumes"`
- Skipped []string `json:"skipped,omitempty"`
- Entries []Entry `json:"entries"`
+ Format int `json:"format"`
+ Release string `json:"release"`
+ Project string `json:"project"`
+ Domain string `json:"domain"`
+ CreatedAt time.Time `json:"created_at"`
+ Reason string `json:"reason,omitempty"`
+ Database string `json:"database"`
+ Volumes []string `json:"volumes"`
+ Skipped []string `json:"skipped,omitempty"`
+ Scope string `json:"scope,omitempty"`
+ Uploads *UploadsRef `json:"uploads,omitempty"`
+ Entries []Entry `json:"entries"`
+}
+
+type UploadsRef struct {
+ Volume string `json:"volume,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ Bind string `json:"bind,omitempty"`
+ ID string `json:"id,omitempty"`
+ Inode uint64 `json:"inode,omitempty"`
+ Definition string `json:"definition,omitempty"`
+}
+
+func (m *Manifest) WithoutUploads() bool {
+ return m.Scope == ScopeWithoutUploads
}
func (m *Manifest) HasSkipped(what string) bool {
@@ -75,7 +97,31 @@ type Info struct {
Path string `json:"path"`
CreatedAt time.Time `json:"created_at"`
Release string `json:"release"`
+ Reason string `json:"reason,omitempty"`
+ Scope string `json:"scope,omitempty"`
SizeBytes int64 `json:"size_bytes"`
+ Domain string `json:"-"`
+ Project string `json:"-"`
+}
+
+func (b Info) WithoutUploads() bool {
+ return b.Scope == ScopeWithoutUploads
+}
+
+func Stat(path string) (*Info, error) {
+ m, err := ReadManifest(path)
+ if err != nil {
+ return nil, err
+ }
+ fi, err := os.Stat(path)
+ if err != nil {
+ return nil, err
+ }
+ return infoFor(path, m, fi.Size()), nil
+}
+
+func infoFor(path string, m *Manifest, size int64) *Info {
+ return &Info{File: filepath.Base(path), Path: path, CreatedAt: m.CreatedAt, Release: m.Release, Reason: m.Reason, Scope: m.Scope, SizeBytes: size, Domain: m.Domain, Project: m.Project}
}
func List(dir string) ([]Info, error) {
@@ -101,7 +147,7 @@ func List(dir string) ([]Info, error) {
if err != nil {
continue
}
- out = append(out, Info{File: name, Path: path, CreatedAt: m.CreatedAt, Release: m.Release, SizeBytes: fi.Size()})
+ out = append(out, *infoFor(path, m, fi.Size()))
}
sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) })
return out, nil
@@ -121,6 +167,32 @@ func NewestOf(list []Info, release string) *Info {
return best
}
+func NewestWithUploads(list []Info) *Info {
+ var best *Info
+ for i := range list {
+ b := &list[i]
+ if b.WithoutUploads() {
+ continue
+ }
+ if best == nil || b.CreatedAt.After(best.CreatedAt) {
+ best = b
+ }
+ }
+ return best
+}
+
+func Find(list []Info, path string) *Info {
+ if path == "" {
+ return nil
+ }
+ for i := range list {
+ if samePath(list[i].Path, path) {
+ return &list[i]
+ }
+ }
+ return nil
+}
+
func Prune(dir string, keep int, protect ...string) ([]Info, error) {
list, err := List(dir)
if err != nil || keep <= 0 || len(list) <= keep {
diff --git a/fluxer_rexctl/internal/backup/create.go b/fluxer_rexctl/internal/backup/create.go
index 20267232d..ce0333cf8 100644
--- a/fluxer_rexctl/internal/backup/create.go
+++ b/fluxer_rexctl/internal/backup/create.go
@@ -7,6 +7,8 @@ import (
"bufio"
"bytes"
"context"
+ "crypto/rand"
+ "encoding/hex"
"errors"
"fmt"
"io"
@@ -23,6 +25,7 @@ import (
"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/host"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
@@ -40,6 +43,7 @@ var ErrNeverStarted = errors.New("backup: Fluxer has never run and has no data y
type CreateOptions struct {
Reason string
+ Scope string
Progress func(stage string)
OnEvent func(engine.Event)
}
@@ -111,7 +115,7 @@ func Create(ctx context.Context, inst *instance.Instance, p *engine.Project, opt
if !bundledDB {
m.Skipped = append(m.Skipped, SkippedDatabase)
}
- volumes, err := volumesToCopy(ctx, inst, values, p, model, m)
+ volumes, err := volumesToCopy(ctx, inst, values, p, model, m, opts.Scope, true)
if err != nil {
return nil, err
}
@@ -193,7 +197,7 @@ func Create(ctx context.Context, inst *instance.Instance, p *engine.Project, opt
if err != nil {
return nil, err
}
- return &Info{File: filepath.Base(final), Path: final, CreatedAt: now, Release: m.Release, SizeBytes: fi.Size()}, nil
+ return infoFor(final, m, fi.Size()), nil
}
func syncDir(dir string) {
@@ -282,25 +286,107 @@ func boundData(model *types.Project, short string) string {
return ""
}
-func volumesToCopy(ctx context.Context, inst *instance.Instance, values map[string]string, p *engine.Project, model *types.Project, m *Manifest) ([]volumeRef, error) {
- skipUploads := externalUploads(inst, values)
- if skipUploads {
- m.Skipped = append(m.Skipped, SkippedUploads)
- }
+func volumesToCopy(ctx context.Context, inst *instance.Instance, values map[string]string, p *engine.Project, model *types.Project, m *Manifest, scope string, mark bool) ([]volumeRef, error) {
have, err := p.Engine.Volumes(ctx, p.Name)
if err != nil {
return nil, err
}
+ definition := ""
+ if scope == ScopeWithoutUploads {
+ definition = uploadsDefinition(inst)
+ }
+ return pickVolumes(model, p.Name, have, externalUploads(inst, values), scope, definition, mark, m), nil
+}
+
+func pickVolumes(model *types.Project, project string, have []engine.Volume, skipUploads bool, scope, definition string, mark bool, m *Manifest) []volumeRef {
+ if skipUploads {
+ m.Skipped = append(m.Skipped, SkippedUploads)
+ }
var out []volumeRef
for _, short := range stack.BackupVolumes {
- if skipUploads && short == "seaweedfs-data" {
+ v, ok := dataVolume(model, project, have, short)
+ if short == UploadsVolume && ok && !skipUploads && scope == ScopeWithoutUploads && definition != "" {
+ if ref := uploadsRef(v, have, mark); ref != nil {
+ ref.Definition = definition
+ m.Scope, m.Uploads = ScopeWithoutUploads, ref
+ continue
+ }
+ }
+ if skipUploads && short == UploadsVolume {
continue
}
- if v, ok := dataVolume(model, p.Name, have, short); ok {
+ if ok {
out = append(out, v)
}
}
- return out, nil
+ return out
+}
+
+const UploadsIDFile = ".rexctl-uploads-id"
+
+func uploadsRef(v volumeRef, have []engine.Volume, mark bool) *UploadsRef {
+ if v.bind != "" {
+ ino, ok := fileInode(v.bind)
+ if !ok {
+ return nil
+ }
+ id, err := bindID(v.bind, mark)
+ if err != nil || (mark && id == "") {
+ return nil
+ }
+ return &UploadsRef{Bind: v.bind, ID: id, Inode: ino}
+ }
+ ref := &UploadsRef{Volume: v.full}
+ for _, h := range have {
+ if h.Name == v.full {
+ ref.CreatedAt = h.CreatedAt
+ }
+ }
+ return ref
+}
+
+func UploadsDefinition(set *stack.Set, st *instance.State) string {
+ def, err := stack.ServicesDefinition(set, stack.OverlaysFor(st.Settings), st.Images.Refs, stack.UploadsServices...)
+ if err != nil {
+ return ""
+ }
+ return stack.Hash([]byte(settings.ImageRef(st.Settings, st.Images.Refs, "seaweedfs") + "\n" + def))
+}
+
+func uploadsDefinition(inst *instance.Instance) string {
+ if inst == nil || inst.State == nil {
+ return ""
+ }
+ set, err := release.LoadSet(inst, inst.State.Release)
+ if err != nil {
+ if set, err = inst.Set(); err != nil {
+ return ""
+ }
+ }
+ return UploadsDefinition(set, inst.State)
+}
+
+func bindID(dir string, create bool) (string, error) {
+ path := filepath.Join(dir, UploadsIDFile)
+ data, err := os.ReadFile(path)
+ if err == nil && strings.TrimSpace(string(data)) != "" {
+ return strings.TrimSpace(string(data)), nil
+ }
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return "", err
+ }
+ if !create {
+ return "", nil
+ }
+ raw := make([]byte, 16)
+ if _, err := rand.Read(raw); err != nil {
+ return "", err
+ }
+ id := hex.EncodeToString(raw)
+ if err := envfile.WriteFileAtomic(path, []byte(id+"\n"), false); err != nil {
+ return "", err
+ }
+ return id, nil
}
func findVolume(vols []engine.Volume, project, short string) (string, bool) {
@@ -372,10 +458,10 @@ func (e *HelperError) Error() string {
func (e *HelperError) Unwrap() error { return e.Err }
-func Estimate(ctx context.Context, inst *instance.Instance, p *engine.Project) (uint64, error) {
+func Estimate(ctx context.Context, inst *instance.Instance, p *engine.Project, scope string) (uint64, error) {
values := instanceValues(inst)
model := projectModel(ctx, inst, p)
- volumes, err := volumesToCopy(ctx, inst, values, p, model, &Manifest{})
+ volumes, err := volumesToCopy(ctx, inst, values, p, model, &Manifest{}, scope, false)
if err != nil {
return 0, err
}
@@ -796,6 +882,10 @@ func relayVolume(spool *volumeSpool, short string, tr *tar.Reader) (int64, error
}
inner := strings.TrimPrefix(strings.TrimPrefix(hdr.Name, "./"), "/")
inner = strings.TrimSuffix(inner, "/")
+ if short == UploadsVolume && inner == UploadsIDFile && hdr.Typeflag == tar.TypeReg {
+ copied += hdr.Size
+ continue
+ }
name := VolumesPrefix + short
if inner != "" && inner != "." {
name += "/" + inner
diff --git a/fluxer_rexctl/internal/backup/fileid_unix.go b/fluxer_rexctl/internal/backup/fileid_unix.go
new file mode 100644
index 000000000..5a094ba16
--- /dev/null
+++ b/fluxer_rexctl/internal/backup/fileid_unix.go
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+//go:build !windows
+
+package backup
+
+import (
+ "os"
+ "syscall"
+)
+
+func fileInode(path string) (uint64, bool) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return 0, false
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, true
+ }
+ return uint64(st.Ino), true
+}
diff --git a/fluxer_rexctl/internal/backup/fileid_windows.go b/fluxer_rexctl/internal/backup/fileid_windows.go
new file mode 100644
index 000000000..14e37caa7
--- /dev/null
+++ b/fluxer_rexctl/internal/backup/fileid_windows.go
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package backup
+
+import "os"
+
+func fileInode(path string) (uint64, bool) {
+ _, err := os.Stat(path)
+ return 0, err == nil
+}
diff --git a/fluxer_rexctl/internal/backup/restore.go b/fluxer_rexctl/internal/backup/restore.go
index 0a735d21c..4401677a1 100644
--- a/fluxer_rexctl/internal/backup/restore.go
+++ b/fluxer_rexctl/internal/backup/restore.go
@@ -6,6 +6,7 @@ import (
"archive/tar"
"bytes"
"context"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -28,6 +29,16 @@ const postgresReadyTimeout = 3 * time.Minute
var errStop = errors.New("backup: stop")
+var ErrUploadsNotHere = errors.New("backup: the uploads this backup belongs with aren't on this machine")
+
+type UploadsNotHereError struct {
+ Why string
+}
+
+func (e *UploadsNotHereError) Error() string { return ErrUploadsNotHere.Error() + ": " + e.Why }
+
+func (e *UploadsNotHereError) Unwrap() error { return ErrUploadsNotHere }
+
type RestoreOptions struct {
Progress func(stage string)
OnEvent func(engine.Event)
@@ -82,6 +93,9 @@ func Restore(ctx context.Context, path, dir string, e *engine.Engine, opts Resto
if err != nil && !errors.Is(err, instance.ErrNotFound) {
return nil, err
}
+ if err := CheckUploadsInPlace(ctx, dir, existing, e, m); err != nil {
+ return nil, err
+ }
if err := checkProjectFree(ctx, e, m.Project, dir); err != nil {
return nil, err
}
@@ -92,18 +106,9 @@ func Restore(ctx context.Context, path, dir string, e *engine.Engine, opts Resto
}
progress(StageClearing)
- var stale []string
- if existing != nil {
- if existing.State != nil {
- stale = slices.Collect(maps.Values(existing.State.Images.Refs))
- }
- stale = append(stale, release.KeptImages(existing)...)
- if err := e.Named(existing.Project(), existing.Dir).Down(ctx, true); err != nil {
- return nil, err
- }
- if err := clearInstanceFiles(dir); err != nil {
- return nil, err
- }
+ stale, err := clearForRestore(ctx, dir, existing, e, m)
+ if err != nil {
+ return nil, err
}
progress(StageFiles)
@@ -133,7 +138,7 @@ func Restore(ctx context.Context, path, dir string, e *engine.Engine, opts Resto
if err != nil {
return nil, &RestoreError{Part: "containers", Err: err}
}
- if err := p.Down(ctx, true); err != nil {
+ if err := down(ctx, p, m); err != nil {
return nil, err
}
if err := p.Create(ctx); err != nil {
@@ -167,10 +172,181 @@ func Restore(ctx context.Context, path, dir string, e *engine.Engine, opts Resto
if _, err := deploy.Apply(ctx, inst, e, deploy.ApplyOptions{}); err != nil {
return nil, err
}
+ if err := os.Remove(restoreMarkerPath(dir)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
removeStaleImages(ctx, p, stale)
return inst, nil
}
+func clearForRestore(ctx context.Context, dir string, existing *instance.Instance, e *engine.Engine, m *Manifest) ([]string, error) {
+ if existing == nil {
+ return nil, nil
+ }
+ var stale []string
+ if existing.State != nil {
+ stale = slices.Collect(maps.Values(existing.State.Images.Refs))
+ }
+ stale = append(stale, release.KeptImages(existing)...)
+ if m.WithoutUploads() {
+ if err := writeRestoreMarker(dir, m, e); err != nil {
+ return nil, err
+ }
+ }
+ if err := down(ctx, e.Named(existing.Project(), existing.Dir), m); err != nil {
+ return nil, err
+ }
+ if err := clearInstanceFiles(dir); err != nil {
+ return nil, err
+ }
+ return stale, nil
+}
+
+var downProject = func(ctx context.Context, p *engine.Project, keep []string) error {
+ if len(keep) > 0 {
+ return p.DownKeeping(ctx, keep...)
+ }
+ return p.Down(ctx, true)
+}
+
+func down(ctx context.Context, p *engine.Project, m *Manifest) error {
+ return downProject(ctx, p, keptVolumes(m))
+}
+
+const restoreMarkerName = "restoring-without-uploads.json"
+
+type restoreMarker struct {
+ Project string `json:"project"`
+ Domain string `json:"domain"`
+ Engine instance.EngineRef `json:"engine"`
+ Uploads UploadsRef `json:"uploads"`
+}
+
+func restoreMarkerPath(dir string) string {
+ return filepath.Join(dir, instance.StateDirName, restoreMarkerName)
+}
+
+func writeRestoreMarker(dir string, m *Manifest, e *engine.Engine) error {
+ data, err := json.Marshal(restoreMarker{Project: m.Project, Domain: m.Domain, Engine: instance.EngineRef{Kind: string(e.Kind), Host: e.Host, ID: e.ID}, Uploads: *m.Uploads})
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(restoreMarkerPath(dir)), 0o700); err != nil {
+ return err
+ }
+ return envfile.WriteFileAtomic(restoreMarkerPath(dir), data, true)
+}
+
+func ResumesRestore(dir string, m *Manifest) bool {
+ mk := readRestoreMarker(dir)
+ return mk != nil && m.Uploads != nil && mk.Project == m.Project && mk.Domain == m.Domain && mk.Uploads == *m.Uploads
+}
+
+func readRestoreMarker(dir string) *restoreMarker {
+ if dir == "" {
+ return nil
+ }
+ data, err := os.ReadFile(restoreMarkerPath(dir))
+ if err != nil {
+ return nil
+ }
+ var mk restoreMarker
+ if json.Unmarshal(data, &mk) != nil {
+ return nil
+ }
+ return &mk
+}
+
+func keptVolumes(m *Manifest) []string {
+ if m.WithoutUploads() {
+ return []string{UploadsVolume}
+ }
+ return nil
+}
+
+func CheckUploadsInPlace(ctx context.Context, dir string, existing *instance.Instance, e *engine.Engine, m *Manifest) error {
+ if existing != nil {
+ if err := os.Remove(restoreMarkerPath(dir)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ }
+ if !m.WithoutUploads() {
+ return nil
+ }
+ var vols []engine.Volume
+ if m.Uploads != nil && m.Uploads.Bind == "" && e != nil && (existing != nil || ResumesRestore(dir, m)) {
+ var err error
+ if vols, err = e.Volumes(ctx, m.Project); err != nil {
+ return err
+ }
+ }
+ return uploadsInPlace(dir, existing, e, vols, m)
+}
+
+func uploadsInPlace(dir string, existing *instance.Instance, e *engine.Engine, vols []engine.Volume, m *Manifest) error {
+ refuse := func(why string) error { return &UploadsNotHereError{Why: why} }
+ if existing == nil && ResumesRestore(dir, m) {
+ mk := readRestoreMarker(dir)
+ switch {
+ case e == nil:
+ return refuse("no engine to check the uploads on")
+ case movesEngine(mk.Engine, e):
+ return refuse("the restore moves the instance to another engine")
+ }
+ return uploadsIdentity(m.Uploads, vols)
+ }
+ switch {
+ case existing == nil || existing.State == nil:
+ return refuse("there is no instance here")
+ case m.Project != existing.Project() || m.Domain != existing.Domain():
+ return refuse(fmt.Sprintf("the backup is for %s and the instance here is %s", m.Domain, existing.Domain()))
+ case e == nil:
+ return refuse("no engine to check the uploads on")
+ case movesEngine(existing.State.Engine, e):
+ return refuse("the restore moves the instance to another engine")
+ case m.Uploads == nil:
+ return refuse("the backup doesn't record which uploads it belongs with")
+ case m.Uploads.Definition == "" || m.Uploads.Definition != uploadsDefinition(existing):
+ return refuse("the uploads here were written by another version of the uploads service")
+ }
+ return uploadsIdentity(m.Uploads, vols)
+}
+
+func uploadsIdentity(u *UploadsRef, vols []engine.Volume) error {
+ refuse := func(why string) error { return &UploadsNotHereError{Why: why} }
+ if u.Bind != "" {
+ ino, ok := fileInode(u.Bind)
+ if !ok {
+ return refuse(u.Bind + " is missing")
+ }
+ id, err := bindID(u.Bind, false)
+ if err != nil {
+ return refuse("couldn't read " + filepath.Join(u.Bind, UploadsIDFile))
+ }
+ if u.ID == "" || id != u.ID || ino != u.Inode {
+ return refuse(u.Bind + " was made again since the backup")
+ }
+ return nil
+ }
+ for _, v := range vols {
+ if v.Name != u.Volume {
+ continue
+ }
+ if v.CreatedAt != u.CreatedAt {
+ return refuse("volume " + u.Volume + " was made again since the backup")
+ }
+ return nil
+ }
+ return refuse("volume " + u.Volume + " is missing")
+}
+
+func movesEngine(was instance.EngineRef, e *engine.Engine) bool {
+ if was.Kind != "" && was.Kind != string(e.Kind) {
+ return true
+ }
+ return was.ID != "" && e.ID != "" && was.ID != e.ID
+}
+
func adoptRestored(inst *instance.Instance, e *engine.Engine) error {
st := inst.State
if st == nil {
@@ -187,6 +363,11 @@ func adoptRestored(inst *instance.Instance, e *engine.Engine) error {
st.PreviousRelease = ""
}
}
+ if st.PreviousBackup != "" {
+ if _, err := os.Stat(st.PreviousBackup); err != nil || st.PreviousRelease == "" {
+ st.PreviousBackup = ""
+ }
+ }
rendered, err := renderRestored(inst)
if err != nil {
return err
@@ -434,6 +615,7 @@ func restoreData(ctx context.Context, path string, p *engine.Project, image stri
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var sink *volumeSink
+ uploadsBind := ""
closeSink := func(failed error) error {
if sink == nil {
return failed
@@ -461,6 +643,9 @@ func restoreData(ctx context.Context, path string, p *engine.Project, image stri
if !ok {
return &RestoreError{Part: short, Err: errors.New("the volume wasn't created")}
}
+ if short == UploadsVolume && v.bind != "" {
+ uploadsBind = v.bind
+ }
pr, pw := io.Pipe()
s := &volumeSink{name: short, pw: pw, tw: tar.NewWriter(pw), done: make(chan error, 1), out: &bytes.Buffer{}}
go func() {
@@ -539,9 +724,23 @@ func restoreData(ctx context.Context, path string, p *engine.Project, image stri
return nil
})
if err != nil {
- return closeSink(err)
+ err = closeSink(err)
+ } else {
+ err = closeSink(nil)
+ }
+ if uploadsBind != "" {
+ if ferr := forgetUploadsID(uploadsBind); err == nil {
+ err = ferr
+ }
+ }
+ return err
+}
+
+func forgetUploadsID(bind string) error {
+ if err := os.Remove(filepath.Join(bind, UploadsIDFile)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return &RestoreError{Part: UploadsVolume, Err: err}
}
- return closeSink(nil)
+ return nil
}
func restoreDump(ctx context.Context, p *engine.Project, r io.Reader) error {
diff --git a/fluxer_rexctl/internal/backup/scope_test.go b/fluxer_rexctl/internal/backup/scope_test.go
new file mode 100644
index 000000000..b67ddd5a5
--- /dev/null
+++ b/fluxer_rexctl/internal/backup/scope_test.go
@@ -0,0 +1,627 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package backup
+
+import (
+ "archive/tar"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "maps"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/compose-spec/compose-go/v2/types"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"
+)
+
+const (
+ uploadsCreated = "2026-10-01T04:00:00Z"
+ testDefinition = "sha256:uploads"
+)
+
+func projectVolumes() []engine.Volume {
+ var out []engine.Volume
+ for _, short := range []string{"postgres-data", "valkey-data", "nats-data", "meilisearch-data", UploadsVolume} {
+ out = append(out, engine.Volume{Name: "fluxer_" + short, Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": short}, CreatedAt: uploadsCreated})
+ }
+ return out
+}
+
+func shorts(vols []volumeRef) []string {
+ var out []string
+ for _, v := range vols {
+ out = append(out, v.short)
+ }
+ return out
+}
+
+func TestWithoutUploadsLeavesSeaweedOut(t *testing.T) {
+ m := &Manifest{}
+ got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, m))
+ if slices.Contains(got, UploadsVolume) || !slices.Equal(got, []string{"valkey-data", "nats-data", "meilisearch-data"}) {
+ t.Errorf("a backup without uploads copies %v", got)
+ }
+ if m.Scope != ScopeWithoutUploads || m.Uploads == nil || m.Uploads.Volume != "fluxer_seaweedfs-data" || m.Uploads.CreatedAt != uploadsCreated {
+ t.Errorf("manifest = %+v, uploads %+v", m, m.Uploads)
+ }
+ if m.HasSkipped(SkippedUploads) {
+ t.Error("leaving uploads out on purpose was recorded as uploads stored outside Fluxer")
+ }
+ if m.Uploads.Definition != testDefinition {
+ t.Errorf("the backup records the uploads service as %q", m.Uploads.Definition)
+ }
+ unknown := &Manifest{}
+ if got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, "", true, unknown)); !slices.Contains(got, UploadsVolume) || unknown.WithoutUploads() {
+ t.Errorf("without a known uploads service the backup copies %v with scope %q", got, unknown.Scope)
+ }
+ full := &Manifest{}
+ if got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeFull, testDefinition, true, full)); !slices.Contains(got, UploadsVolume) || full.Scope != "" || full.Uploads != nil {
+ t.Errorf("a full backup copies %v with scope %q", got, full.Scope)
+ }
+ none := &Manifest{}
+ pickVolumes(nil, "fluxer", projectVolumes()[:4], false, ScopeWithoutUploads, testDefinition, true, none)
+ if none.Scope != "" {
+ t.Error("an instance without an uploads volume made a backup that can't restore on its own")
+ }
+}
+
+func writeScoped(t *testing.T, m *Manifest) string {
+ t.Helper()
+ final := filepath.Join(t.TempDir(), "fluxer-test"+Extension)
+ w, err := createArchive(final + PartialSuffix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.finish(m); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(final+PartialSuffix, final); err != nil {
+ t.Fatal(err)
+ }
+ return final
+}
+
+func TestWithoutUploadsWritesFormatTwo(t *testing.T) {
+ path := writeScoped(t, &Manifest{Project: "fluxer", Domain: "chat.example.com", CreatedAt: time.Now().UTC(), Scope: ScopeWithoutUploads, Uploads: &UploadsRef{Volume: "fluxer_seaweedfs-data", CreatedAt: uploadsCreated}})
+ m, err := Verify(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m.Format != 2 || !m.WithoutUploads() || m.Uploads.Volume != "fluxer_seaweedfs-data" {
+ t.Errorf("manifest = %+v", m)
+ }
+ info, err := Stat(path)
+ if err != nil || !info.WithoutUploads() {
+ t.Errorf("Stat = %+v, %v", info, err)
+ }
+ if _, err := parseManifest([]byte(`{"format":3,"release":"x"}`)); !errors.Is(err, ErrNewer) {
+ t.Errorf("format 3 = %v, want ErrNewer", err)
+ }
+}
+
+func TestFullBackupStaysFormatOne(t *testing.T) {
+ path := writeScoped(t, &Manifest{Project: "fluxer", Domain: "chat.example.com", CreatedAt: time.Now().UTC()})
+ m, err := ReadManifest(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m.Format != 1 || m.Scope != "" || m.Uploads != nil {
+ t.Errorf("manifest = %+v", m)
+ }
+}
+
+func TestEstimateAndCreatePickTheSameVolumes(t *testing.T) {
+ lean := pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, &Manifest{})
+ full := pickVolumes(nil, "fluxer", projectVolumes(), false, ScopeFull, "", true, &Manifest{})
+ if len(full)-len(lean) != 1 || slices.Contains(shorts(lean), UploadsVolume) {
+ t.Errorf("the estimate measures %v without uploads and %v with them", shorts(lean), shorts(full))
+ }
+}
+
+func TestExternalUploadsStillMarkedSkipped(t *testing.T) {
+ for _, scope := range []string{ScopeFull, ScopeWithoutUploads} {
+ m := &Manifest{}
+ got := shorts(pickVolumes(nil, "fluxer", projectVolumes(), true, scope, testDefinition, true, m))
+ if slices.Contains(got, UploadsVolume) || !m.HasSkipped(SkippedUploads) || m.Scope != "" || m.Uploads != nil {
+ t.Errorf("%s with external uploads copies %v with manifest %+v", scope, got, m)
+ }
+ }
+}
+
+func leanInstance(t *testing.T) *instance.Instance {
+ t.Helper()
+ inst, err := instance.Create(t.TempDir(), "fluxer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Settings["FLUXER_DOMAIN"] = "chat.example.com"
+ inst.State.Engine = instance.EngineRef{Kind: "docker", ID: "engine-1"}
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ return inst
+}
+
+func leanManifest(inst *instance.Instance) *Manifest {
+ return &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: &UploadsRef{Volume: "fluxer_seaweedfs-data", CreatedAt: uploadsCreated, Definition: uploadsDefinition(inst)}}
+}
+
+var dockerEngine = &engine.Engine{Kind: engine.Docker, ID: "engine-1"}
+
+func recordDown(t *testing.T) *[]string {
+ t.Helper()
+ var calls []string
+ prev := downProject
+ t.Cleanup(func() { downProject = prev })
+ downProject = func(_ context.Context, p *engine.Project, keep []string) error {
+ calls = append(calls, p.Name+" keeping "+strings.Join(keep, ","))
+ return nil
+ }
+ return &calls
+}
+
+func TestRestoreWithoutUploadsKeepsUploadsVolume(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m); err != nil {
+ t.Fatalf("the instance the backup was made for refused it with %v", err)
+ }
+ calls := recordDown(t)
+ if _, err := clearForRestore(context.Background(), inst.Dir, inst, dockerEngine, m); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{"fluxer keeping " + UploadsVolume}; !slices.Equal(*calls, want) {
+ t.Errorf("a restore without uploads ran %q, want %q", *calls, want)
+ }
+ *calls = nil
+ full := leanInstance(t)
+ if _, err := clearForRestore(context.Background(), full.Dir, full, dockerEngine, &Manifest{Project: "fluxer"}); err != nil {
+ t.Fatal(err)
+ }
+ if want := []string{"fluxer keeping "}; !slices.Equal(*calls, want) {
+ t.Errorf("a full restore ran %q, want %q", *calls, want)
+ }
+ if _, err := os.Stat(restoreMarkerPath(full.Dir)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("a full restore left a marker (%v)", err)
+ }
+}
+
+func TestRestoreWithoutUploadsLeavesUploadsDataAlone(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ m.Volumes = []string{"valkey-data"}
+ final := filepath.Join(t.TempDir(), "fluxer-test"+Extension)
+ w, err := createArchive(final + PartialSuffix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.addBytes(VolumesPrefix+UploadsVolume+"/1.dat", 0o644, []byte("volume")); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.finish(m); err != nil {
+ t.Fatal(err)
+ }
+ err = restoreData(context.Background(), final+PartialSuffix, &engine.Project{Name: "fluxer"}, "helper", m, projectVolumes(), "", func(string) {})
+ if !errors.Is(err, ErrDamaged) {
+ t.Errorf("restoring uploads data from a backup without uploads gave %v, want ErrDamaged", err)
+ }
+}
+
+func TestRestoreWithoutUploadsRefusesNewerUploadsService(t *testing.T) {
+ inst := leanInstance(t)
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Images.Refs = maps.Clone(images.Images)
+ onB := leanManifest(inst)
+ if onB.Uploads.Definition == "" {
+ t.Fatal("the uploads service of release B has no definition")
+ }
+ if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB); err != nil {
+ t.Fatalf("the same seaweedfs was refused with %v", err)
+ }
+ inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
+ refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB), "a backup from before a new seaweedfs")
+ onB.Uploads.Definition = ""
+ refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), onB), "a backup that doesn't record the uploads service")
+}
+
+func TestRestoreWithoutUploadsRefusesSeaweedImageSetting(t *testing.T) {
+ inst := leanInstance(t)
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Images.Refs = maps.Clone(images.Images)
+ m := leanManifest(inst)
+ inst.State.Settings["images.seaweedfs"] = "chrislusf/seaweedfs:99.1"
+ refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m), "a backup from before images.seaweedfs was set")
+ delete(inst.State.Settings, "images.seaweedfs")
+ inst.State.Settings["FLUXER_SEAWEEDFS_IMAGE"] = "chrislusf/seaweedfs:99.1"
+ refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m), "a backup from before FLUXER_SEAWEEDFS_IMAGE was set")
+ delete(inst.State.Settings, "FLUXER_SEAWEEDFS_IMAGE")
+ if err := uploadsInPlace(inst.Dir, inst, dockerEngine, projectVolumes(), m); err != nil {
+ t.Errorf("the same seaweedfs image was refused with %v", err)
+ }
+}
+
+func TestLeanRestoreCanRunAgainAfterFailing(t *testing.T) {
+ inst := leanInstance(t)
+ uploads := filepath.Join(inst.Dir, "uploads")
+ if err := os.Mkdir(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ m := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
+ path := writeScoped(t, m)
+ recordDown(t)
+ if _, err := clearForRestore(context.Background(), inst.Dir, inst, dockerEngine, m); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := instance.Find(inst.Dir); !errors.Is(err, instance.ErrNotFound) {
+ t.Fatalf("after clearing, Find = %v", err)
+ }
+ if err := CheckUploadsInPlace(context.Background(), inst.Dir, nil, dockerEngine, m); err != nil {
+ t.Errorf("running the same restore again was refused with %v", err)
+ }
+ if !ResumesRestore(inst.Dir, m) {
+ t.Error("the restore that was cut short isn't recognised")
+ }
+ if err := uploadsInPlace(inst.Dir, nil, &engine.Engine{Kind: engine.Podman, ID: "engine-1"}, nil, m); err == nil {
+ t.Error("running it again on another engine was allowed")
+ }
+ other := *m
+ otherRef := *m.Uploads
+ otherRef.Definition = "sha256:other"
+ other.Uploads = &otherRef
+ refused(t, uploadsInPlace(inst.Dir, nil, dockerEngine, nil, &other), "another backup without uploads")
+ if err := os.RemoveAll(uploads); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsInPlace(inst.Dir, nil, dockerEngine, nil, m), "the same restore with the uploads gone")
+ if err := os.Remove(restoreMarkerPath(inst.Dir)); err != nil {
+ t.Fatal(err)
+ }
+ _, err := Restore(context.Background(), path, inst.Dir, dockerEngine, RestoreOptions{})
+ refused(t, err, "a restore without the marker or the state")
+}
+
+func TestRestoreWithoutUploadsKeepsBindMount(t *testing.T) {
+ inst := leanInstance(t)
+ uploads := filepath.Join(inst.Dir, "uploads")
+ if err := os.MkdirAll(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(uploads, "a.bin"), []byte("attachment"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
+ m := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
+ got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, m))
+ if slices.Contains(got, UploadsVolume) || m.Uploads == nil || m.Uploads.Bind != uploads {
+ t.Fatalf("volumes %v, uploads %+v", got, m.Uploads)
+ }
+ if m.Uploads.ID == "" {
+ t.Fatal("the backup doesn't record which uploads folder it belongs with")
+ }
+ if err := uploadsInPlace("", inst, dockerEngine, nil, m); err != nil {
+ t.Fatalf("the bind mount the backup was made with was refused with %v", err)
+ }
+ again := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
+ pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, again)
+ if again.Uploads == nil || again.Uploads.ID != m.Uploads.ID {
+ t.Errorf("a second backup records %+v, want the same identity as %+v", again.Uploads, m.Uploads)
+ }
+ if err := clearInstanceFiles(inst.Dir); err != nil {
+ t.Fatal(err)
+ }
+ if data, err := os.ReadFile(filepath.Join(uploads, "a.bin")); err != nil || string(data) != "attachment" {
+ t.Errorf("clearing the instance touched the uploads, which hold %q (%v)", data, err)
+ }
+ if err := os.RemoveAll(uploads); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsInPlace("", inst, dockerEngine, nil, m), "an uploads folder removed and made again")
+ recreated := *m.Uploads
+ recreated.Inode, _ = fileInode(uploads)
+ refused(t, uploadsIdentity(&recreated, nil), "a folder made again with the same inode")
+ if err := os.WriteFile(filepath.Join(uploads, UploadsIDFile), []byte("someone-else\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsIdentity(&recreated, nil), "a folder with another identity")
+}
+
+func TestBindMountIdentityIgnoresDeviceNumber(t *testing.T) {
+ inst := leanInstance(t)
+ uploads := filepath.Join(inst.Dir, "uploads")
+ if err := os.MkdirAll(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
+ m := &Manifest{Project: inst.Project(), Domain: inst.Domain()}
+ pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, uploadsDefinition(inst), true, m)
+ if m.Uploads == nil || m.Uploads.ID == "" {
+ t.Fatalf("uploads %+v", m.Uploads)
+ }
+ data, err := json.Marshal(m.Uploads)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(data), `"dev"`) {
+ t.Errorf("the backup records the device number of the uploads folder in %s", data)
+ }
+ var afterReboot UploadsRef
+ moved := strings.Replace(string(data), "{", `{"dev":4242,`, 1)
+ if err := json.Unmarshal([]byte(moved), &afterReboot); err != nil {
+ t.Fatal(err)
+ }
+ if err := uploadsIdentity(&afterReboot, nil); err != nil {
+ t.Errorf("the same folder with another device number was refused with %v", err)
+ }
+ otherInode := *m.Uploads
+ otherInode.Inode++
+ refused(t, uploadsIdentity(&otherInode, nil), "the same identity file in another folder")
+}
+
+func TestEstimateDoesNotMarkBindMount(t *testing.T) {
+ uploads := t.TempDir()
+ model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
+ got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, false, &Manifest{}))
+ if slices.Contains(got, UploadsVolume) {
+ t.Errorf("the estimate for a bind mount copies %v", got)
+ }
+ if _, err := os.Stat(filepath.Join(uploads, UploadsIDFile)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("the estimate wrote %s (%v)", UploadsIDFile, err)
+ }
+}
+
+func TestBindMountWithoutIdentityGetsFullBackup(t *testing.T) {
+ uploads := t.TempDir()
+ if err := os.Mkdir(filepath.Join(uploads, UploadsIDFile), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ model := &types.Project{Services: types.Services{"seaweedfs": {Name: "seaweedfs", Volumes: []types.ServiceVolumeConfig{{Type: types.VolumeTypeBind, Source: uploads, Target: "/data"}}}}}
+ m := &Manifest{}
+ got := shorts(pickVolumes(model, "fluxer", projectVolumes(), false, ScopeWithoutUploads, testDefinition, true, m))
+ if !slices.Contains(got, UploadsVolume) || m.WithoutUploads() {
+ t.Errorf("a bind mount rexctl can't mark copies %v with scope %q", got, m.Scope)
+ }
+}
+
+func refused(t *testing.T, err error, what string) {
+ t.Helper()
+ var ue *UploadsNotHereError
+ if !errors.Is(err, ErrUploadsNotHere) || !errors.As(err, &ue) {
+ t.Errorf("%s gave %v, want a refusal", what, err)
+ }
+}
+
+func TestRestoreWithoutUploadsRefusesNewMachine(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ refused(t, uploadsInPlace("", nil, dockerEngine, nil, m), "no instance")
+ path := writeScoped(t, m)
+ fresh := filepath.Join(t.TempDir(), "fluxer")
+ _, err := Restore(context.Background(), path, fresh, dockerEngine, RestoreOptions{})
+ refused(t, err, "Restore on a new machine")
+ if _, err := os.Stat(fresh); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("the refused restore made %s", fresh)
+ }
+ if err := CheckUploadsInPlace(context.Background(), "", nil, nil, &Manifest{}); err != nil {
+ t.Errorf("a full backup was refused with %v", err)
+ }
+}
+
+func TestRestoreWithoutUploadsRefusesOtherInstance(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ m.Domain = "other.example.com"
+ refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes(), m), "another domain")
+ m = leanManifest(inst)
+ m.Project = "blue"
+ refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes(), m), "another project")
+}
+
+func TestRestoreWithoutUploadsRefusesReplacedVolume(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ vols := projectVolumes()
+ vols[4].CreatedAt = "2026-11-02T09:00:00Z"
+ refused(t, uploadsInPlace("", inst, dockerEngine, vols, m), "a volume made again")
+ refused(t, uploadsInPlace("", inst, dockerEngine, projectVolumes()[:4], m), "a missing volume")
+
+ root := t.TempDir()
+ uploads := filepath.Join(root, "uploads")
+ if err := os.Mkdir(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ b := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
+ if err := uploadsInPlace("", inst, dockerEngine, nil, b); err != nil {
+ t.Fatalf("the same folder was refused with %v", err)
+ }
+ if err := os.Rename(uploads, filepath.Join(root, "old")); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsInPlace("", inst, dockerEngine, nil, b), "a missing folder")
+ if err := os.Mkdir(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsInPlace("", inst, dockerEngine, nil, b), "a folder made again")
+}
+
+func bindRef(t *testing.T, dir, definition string) *UploadsRef {
+ t.Helper()
+ ref := uploadsRef(volumeRef{short: UploadsVolume, bind: dir}, nil, true)
+ if ref == nil || ref.ID == "" {
+ t.Fatalf("no identity for %s: %+v", dir, ref)
+ }
+ ref.Definition = definition
+ return ref
+}
+
+func TestRestoreWithoutUploadsRefusesEngineMove(t *testing.T) {
+ inst := leanInstance(t)
+ m := leanManifest(inst)
+ refused(t, uploadsInPlace("", inst, &engine.Engine{Kind: engine.Podman, ID: "engine-1"}, projectVolumes(), m), "another kind of engine")
+ refused(t, uploadsInPlace("", inst, &engine.Engine{Kind: engine.Docker, ID: "engine-2"}, projectVolumes(), m), "another engine")
+ refused(t, uploadsInPlace("", inst, nil, projectVolumes(), m), "no engine")
+}
+
+func TestRestoreForgetsBackupOfAMissingRelease(t *testing.T) {
+ inst := leanInstance(t)
+ kept := filepath.Join(inst.BackupDir(), "fluxer-a"+Extension)
+ if err := os.WriteFile(kept, []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ inst.State.PreviousRelease, inst.State.PreviousBackup = "2026.1001.100000", kept
+ if err := adoptRestored(inst, dockerEngine); err != nil {
+ t.Fatal(err)
+ }
+ if inst.State.PreviousRelease != "" || inst.State.PreviousBackup != "" {
+ t.Errorf("after the restore the previous release is %q and the previous backup %q", inst.State.PreviousRelease, inst.State.PreviousBackup)
+ }
+}
+
+func TestLeftoverRestoreMarkerKeepsUploadsServiceCheck(t *testing.T) {
+ inst := leanInstance(t)
+ images, err := stack.EmbeddedImages()
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.Images.Refs = maps.Clone(images.Images)
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ uploads := filepath.Join(inst.Dir, "uploads")
+ if err := os.Mkdir(uploads, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ m := &Manifest{Project: inst.Project(), Domain: inst.Domain(), Scope: ScopeWithoutUploads, Uploads: bindRef(t, uploads, uploadsDefinition(inst))}
+ if err := writeRestoreMarker(inst.Dir, m, dockerEngine); err != nil {
+ t.Fatal(err)
+ }
+ if err := uploadsInPlace(inst.Dir, inst, dockerEngine, nil, m); err != nil {
+ t.Fatalf("the same backup after a failed restore was refused with %v", err)
+ }
+ inst.State.Images.Refs["seaweedfs"] = "chrislusf/seaweedfs:99.1"
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsInPlace(inst.Dir, inst, dockerEngine, nil, m), "a leftover marker with a newer seaweedfs")
+ refused(t, CheckUploadsInPlace(context.Background(), inst.Dir, inst, dockerEngine, m), "the check with a leftover marker and a newer seaweedfs")
+ if _, err := os.Stat(restoreMarkerPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("the check left the marker in place (%v)", err)
+ }
+ if err := writeRestoreMarker(inst.Dir, m, dockerEngine); err != nil {
+ t.Fatal(err)
+ }
+ path := writeScoped(t, m)
+ _, err = Restore(context.Background(), path, inst.Dir, dockerEngine, RestoreOptions{})
+ refused(t, err, "Restore with a leftover marker and a newer seaweedfs")
+ if _, err := os.Stat(restoreMarkerPath(inst.Dir)); !errors.Is(err, os.ErrNotExist) {
+ t.Errorf("the leftover marker is still there (%v)", err)
+ }
+}
+
+func TestFullRestoreGivesBindUploadsNewIdentity(t *testing.T) {
+ uploads := t.TempDir()
+ if err := os.WriteFile(filepath.Join(uploads, "new.bin"), []byte("after the full backup"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ lean := bindRef(t, uploads, testDefinition)
+ idFile := filepath.Join(uploads, UploadsIDFile)
+ ents, err := os.ReadDir(uploads)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range ents {
+ if err := os.RemoveAll(filepath.Join(uploads, e.Name())); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(idFile, []byte(lean.ID+"\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(uploads, "old.bin"), []byte("from the full backup"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := forgetUploadsID(uploads); err != nil {
+ t.Fatal(err)
+ }
+ refused(t, uploadsIdentity(lean, nil), "a newer backup without uploads after a full restore")
+ again := bindRef(t, uploads, testDefinition)
+ if again.ID == lean.ID {
+ t.Error("the next backup without uploads kept the identity from before the full restore")
+ }
+ if err := forgetUploadsID(t.TempDir()); err != nil {
+ t.Errorf("a folder without an identity gave %v", err)
+ }
+}
+
+func TestVolumeCopyLeavesUploadsIdentityOut(t *testing.T) {
+ var src bytes.Buffer
+ tw := tar.NewWriter(&src)
+ for _, e := range []struct{ name, body string }{{"./" + UploadsIDFile, "abc\n"}, {"./a.bin", "attachment"}} {
+ if err := tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o644, Size: int64(len(e.body)), Typeflag: tar.TypeReg}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write([]byte(e.body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ for _, short := range []string{UploadsVolume, "valkey-data"} {
+ path := filepath.Join(t.TempDir(), "spool")
+ s, err := createSpool(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ copied, err := relayVolume(s, short, tar.NewReader(bytes.NewReader(src.Bytes())))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.finish(); err != nil {
+ t.Fatal(err)
+ }
+ if copied != int64(len("abc\n")+len("attachment")) {
+ t.Errorf("%s counted %d bytes", short, copied)
+ }
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ tr := tar.NewReader(bytes.NewReader(raw))
+ for {
+ hdr, err := tr.Next()
+ if err != nil {
+ break
+ }
+ names = append(names, hdr.Name)
+ }
+ stored := slices.Contains(names, VolumesPrefix+short+"/"+UploadsIDFile)
+ if stored != (short != UploadsVolume) {
+ t.Errorf("%s stored %v", short, names)
+ }
+ }
+}
diff --git a/fluxer_rexctl/internal/engine/api.go b/fluxer_rexctl/internal/engine/api.go
index 2571fdefc..eb7ef27e5 100644
--- a/fluxer_rexctl/internal/engine/api.go
+++ b/fluxer_rexctl/internal/engine/api.go
@@ -149,6 +149,7 @@ type Volume struct {
Labels map[string]string
Mountpoint string
Device string
+ CreatedAt string
}
type ProjectInfo struct {
diff --git a/fluxer_rexctl/internal/engine/apply.go b/fluxer_rexctl/internal/engine/apply.go
index b1a4675c4..b619d1a78 100644
--- a/fluxer_rexctl/internal/engine/apply.go
+++ b/fluxer_rexctl/internal/engine/apply.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/compose-spec/compose-go/v2/types"
+ cerrdefs "github.com/containerd/errdefs"
"github.com/docker/compose/v5/pkg/api"
"github.com/moby/moby/client"
)
@@ -359,6 +360,56 @@ func (p *Project) Down(ctx context.Context, volumes bool) error {
return p.wrap("down", c.svc.Down(ctx, p.Name, api.DownOptions{Project: p.modelOrNil(), RemoveOrphans: true, Volumes: volumes}))
}
+func (p *Project) DownKeeping(ctx context.Context, keep ...string) error {
+ if err := p.Down(ctx, false); err != nil {
+ return err
+ }
+ vols, err := p.Engine.Volumes(ctx, p.Name)
+ if err != nil {
+ return err
+ }
+ a, err := p.Engine.api()
+ if err != nil {
+ return err
+ }
+ for _, name := range volumesToDrop(p.Model, vols, p.Name, keep) {
+ if _, err := a.VolumeRemove(ctx, name, client.VolumeRemoveOptions{}); err != nil && !cerrdefs.IsNotFound(err) {
+ return p.wrap("down", err)
+ }
+ }
+ return nil
+}
+
+func volumesToDrop(model *types.Project, vols []Volume, project string, keep []string) []string {
+ var kept, out []string
+ if model != nil {
+ for short, v := range model.Volumes {
+ if slices.Contains(keep, short) {
+ kept = append(kept, v.Name)
+ }
+ }
+ for short, v := range model.Volumes {
+ if !bool(v.External) && v.Name != "" && !slices.Contains(keep, short) && !slices.Contains(kept, v.Name) {
+ out = append(out, v.Name)
+ }
+ }
+ }
+ for _, v := range vols {
+ if v.Project != project || slices.Contains(kept, v.Name) {
+ continue
+ }
+ short := v.Labels[api.VolumeLabel]
+ if short == "" {
+ short = strings.TrimPrefix(v.Name, project+"_")
+ }
+ if !slices.Contains(keep, short) {
+ out = append(out, v.Name)
+ }
+ }
+ slices.Sort(out)
+ return slices.Compact(out)
+}
+
func (p *Project) modelOrNil() *types.Project {
if p.Model == nil {
return nil
diff --git a/fluxer_rexctl/internal/engine/down_test.go b/fluxer_rexctl/internal/engine/down_test.go
new file mode 100644
index 000000000..1a5d3b690
--- /dev/null
+++ b/fluxer_rexctl/internal/engine/down_test.go
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package engine
+
+import (
+ "slices"
+ "testing"
+
+ "github.com/compose-spec/compose-go/v2/types"
+)
+
+func TestDownKeepingRemovesOtherVolumes(t *testing.T) {
+ label := func(short string) map[string]string { return map[string]string{"com.docker.compose.volume": short} }
+ vols := []Volume{
+ {Name: "fluxer_postgres-data", Project: "fluxer", Labels: label("postgres-data")},
+ {Name: "fluxer_seaweedfs-data", Project: "fluxer", Labels: label("seaweedfs-data")},
+ {Name: "fluxer_meilisearch-data", Project: "fluxer", Labels: label("meilisearch-data")},
+ {Name: "custom-uploads", Project: "fluxer", Labels: label("seaweedfs-data")},
+ {Name: "fluxer_valkey-data", Project: "fluxer", Labels: map[string]string{}},
+ {Name: "fluxer_seaweedfs-old", Project: "", Labels: map[string]string{}},
+ {Name: "blue_postgres-data", Project: "blue", Labels: label("postgres-data")},
+ }
+ got := volumesToDrop(nil, vols, "fluxer", []string{"seaweedfs-data"})
+ want := []string{"fluxer_meilisearch-data", "fluxer_postgres-data", "fluxer_valkey-data"}
+ if !slices.Equal(got, want) {
+ t.Errorf("volumesToDrop = %v, want %v", got, want)
+ }
+ if got := volumesToDrop(nil, vols, "fluxer", nil); len(got) != 5 {
+ t.Errorf("keeping nothing drops %v", got)
+ }
+}
+
+func TestDownKeepingRemovesUnlabelledModelVolumes(t *testing.T) {
+ model := &types.Project{Name: "fluxer", Volumes: types.Volumes{
+ "postgres-data": {Name: "fluxer_postgres-data"},
+ "seaweedfs-data": {Name: "fluxer_seaweedfs-data"},
+ "edge-data": {Name: "fluxer_edge-data"},
+ "edge-config": {Name: "fluxer_edge-config"},
+ "shared": {Name: "shared", External: true},
+ }}
+ unlabelled := map[string]string{}
+ vols := []Volume{
+ {Name: "fluxer_edge-config", Labels: unlabelled},
+ {Name: "fluxer_edge-data", Labels: unlabelled},
+ {Name: "fluxer_postgres-data", Labels: unlabelled},
+ {Name: "fluxer_seaweedfs-data", Labels: unlabelled},
+ {Name: "shared", Labels: unlabelled},
+ }
+ got := volumesToDrop(model, vols, "fluxer", []string{"seaweedfs-data"})
+ want := []string{"fluxer_edge-config", "fluxer_edge-data", "fluxer_postgres-data"}
+ if !slices.Equal(got, want) {
+ t.Errorf("volumesToDrop = %v, want %v", got, want)
+ }
+ renamed := &types.Project{Name: "fluxer", Volumes: types.Volumes{
+ "postgres-data": {Name: "fluxer_postgres-data"},
+ "seaweedfs-data": {Name: "custom-uploads"},
+ }}
+ labelled := []Volume{
+ {Name: "custom-uploads", Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": "uploads-old"}},
+ {Name: "fluxer_postgres-data", Project: "fluxer", Labels: map[string]string{"com.docker.compose.volume": "postgres-data"}},
+ }
+ if got := volumesToDrop(renamed, labelled, "fluxer", []string{"seaweedfs-data"}); !slices.Equal(got, []string{"fluxer_postgres-data"}) {
+ t.Errorf("volumesToDrop with a renamed uploads volume = %v", got)
+ }
+}
diff --git a/fluxer_rexctl/internal/engine/ps.go b/fluxer_rexctl/internal/engine/ps.go
index f461060ed..f4af62876 100644
--- a/fluxer_rexctl/internal/engine/ps.go
+++ b/fluxer_rexctl/internal/engine/ps.go
@@ -120,7 +120,7 @@ func (e *Engine) Volumes(ctx context.Context, project string) ([]Volume, error)
if labels == nil {
labels = map[string]string{}
}
- out = append(out, Volume{Name: v.Name, Project: labels[api.ProjectLabel], Labels: labels, Mountpoint: v.Mountpoint, Device: v.Options["device"]})
+ out = append(out, Volume{Name: v.Name, Project: labels[api.ProjectLabel], Labels: labels, Mountpoint: v.Mountpoint, Device: v.Options["device"], CreatedAt: v.CreatedAt})
}
slices.SortFunc(out, func(a, b Volume) int { return strings.Compare(a.Name, b.Name) })
return out, nil
diff --git a/fluxer_rexctl/internal/host/autoupgrade.go b/fluxer_rexctl/internal/host/autoupgrade.go
index 44d08d8bd..aa3f65379 100644
--- a/fluxer_rexctl/internal/host/autoupgrade.go
+++ b/fluxer_rexctl/internal/host/autoupgrade.go
@@ -34,6 +34,19 @@ const (
const UpgradeWindow = 30 * time.Minute
+const BackupFull = "full"
+
+const FullBackupMonthly = "monthly"
+
+const fullBackupLead = 3 * 60
+
+const fullBackupLog = "full-backup.log"
+
+const (
+ minutesPerDay = 24 * 60
+ minutesPerWeek = 7 * minutesPerDay
+)
+
func UpgradeScheduler() Scheduler {
if BootUnitSupported() {
return Systemd
@@ -48,25 +61,33 @@ func UpgradeScheduler() Scheduler {
}
type AutoUpgrade struct {
- Scheduler Scheduler
- Project string
- Domain string
- Dir string
- Binary string
- Podman bool
- Rootless bool
- At string
- Log string
+ Scheduler Scheduler
+ Project string
+ Domain string
+ Dir string
+ Binary string
+ Podman bool
+ Rootless bool
+ At string
+ Day string
+ Backup string
+ FullBackup string
+ Log string
}
type AutoUpgradeState struct {
- On bool
- At string
- Next string
- Last string
- Ran bool
- ExitCode int
- Running bool
+ On bool
+ At string
+ Day string
+ Backup string
+ FullBackup string
+ FullBackupRan bool
+ FullBackupAt string
+ Next string
+ Last string
+ Ran bool
+ ExitCode int
+ Running bool
}
func (a AutoUpgrade) name() string { return a.Project + "-upgrade" }
@@ -75,6 +96,25 @@ func (a AutoUpgrade) ServiceName() string { return a.name() + ".service" }
func (a AutoUpgrade) TimerName() string { return a.name() + ".timer" }
+func (a AutoUpgrade) backupName() string { return a.Project + "-backup" }
+
+func (a AutoUpgrade) BackupServiceName() string { return a.backupName() + ".service" }
+
+func (a AutoUpgrade) BackupTimerName() string { return a.backupName() + ".timer" }
+
+func (a AutoUpgrade) BackupLog() string { return filepath.Join(filepath.Dir(a.Log), fullBackupLog) }
+
+func (a AutoUpgrade) BackupPaths() ([]string, error) {
+ if a.Scheduler == Cron {
+ return []string{filepath.Join(cronDir, a.backupName())}, nil
+ }
+ dir, err := unitDir(a.Rootless)
+ if err != nil {
+ return nil, err
+ }
+ return []string{filepath.Join(dir, a.BackupServiceName()), filepath.Join(dir, a.BackupTimerName())}, nil
+}
+
func (a AutoUpgrade) Paths() ([]string, error) {
if a.Scheduler == Cron {
return []string{filepath.Join(cronDir, a.name())}, nil
@@ -107,27 +147,111 @@ func (a AutoUpgrade) clock() (int, int, error) {
return t.Hour(), t.Minute(), nil
}
-func (a AutoUpgrade) start() (int, int, error) {
+func (a AutoUpgrade) weekday() (int, error) {
+ if a.Day == "" {
+ return -1, nil
+ }
+ if d, ok := Weekday(a.Day); ok {
+ return d, nil
+ }
+ return 0, fmt.Errorf("host: %q is not a day of the week", a.Day)
+}
+
+func (a AutoUpgrade) start() (int, int, int, error) {
hour, minute, err := a.clock()
+ if err != nil {
+ return 0, 0, 0, err
+ }
+ day, err := a.weekday()
if err != nil || a.Scheduler != Cron {
- return hour, minute, err
+ return day, hour, minute, err
+ }
+ offset := a.cronOffset()
+ if day < 0 {
+ m := (hour*60 + minute + offset) % minutesPerDay
+ return day, m / 60, m % 60, nil
}
+ m := (day*minutesPerDay + hour*60 + minute + offset) % minutesPerWeek
+ return m / minutesPerDay, m % minutesPerDay / 60, m % 60, nil
+}
+
+func (a AutoUpgrade) cronOffset() int {
h := fnv.New32a()
h.Write([]byte(a.Domain + "\x00" + a.Project + "\x00" + a.Dir))
- m := (hour*60 + minute + int(h.Sum32()%uint32(UpgradeWindow.Minutes()))) % (24 * 60)
- return m / 60, m % 60, nil
+ return int(h.Sum32() % uint32(UpgradeWindow.Minutes()))
}
-func (a AutoUpgrade) Start() (string, error) {
- hour, minute, err := a.start()
+func (a AutoUpgrade) Requested(day, at string) (string, string) {
+ if a.Scheduler != Cron {
+ return day, at
+ }
+ t, err := time.Parse("15:04", at)
if err != nil {
- return "", err
+ return day, at
+ }
+ m := t.Hour()*60 + t.Minute() - a.cronOffset()
+ d, weekly := Weekday(day)
+ if !weekly {
+ m = (m + minutesPerDay) % minutesPerDay
+ return "", fmt.Sprintf("%02d:%02d", m/60, m%60)
+ }
+ m = (d*minutesPerDay + m + minutesPerWeek) % minutesPerWeek
+ return dayName(m / minutesPerDay), fmt.Sprintf("%02d:%02d", m%minutesPerDay/60, m%60)
+}
+
+func (a AutoUpgrade) Start() (string, string, error) {
+ day, hour, minute, err := a.start()
+ if err != nil {
+ return "", "", err
+ }
+ return dayName(day), fmt.Sprintf("%02d:%02d", hour, minute), nil
+}
+
+func Weekday(s string) (int, bool) {
+ s = strings.ToLower(strings.TrimSpace(s))
+ for d := time.Sunday; d <= time.Saturday; d++ {
+ full := strings.ToLower(d.String())
+ if s != "" && (s == full || s == full[:3]) {
+ return int(d), true
+ }
+ }
+ return 0, false
+}
+
+func dayName(day int) string {
+ if day < 0 || day > 6 {
+ return ""
+ }
+ return time.Weekday(day).String()[:3]
+}
+
+func DayLong(day string) string {
+ d, ok := Weekday(day)
+ if !ok {
+ return ""
+ }
+ return time.Weekday(d).String()
+}
+
+func every(day int) string {
+ if day < 0 {
+ return "every day"
}
- return fmt.Sprintf("%02d:%02d", hour, minute), nil
+ return "every " + time.Weekday(day).String()
+}
+
+func (a AutoUpgrade) upgradeArgs() string {
+ if a.Backup == "" || a.Backup == BackupFull {
+ return "upgrade --yes"
+ }
+ return "upgrade --yes --backup " + a.Backup
}
func (a AutoUpgrade) service(runAs string) string {
after := []string{a.Project + ".service"}
+ if a.FullBackup != "" {
+ after = append(after, a.BackupServiceName())
+ }
var b strings.Builder
b.WriteString("[Unit]\n")
fmt.Fprintf(&b, "Description=Upgrade Fluxer in %s\n", strings.ReplaceAll(a.Dir, "%", "%%"))
@@ -141,19 +265,23 @@ func (a AutoUpgrade) service(runAs string) string {
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))
+ fmt.Fprintf(&b, "ExecStart=%s %s --dir %s\n", systemdQuote(a.Binary), a.upgradeArgs(), 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 {
+func (a AutoUpgrade) timer(day, 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, "%", "%%"))
+ fmt.Fprintf(&b, "Description=Upgrade Fluxer in %s %s\n", strings.ReplaceAll(a.Dir, "%", "%%"), every(day))
b.WriteString("\n[Timer]\n")
- fmt.Fprintf(&b, "OnCalendar=*-*-* %02d:%02d:00\n", hour, minute)
+ b.WriteString("OnCalendar=")
+ if day >= 0 {
+ b.WriteString(dayName(day) + " ")
+ }
+ fmt.Fprintf(&b, "*-*-* %02d:%02d:00\n", hour, minute)
fmt.Fprintf(&b, "RandomizedDelaySec=%dmin\n", int(UpgradeWindow.Minutes()))
b.WriteString("Persistent=true\n")
b.WriteString("\n[Install]\n")
@@ -161,18 +289,88 @@ func (a AutoUpgrade) timer(hour, minute int) string {
return b.String()
}
-func (a AutoUpgrade) cron(hour, minute int, runAs string) string {
+func (a AutoUpgrade) cron(day, hour, minute int, runAs string) string {
if runAs == "" {
runAs = "root"
}
+ dow := "*"
+ if day >= 0 {
+ dow = strconv.Itoa(day)
+ }
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)
+ fmt.Fprintf(&b, "%d %d * * %s %s %s %s --dir %s >%s 2>&1; echo \"%s$?\" >>%s\n", minute, hour, dow, runAs, cronQuote(a.Binary), a.upgradeArgs(), cronQuote(a.Dir), log, cronExitPrefix, log)
+ return b.String()
+}
+
+func (a AutoUpgrade) BackupStart() (string, error) {
+ hour, minute, err := a.clock()
+ if err != nil {
+ return "", err
+ }
+ m := (hour*60 + minute + minutesPerDay - fullBackupLead) % minutesPerDay
+ return fmt.Sprintf("%02d:%02d", m/60, m%60), nil
+}
+
+func (a AutoUpgrade) backupService(runAs string) string {
+ var b strings.Builder
+ b.WriteString("[Unit]\n")
+ fmt.Fprintf(&b, "Description=Back up Fluxer in %s\n", strings.ReplaceAll(a.Dir, "%", "%%"))
+ fmt.Fprintf(&b, "After=%s.service\n", a.Project)
+ b.WriteString("\n[Service]\n")
+ b.WriteString("Type=oneshot\n")
+ if runAs != "" {
+ fmt.Fprintf(&b, "User=%s\n", runAs)
+ }
+ fmt.Fprintf(&b, "ExecStart=%s backup --dir %s\n", systemdQuote(a.Binary), systemdQuote(a.Dir))
+ return b.String()
+}
+
+func (a AutoUpgrade) backupTimer(at string) string {
+ var b strings.Builder
+ b.WriteString("[Unit]\n")
+ fmt.Fprintf(&b, "Description=Back up Fluxer in %s once a month\n", strings.ReplaceAll(a.Dir, "%", "%%"))
+ b.WriteString("\n[Timer]\n")
+ fmt.Fprintf(&b, "OnCalendar=*-*-01 %s:00\n", at)
+ b.WriteString("Persistent=true\n")
+ b.WriteString("\n[Install]\n")
+ b.WriteString("WantedBy=timers.target\n")
+ return b.String()
+}
+
+func (a AutoUpgrade) backupCron(at, runAs string) string {
+ if runAs == "" {
+ runAs = "root"
+ }
+ hour, minute, _ := AutoUpgrade{At: at}.clock()
+ log := cronQuote(a.BackupLog())
+ var b strings.Builder
+ b.WriteString("SHELL=/bin/sh\n")
+ fmt.Fprintf(&b, "PATH=%s\n", cronPath)
+ fmt.Fprintf(&b, "%d %d 1 * * %s %s backup --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 (a AutoUpgrade) backupFiles() ([][]byte, error) {
+ at, err := a.BackupStart()
+ if err != nil {
+ return nil, err
+ }
+ runAs := a.runAs()
+ switch a.Scheduler {
+ case Systemd:
+ if a.Rootless {
+ runAs = ""
+ }
+ return [][]byte{[]byte(a.backupService(runAs)), []byte(a.backupTimer(at))}, nil
+ case Cron:
+ return [][]byte{[]byte(a.backupCron(at, runAs))}, nil
+ }
+ return nil, fmt.Errorf("host: no scheduler for automatic upgrades")
+}
+
func cronQuote(s string) string {
s = "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
return strings.ReplaceAll(s, "%", `\%`)
@@ -182,7 +380,7 @@ 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.start()
+ day, hour, minute, err := a.start()
if err != nil {
return nil, err
}
@@ -192,12 +390,12 @@ func (a AutoUpgrade) files() ([][]byte, error) {
if a.Rootless {
runAs = ""
}
- return [][]byte{[]byte(a.service(runAs)), []byte(a.timer(hour, minute))}, nil
+ return [][]byte{[]byte(a.service(runAs)), []byte(a.timer(day, 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 [][]byte{[]byte(a.cron(day, hour, minute, runAs))}, nil
}
return nil, fmt.Errorf("host: no scheduler for automatic upgrades")
}
@@ -211,6 +409,33 @@ func InstallAutoUpgrade(ctx context.Context, a AutoUpgrade) error {
if err != nil {
return err
}
+ if err := installUnits(ctx, a, paths, data, a.TimerName()); err != nil {
+ return err
+ }
+ backupPaths, err := a.BackupPaths()
+ if err != nil {
+ return err
+ }
+ if a.FullBackup == "" {
+ if _, err := removeUnits(ctx, a, backupPaths, a.BackupTimerName()); err != nil {
+ return err
+ }
+ } else {
+ backupData, err := a.backupFiles()
+ if err != nil {
+ return err
+ }
+ if err := installUnits(ctx, a, backupPaths, backupData, a.BackupTimerName()); err != nil {
+ return err
+ }
+ }
+ if a.Scheduler == Systemd && a.Rootless && !lingering(ctx) {
+ return enableLinger(ctx)
+ }
+ return nil
+}
+
+func installUnits(ctx context.Context, a AutoUpgrade, paths []string, data [][]byte, timer string) error {
userScope := a.Scheduler == Systemd && a.Rootless
changed := false
for i, p := range paths {
@@ -228,19 +453,16 @@ func InstallAutoUpgrade(ctx context.Context, a AutoUpgrade) error {
return err
}
}
- if !unitIs(ctx, a.Rootless, a.TimerName(), "enabled") {
- if err := systemctlRun(ctx, a.Rootless, "enable", a.TimerName()); err != nil {
+ if !unitIs(ctx, a.Rootless, timer, "enabled") {
+ if err := systemctlRun(ctx, a.Rootless, "enable", timer); err != nil {
return err
}
}
- if changed || !unitIs(ctx, a.Rootless, a.TimerName(), "active") {
- if err := systemctlRun(ctx, a.Rootless, "restart", a.TimerName()); err != nil {
+ if changed || !unitIs(ctx, a.Rootless, timer, "active") {
+ if err := systemctlRun(ctx, a.Rootless, "restart", timer); err != nil {
return err
}
}
- if a.Rootless && !lingering(ctx) {
- return enableLinger(ctx)
- }
return nil
}
@@ -249,6 +471,19 @@ func RemoveAutoUpgrade(ctx context.Context, a AutoUpgrade) (bool, error) {
if err != nil {
return false, err
}
+ backupPaths, err := a.BackupPaths()
+ if err != nil {
+ return false, err
+ }
+ removed, err := removeUnits(ctx, a, paths, a.TimerName())
+ if err != nil {
+ return false, err
+ }
+ removedBackup, err := removeUnits(ctx, a, backupPaths, a.BackupTimerName())
+ return removed || removedBackup, err
+}
+
+func removeUnits(ctx context.Context, a AutoUpgrade, paths []string, timer string) (bool, error) {
var found []string
for _, p := range paths {
if _, err := os.Stat(p); err == nil {
@@ -261,8 +496,8 @@ func RemoveAutoUpgrade(ctx context.Context, a AutoUpgrade) (bool, error) {
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 {
+ if unitIs(ctx, a.Rootless, timer, "enabled") || unitIs(ctx, a.Rootless, timer, "active") {
+ if err := systemctlRun(ctx, a.Rootless, "disable", "--now", timer); err != nil {
return false, err
}
}
@@ -272,6 +507,36 @@ func RemoveAutoUpgrade(ctx context.Context, a AutoUpgrade) (bool, error) {
return true, systemctlRun(ctx, a.Rootless, "daemon-reload")
}
+func DropBackupFlag(ctx context.Context, a AutoUpgrade) (bool, error) {
+ paths, err := a.Paths()
+ if err != nil {
+ return false, err
+ }
+ data, err := os.ReadFile(paths[0])
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ backup := serviceBackup(data)
+ if backup == BackupFull {
+ return false, nil
+ }
+ full := bytes.ReplaceAll(data, []byte(" upgrade --yes --backup "+backup+" "), []byte(" upgrade --yes "))
+ if bytes.Equal(full, data) {
+ return false, fmt.Errorf("host: couldn't find --backup %s in %s", backup, paths[0])
+ }
+ userScope := a.Scheduler == Systemd && a.Rootless
+ if _, err := writeHostFile(ctx, userScope, paths[0], full); err != nil {
+ return false, err
+ }
+ if a.Scheduler == Systemd {
+ return true, systemctlRun(ctx, a.Rootless, "daemon-reload")
+ }
+ return true, nil
+}
+
func CheckAutoUpgrade(ctx context.Context, a AutoUpgrade, now time.Time) (AutoUpgradeState, error) {
paths, err := a.Paths()
if err != nil {
@@ -285,18 +550,41 @@ func CheckAutoUpgrade(ctx context.Context, a AutoUpgrade, now time.Time) (AutoUp
return AutoUpgradeState{}, err
}
s := AutoUpgradeState{On: true}
+ var backupSince time.Time
+ if backupPaths, err := a.BackupPaths(); err == nil {
+ if data, err := os.ReadFile(backupPaths[len(backupPaths)-1]); err == nil {
+ s.FullBackup = FullBackupMonthly
+ if info, err := os.Stat(backupPaths[len(backupPaths)-1]); err == nil {
+ backupSince = info.ModTime()
+ }
+ if a.Scheduler == Cron {
+ _, s.FullBackupAt = cronSchedule(data)
+ } else {
+ s.FullBackupAt = backupTimerAt(data)
+ }
+ }
+ }
if a.Scheduler == Cron {
- s.At = cronAt(data)
+ s.Day, s.At = cronSchedule(data)
+ s.Backup = serviceBackup(data)
if hour, minute, err := (AutoUpgrade{At: s.At}).clock(); err == nil {
- s.Next = nextDaily(now, hour, minute).Format(systemdTimeLayout)
+ s.Next = nextRun(now, s.Day, 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)
}
+ if s.FullBackup != "" {
+ _, err := os.Stat(a.BackupLog())
+ s.FullBackupRan = err == nil
+ }
return s, nil
}
- s.At = timerAt(data)
+ s.Day, s.At = timerSchedule(data)
+ s.Backup = BackupFull
+ if service, err := os.ReadFile(paths[0]); err == nil {
+ s.Backup = serviceBackup(service)
+ }
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")
@@ -305,9 +593,25 @@ func CheckAutoUpgrade(ctx context.Context, a AutoUpgrade, now time.Time) (AutoUp
s.Ran = true
s.ExitCode, _ = strconv.Atoi(svc["ExecMainStatus"])
}
+ if s.FullBackup != "" {
+ service := systemctlShow(ctx, a.Rootless, a.BackupServiceName(), "ExecMainExitTimestamp")
+ s.FullBackupRan = service["ExecMainExitTimestamp"] != "" || monthlyRunPassed(backupSince, now, s.FullBackupAt)
+ }
return s, nil
}
+func monthlyRunPassed(since, now time.Time, at string) bool {
+ t, err := time.Parse("15:04", at)
+ if err != nil || since.IsZero() {
+ return false
+ }
+ last := time.Date(now.Year(), now.Month(), 1, t.Hour(), t.Minute(), 0, 0, now.Location())
+ if last.After(now) {
+ last = last.AddDate(0, -1, 0)
+ }
+ return last.After(since)
+}
+
func systemctlShow(ctx context.Context, rootless bool, unit string, props ...string) map[string]string {
args := []string{"show", unit}
if rootless {
@@ -337,28 +641,72 @@ func parseShow(out []byte) map[string]string {
return m
}
-func timerAt(data []byte) string {
+func timerSchedule(data []byte) (string, string) {
+ for _, line := range strings.Split(string(data), "\n") {
+ v, ok := strings.CutPrefix(line, "OnCalendar=")
+ if !ok {
+ continue
+ }
+ f := strings.Fields(v)
+ day := ""
+ if len(f) == 3 {
+ d, ok := Weekday(f[0])
+ if !ok {
+ continue
+ }
+ day, f = dayName(d), f[1:]
+ }
+ if len(f) == 2 && f[0] == "*-*-*" && len(f[1]) >= 5 {
+ return day, f[1][:5]
+ }
+ }
+ return "", ""
+}
+
+func backupTimerAt(data []byte) string {
for _, line := range strings.Split(string(data), "\n") {
- if v, ok := strings.CutPrefix(line, "OnCalendar=*-*-* "); ok && len(v) >= 5 {
+ v, ok := strings.CutPrefix(line, "OnCalendar=*-*-01 ")
+ if ok && len(v) >= 5 {
return v[:5]
}
}
return ""
}
-func cronAt(data []byte) string {
+func cronSchedule(data []byte) (string, string) {
for _, line := range strings.Split(string(data), "\n") {
f := strings.Fields(line)
- if len(f) < 2 || strings.Contains(f[0], "=") {
+ if len(f) < 5 || 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)
+ if merr != nil || herr != nil {
+ continue
+ }
+ day := ""
+ if f[4] != "*" {
+ d, err := strconv.Atoi(f[4])
+ if err != nil || d < 0 || d > 7 {
+ continue
+ }
+ day = dayName(d % 7)
}
+ return day, fmt.Sprintf("%02d:%02d", hour, minute)
}
- return ""
+ return "", ""
+}
+
+func serviceBackup(data []byte) string {
+ for _, line := range strings.Split(string(data), "\n") {
+ f := strings.Fields(line)
+ for i := 0; i+1 < len(f); i++ {
+ if f[i] == "--backup" {
+ return f[i+1]
+ }
+ }
+ }
+ return BackupFull
}
func cronExit(log string) (bool, int) {
@@ -375,10 +723,12 @@ func cronExit(log string) (bool, int) {
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)
+func nextRun(now time.Time, day string, hour, minute int) time.Time {
+ want, weekly := Weekday(day)
+ for i := 0; ; i++ {
+ next := time.Date(now.Year(), now.Month(), now.Day()+i, hour, minute, 0, 0, now.Location())
+ if next.After(now) && (!weekly || int(next.Weekday()) == want) {
+ return next
+ }
}
- return next
}
diff --git a/fluxer_rexctl/internal/host/autoupgrade_test.go b/fluxer_rexctl/internal/host/autoupgrade_test.go
index d3a2b6616..837ec4371 100644
--- a/fluxer_rexctl/internal/host/autoupgrade_test.go
+++ b/fluxer_rexctl/internal/host/autoupgrade_test.go
@@ -48,6 +48,21 @@ ExecStopPost=-+/usr/bin/install -D -m 0755 /home/alice/.local/bin/rexctl /usr/lo
}
}
+func TestUpgradeWaitsForMonthlyBackup(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
+ if got := a.service(""); !strings.Contains(got, "\nAfter=network-online.target fluxer.service\n") {
+ t.Errorf("without a monthly backup the upgrade waits for:\n%s", got)
+ }
+ a.FullBackup = FullBackupMonthly
+ if got := a.service(""); !strings.Contains(got, "\nAfter=network-online.target fluxer.service fluxer-backup.service\n") {
+ t.Errorf("with a monthly backup the upgrade doesn't wait for it:\n%s", got)
+ }
+ a.Rootless = true
+ if got := a.service(""); !strings.Contains(got, "\nAfter=fluxer.service fluxer-backup.service\n") {
+ t.Errorf("rootless, with a monthly backup the upgrade doesn't wait for it:\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()
@@ -65,12 +80,12 @@ Persistent=true
[Install]
WantedBy=timers.target
`
- got := a.timer(hour, minute)
+ got := a.timer(-1, 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 day, at := timerSchedule([]byte(got)); day != "" || at != "23:05" {
+ t.Errorf("timerSchedule = %q %q, want every day at 23:05", day, at)
}
if a.TimerName() != "blue-upgrade.timer" || a.ServiceName() != "blue-upgrade.service" {
t.Errorf("unit names are %s and %s", a.TimerName(), a.ServiceName())
@@ -83,14 +98,14 @@ func TestAutoUpgradeCron(t *testing.T) {
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, "")
+ got := a.cron(-1, 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 day, at := cronSchedule([]byte(got)); day != "" || at != "04:07" {
+ t.Errorf("cronSchedule = %q %q, want every day at 04:07", day, at)
}
- if !strings.Contains(a.cron(4, 7, "alice"), " * * * alice ") {
+ if !strings.Contains(a.cron(-1, 4, 7, "alice"), " * * * alice ") {
t.Error("cron doesn't run as the instance owner")
}
paths, err := a.Paths()
@@ -114,26 +129,26 @@ func TestAutoUpgradeRefusesBadInput(t *testing.T) {
func TestAutoUpgradeCronStart(t *testing.T) {
a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
- start, err := a.Start()
+ _, start, err := a.Start()
if err != nil {
t.Fatal(err)
}
- if again, _ := a.Start(); again != start {
+ if _, again, _ := a.Start(); again != start {
t.Errorf("Start() = %q then %q, want the same time every time", start, again)
}
if start < "04:00" || start >= "04:30" {
t.Errorf("Start() = %q, want a time from 04:00 to 04:29", start)
}
files, err := a.files()
- if err != nil || cronAt(files[0]) != start {
- t.Errorf("cron file runs at %q, want %q (%v)", cronAt(files[0]), start, err)
+ if _, at := cronSchedule(files[0]); err != nil || at != start {
+ t.Errorf("cron file runs at %q, want %q (%v)", at, start, err)
}
spread := func(vary func(*AutoUpgrade, int)) int {
starts := map[string]bool{}
for i := range 8 {
b := a
vary(&b, i)
- s, _ := b.Start()
+ _, s, _ := b.Start()
starts[s] = true
}
return len(starts)
@@ -146,12 +161,12 @@ func TestAutoUpgradeCronStart(t *testing.T) {
}
late := a
late.At = "23:59"
- if s, _ := late.Start(); s >= "00:29" && s < "23:59" {
+ if _, s, _ := late.Start(); s >= "00:29" && s < "23:59" {
t.Errorf("Start() for 23:59 = %q, want it to wrap past midnight", s)
}
sd := a
sd.Scheduler = Systemd
- if s, _ := sd.Start(); s != "04:00" {
+ if _, s, _ := sd.Start(); s != "04:00" {
t.Errorf("systemd Start() = %q, want 04:00 because the timer adds its own delay", s)
}
}
@@ -175,17 +190,212 @@ func TestCronExit(t *testing.T) {
}
}
-func TestNextDaily(t *testing.T) {
+func TestNextRunDaily(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)) {
+ if got := nextRun(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)) {
+ if got := nextRun(now, "", 6, 30); !got.Equal(time.Date(2026, 10, 27, 6, 30, 0, 0, loc)) {
t.Errorf("before the time: %v", got)
}
}
+func TestNextRunWeeklyAcrossDST(t *testing.T) {
+ loc, err := time.LoadLocation("Europe/Stockholm")
+ if err != nil {
+ t.Skip("no time zone data on this machine")
+ }
+ now := time.Date(2026, 10, 18, 5, 0, 0, 0, loc)
+ got := nextRun(now, "Sun", 4, 0)
+ want := time.Date(2026, 10, 25, 4, 0, 0, 0, loc)
+ if !got.Equal(want) || got.Hour() != 4 {
+ t.Errorf("next Sunday run across the clock change = %v, want %v", got, want)
+ }
+ if got.Sub(now) == 7*24*time.Hour-time.Hour {
+ t.Error("the next run was counted in hours and lost the clock change")
+ }
+ if got := nextRun(time.Date(2026, 10, 25, 3, 0, 0, 0, loc), "sun", 4, 0); !got.Equal(want) {
+ t.Errorf("earlier the same Sunday = %v, want %v", got, want)
+ }
+ if got := nextRun(time.Date(2026, 10, 26, 3, 0, 0, 0, loc), "Mon", 4, 0); got.Weekday() != time.Monday || got.Day() != 26 {
+ t.Errorf("Monday run = %v, want Monday 26 October", got)
+ }
+}
+
+func TestTimerDailyIsUnchanged(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
+ files, err := a.files()
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := `[Unit]
+Description=Upgrade Fluxer in /opt/fluxer every day
+
+[Timer]
+OnCalendar=*-*-* 04:00:00
+RandomizedDelaySec=30min
+Persistent=true
+
+[Install]
+WantedBy=timers.target
+`
+ if string(files[1]) != want {
+ t.Errorf("daily timer:\n%s\nwant:\n%s", files[1], want)
+ }
+ a.Backup = BackupFull
+ full, err := a.files()
+ if err != nil || string(full[0]) != string(files[0]) || string(full[1]) != want {
+ t.Errorf("a full backup changed the units (%v)", err)
+ }
+}
+
+func TestTimerWeeklyAddsWeekday(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Day: "Sun"}
+ files, err := a.files()
+ if err != nil {
+ t.Fatal(err)
+ }
+ timer := string(files[1])
+ for _, line := range []string{"Description=Upgrade Fluxer in /opt/fluxer every Sunday\n", "OnCalendar=Sun *-*-* 04:00:00\n", "RandomizedDelaySec=30min\n", "Persistent=true\n"} {
+ if !strings.Contains(timer, line) {
+ t.Errorf("weekly timer has no %q:\n%s", line, timer)
+ }
+ }
+ if day, at := timerSchedule(files[1]); day != "Sun" || at != "04:00" {
+ t.Errorf("timerSchedule = %q %q, want Sun 04:00", day, at)
+ }
+ day, start, err := a.Start()
+ if err != nil || day != "Sun" || start != "04:00" {
+ t.Errorf("Start() = %q %q %v, want Sun 04:00", day, start, err)
+ }
+ a.Day = "Funday"
+ if _, err := a.files(); err == nil {
+ t.Error("files() accepted a day that doesn't exist")
+ }
+}
+
+func TestCronWeeklyDayField(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00", Day: "Wed", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
+ got := a.cron(3, 4, 7, "")
+ if !strings.Contains(got, "\n7 4 * * 3 root ") {
+ t.Errorf("weekly cron line:\n%s", got)
+ }
+ if day, at := cronSchedule([]byte(got)); day != "Wed" || at != "04:07" {
+ t.Errorf("cronSchedule = %q %q, want Wed 04:07", day, at)
+ }
+ files, err := a.files()
+ if err != nil {
+ t.Fatal(err)
+ }
+ day, start, _ := a.Start()
+ if d, at := cronSchedule(files[0]); d != day || at != start || day != "Wed" {
+ t.Errorf("cron file runs %q %q, Start() says %q %q", d, at, day, start)
+ }
+}
+
+func TestCronOffsetPastMidnightMovesWeekday(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/srv/fluxer", Binary: "/usr/local/bin/rexctl", Day: "sun", At: "23:50", Log: "/srv/fluxer/.rexctl/auto-upgrade.log"}
+ found := false
+ for i := range 64 {
+ b := a
+ b.Domain = fmt.Sprintf("chat%d.example.com", i)
+ day, hour, minute, err := b.start()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if hour*60+minute >= 23*60+50 {
+ if day != 0 {
+ t.Errorf("%s starts at %02d:%02d on day %d, want Sunday", b.Domain, hour, minute, day)
+ }
+ continue
+ }
+ found = true
+ if day != 1 {
+ t.Errorf("%s starts at %02d:%02d on day %d, want Monday", b.Domain, hour, minute, day)
+ }
+ files, err := b.files()
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := fmt.Sprintf("\n%d %d * * 1 root ", minute, hour)
+ if !strings.Contains(string(files[0]), want) {
+ t.Errorf("cron file has no %q:\n%s", want, files[0])
+ }
+ }
+ if !found {
+ t.Fatal("no domain pushed the start past midnight")
+ }
+ sat := a
+ sat.Day = "Saturday"
+ for i := range 64 {
+ sat.Domain = fmt.Sprintf("chat%d.example.com", i)
+ if day, hour, _, _ := sat.start(); hour == 0 && day != 0 {
+ t.Errorf("Saturday 23:50 moved past midnight to day %d, want Sunday", day)
+ }
+ }
+}
+
+func TestScheduleReadsOlderFiles(t *testing.T) {
+ timer := "[Unit]\nDescription=Upgrade Fluxer in /opt/fluxer every day\n\n[Timer]\nOnCalendar=*-*-* 04:00:00\nRandomizedDelaySec=30min\nPersistent=true\n"
+ if day, at := timerSchedule([]byte(timer)); day != "" || at != "04:00" {
+ t.Errorf("older timer reads as %q %q", day, at)
+ }
+ cron := "SHELL=/bin/sh\nPATH=/usr/bin:/bin\n12 4 * * * root '/usr/local/bin/rexctl' upgrade --yes --dir '/opt/fluxer' >'/opt/fluxer/.rexctl/auto-upgrade.log' 2>&1\n"
+ if day, at := cronSchedule([]byte(cron)); day != "" || at != "04:12" {
+ t.Errorf("older cron reads as %q %q", day, at)
+ }
+ if b := serviceBackup([]byte(cron)); b != BackupFull {
+ t.Errorf("older cron reads as backup %q", b)
+ }
+ if day, _ := cronSchedule([]byte("0 4 * * 7 root rexctl upgrade --yes\n")); day != "Sun" {
+ t.Errorf("cron day 7 reads as %q, want Sun", day)
+ }
+}
+
+func TestServiceAddsBackupFlagOnlyWhenLean(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
+ if got := a.service(""); strings.Contains(got, "--backup") {
+ t.Errorf("default service passes --backup:\n%s", got)
+ }
+ a.Backup = "without-uploads"
+ got := a.service("")
+ if !strings.Contains(got, "ExecStart=/usr/local/bin/rexctl upgrade --yes --backup without-uploads --dir /opt/fluxer\n") {
+ t.Errorf("lean service:\n%s", got)
+ }
+ if b := serviceBackup([]byte(got)); b != "without-uploads" {
+ t.Errorf("serviceBackup = %q", b)
+ }
+ c := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", Backup: "without-uploads", Log: "/opt/fluxer/.rexctl/auto-upgrade.log"}
+ line := c.cron(-1, 4, 0, "")
+ if !strings.Contains(line, "upgrade --yes --backup without-uploads --dir '/opt/fluxer'") || serviceBackup([]byte(line)) != "without-uploads" {
+ t.Errorf("lean cron line:\n%s", line)
+ }
+}
+
+func TestServiceWithoutBackupFlagReadsFull(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "04:00"}
+ if b := serviceBackup([]byte(a.service(""))); b != BackupFull {
+ t.Errorf("serviceBackup = %q, want full", b)
+ }
+ if b := serviceBackup(nil); b != BackupFull {
+ t.Errorf("serviceBackup of nothing = %q, want full", b)
+ }
+}
+
+func TestWeekday(t *testing.T) {
+ for in, want := range map[string]int{"sun": 0, "Mon": 1, "TUESDAY": 2, "wednesday": 3, "Sat": 6} {
+ if got, ok := Weekday(in); !ok || got != want {
+ t.Errorf("Weekday(%q) = %d, %v, want %d", in, got, ok, want)
+ }
+ }
+ for _, in := range []string{"", "su", "mond", "funday", "7"} {
+ if _, ok := Weekday(in); ok {
+ t.Errorf("Weekday(%q) accepted", in)
+ }
+ }
+}
+
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"] != "" {
@@ -193,6 +403,49 @@ func TestParseShow(t *testing.T) {
}
}
+func TestRequestedUndoesCronOffset(t *testing.T) {
+ for _, sched := range []Scheduler{Cron, Systemd} {
+ for _, c := range []struct{ day, at string }{{"", "04:00"}, {"", "23:50"}, {"Sun", "23:50"}, {"Sat", "23:59"}, {"Mon", "00:00"}} {
+ a := AutoUpgrade{Scheduler: sched, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", Day: c.day, At: c.at}
+ day, at, err := a.Start()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if sched == Systemd {
+ day = c.day
+ }
+ gotDay, gotAt := a.Requested(day, at)
+ if gotDay != c.day || gotAt != c.at {
+ t.Errorf("%s %q %s started %q %s and reads back as %q %s", sched, c.day, c.at, day, at, gotDay, gotAt)
+ }
+ }
+ }
+}
+
+func TestMonthlyRunPassedSurvivesReboot(t *testing.T) {
+ stockholm, err := time.LoadLocation("Europe/Stockholm")
+ if err != nil {
+ t.Skip(err)
+ }
+ turnedOn := time.Date(2026, 10, 20, 12, 0, 0, 0, stockholm)
+ for _, c := range []struct {
+ now time.Time
+ want bool
+ }{
+ {time.Date(2026, 10, 30, 9, 0, 0, 0, stockholm), false},
+ {time.Date(2026, 11, 1, 0, 29, 0, 0, stockholm), false},
+ {time.Date(2026, 11, 1, 0, 30, 0, 0, stockholm), true},
+ {time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), true},
+ } {
+ if got := monthlyRunPassed(turnedOn, c.now, "00:30"); got != c.want {
+ t.Errorf("turned on %s, at %s the monthly backup has run = %v, want %v", turnedOn, c.now, got, c.want)
+ }
+ }
+ if monthlyRunPassed(time.Time{}, time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), "00:30") || monthlyRunPassed(turnedOn, time.Date(2026, 12, 15, 9, 0, 0, 0, stockholm), "") {
+ t.Error("a monthly backup with no known start or time reads as run")
+ }
+}
+
const fakeSystemctl = `#!/bin/sh
echo "$*" >> "$SYSTEMCTL_LOG"
case "$2" in
@@ -264,7 +517,7 @@ func TestAutoUpgradeInstallAndRemove(t *testing.T) {
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" {
+ if _, at := timerSchedule(timer); err != nil || at != "05:30" {
t.Errorf("the timer doesn't run at 05:30: %v", err)
}
removed, err := RemoveAutoUpgrade(ctx, a)
@@ -287,3 +540,214 @@ func TestAutoUpgradeInstallAndRemove(t *testing.T) {
t.Errorf("second remove ran %v", got)
}
}
+
+func TestFullBackupRunsHoursBeforeUpgrades(t *testing.T) {
+ for _, tc := range []struct{ at, want string }{{"04:00", "01:00"}, {"02:45", "23:45"}, {"03:00", "00:00"}, {"03:30", "00:30"}, {"00:10", "21:10"}} {
+ a := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", At: tc.at}
+ got, err := a.BackupStart()
+ if err != nil || got != tc.want {
+ t.Errorf("--at %s backs up at %q (%v), want %s", tc.at, got, err, tc.want)
+ continue
+ }
+ _, start, _ := a.Start()
+ up, _ := time.Parse("15:04", start)
+ back, _ := time.Parse("15:04", got)
+ gap := up.Sub(back)
+ if gap < 0 {
+ gap += 24 * time.Hour
+ }
+ if gap < 3*time.Hour || gap+UpgradeWindow > 24*time.Hour-time.Hour {
+ t.Errorf("--at %s upgrades at %s and backs up at %s, %v apart", tc.at, start, got, gap)
+ }
+ }
+}
+
+func TestFullBackupUnitsUseFullPaths(t *testing.T) {
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: "/opt/fluxer-missing", Binary: "/usr/local/bin/rexctl", Podman: true, At: "02:45", Log: "/opt/fluxer-missing/.rexctl/auto-upgrade.log"}
+ files, err := a.backupFiles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantService := `[Unit]
+Description=Back up Fluxer in /opt/fluxer-missing
+After=fluxer.service
+
+[Service]
+Type=oneshot
+ExecStart=/usr/local/bin/rexctl backup --dir /opt/fluxer-missing
+`
+ wantTimer := `[Unit]
+Description=Back up Fluxer in /opt/fluxer-missing once a month
+
+[Timer]
+OnCalendar=*-*-01 23:45:00
+Persistent=true
+
+[Install]
+WantedBy=timers.target
+`
+ if len(files) != 2 || string(files[0]) != wantService || string(files[1]) != wantTimer {
+ t.Errorf("systemd backup units:\n%s\n%s", files[0], files[1])
+ }
+ paths, err := a.BackupPaths()
+ if err != nil || len(paths) != 2 || paths[0] != "/etc/systemd/system/fluxer-backup.service" || paths[1] != "/etc/systemd/system/fluxer-backup.timer" {
+ t.Errorf("systemd backup paths = %v, %v", paths, err)
+ }
+ a.Scheduler = Cron
+ files, err = a.backupFiles()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantCron := "SHELL=/bin/sh\nPATH=" + cronPath + "\n45 23 1 * * root '/usr/local/bin/rexctl' backup --dir '/opt/fluxer-missing' >'/opt/fluxer-missing/.rexctl/full-backup.log' 2>&1; echo \"rexctl exited with $?\" >>'/opt/fluxer-missing/.rexctl/full-backup.log'\n"
+ if len(files) != 1 || string(files[0]) != wantCron {
+ t.Errorf("cron backup file:\n%s\nwant:\n%s", files[0], wantCron)
+ }
+ if day, at := cronSchedule(files[0]); day != "" || at != "23:45" {
+ t.Errorf("the cron backup file reads back as %q %q", day, at)
+ }
+ a.Domain = "chat.example.com"
+ if _, start, _ := a.Start(); start == "02:45" {
+ t.Fatal("the test needs a cron offset")
+ }
+ if files, _ := a.backupFiles(); !strings.Contains(string(files[0]), "\n45 23 1 * * ") {
+ t.Errorf("the cron offset moved the backup:\n%s", files[0])
+ }
+ if paths, _ := a.BackupPaths(); len(paths) != 1 || paths[0] != "/etc/cron.d/fluxer-backup" {
+ t.Errorf("cron backup paths = %v", paths)
+ }
+}
+
+func fakeSystemd(t *testing.T) (string, func() []string) {
+ t.Helper()
+ 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)
+ return root, func() []string {
+ data, _ := os.ReadFile(log)
+ _ = os.Remove(log)
+ return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(data)), " ", "_"))
+ }
+}
+
+func TestFullBackupTimerInstallAndRemove(t *testing.T) {
+ root, calls := fakeSystemd(t)
+ ctx := context.Background()
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(root, "bin", "rexctl"), Rootless: true, At: "04:00", FullBackup: FullBackupMonthly, Log: filepath.Join(root, "fluxer", ".rexctl", "auto-upgrade.log")}
+ if err := InstallAutoUpgrade(ctx, a); err != nil {
+ t.Fatal(err)
+ }
+ got := strings.Join(calls(), " ")
+ if !strings.Contains(got, "--user_restart_fluxer-backup.timer") || !strings.Contains(got, "--user_restart_fluxer-upgrade.timer") {
+ t.Errorf("installing with a monthly full backup ran %s", got)
+ }
+ unitDir := filepath.Join(root, "config", "systemd", "user")
+ timer, err := os.ReadFile(filepath.Join(unitDir, "fluxer-backup.timer"))
+ if err != nil || !strings.Contains(string(timer), "OnCalendar=*-*-01 01:00:00\n") {
+ t.Errorf("backup timer = %q, %v", timer, err)
+ }
+ s, err := CheckAutoUpgrade(ctx, a, time.Now())
+ if err != nil || s.FullBackup != FullBackupMonthly || s.FullBackupAt != "01:00" || s.FullBackupRan {
+ t.Errorf("status = %+v, %v, want a monthly full backup at 01:00 that hasn't run", s, err)
+ }
+ if !strings.Contains(string(timer), "Persistent=true\n") {
+ t.Errorf("a monthly backup missed while the machine is off isn't made later, timer %q", timer)
+ }
+ installed := time.Now().AddDate(0, -2, 0)
+ if err := os.Chtimes(filepath.Join(unitDir, "fluxer-backup.timer"), installed, installed); err != nil {
+ t.Fatal(err)
+ }
+ if s, err := CheckAutoUpgrade(ctx, a, time.Now()); err != nil || !s.FullBackupRan {
+ t.Errorf("status = %+v, %v, want a monthly full backup that was due since it was turned on", s, err)
+ }
+ a.FullBackup = ""
+ if err := InstallAutoUpgrade(ctx, a); err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(calls(), " "); !strings.Contains(got, "--user_disable_--now_fluxer-backup.timer") {
+ t.Errorf("installing without a full backup ran %s", got)
+ }
+ for _, name := range []string{"fluxer-backup.service", "fluxer-backup.timer"} {
+ if _, err := os.Stat(filepath.Join(unitDir, name)); !os.IsNotExist(err) {
+ t.Errorf("%s is still there (%v)", name, err)
+ }
+ }
+ if s, _ := CheckAutoUpgrade(ctx, a, time.Now()); s.FullBackup != "" {
+ t.Errorf("status still shows a full backup %q", s.FullBackup)
+ }
+ a.FullBackup = FullBackupMonthly
+ if err := InstallAutoUpgrade(ctx, a); err != nil {
+ t.Fatal(err)
+ }
+ calls()
+ removed, err := RemoveAutoUpgrade(ctx, a)
+ if err != nil || !removed {
+ t.Fatalf("RemoveAutoUpgrade = %v, %v", removed, err)
+ }
+ if got := strings.Join(calls(), " "); !strings.Contains(got, "fluxer-backup.timer") || !strings.Contains(got, "fluxer-upgrade.timer") {
+ t.Errorf("remove ran %s", got)
+ }
+ if entries, _ := os.ReadDir(unitDir); len(entries) != 0 {
+ t.Errorf("remove left %d files", len(entries))
+ }
+}
+
+func TestDropBackupFlagKeepsTheSchedule(t *testing.T) {
+ root, calls := fakeSystemd(t)
+ ctx := context.Background()
+ a := AutoUpgrade{Scheduler: Systemd, Project: "fluxer", Dir: filepath.Join(root, "fluxer"), Binary: filepath.Join(root, "bin", "rexctl"), Rootless: true, At: "02:45", Day: "Sun", Backup: "without-uploads"}
+ if err := InstallAutoUpgrade(ctx, a); err != nil {
+ t.Fatal(err)
+ }
+ unitDir := filepath.Join(root, "config", "systemd", "user")
+ timerBefore, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer"))
+ calls()
+ changed, err := DropBackupFlag(ctx, a)
+ if err != nil || !changed {
+ t.Fatalf("DropBackupFlag = %v, %v", changed, err)
+ }
+ service, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.service"))
+ full := a
+ full.Backup = BackupFull
+ if string(service) != full.service("") {
+ t.Errorf("service after dropping --backup:\n%s\nwant:\n%s", service, full.service(""))
+ }
+ if timer, _ := os.ReadFile(filepath.Join(unitDir, "fluxer-upgrade.timer")); string(timer) != string(timerBefore) {
+ t.Errorf("dropping --backup changed the timer to\n%s", timer)
+ }
+ if got := calls(); strings.Join(got, " ") != "--user_daemon-reload" {
+ t.Errorf("dropping --backup ran %v", got)
+ }
+ if changed, err := DropBackupFlag(ctx, a); err != nil || changed {
+ t.Errorf("second DropBackupFlag = %v, %v, want false, nil", changed, err)
+ }
+
+ cron := AutoUpgrade{Scheduler: Cron, Project: "fluxer", Domain: "chat.example.com", Dir: "/opt/fluxer", Binary: "/usr/local/bin/rexctl", At: "23:50", Day: "Sun", Backup: "without-uploads", Log: "/opt/fluxer/.rexctl/auto-upgrade.log"}
+ day, hour, minute, err := cron.start()
+ if err != nil {
+ t.Fatal(err)
+ }
+ lean := cron.cron(day, hour, minute, "root")
+ cron.Backup = BackupFull
+ if got := strings.ReplaceAll(lean, " upgrade --yes --backup without-uploads ", " upgrade --yes "); got != cron.cron(day, hour, minute, "root") {
+ t.Errorf("the cron line without --backup is\n%s\nwant\n%s", got, cron.cron(day, hour, minute, "root"))
+ }
+}
diff --git a/fluxer_rexctl/internal/host/bootunit_test.go b/fluxer_rexctl/internal/host/bootunit_test.go
index a2c2f81ae..c4c14f59d 100644
--- a/fluxer_rexctl/internal/host/bootunit_test.go
+++ b/fluxer_rexctl/internal/host/bootunit_test.go
@@ -22,7 +22,7 @@ func TestUnitBinariesReadWhatRexctlWrites(t *testing.T) {
"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},
+ "cron job": {a.cron(-1, 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)
diff --git a/fluxer_rexctl/internal/instance/eject.go b/fluxer_rexctl/internal/instance/eject.go
index f82a8ee0d..f18af6f37 100644
--- a/fluxer_rexctl/internal/instance/eject.go
+++ b/fluxer_rexctl/internal/instance/eject.go
@@ -169,7 +169,7 @@ func importEjected(ctx context.Context, dir string, e *engine.Engine, s *State,
return nil, nil, err
}
r.Minted, r.Release = minted, updated.Release
- s.PreviousRelease, s.Release = s.Release, updated.Release
+ s.PreviousRelease, s.Release, s.PreviousBackup = s.Release, updated.Release, ""
s.Images = Images{Release: updated.Release, Refs: maps.Clone(updated.Images)}
if s.Rendered, err = stack.Hashes(stack.Embedded(), stack.OverlaysFor(s.Settings), s.Images.Refs, s.Project); err != nil {
return nil, nil, err
diff --git a/fluxer_rexctl/internal/instance/eject_test.go b/fluxer_rexctl/internal/instance/eject_test.go
index ed9bffc21..92e9b60ad 100644
--- a/fluxer_rexctl/internal/instance/eject_test.go
+++ b/fluxer_rexctl/internal/instance/eject_test.go
@@ -133,3 +133,28 @@ func TestTakeoverOfEjectedInstanceNeverGoesBack(t *testing.T) {
}
})
}
+
+func TestTakeoverAfterHandUpgradeForgetsPreviousBackup(t *testing.T) {
+ shipped := stack.Embedded()
+ dir := ejectedInstance(t, shipped, fluxerRefs("b"))
+ path := filepath.Join(dir, StateDirName, StateFileName)
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s, err := ParseState(data, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.PreviousRelease, s.PreviousBackup = "2026.1001.100000", filepath.Join(dir, "backups", "fluxer-a.tar.zst")
+ if err := s.Save(path); err != nil {
+ t.Fatal(err)
+ }
+ got, _, err := Import(dir, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.PreviousRelease != ejectedAt || got.PreviousBackup != "" {
+ t.Errorf("after takeover the previous release is %s and the previous backup %q", got.PreviousRelease, got.PreviousBackup)
+ }
+}
diff --git a/fluxer_rexctl/internal/instance/state.go b/fluxer_rexctl/internal/instance/state.go
index f56ccf9e9..ae538848f 100644
--- a/fluxer_rexctl/internal/instance/state.go
+++ b/fluxer_rexctl/internal/instance/state.go
@@ -28,6 +28,7 @@ type State struct {
Engine EngineRef `json:"engine"`
Release string `json:"release"`
PreviousRelease string `json:"previous_release"`
+ PreviousBackup string `json:"previous_backup,omitempty"`
FailedRelease string `json:"failed_release"`
Upgrade *Upgrade `json:"upgrade"`
Pending *Pending `json:"pending"`
@@ -144,7 +145,7 @@ func parseStateRepairing(data []byte, dir string, repairing []string) (*State, e
}
var stateFields = map[string]bool{
- "schema": true, "project": true, "engine": true, "release": true, "previous_release": true, "failed_release": true,
+ "schema": true, "project": true, "engine": true, "release": true, "previous_release": true, "previous_backup": 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, "left_in_root": true, "ejected": true,
"installed_at": true, "updated_at": true, "backup_dir": true, "keep_backups": true, "notify_url": true,
diff --git a/fluxer_rexctl/internal/instance/state_test.go b/fluxer_rexctl/internal/instance/state_test.go
new file mode 100644
index 000000000..8df7882af
--- /dev/null
+++ b/fluxer_rexctl/internal/instance/state_test.go
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package instance
+
+import (
+ "slices"
+ "testing"
+)
+
+func TestStateKnowsPreviousBackup(t *testing.T) {
+ inst, err := Create(t.TempDir(), "fluxer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ inst.State.PreviousRelease = "2026.1020.100000"
+ inst.State.PreviousBackup = "/opt/fluxer/backups/fluxer-chat.example.com-20261025-040000.tar.zst"
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ again, err := Find(inst.Dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if again.State.PreviousBackup != inst.State.PreviousBackup {
+ t.Errorf("PreviousBackup = %q, want %q", again.State.PreviousBackup, inst.State.PreviousBackup)
+ }
+ if slices.Contains(again.State.Unknown, "previous_backup") {
+ t.Errorf("previous_backup reads as an unknown setting in %v", again.State.Unknown)
+ }
+ s, err := ParseState([]byte(`{"schema":1,"project":"fluxer","previous_release":"2026.1020.100000"}`), inst.Dir)
+ if err != nil || s.PreviousBackup != "" {
+ t.Errorf("older state = %+v, %v", s, err)
+ }
+}
diff --git a/fluxer_rexctl/internal/settings/keys.go b/fluxer_rexctl/internal/settings/keys.go
index 26869af3d..1c51bf1f5 100644
--- a/fluxer_rexctl/internal/settings/keys.go
+++ b/fluxer_rexctl/internal/settings/keys.go
@@ -69,6 +69,15 @@ const (
EdgeTunnel = "tunnel"
)
+func ImageRef(chosen, refs map[string]string, svc string) string {
+ for _, v := range []string{chosen[ImagesPrefix+svc], chosen[ImageVars[svc]], refs[svc]} {
+ if v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
var ImageVars = map[string]string{
"postgres": "FLUXER_POSTGRES_IMAGE",
"valkey": "FLUXER_VALKEY_IMAGE",
diff --git a/fluxer_rexctl/internal/stack/definition.go b/fluxer_rexctl/internal/stack/definition.go
new file mode 100644
index 000000000..b1fc46832
--- /dev/null
+++ b/fluxer_rexctl/internal/stack/definition.go
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package stack
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "go.yaml.in/yaml/v4"
+)
+
+func ServicesDefinition(set *Set, overlays []Overlay, images map[string]string, services ...string) (string, error) {
+ files, _, err := renderFiles(set, overlays, images, defaultProject)
+ if err != nil {
+ return "", err
+ }
+ out := map[string][]any{}
+ for _, f := range files {
+ if f.name == Caddyfile {
+ continue
+ }
+ var doc struct {
+ Services map[string]any `yaml:"services"`
+ }
+ if err := yaml.Unmarshal(f.data, &doc); err != nil {
+ return "", fmt.Errorf("stack: %s isn't valid YAML: %w", f.name, err)
+ }
+ for _, svc := range services {
+ if def, ok := doc.Services[svc]; ok {
+ out[svc] = append(out[svc], def)
+ }
+ }
+ }
+ data, err := json.Marshal(out)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
diff --git a/fluxer_rexctl/internal/stack/services.go b/fluxer_rexctl/internal/stack/services.go
index 611a4ef65..2599b1505 100644
--- a/fluxer_rexctl/internal/stack/services.go
+++ b/fluxer_rexctl/internal/stack/services.go
@@ -21,6 +21,8 @@ var Volumes = []string{
var BackupVolumes = []string{"seaweedfs-data", "valkey-data", "nats-data", "meilisearch-data"}
+var UploadsServices = []string{"seaweedfs", "seaweedfs-init"}
+
type DataMount struct {
Service string
Target string