A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): choose where backups go and keep only the newest (#3565)
Hampusd1a8c2ee8032
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdxindex cc847ba8e..162bf25c6 100644--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx@@ -60,6 +60,18 @@ Back up your instance. Fluxer pauses while uploads are copied.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.++```sh+rexctl backup keep [count|all] [flags]+```++- `--json`++ Print JSON.+### rexctl backup listList your backups.@@ -68,6 +80,18 @@ List your backups.rexctl backup list [flags]```+- `--json`++ Print JSON.++### rexctl backup location++Show the folder rexctl saves backups in, or pass a full path to save new backups there. Backups that are already saved stay where they are.++```sh+rexctl backup location [folder] [flags]+```+- `--json`Print JSON.diff --git a/fluxer_docs/src/content/docs/operator/running.mdx b/fluxer_docs/src/content/docs/operator/running.mdxindex d3af17a51..e735e97f0 100644--- a/fluxer_docs/src/content/docs/operator/running.mdx+++ b/fluxer_docs/src/content/docs/operator/running.mdx@@ -32,6 +32,8 @@ rexctl backupThis saves your settings, database and uploads in one file in the `backups` folder of your instance. Fluxer pauses while it copies uploads. Keep a copy of your backups on another machine.+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`.```shdiff --git a/fluxer_rexctl/cmd/backup.go b/fluxer_rexctl/cmd/backup.goindex a23d19cd1..0093d7d77 100644--- a/fluxer_rexctl/cmd/backup.go+++ b/fluxer_rexctl/cmd/backup.go@@ -9,6 +9,7 @@ import ("os""path/filepath""slices"+ "strconv""strings""time"@@ -48,7 +49,33 @@ func newBackupCmd(app *App) *cobra.Command {return runBackupVerify(c.Context(), app, args[0])},}- c.AddCommand(list, verify)+ location := &cobra.Command{+ Use: "location [folder]",+ Short: "Show or change the folder rexctl saves backups in",+ Long: "Show the folder rexctl saves backups in, or pass a full path to save new backups there. Backups that are already saved stay where they are.",+ Args: maxArgs(1),+ RunE: func(c *cobra.Command, args []string) error {+ if len(args) == 0 {+ return runBackupLocationShow(app)+ }+ return runBackupLocation(c.Context(), app, args[0])+ },+ }+ 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.",+ Args: maxArgs(1),+ RunE: func(c *cobra.Command, args []string) error {+ if len(args) == 0 {+ return runBackupKeepShow(app)+ }+ return runBackupKeep(c.Context(), app, args[0])+ },+ }+ app.jsonFlag(location)+ app.jsonFlag(keep)+ c.AddCommand(list, verify, location, keep)return c}@@ -122,6 +149,7 @@ func runBackup(ctx context.Context, app *App) error {if len(down) > 0 {app.UI.Warn(fmt.Sprintf("These services weren't running before the backup and are still stopped: %s.", strings.Join(down, ", ")), "Run rexctl start to start them.")}+ pruneBackups(app, inst)app.UI.Result(info.Path)return nil})@@ -238,8 +266,8 @@ func resolveBackupPath(app *App, arg string) string {}return arg}- if dir, err := app.Dir(); err == nil {- p := filepath.Join(dir, instance.BackupsDir, arg)+ if inst, err := app.Instance(); err == nil {+ p := filepath.Join(inst.BackupDir(), arg)if _, err := os.Stat(p); err == nil {return p}@@ -270,3 +298,164 @@ func backupFileErr(path string, err error) error {func backupTime(t time.Time) string {return t.UTC().Format("2 January 2006 at 15:04 UTC")}++func pruneBackups(app *App, inst *instance.Instance) {+ keep := inst.KeepBackups()+ if keep == instance.KeepAllBackups || inst.State == nil {+ return+ }+ dir := inst.BackupDir()+ 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)+ }+ }+ 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 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 runBackupLocationShow(app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ if app.Flags.JSON {+ return app.UI.JSON(map[string]string{"location": inst.BackupDir()})+ }+ app.UI.Result(inst.BackupDir())+ return nil+}++func runBackupLocation(ctx context.Context, app *App, arg string) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ if !filepath.IsAbs(arg) {+ return ui.Usage("Pass the full path of the folder, for example /mnt/backups/fluxer.")+ }+ dir := filepath.Clean(arg)+ if why := backupLocationProblem(ctx, app, inst, dir); why != "" {+ return ui.Refused(why, "Pick a folder outside your instance's data, then try again.")+ }+ if err := os.MkdirAll(dir, 0o700); err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't make %s.", dir), "Check that you can make folders there, then try again.")+ }+ if err := os.Chmod(dir, 0o700); err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't change who can open %s.", dir), "Check that you own that folder, then try again.")+ }+ probe, err := os.CreateTemp(dir, ".rexctl-write-")+ if err != nil {+ return ui.Wrap(err, fmt.Sprintf("Couldn't save files in %s.", dir), "Check that you can change files in that folder, then try again.")+ }+ probe.Close()+ os.Remove(probe.Name())+ old := inst.BackupDir()+ return app.Locked(ctx, inst, func() error {+ inst.State.BackupDir = dir+ if dir == filepath.Clean(inst.Path(instance.BackupsDir)) {+ inst.State.BackupDir = ""+ }+ if err := inst.Save(); err != nil {+ return ui.Wrap(err, "Couldn't save your instance's state.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ app.UI.OK("New backups go to %s.", dir)+ if old != dir {+ if list, err := backup.List(old); err == nil && len(list) == 1 {+ app.UI.Info("Your backup in %s stays there. Move it to %s if you want rexctl to list it and use it for rollback.", old, dir)+ } else if err == nil && len(list) > 1 {+ app.UI.Info("Your %d backups in %s stay there. Move them to %s if you want rexctl to list them and use them for rollback.", len(list), old, dir)+ }+ }+ return nil+ })+}++func backupLocationProblem(ctx context.Context, app *App, inst *instance.Instance, dir string) string {+ if filepath.Clean(inst.Dir) == dir {+ return fmt.Sprintf("%s is your instance folder, and every backup copies the files in it.", dir)+ }+ for _, sub := range []string{instance.StateDirName, instance.CertsDir, instance.CaddyDropInDir} {+ if within(inst.Path(sub), dir) {+ return fmt.Sprintf("%s is inside %s, which every backup copies.", dir, inst.Path(sub))+ }+ }+ p, err := app.Named(ctx, inst)+ if err != nil {+ return ""+ }+ vols, err := p.Engine.Volumes(ctx, p.Name)+ if err != nil {+ return ""+ }+ for _, v := range vols {+ for _, root := range []string{v.Mountpoint, v.Device} {+ if root != "" && within(root, dir) {+ return fmt.Sprintf("%s is inside your instance's %s volume.", dir, v.Name)+ }+ }+ }+ return ""+}++func within(root, dir string) bool {+ rel, err := filepath.Rel(filepath.Clean(root), dir)+ return err == nil && filepath.IsLocal(rel)+}++func runBackupKeepShow(app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ keep := inst.KeepBackups()+ if app.Flags.JSON {+ return app.UI.JSON(map[string]int{"keep": keep})+ }+ if keep == instance.KeepAllBackups {+ app.UI.Result("all")+ return nil+ }+ app.UI.Result(strconv.Itoa(keep))+ return nil+}++func runBackupKeep(ctx context.Context, app *App, arg string) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ keep := instance.KeepAllBackups+ if !strings.EqualFold(arg, "all") {+ n, err := strconv.Atoi(arg)+ if err != nil || n < 1 || n > 1000 {+ return ui.Usage("Pass a number from 1 to 1000, or all.")+ }+ keep = n+ }+ return app.Locked(ctx, inst, func() error {+ inst.State.KeepBackups = keep+ if keep == instance.DefaultKeepBackups {+ inst.State.KeepBackups = 0+ }+ if err := inst.Save(); err != nil {+ return ui.Wrap(err, "Couldn't save your instance's state.", "Check that you can write to "+inst.Dir+", then try again.")+ }+ if keep == instance.KeepAllBackups {+ app.UI.OK("rexctl keeps every backup.")+ return nil+ }+ app.UI.OK("rexctl keeps the newest %d backups.", keep)+ pruneBackups(app, inst)+ return nil+ })+}diff --git a/fluxer_rexctl/cmd/rollback.go b/fluxer_rexctl/cmd/rollback.goindex 208785454..04fe4874f 100644--- a/fluxer_rexctl/cmd/rollback.go+++ b/fluxer_rexctl/cmd/rollback.go@@ -236,16 +236,7 @@ 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.")}- var best *backup.Info- for i := range list {- b := &list[i]- if b.Release != prev {- continue- }- if best == nil || b.CreatedAt.After(best.CreatedAt) {- best = b- }- }+ best := backup.NewestOf(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.")}diff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.goindex a52479d70..59115bec0 100644--- a/fluxer_rexctl/cmd/upgrade.go+++ b/fluxer_rexctl/cmd/upgrade.go@@ -461,6 +461,7 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *engif err := setPhase(inst, from, to, release.PhaseBackedUp); err != nil {return err}+ pruneBackups(app, inst)}if err := setPhase(inst, from, to, release.PhaseMigrated); err != nil {return abortUpgrade(ctx, app, inst, e, err, ui.Wrap(err, "Couldn't save your settings.", "Run rexctl upgrade --verbose to see why."))diff --git a/fluxer_rexctl/internal/backup/backup.go b/fluxer_rexctl/internal/backup/backup.goindex 8052f7fe5..625b22af2 100644--- a/fluxer_rexctl/internal/backup/backup.go+++ b/fluxer_rexctl/internal/backup/backup.go@@ -106,6 +106,38 @@ func List(dir string) ([]Info, error) {return out, nil}+func NewestOf(list []Info, release string) *Info {+ var best *Info+ for i := range list {+ b := &list[i]+ if b.Release != release {+ continue+ }+ if best == nil || b.CreatedAt.After(best.CreatedAt) {+ best = b+ }+ }+ return best+}++func Prune(dir string, keep int, protect ...string) ([]Info, error) {+ list, err := List(dir)+ if err != nil || keep <= 0 || len(list) <= keep {+ return nil, err+ }+ var removed []Info+ for _, b := range list[keep:] {+ if slices.ContainsFunc(protect, func(p string) bool { return p != "" && samePath(p, b.Path) }) {+ continue+ }+ if err := os.Remove(b.Path); err != nil && !errors.Is(err, os.ErrNotExist) {+ return removed, err+ }+ removed = append(removed, b)+ }+ return removed, nil+}+func fileName(domain string, at time.Time, n int) string {var b strings.Builderfor _, r := range strings.ToLower(domain) {diff --git a/fluxer_rexctl/internal/engine/api.go b/fluxer_rexctl/internal/engine/api.goindex d194bf040..397e5ee3e 100644--- a/fluxer_rexctl/internal/engine/api.go+++ b/fluxer_rexctl/internal/engine/api.go@@ -142,9 +142,11 @@ type Container struct {}type Volume struct {- Name string- Project string- Labels map[string]string+ Name string+ Project string+ Labels map[string]string+ Mountpoint string+ Device string}type ProjectInfo struct {diff --git a/fluxer_rexctl/internal/engine/ps.go b/fluxer_rexctl/internal/engine/ps.goindex 710d1f4f5..f18d8096a 100644--- a/fluxer_rexctl/internal/engine/ps.go+++ b/fluxer_rexctl/internal/engine/ps.go@@ -123,7 +123,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})+ out = append(out, Volume{Name: v.Name, Project: labels[api.ProjectLabel], Labels: labels, Mountpoint: v.Mountpoint, Device: v.Options["device"]})}slices.SortFunc(out, func(a, b Volume) int { return strings.Compare(a.Name, b.Name) })return out, nildiff --git a/fluxer_rexctl/internal/instance/instance.go b/fluxer_rexctl/internal/instance/instance.goindex 8c0df1483..021c0cc4f 100644--- a/fluxer_rexctl/internal/instance/instance.go+++ b/fluxer_rexctl/internal/instance/instance.go@@ -42,6 +42,9 @@ const (CertsDir = "certs"CaddyDropInDir = "caddy.d"KeepReleases = 3++ DefaultKeepBackups = 3+ KeepAllBackups = -1)var legacyComposeNames = []string{"compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"}@@ -176,7 +179,19 @@ func (i *Instance) SetDir(version string) string {return filepath.Join(i.ReleaseDir(version), StackDir)}-func (i *Instance) BackupDir() string { return i.Path(BackupsDir) }+func (i *Instance) BackupDir() string {+ if i.State != nil && i.State.BackupDir != "" {+ return i.State.BackupDir+ }+ return i.Path(BackupsDir)+}++func (i *Instance) KeepBackups() int {+ if i.State == nil || i.State.KeepBackups == 0 {+ return DefaultKeepBackups+ }+ return i.State.KeepBackups+}func (i *Instance) Project() string {if i.State != nil {diff --git a/fluxer_rexctl/internal/instance/state.go b/fluxer_rexctl/internal/instance/state.goindex e0de18f61..fd5da7296 100644--- a/fluxer_rexctl/internal/instance/state.go+++ b/fluxer_rexctl/internal/instance/state.go@@ -41,6 +41,8 @@ type State struct {Rendered map[string]string `json:"rendered"`Mounted map[string]string `json:"mounted"`Ejected *Ejected `json:"ejected"`+ BackupDir string `json:"backup_dir,omitempty"`+ KeepBackups int `json:"keep_backups,omitempty"`InstalledAt time.Time `json:"installed_at"`UpdatedAt time.Time `json:"updated_at"`@@ -133,7 +135,7 @@ var stateFields = map[string]bool{"schema": true, "project": true, "engine": true, "release": true, "previous_release": true, "failed_release": true,"upgrade": true, "pending": true, "images": true, "settings": true, "secrets": true, "admin_import": true,"setup_done": true, "installing": true, "stopped": true, "rendered": true, "mounted": true, "ejected": true,- "installed_at": true, "updated_at": true,+ "installed_at": true, "updated_at": true, "backup_dir": true, "keep_backups": true,}func parseState(data []byte, dir string) (*State, error) {