A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(rexctl): check disk space before pulling images (#3609)
Hampus4b701472a245
diff --git a/fluxer_rexctl/cmd/takeover.go b/fluxer_rexctl/cmd/takeover.goindex 7309dcb0d..0a1eab081 100644--- a/fluxer_rexctl/cmd/takeover.go+++ b/fluxer_rexctl/cmd/takeover.go@@ -16,6 +16,7 @@ import ("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/setup""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"@@ -86,6 +87,10 @@ func takeoverDir(ctx context.Context, app *App, dir string, opts takeoverOptionsif opts.DryRun {if opts.Then != "" && len(report.KeepAsMine) == 0 {u.Info("%s", opts.Then)+ if e != nil {+ legacy := &instance.Instance{Dir: dir, State: &instance.State{Project: report.Project, Images: instance.Images{Refs: report.Images}}}+ printSpace(ctx, app, legacy, e, embeddedRefs(), &upgradeFlags{}, release.Short(stack.Embedded().Release))+ }}u.Info("Dry run. Nothing changed.")return nil, nil, nildiff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.goindex c4aaad0b2..a599cbd81 100644--- a/fluxer_rexctl/cmd/upgrade.go+++ b/fluxer_rexctl/cmd/upgrade.go@@ -147,7 +147,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(app, f, needSelf, to)+ printUpgradePlan(ctx, app, inst, f, needSelf, to)return nil}if f.Prefetch {@@ -344,11 +344,18 @@ func resumeUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {})}-func printUpgradePlan(app *App, f *upgradeFlags, needSelf bool, to string) {+func printUpgradePlan(ctx context.Context, app *App, inst *instance.Instance, f *upgradeFlags, needSelf bool, to string) {if needSelf {app.UI.Info("rexctl updates itself to %s.", to)}app.UI.Info("Fluxer %s downloads while your instance keeps running.", to)+ 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)+ }if f.Prefetch {app.UI.Info("Dry run. Nothing changed.")return@@ -363,6 +370,50 @@ func printUpgradePlan(app *App, f *upgradeFlags, needSelf bool, to string) {app.UI.Info("Dry run. Nothing changed.")}+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() {+ app.UI.Warn(spaceLine(sp, to), spaceFix(e, sp))+ } else {+ app.UI.Info("%s", spaceLine(sp, to))+ }+ }+}++func embeddedRefs() map[string]string {+ images, err := stack.EmbeddedImages()+ if err != nil {+ return nil+ }+ return images.Images+}++func upgradeSpace(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, next map[string]string, f *upgradeFlags) []checks.Space {+ old := e.Named(inst.Project(), inst.Dir)+ pull, err := checks.PullNeed(ctx, e, inst.State.Images.Refs, next)+ if err != nil {+ app.UI.Detail("%v", err)+ }+ var saved uint64+ if !f.Prefetch && !f.NoBackup {+ if saved, err = backup.Estimate(ctx, inst, old); err != nil {+ app.UI.Detail("%v", err)+ }+ }+ return checkEnv(ctx, inst, e, old).Space(pull, saved)+}++func spaceLine(sp checks.Space, to string) string {+ return fmt.Sprintf("Fluxer %s needs about %s of free disk space in %s, and %s is free.", to, ui.Bytes(int64(sp.Need)), sp.Path, ui.Bytes(int64(sp.Free)))+}++func spaceFix(e *engine.Engine, sp checks.Space) string {+ if sp.Images {+ return fmt.Sprintf("Free up space there, for example with %s image prune -a, which removes the images no container uses. Then run rexctl upgrade again.", strings.ToLower(e.Kind.Name()))+ }+ return "Free up space there, then run rexctl upgrade again."+}+func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *engine.Engine, f *upgradeFlags) error {pend := inst.State.Upgradefrom, to := pend.From, pend.To@@ -415,10 +466,10 @@ func upgradeStack(ctx context.Context, app *App, inst *instance.Instance, e *engreturn 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.")}old := e.Named(inst.Project(), inst.Dir)- if c, ok := checks.Get("disk"); ok && c.Run != nil {- if r := checks.RunIn(ctx, checkEnv(ctx, inst, e, old), checks.Installed, c); r.Status == checks.Fail || r.Status == checks.Warn {+ for _, sp := range upgradeSpace(ctx, app, inst, e, next.Images.Refs, f) {+ if sp.Short() {clearUpgrade(inst)- return ui.Refused(r.Message, r.Fix)+ return ui.Refused(spaceLine(sp, toShort)+" "+capitalise(fluxerName(fromShort))+" is still running.", spaceFix(e, sp))}}if err := pullRelease(ctx, app, inst, e, set, next, toShort); err != nil {diff --git a/fluxer_rexctl/internal/backup/create.go b/fluxer_rexctl/internal/backup/create.goindex da3edd3c6..2ce9052d3 100644--- a/fluxer_rexctl/internal/backup/create.go+++ b/fluxer_rexctl/internal/backup/create.go@@ -106,13 +106,8 @@ func Create(ctx context.Context, inst *instance.Instance, p *engine.Project, optm.Release = inst.State.Release}values := instanceValues(inst)- model := p.Model- if model == nil {- if loaded, err := deploy.Load(ctx, inst, p.Engine); err == nil {- model = loaded.Model- }- }- bundledDB := !externalPostgres(values) && (model == nil || hasService(model, postgresService))+ model := projectModel(ctx, inst, p)+ bundledDB := bundledDatabase(values, model)if !bundledDB {m.Skipped = append(m.Skipped, SkippedDatabase)}@@ -140,7 +135,7 @@ func Create(ctx context.Context, inst *instance.Instance, p *engine.Project, optif err != nil {return nil, err}- if err := checkDisk(ctx, p, image, dir, volumes); err != nil {+ if err := checkDisk(ctx, p, image, dir, volumes, bundledDB); err != nil {return nil, err}@@ -231,8 +226,14 @@ func externalPostgres(values map[string]string) bool {return false}-func hasService(model *types.Project, name string) bool {- _, ok := model.Services[name]+func bundledDatabase(values map[string]string, model *types.Project) bool {+ if externalPostgres(values) {+ return false+ }+ if model == nil {+ return true+ }+ _, ok := model.Services[postgresService]return ok}@@ -370,11 +371,63 @@ func (e *HelperError) Error() string {func (e *HelperError) Unwrap() error { return e.Err }-func checkDisk(ctx context.Context, p *engine.Project, image, dir string, volumes []volumeRef) error {+func Estimate(ctx context.Context, inst *instance.Instance, p *engine.Project) (uint64, error) {+ values := instanceValues(inst)+ model := projectModel(ctx, inst, p)+ volumes, err := volumesToCopy(ctx, inst, values, p, model, &Manifest{})+ if err != nil {+ return 0, err+ }+ var image string+ if len(volumes) > 0 {+ if image, err = helperImage(ctx, inst, p, model); err != nil {+ return 0, err+ }+ }+ return diskNeed(ctx, p, image, volumes, bundledDatabase(values, model))+}++func projectModel(ctx context.Context, inst *instance.Instance, p *engine.Project) *types.Project {+ if p.Model != nil {+ return p.Model+ }+ if loaded, err := deploy.Load(ctx, inst, p.Engine); err == nil {+ return loaded.Model+ }+ return nil+}++func checkDisk(ctx context.Context, p *engine.Project, image, dir string, volumes []volumeRef, bundledDB bool) error {free, err := host.FreeDisk(dir)- if err != nil || len(volumes) == 0 {+ if err != nil {return nil}+ need, err := diskNeed(ctx, p, image, volumes, bundledDB)+ if err != nil {+ return err+ }+ if free < need {+ return &DiskError{Dir: dir, Need: need, Available: free}+ }+ return nil+}++func diskNeed(ctx context.Context, p *engine.Project, image string, volumes []volumeRef, bundledDB bool) (uint64, error) {+ var total uint64+ if bundledDB {+ total = databaseSize(ctx, p)+ }+ if len(volumes) > 0 {+ kb, err := volumesSize(ctx, p, image, volumes)+ if err != nil {+ return 0, err+ }+ total += kb * 1024+ }+ return total * diskHeadroomPct / 100, nil+}++func volumesSize(ctx context.Context, p *engine.Project, image string, volumes []volumeRef) (uint64, error) {var mounts []engine.Mountvar paths []stringfor i, v := range volumes {@@ -384,7 +437,7 @@ func checkDisk(ctx context.Context, p *engine.Project, image, dir string, volume}var out bytes.Bufferif err := helper(ctx, p, image, mounts, nil, &out, "du", append([]string{"-sk"}, paths...)...); err != nil {- return fmt.Errorf("backup: measuring volumes: %w", err)+ return 0, fmt.Errorf("backup: measuring volumes: %w", err)}var kb uint64sc := bufio.NewScanner(&out)@@ -398,11 +451,21 @@ func checkDisk(ctx context.Context, p *engine.Project, image, dir string, volumekb += n}}- need := kb * 1024 * diskHeadroomPct / 100- if free < need {- return &DiskError{Dir: dir, Need: need, Available: free}+ return kb, nil+}++func databaseSize(ctx context.Context, p *engine.Project) uint64 {+ var out bytes.Buffer+ err := p.Exec(ctx, postgresService, engine.ExecOptions{Stdout: &out, KillOnCancel: true}, "sh", "-c",+ `exec psql -X -tA -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c 'select pg_database_size(current_database())'`)+ if err != nil {+ return 0}- return nil+ n, err := strconv.ParseUint(strings.TrimSpace(out.String()), 10, 64)+ if err != nil {+ return 0+ }+ return n}func instanceFiles(dir string) ([]string, error) {diff --git a/fluxer_rexctl/internal/checks/disk.go b/fluxer_rexctl/internal/checks/disk.goindex 5c04dbbfd..d63618ddf 100644--- a/fluxer_rexctl/internal/checks/disk.go+++ b/fluxer_rexctl/internal/checks/disk.go@@ -5,8 +5,9 @@ package checksimport ("context""fmt"+ "maps""os"- "runtime"+ "slices""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine""github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"@@ -16,6 +17,8 @@ const (diskNeededInstall = 20 << 30diskLow = 10 << 30diskCritical = 5 << 30+ imageGuess = 1 << 30+ pullHeadroomPct = 125)func init() {@@ -47,16 +50,8 @@ func runDisk(ctx context.Context, e *Env) Result {func (e *Env) freeDisk() (uint64, bool) {paths := []string{e.Dir}- if runtime.GOOS == "linux" {- root := "/var/lib/docker"- if e.Engine != nil && e.Engine.Kind == engine.Podman {- root = "/var/lib/containers"- }- if e.Engine == nil || !e.Engine.Rootless {- if _, err := os.Stat(root); err == nil {- paths = append(paths, root)- }- }+ if store := e.imageStore(); store != e.Dir {+ paths = append(paths, store)}var lowest uint64found := false@@ -72,6 +67,93 @@ func (e *Env) freeDisk() (uint64, bool) {return lowest, found}+func (e *Env) imageStore() string {+ if e.Engine != nil && e.Engine.DataRoot != "" {+ if _, err := os.Stat(e.Engine.DataRoot); err == nil {+ return e.Engine.DataRoot+ }+ }+ return e.Dir+}++type Space struct {+ Path string+ Images bool+ Need uint64+ Free uint64+}++func (s Space) Short() bool { return s.Free < s.Need }++func (e *Env) Space(pull, backup uint64) []Space {+ wants := []Space{{Path: e.imageStore(), Images: true, Need: pull}, {Path: e.Dir}}+ if e.Instance != nil {+ wants = append(wants, Space{Path: e.Instance.BackupDir(), Need: backup})+ }+ var out []Space+ disks := map[string]int{}+ for _, w := range wants {+ id, err := host.DiskID(w.Path)+ if err != nil {+ id = w.Path+ }+ if i, ok := disks[id]; ok {+ out[i].Need += w.Need+ continue+ }+ free, err := host.FreeDisk(w.Path)+ if err != nil {+ continue+ }+ disks[id] = len(out)+ w.Free = free+ w.Need += diskCritical+ out = append(out, w)+ }+ return out+}++func PullNeed(ctx context.Context, e *engine.Engine, cur, next map[string]string) (uint64, error) {+ services := slices.Collect(maps.Keys(next))+ if next == nil {+ services = slices.Collect(maps.Keys(cur))+ }+ var need uint64+ seen := map[string]bool{}+ for _, svc := range services {+ if ref := next[svc]; ref != "" {+ if seen[ref] {+ continue+ }+ seen[ref] = true+ _, found, err := e.LocalImage(ctx, ref)+ if err != nil {+ return 0, err+ }+ if found {+ continue+ }+ }+ size, err := imageSize(ctx, e, cur[svc])+ if err != nil {+ return 0, err+ }+ need += size+ }+ return need * pullHeadroomPct / 100, nil+}++func imageSize(ctx context.Context, e *engine.Engine, ref string) (uint64, error) {+ if ref == "" {+ return imageGuess, nil+ }+ size, found, err := e.ImageSize(ctx, ref)+ if err != nil || !found {+ return imageGuess, err+ }+ return size, nil+}+func freeGB(bytes uint64) string {return fmt.Sprintf("%d GB", bytes>>30)}diff --git a/fluxer_rexctl/internal/checks/disk_test.go b/fluxer_rexctl/internal/checks/disk_test.gonew file mode 100644index 000000000..6e13821d5--- /dev/null+++ b/fluxer_rexctl/internal/checks/disk_test.go@@ -0,0 +1,22 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "path/filepath"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+)++func TestSpaceAddsNeedsOnOneDisk(t *testing.T) {+ dir := t.TempDir()+ e := &Env{Dir: dir, Instance: &instance.Instance{Dir: dir, State: &instance.State{BackupDir: filepath.Join(dir, "backups")}}}+ got := e.Space(3<<30, 2<<30)+ if len(got) != 1 {+ t.Fatalf("got %d disks, want 1", len(got))+ }+ if want := uint64(5<<30 + diskCritical); got[0].Need != want || !got[0].Images {+ t.Fatalf("got %+v, want need %d on the image disk", got[0], want)+ }+}diff --git a/fluxer_rexctl/internal/engine/api.go b/fluxer_rexctl/internal/engine/api.goindex 4a265c7a6..2571fdefc 100644--- a/fluxer_rexctl/internal/engine/api.go+++ b/fluxer_rexctl/internal/engine/api.go@@ -34,6 +34,7 @@ type Engine struct {OSType stringRootless boolDesktop string+ DataRoot stringTooOld bool}diff --git a/fluxer_rexctl/internal/engine/connect.go b/fluxer_rexctl/internal/engine/connect.goindex 9de5a7122..c03f6a5d1 100644--- a/fluxer_rexctl/internal/engine/connect.go+++ b/fluxer_rexctl/internal/engine/connect.go@@ -305,6 +305,9 @@ func dial(ctx context.Context, host string) (*Engine, *conn, error) {e.Rootless = true}}+ if _, local := socketPath(host); local && runtime.GOOS == "linux" && e.Desktop == "" {+ e.DataRoot = info.Info.DockerRootDir+ }if e.Kind == Podman {sum := sha256.Sum256([]byte(info.Info.Name + "\n" + info.Info.DockerRootDir))e.ID = "podman:" + hex.EncodeToString(sum[:12])diff --git a/fluxer_rexctl/internal/engine/ps.go b/fluxer_rexctl/internal/engine/ps.goindex 4a117f560..fe01ba6b4 100644--- a/fluxer_rexctl/internal/engine/ps.go+++ b/fluxer_rexctl/internal/engine/ps.go@@ -179,6 +179,21 @@ func (e *Engine) LocalImage(ctx context.Context, ref string) (string, bool, erroreturn res.ID, true, nil}+func (e *Engine) ImageSize(ctx context.Context, ref string) (uint64, bool, error) {+ c, err := e.api()+ if err != nil {+ return 0, false, err+ }+ res, err := c.ImageInspect(ctx, ref)+ if err != nil {+ if cerrdefs.IsNotFound(err) {+ return 0, false, nil+ }+ return 0, false, &Error{Op: "image", Class: ClassOf(err), Err: err}+ }+ return uint64(max(res.Size, 0)), true, nil+}+func (e *Engine) RepoDigest(ctx context.Context, image, ref string) (string, error) {named, err := reference.ParseNormalizedNamed(ref)if err != nil {diff --git a/fluxer_rexctl/internal/host/sys_darwin.go b/fluxer_rexctl/internal/host/sys_darwin.goindex fe0d30590..b953af4cb 100644--- a/fluxer_rexctl/internal/host/sys_darwin.go+++ b/fluxer_rexctl/internal/host/sys_darwin.go@@ -9,6 +9,7 @@ import ("errors""fmt""os/exec"+ "strconv""strings""syscall""time"@@ -26,6 +27,14 @@ func FreeDisk(path string) (uint64, error) {return st.Bavail * uint64(st.Bsize), nil}+func DiskID(path string) (string, error) {+ var st unix.Stat_t+ if err := unix.Stat(existingParent(path), &st); err != nil {+ return "", err+ }+ return strconv.FormatInt(int64(st.Dev), 10), nil+}+func addrInUse(err error) bool { return errors.Is(err, syscall.EADDRINUSE) }func portInUse(proto string, port int) (bool, string, error) {diff --git a/fluxer_rexctl/internal/host/sys_linux.go b/fluxer_rexctl/internal/host/sys_linux.goindex f55b8a2ed..cb04f2eb1 100644--- a/fluxer_rexctl/internal/host/sys_linux.go+++ b/fluxer_rexctl/internal/host/sys_linux.go@@ -45,6 +45,14 @@ func FreeDisk(path string) (uint64, error) {return st.Bavail * uint64(st.Bsize), nil}+func DiskID(path string) (string, error) {+ var st syscall.Stat_t+ if err := syscall.Stat(existingParent(path), &st); err != nil {+ return "", err+ }+ return strconv.FormatUint(st.Dev, 10), nil+}+func addrInUse(err error) bool { return errors.Is(err, syscall.EADDRINUSE) }func portInUse(proto string, port int) (bool, string, error) {diff --git a/fluxer_rexctl/internal/host/sys_windows.go b/fluxer_rexctl/internal/host/sys_windows.goindex 03b841805..3dc2eb33e 100644--- a/fluxer_rexctl/internal/host/sys_windows.go+++ b/fluxer_rexctl/internal/host/sys_windows.go@@ -4,6 +4,7 @@ package hostimport ("errors"+ "strings""unsafe""golang.org/x/sys/windows"@@ -45,6 +46,18 @@ func FreeDisk(path string) (uint64, error) {return free, nil}+func DiskID(path string) (string, error) {+ p, err := windows.UTF16PtrFromString(existingParent(path))+ if err != nil {+ return "", err+ }+ buf := make([]uint16, windows.MAX_PATH+1)+ if err := windows.GetVolumePathName(p, &buf[0], uint32(len(buf))); err != nil {+ return "", err+ }+ return strings.ToLower(windows.UTF16ToString(buf)), nil+}+func addrInUse(err error) bool {return errors.Is(err, windows.WSAEADDRINUSE) || errors.Is(err, windows.WSAEACCES)}diff --git a/fluxer_rexctl/internal/instance/import.go b/fluxer_rexctl/internal/instance/import.goindex 03f4374eb..c4d0c68e8 100644--- a/fluxer_rexctl/internal/instance/import.go+++ b/fluxer_rexctl/internal/instance/import.go@@ -54,6 +54,7 @@ type ImportReport struct {DedupedEnv boolEngineProxies boolRemovedEnv bool+ Images map[string]string}func (r *ImportReport) DroppedLine() string {@@ -156,6 +157,7 @@ func importInstaller(ctx context.Context, dir string, e *engine.Engine, dry boolreturn nil, nil, err}r.PodmanCompose = live.podmanCompose+ r.Images = live.imagesif live.podmanCompose && e.Kind == engine.Podman && VersionBelow(e.Version, engine.MinPodman) {return nil, nil, &AdoptError{Msg: "rexctl can't manage this setup.",