mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 06:23:17 -10:00
Any work that can take noticeable time now runs under the UI's status line: a Reporter's Status with a label message, or a LoggedCmd step. The UI: - status lines are a stack: a Status or LoggedCmd inside another shows its own line, then the outer one is drawn again, where before it ended the outer one for good - a message (Info, Warn, Note, Say, data on Stdout/Stderr) clears the line, prints and draws it again below; an unended line holds it - a question (Ask, Confirm, Answer, Secret), the picker and ui.Terminal hold it until they're done - no status line starts once the run is interrupted, as nothing would clear it - the run log's path is read without the log's lock, as the status line reads it under outMu Covered, by site and label: - finder.target: finding_vm; Lima's limactl --version: checking_backend - bringUp's checks (seeds, instance, recordFolder, hostChecks, ssh, requirements) and a running VM's go-on (proxy, pins, mount check): checking_vm; startOnce after the agent: starting; the self-check's probes: checking_network; pinHostKeys: reading_host_keys - setUpVM (sync, ssh config, links, clone seed): setting_up_vm; each devcontainer command: running_script; makeMachine: creating; buildOnce: checking_image; paste's count and rm: reading_pasted - volumeOf's lookup (diskutil), for launch, adopt, move, ls and rm: looking_up_volume - vm.ListAll (devvm ls): reading_vms; devvm doctor's checks: doctor_checking - devvm agent import: agent_import_reading (walk, links, opencode), agent_store_saving (copy, marketplace git checks, tmutil); devvm agent save: agent_save_reading, agent_save_comparing, agent_store_saving - devvm stop (from its pins check on): checking_vm; a delete, an orphan's teardown and Lima's DeleteImage: deleting; devvm git-protect and clone on/off's .git work (leftBehind, mountFolder, unmountFolder): git_protecting; git-protect's re-read: finding_vm - devvm clone add: clone_reading, clone_adding; clone fetch: clone_fetching; planClone: clone_planning; the clone check before rm or a remake: clone_checking; history export and import: history_exporting, history_importing; a remake's home: saving_home, restoring_home - devvm upgrade's install: upgrade_installing; the shared tools' step back and .NET's downloads: resolving_tools; gc's caches: reading_space; the retention settings (daily and in gc): retaining Work that takes the terminal stays off: the shell, ssh-add's passphrase (checkAgent, Agent.Ensure, reloadAgent) and an agent's login. Tests and guard: - msg.Fake: OnStatus and Showing; its LoggedCmd shows its step - backendtest.Fake: OnCall - TestLaunchStatusLines: every backend call of a new, running and stopped VM's launch runs under a status line but the shell's and Running's (pid files) - TestSSHAddOffStatusLine: ssh-add, on the user's agent or devvm's, never runs under one; chflagsCalls fails a .git lock or unlock with none - the structure test's status-lines rule (statusSites, statusFree) - TestStatusLinesNest, TestMessagesClearTheStatusLine, TestQuestionsHoldTheStatusLine, TestSecretAndPickerHoldTheStatusLine, TestTerminalHoldsTheStatusLine, TestNoStatusLineOnceInterrupted, TestFakeStatus, TestAgentImportStatus, TestAgentSaveStatus, TestDoctorReport, TestProblems, TestList, TestListLooksUpVolumesOnce, TestVolumeOfCache, TestWithSDKDownloads, TestRetainStatus, TestSetCloneOn, TestTeardownLeavesNothing The rule is written in the cli skill (rule 14, checklist, review), the codebase-standards skill (Show what devvm waits for, its checklist line and rules.md's row), Contributing's CLI page (Status lines), its tests and structure pages, and the troubleshooting page. Co-Authored-By: Claude Opus 5.5 <[email protected]>
419 lines
13 KiB
Go
419 lines
13 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/devvmhq/devvm/assets"
|
|
"github.com/devvmhq/devvm/internal/backend"
|
|
"github.com/devvmhq/devvm/internal/hostsafety"
|
|
"github.com/devvmhq/devvm/internal/msg"
|
|
"github.com/devvmhq/devvm/internal/netpolicy"
|
|
"github.com/devvmhq/devvm/internal/paths"
|
|
"github.com/devvmhq/devvm/internal/settings"
|
|
"github.com/devvmhq/devvm/internal/state"
|
|
"github.com/devvmhq/devvm/internal/trust"
|
|
"github.com/devvmhq/devvm/internal/ui"
|
|
"github.com/devvmhq/devvm/internal/upgrade"
|
|
"github.com/devvmhq/devvm/internal/vm"
|
|
)
|
|
|
|
// newDoctorCmd is devvm doctor.
|
|
func newDoctorCmd(a *app) *cobra.Command {
|
|
u := a.u
|
|
var asJSON bool
|
|
cmd := &cobra.Command{
|
|
Use: "doctor",
|
|
Annotations: about{docs: "getting-started/install#checking-what-devvm-needs", group: groupMachine}.annotations(),
|
|
Short: "Check what devvm needs on this machine",
|
|
Long: "Check what Lima needs on this machine, and say how to get what's missing, " +
|
|
"because devvm never installs it itself. Then list the features Lima gives VMs. " +
|
|
"doctor fails when something is missing, but never for a warning, such as one about low free space.",
|
|
Example: examples(
|
|
"devvm doctor", "check what devvm needs", "devvm doctor --json", "the same as JSON, for scripts",
|
|
),
|
|
Args: noArgs,
|
|
ValidArgsFunction: cobra.NoFileCompletions,
|
|
RunE: func(cmd *cobra.Command, _ []string) error {
|
|
reg, b, err := doctorBackend(a)
|
|
if err != nil {
|
|
return failed(err, msg.DoctorFailed)
|
|
}
|
|
d := doctor{
|
|
GitBare: func() bool { return hostsafety.BareExplicit(cmd.Context()) },
|
|
Path: onPath{LookPath: exec.LookPath, Executable: os.Executable},
|
|
Free: reg.Host.FreeSpace,
|
|
Host: func() (vm.Host, error) { return vm.ThisHost(reg.Host) },
|
|
Dirs: a.dirs,
|
|
Policies: func() []msg.M {
|
|
dirs, err := a.dirs()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return netpolicy.NotRules(dirs)
|
|
},
|
|
Folders: func() []msg.M {
|
|
dirs, err := a.dirs()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return state.VMFolderProblems(dirs)
|
|
},
|
|
States: func() []msg.M {
|
|
dirs, err := a.dirs()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return vm.StateProblems(dirs)
|
|
},
|
|
Release: func() upgrade.Known {
|
|
dirs, err := a.dirs()
|
|
if err != nil {
|
|
return upgrade.Known{}
|
|
}
|
|
return upgrade.ReadKnown(dirs.ReleaseCheck())
|
|
},
|
|
Pins: newPinsCheck(reg),
|
|
Proxies: func() []msg.M {
|
|
dirs, err := a.dirs()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
inv, err := vm.ReadStates(dirs)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
// Its own binary, which a proxy that another devvm started differs from (proxy_old);
|
|
// none read counts every such proxy as another's.
|
|
self, _ := paths.Self()
|
|
return netpolicy.Unconfined(netpolicy.NewProxy(dirs, assets.FS, self, nil, u), inv.States())
|
|
},
|
|
}
|
|
if asJSON {
|
|
return printJSON(u, d.report(cmd.Context(), u, u.Text, reg.All(), b))
|
|
}
|
|
return d.run(cmd.Context(), u, b)
|
|
},
|
|
}
|
|
cmd.Flags().BoolVar(&asJSON, "json", false, "print what it found as JSON, and succeed whatever is missing")
|
|
return cmd
|
|
}
|
|
|
|
// doctorOutput is devvm doctor --json: the backend new VMs get and what
|
|
// it's missing, doctor's warnings and tips, whether Docker is installed,
|
|
// and every backend's features.
|
|
type doctorOutput struct {
|
|
Backend string `json:"backend"`
|
|
Problems []problemJSON `json:"problems"`
|
|
Warnings []string `json:"warnings"`
|
|
// Tips is doctor's advice, which isn't a problem: git's
|
|
// safe.bareRepository.
|
|
Tips []string `json:"tips"`
|
|
Docker bool `json:"docker"`
|
|
// Features is, for each backend, how it has each feature: native,
|
|
// emulated, unreviewed or none.
|
|
Features map[string]map[string]string `json:"features"`
|
|
// Release is the newest release the daily check found, and when;
|
|
// null before it found one.
|
|
Release *releaseJSON `json:"release"`
|
|
}
|
|
|
|
// releaseJSON is the newest devvm release a launch's daily check found,
|
|
// and when, in RFC 3339.
|
|
type releaseJSON struct {
|
|
Latest string `json:"latest"`
|
|
Checked string `json:"checked"`
|
|
}
|
|
|
|
// problemJSON is something the backend is missing: its key, the command
|
|
// that fixes it (null when there's none to run) and the message.
|
|
type problemJSON struct {
|
|
Key string `json:"key"`
|
|
Fix *string `json:"fix"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// found is what doctor's checks found of a backend: its problems, and
|
|
// doctor's warnings and tips.
|
|
type found struct {
|
|
problems []backend.Problem
|
|
warnings, tips []msg.M
|
|
}
|
|
|
|
// check runs doctor's checks of b under r's status line, as they run
|
|
// the backend's tools and git and read every VM's state.
|
|
func (d doctor) check(ctx context.Context, r msg.Reporter, b backend.Backend) found {
|
|
defer r.Status(msg.DoctorChecking())()
|
|
return found{problems: b.Problems(ctx), warnings: d.warnings(b), tips: d.tips()}
|
|
}
|
|
|
|
// report is what doctor finds, as doctor --json shows it, each message
|
|
// as text shows it (the UI's Text). It prints nothing but r's status
|
|
// line while it checks.
|
|
func (d doctor) report(ctx context.Context, r msg.Reporter, text func(msg.M) string, all []backend.Backend, b backend.Backend) doctorOutput {
|
|
out := doctorOutput{
|
|
Backend: b.Name(),
|
|
Problems: []problemJSON{}, Warnings: []string{}, Tips: []string{}, Features: map[string]map[string]string{},
|
|
}
|
|
f := d.check(ctx, r, b)
|
|
for _, p := range f.problems {
|
|
j := problemJSON{Key: p.Key, Message: text(p.Msg)}
|
|
if p.Fix != "" {
|
|
j.Fix = &p.Fix
|
|
}
|
|
out.Problems = append(out.Problems, j)
|
|
}
|
|
for _, m := range f.warnings {
|
|
out.Warnings = append(out.Warnings, text(m))
|
|
}
|
|
for _, m := range f.tips {
|
|
out.Tips = append(out.Tips, text(m))
|
|
}
|
|
_, err := exec.LookPath("docker")
|
|
out.Docker = err == nil
|
|
for _, be := range all {
|
|
fs := map[string]string{}
|
|
for _, f := range backend.Features {
|
|
fs[string(f)] = be.Caps()[f].String()
|
|
}
|
|
out.Features[be.Name()] = fs
|
|
}
|
|
if k := d.known(); k.Latest != "" {
|
|
out.Release = &releaseJSON{Latest: k.Latest, Checked: k.Checked.UTC().Format(time.RFC3339)}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// warnings are doctor's warnings, which never make it fail: another devvm
|
|
// first on PATH, low free space, a small host, policy files' lines that
|
|
// aren't rules, what in the VMs' folder isn't a VM's, VMs whose state
|
|
// devvm can't read, and running VMs' proxies that aren't confined.
|
|
func (d doctor) warnings(b backend.Backend) []msg.M {
|
|
var ms []msg.M
|
|
if m, ok := d.Path.other(); ok {
|
|
ms = append(ms, m)
|
|
}
|
|
if m, low := (backend.Space{Free: d.Free}).Warning(b); low {
|
|
ms = append(ms, m)
|
|
}
|
|
ms = append(ms, smallHost(d.Host)...)
|
|
if d.Policies != nil {
|
|
ms = append(ms, d.Policies()...)
|
|
}
|
|
if d.Folders != nil {
|
|
ms = append(ms, d.Folders()...)
|
|
}
|
|
if d.States != nil {
|
|
ms = append(ms, d.States()...)
|
|
}
|
|
if m, ok := d.Pins.warning(); ok {
|
|
ms = append(ms, m)
|
|
}
|
|
if d.Proxies != nil {
|
|
ms = append(ms, d.Proxies()...)
|
|
}
|
|
return ms
|
|
}
|
|
|
|
// tips are doctor's advice, which it says rather than warns, as nothing
|
|
// is wrong: git's safe.bareRepository, which hardens git on this machine
|
|
// against a bare repo a VM makes.
|
|
func (d doctor) tips() []msg.M {
|
|
if d.GitBare != nil && !d.GitBare() {
|
|
return []msg.M{msg.DoctorGitBare()}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// The host devvm recommends: base asks for 4 CPUs and 8 GiB.
|
|
const (
|
|
recommendedCPUs = 4
|
|
recommendedMemoryGiB = 8
|
|
)
|
|
|
|
// doctor is devvm doctor's checks of this machine; tests set its fields.
|
|
type doctor struct {
|
|
Path onPath
|
|
Free func(path string) (uint64, error) // free bytes on path's volume
|
|
Host func() (vm.Host, error)
|
|
// Dirs is devvm's folders, whose CA folder the company proxy's check
|
|
// reads (sayProxyCA).
|
|
Dirs func() (paths.Dirs, error)
|
|
// Policies are the warnings for your policy files' lines that aren't
|
|
// rules (netpolicy.NotRules); nil for none.
|
|
Policies func() []msg.M
|
|
// Folders are the warnings for what in the VMs' folder isn't a VM's
|
|
// (state.VMFolderProblems); nil for none.
|
|
Folders func() []msg.M
|
|
// States are the warnings for VMs whose state devvm can't read
|
|
// (vm.StateProblems); nil for none.
|
|
States func() []msg.M
|
|
// Release is what the daily release check last found
|
|
// (upgrade.ReadKnown); nil for nothing.
|
|
Release func() upgrade.Known
|
|
// Pins is the check of whether this Linux host locks .git, and why
|
|
// not.
|
|
Pins pinsCheck
|
|
// GitBare reports whether this machine's git takes a bare repo only
|
|
// when it's named (hostsafety.BareExplicit); nil checks nothing.
|
|
GitBare func() bool
|
|
// Proxies are the warnings for running VMs whose proxy isn't confined
|
|
// to only what it needs (netpolicy.Proxy.Unconfined); nil for none.
|
|
Proxies func() []msg.M
|
|
}
|
|
|
|
// known is what the daily release check last found, if anything.
|
|
func (d doctor) known() upgrade.Known {
|
|
if d.Release == nil {
|
|
return upgrade.Known{}
|
|
}
|
|
return d.Release()
|
|
}
|
|
|
|
// run checks b, the backend new VMs get, and lists its features. It
|
|
// returns the last problem's message when b has problems, having warned
|
|
// the others. Warnings (another devvm on PATH, low free space, a small
|
|
// host) never change what it returns.
|
|
func (d doctor) run(ctx context.Context, u *ui.UI, b backend.Backend) error {
|
|
f := d.check(ctx, u, b)
|
|
problems := f.problems
|
|
if err := writeFeatures(u.Table(), b); err != nil {
|
|
return err
|
|
}
|
|
if _, err := exec.LookPath("docker"); err == nil {
|
|
u.Say(msg.DockerFound())
|
|
} else {
|
|
u.Say(msg.DockerMissing())
|
|
}
|
|
sayProxyCA(u, d.Dirs)
|
|
for _, m := range f.tips {
|
|
u.Say(m)
|
|
}
|
|
for _, m := range f.warnings {
|
|
u.Warn(m)
|
|
}
|
|
if k := d.known(); k.Latest != "" {
|
|
u.Say(msg.DoctorLatestRelease(k.Checked.Local().Format(time.DateOnly), k.Latest))
|
|
}
|
|
if len(problems) == 0 {
|
|
u.Say(msg.DoctorOK(b.Name(), devvmVersion()))
|
|
return nil
|
|
}
|
|
for _, p := range problems[:len(problems)-1] {
|
|
u.Warn(p.Msg)
|
|
}
|
|
return problems[len(problems)-1].Msg
|
|
}
|
|
|
|
// smallHost returns a warning for each way this machine is below the host
|
|
// devvm recommends: less memory, fewer CPUs. None when host can't say.
|
|
func smallHost(host func() (vm.Host, error)) []msg.M {
|
|
h, err := host()
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
var ms []msg.M
|
|
if h.MemoryGiB > 0 && h.MemoryGiB < recommendedMemoryGiB {
|
|
ms = append(ms, msg.HostMemoryLow(strconv.Itoa(h.MemoryGiB), strconv.Itoa(recommendedMemoryGiB)))
|
|
}
|
|
if h.CPUs > 0 && h.CPUs < recommendedCPUs {
|
|
ms = append(ms, msg.HostCpusFew(strconv.Itoa(h.CPUs), strconv.Itoa(recommendedCPUs)))
|
|
}
|
|
return ms
|
|
}
|
|
|
|
// sayProxyCA says, when HTTPS_PROXY or config.toml's proxy.https is set
|
|
// (settings.HostProxy) and devvm's CA folder has no CAs, that a proxy that
|
|
// inspects TLS needs its CA there: not a problem, as most proxies don't. A
|
|
// folder devvm would refuse is warned about.
|
|
func sayProxyCA(u *ui.UI, folders func() (paths.Dirs, error)) {
|
|
dirs, err := folders()
|
|
if err != nil {
|
|
return
|
|
}
|
|
if host, err := settings.HostProxy(dirs, os.Getenv); err != nil || host.HTTPS == "" {
|
|
return
|
|
}
|
|
cas, err := trust.Read(dirs.TrustedCAs())
|
|
var m msg.M
|
|
switch {
|
|
case errors.As(err, &m):
|
|
u.Warn(m)
|
|
case err == nil && len(cas) == 0:
|
|
u.Say(msg.DoctorProxyCA(dirs.TrustedCAs()))
|
|
}
|
|
}
|
|
|
|
// doctorBackend returns devvm's backends and the one new VMs get.
|
|
func doctorBackend(a *app) (*backend.Registry, backend.Backend, error) {
|
|
reg, err := a.registry()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
c, err := reg.For(new(state.VM))
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return reg, c.Backend, nil
|
|
}
|
|
|
|
// onPath finds the devvm first on PATH; tests set its fields.
|
|
type onPath struct {
|
|
LookPath func(file string) (string, error)
|
|
Executable func() (string, error)
|
|
}
|
|
|
|
// other returns a warning when the devvm first on PATH isn't this binary,
|
|
// both with their links resolved; none when devvm isn't on PATH or either
|
|
// can't be found.
|
|
func (p onPath) other() (msg.M, bool) {
|
|
first, err := p.LookPath("devvm")
|
|
if err != nil {
|
|
return msg.M{}, false
|
|
}
|
|
if first, err = filepath.EvalSymlinks(first); err != nil {
|
|
return msg.M{}, false
|
|
}
|
|
self, err := p.Executable()
|
|
if err != nil {
|
|
return msg.M{}, false
|
|
}
|
|
if self, err = filepath.EvalSymlinks(self); err != nil || self == first {
|
|
return msg.M{}, false
|
|
}
|
|
return msg.DevvmOtherFirst(first, self), true
|
|
}
|
|
|
|
// writeFeatures writes a table of every feature and how b has it: native
|
|
// green, emulated yellow, unreviewed red and none dim.
|
|
func writeFeatures(tab *ui.Table, b backend.Backend) error {
|
|
tab.Header("FEATURE", "SUPPORT")
|
|
for _, f := range backend.Features {
|
|
tab.Row(cell(string(f)), supportCell(b.Caps()[f]))
|
|
}
|
|
return tab.Flush()
|
|
}
|
|
|
|
// supportCell is how a backend has a feature, colored by what it means:
|
|
// none is dim, as a backend lacking a feature is no fault; unreviewed, an
|
|
// emulation devvm refuses, stands out in red.
|
|
func supportCell(s backend.Support) ui.Cell {
|
|
role := ui.Secondary
|
|
switch {
|
|
case s.IsNative():
|
|
role = ui.Good
|
|
case s.Usable():
|
|
role = ui.Attention
|
|
case s.IsEmulated():
|
|
role = ui.Bad
|
|
}
|
|
return ui.Cell{Text: s.String(), Role: role}
|
|
}
|