A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): add doctor and status commands
Hampuscfbd61e83c4d
diff --git a/fluxer_rexctl/cmd/doctor.go b/fluxer_rexctl/cmd/doctor.gonew file mode 100644index 000000000..c18428939--- /dev/null+++ b/fluxer_rexctl/cmd/doctor.go@@ -0,0 +1,237 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "context"+ "errors"+ "strings"++ "github.com/spf13/cobra"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/checks"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/deploy"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"+)++type doctorJSON struct {+ OK bool `json:"ok"`+ Checks []checks.Result `json:"checks"`+}++func newDoctorCmd(app *App) *cobra.Command {+ var fix bool+ c := &cobra.Command{+ Use: "doctor",+ Short: "Check your instance and this machine for problems",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runDoctor(c.Context(), app, fix)+ },+ }+ c.Flags().BoolVar(&fix, "fix", false, "fix the problems rexctl can fix safely")+ app.jsonFlag(c)+ return c+}++func runDoctor(ctx context.Context, app *App, fix bool) error {+ dir, err := app.Dir()+ if err != nil {+ return err+ }+ env := &checks.Env{Dir: dir}+ phase := checks.Installed+ inst, err := instance.Find(dir)+ switch {+ case err == nil:+ env.Instance = inst+ case errors.Is(err, instance.ErrNotFound):+ phase = checks.Preinstall+ case errors.Is(err, instance.ErrLegacy):+ return ui.Refused("rexctl doesn't manage the instance in "+dir+" yet.", "Run "+app.takeOverCommand()+" to hand it to rexctl.")+ default:+ return ui.Wrap(err, "rexctl can't read the instance in "+dir+".", "Run rexctl doctor as the account that installed Fluxer.")+ }+ if err := rootlessGuard(env.Instance); err != nil {+ return err+ }+ if env.Instance != nil {+ if fix {+ if err := managed(env.Instance); err != nil {+ return err+ }+ }+ e, err := app.Engine(ctx, env.Instance)+ env.SetEngine(e, err)+ if err == nil {+ env.Admin = adminapi.New(adminapi.NewExec(e.Named(env.Instance.Project(), env.Instance.Dir)), app.Version)+ }+ }+ run := func() error {+ results := diagnose(ctx, app, env, phase, fix)+ var ej *instance.EjectedError+ if errors.As(env.Instance.Managed(), &ej) && !app.Flags.JSON {+ defer app.UI.Info("%s %s", ej.Error(), ej.Fix())+ }+ return reportDoctor(app, results)+ }+ if fix && env.Instance != nil {+ return app.Locked(ctx, env.Instance, run)+ }+ return run()+}++func diagnose(ctx context.Context, app *App, env *checks.Env, phase checks.Phase, fix bool) []checks.Result {+ check := func() []checks.Result {+ var results []checks.Result+ _ = app.UI.Step(ctx, "Checking your instance", func(ctx context.Context, _ *ui.Step) error {+ results = checks.Run(ctx, env, phase)+ return nil+ })+ return results+ }+ results := check()+ if !fix {+ return results+ }+ fixed := map[string]bool{}+ skipped := map[string]string{}+ failed := map[string]bool{}+ for round := 0; round < 3; round++ {+ progressed := false+ for _, i := range fixOrder(results) {+ r := results[i]+ if !r.Fixable || skipped[r.ID] != "" {+ continue+ }+ c, _ := checks.Get(r.ID)+ if !c.SafeFix {+ if !app.UI.Interactive() && !app.UI.Yes() {+ skipped[r.ID] = "Run rexctl doctor --fix in a terminal, or pass --yes, to confirm this fix."+ continue+ }+ if !app.UI.Yes() {+ app.UI.Warn(r.Message, r.Fix)+ }+ ok, err := app.UI.Confirm("Fix this?", true)+ if err != nil || !ok {+ skipped[r.ID] = r.Fix+ continue+ }+ }+ var after checks.Result+ err := app.UI.Step(ctx, "Fixing it", func(ctx context.Context, _ *ui.Step) error {+ var err error+ after, err = checks.ApplyFix(ctx, env, r.ID)+ return err+ })+ if err != nil {+ app.UI.Detail("%v", err)+ results[i] = checks.Recheck(ctx, env, c)+ failed[r.ID] = true+ continue+ }+ delete(failed, r.ID)+ results[i] = after+ if after.Fixed {+ fixed[r.ID] = true+ progressed = true+ }+ }+ if env.Staged() {+ staged := env.StagedBy()+ err := app.UI.Step(ctx, "Applying the fixes", func(ctx context.Context, s *ui.Step) error {+ if err := checks.Commit(ctx, env, deploy.ApplyOptions{Wait: true}); err != nil {+ return err+ }+ s.Done("Applied the fixes.")+ return nil+ })+ if err != nil {+ app.UI.Detail("%v", err)+ for _, id := range staged {+ delete(fixed, id)+ failed[id] = true+ }+ } else {+ for _, id := range staged {+ fixed[id] = true+ }+ progressed = true+ }+ }+ if !progressed {+ break+ }+ results = check()+ }+ for i, r := range results {+ switch {+ case fixed[r.ID] && r.Status == checks.Pass:+ results[i].Fixed = true+ case skipped[r.ID] != "" && (r.Status == checks.Warn || r.Status == checks.Fail):+ results[i].Fix = skipped[r.ID]+ case failed[r.ID] && r.Fixable && r.Manual != "":+ results[i].Fix = "rexctl couldn't fix this. " + r.Manual+ case failed[r.ID] && r.Fixable && strings.Contains(r.Fix, "rexctl doctor --fix"):+ results[i].Fix = "rexctl couldn't fix this. Run rexctl doctor --fix --verbose to see why."+ case failed[r.ID] && r.Fixable:+ results[i].Fix = "rexctl couldn't fix this. " + r.Fix+ }+ }+ return results+}++func fixOrder(results []checks.Result) []int {+ var first, last []int+ for i, r := range results {+ if r.ID == "services" || r.ID == "stale-containers" {+ last = append(last, i)+ } else {+ first = append(first, i)+ }+ }+ return append(first, last...)+}++func reportDoctor(app *App, results []checks.Result) error {+ for _, r := range results {+ if app.Flags.JSON {+ break+ }+ switch r.Status {+ case checks.Pass:+ if r.Fixed {+ app.UI.OK("Fixed. %s", r.Message)+ } else {+ app.UI.OK("%s", r.Message)+ }+ case checks.Warn:+ app.UI.Warn(r.Message, r.Fix)+ case checks.Fail:+ app.UI.Fail(r.Message, r.Fix)+ case checks.Skip:+ if r.Message != "" {+ app.UI.Detail("%s", r.Message)+ }+ }+ for _, d := range r.Details {+ app.UI.Detail(" %s", d)+ }+ }+ if app.Flags.JSON {+ if err := app.UI.JSON(doctorJSON{OK: !checks.Failed(results), Checks: results}); err != nil {+ return err+ }+ }+ if checks.Failed(results) {+ app.SetExit(ui.ExitRefused)+ return nil+ }+ if checks.AllGood(results) {+ app.UI.AllGreen()+ }+ return nil+}diff --git a/fluxer_rexctl/cmd/status.go b/fluxer_rexctl/cmd/status.gonew file mode 100644index 000000000..d0acf20e4--- /dev/null+++ b/fluxer_rexctl/cmd/status.go@@ -0,0 +1,207 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package cmd++import (+ "context"+ "errors"+ "fmt"+ "slices"++ "github.com/spf13/cobra"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/checks"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/deploy"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/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"+)++type statusService struct {+ Name string `json:"name"`+ State string `json:"state"`+ Health string `json:"health"`+}++type statusJSON struct {+ URL string `json:"url"`+ Domain string `json:"domain"`+ Release string `json:"release"`+ Engine string `json:"engine"`+ Project string `json:"project"`+ Dir string `json:"dir"`+ Running bool `json:"running"`+ Healthy bool `json:"healthy"`+ Services []statusService `json:"services"`+}++const statusLowDisk = 10 << 30++func newStatusCmd(app *App) *cobra.Command {+ c := &cobra.Command{+ Use: "status",+ Short: "Show whether your instance is running",+ Args: noArgs,+ RunE: func(c *cobra.Command, _ []string) error {+ return runStatus(c.Context(), app)+ },+ }+ app.jsonFlag(c)+ return c+}++func runStatus(ctx context.Context, app *App) error {+ inst, err := app.Instance()+ if err != nil {+ return err+ }+ out := statusJSON{+ URL: inst.Origin(),+ Domain: inst.Domain(),+ Release: inst.State.Release,+ Engine: inst.State.Engine.Kind,+ Project: inst.Project(),+ Dir: inst.Dir,+ Services: []statusService{},+ }+ e, engineErr := app.Engine(ctx, inst)+ var p *engine.Project+ var containers []engine.Container+ var psErr error+ if engineErr == nil {+ p = e.Named(inst.Project(), inst.Dir)+ out.Engine = string(e.Kind)+ if containers, psErr = p.PS(ctx); psErr != nil {+ app.UI.Detail("%v", psErr)+ }+ if loaded, err := deploy.Load(ctx, inst, e); err == nil && psErr == nil && len(containers) > 0 {+ containers = withMissing(loaded.Services(), containers)+ }+ }+ running := 0+ var down, unhealthy, never []string+ missing := 0+ for _, c := range containers {+ out.Services = append(out.Services, statusService{Name: c.Service, State: c.State, Health: c.Health})+ switch {+ case c.State == "running":+ running+++ if c.Health == "unhealthy" || c.Health == "starting" {+ unhealthy = append(unhealthy, c.Service)+ }+ case stack.OneShot[c.Service] && c.State == "exited" && c.ExitCode == 0:+ case c.State == "created" || c.State == "missing":+ down = append(down, c.Service)+ if c.State == "created" {+ never = append(never, c.Service)+ } else {+ missing+++ }+ default:+ down = append(down, c.Service)+ }+ }+ out.Running = running > 0+ out.Healthy = len(containers) > 0 && len(down) == 0 && len(unhealthy) == 0++ healthy := engineErr == nil && psErr == nil && out.Running && len(down) == 0+ if !healthy {+ app.SetExit(ui.ExitRefused)+ }+ if app.Flags.JSON {+ return app.UI.JSON(out)+ }+ start := "Run rexctl start."+ var ej *instance.EjectedError+ if errors.As(inst.Managed(), &ej) {+ start = ej.Start()+ }+ unfinished := ej == nil && inst.State.InstallUnfinished() && (len(containers) == 0 || len(never)+missing > 0)+ locked := inst.Busy()+ busy := locked && (!out.Running || len(down) > 0 || len(unhealthy) > 0)+ var ee *ui.ExitError+ switch {+ case errors.As(engineErr, &ee):+ app.UI.Fail(ee.Msg, ee.Fix)+ case engineErr != nil:+ app.UI.Fail(engineErr.Error(), "")+ case psErr != nil:+ app.UI.Fail("rexctl can't see which Fluxer services are running.", "Run rexctl doctor to see why.")+ case busy && inst.State.Upgrade != nil:+ app.UI.Warn(fmt.Sprintf("Fluxer is being upgraded to %s.", inst.State.Upgrade.To), "Run rexctl status again when the upgrade is done.")+ case busy:+ app.UI.Warn("Another rexctl command is changing this instance.", "Run rexctl status again when it's done.")+ case unfinished:+ app.UI.Fail("The install didn't finish.", "Run rexctl install again to finish it.")+ case !out.Running && inst.State.Stopped:+ app.UI.Fail("Fluxer is stopped.", start)+ case !out.Running:+ app.UI.Fail("Fluxer isn't running.", start)+ case len(down) > 0 && len(never) == len(down):+ app.UI.Fail(checks.Services(never, "was never started.", "were never started."), start)+ case len(down) > 0 && len(never)+missing == len(down):+ app.UI.Fail(checks.Services(down, "isn't running.", "aren't running."), start)+ case len(down) > 0:+ app.UI.Fail(checks.Services(down, "isn't running.", "aren't running."), "Run rexctl doctor to find out why.")+ case len(unhealthy) > 0:+ app.UI.Warn(checks.Services(unhealthy, "isn't ready yet.", "aren't ready yet."), "Run rexctl doctor if this doesn't clear up in a few minutes.")+ default:+ app.UI.OK("Fluxer is running.")+ }+ if ej != nil {+ app.UI.Info("%s %s", ej.Error(), ej.Fix())+ }+ if u := inst.State.Upgrade; u != nil && ej == nil && !busy {+ if locked {+ app.UI.Info("Fluxer is being upgraded to %s.", u.To)+ } else {+ app.UI.Warn(fmt.Sprintf("The upgrade to %s didn't finish.", u.To), release.UnfinishedFix(u))+ }+ }+ if p != nil && out.Running && !inst.State.SetupDone {+ client := app.adminClient(inst, p)+ if done, err := setup.Done(ctx, client); err == nil && !done {+ fix := "Run rexctl setup to finish it here, or rexctl setup token to finish it in your browser."+ if admin, exists, err := setup.AccountsExist(ctx, client); err == nil && exists {+ fix = browserSetupFix(inst.Origin(), admin)+ }+ app.UI.Warn("Setup isn't finished yet.", fix)+ }+ }+ if free, err := host.FreeDisk(inst.Dir); err == nil && free < statusLowDisk {+ app.UI.Warn(fmt.Sprintf("This machine has only %s of free disk space left.", diskGB(free)), "Free up space on this machine before you upgrade.")+ }+ for _, s := range out.Services {+ health := s.Health+ if health == "" {+ health = "-"+ }+ app.UI.Detail("%-20s %-10s %s", s.Name, s.State, health)+ }+ rows := [][]string{{"Address", out.URL}}+ if out.Release != "" {+ rows = append(rows, []string{"Version", out.Release})+ }+ rows = append(rows, []string{"Folder", out.Dir})+ for _, r := range rows {+ app.UI.Result(fmt.Sprintf("%-9s %s", r[0], r[1]))+ }+ return nil+}++func withMissing(expected []string, containers []engine.Container) []engine.Container {+ for _, name := range expected {+ if !slices.ContainsFunc(containers, func(c engine.Container) bool { return c.Service == name }) {+ containers = append(containers, engine.Container{Service: name, State: "missing"})+ }+ }+ return containers+}++func diskGB(b uint64) string {+ return fmt.Sprintf("%d GB", (b+(1<<29))>>30)+}