doctor

package
v0.1.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 6, 2026 License: AGPL-3.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package doctor is the node's self-diagnosis: sixteen host checks that each come from a real incident, and five safe fixes the panel may ask for.

Rules the package keeps:

  • Read-only by default. A check only reads /proc, /sys, a few config files and runs read-only commands (systemctl list-*, nft list, timedatectl show, dmesg, journalctl -k). Only Apply changes anything, only for the five compiled fix ids, never from a string the panel sends (params are validated), and a dry run changes nothing.
  • A check that cannot run here (container, no systemd, not root, not Linux) is SKIP with a reason, never a false OK.
  • Runs are bounded: every check has its own 10 s budget and the whole run 30 s, output of external commands is capped, a hung or panicking check becomes a SKIP. One run at a time (ErrBusy).
  • The package knows nothing about the agent: everything it needs from the agent (inbounds, settings, the stats ring, the clock offset) and from the machine (files, commands, sockets) arrives through Env, so tests run against a fake root directory and fake command runners.

Thresholds are constants in thresholds.go.

Index

Constants

View Source
const (
	// disk_space: mount, used_pct, free_mb, inode_pct
	CodeDiskUsage      = "disk_space.usage"
	CodeDiskUnreadable = "disk_space.unreadable"
	// journald_size: journal_mb, cap_mb
	CodeJournalSize = "journald_size.size"
	CodeJournalNone = "journald_size.none"
	// dstate_tasks: stuck, tasks
	CodeDstateNone      = "dstate_tasks.none"
	CodeDstateStuck     = "dstate_tasks.stuck"
	CodeDstateLoadIdle  = "dstate_tasks.load_idle"
	CodeDstateStuckLoad = "dstate_tasks.stuck_load_idle"
	CodeDstateNoProc    = "dstate_tasks.no_proc"
	CodeDstateCut       = "dstate_tasks.interrupted"
	// time_sync: offset_s, ntp_synced (yes | no | unknown)
	CodeTimeOffset = "time_sync.offset"
	// resolver: domains, failed_count, failed, median_ms
	CodeResolverOK     = "resolver.ok"
	CodeResolverFailed = "resolver.failed"
	// ipv6: ipv6 (yes | no), connect (ok | failed), warp_inbounds
	CodeIPv6None     = "ipv6.none"
	CodeIPv6NoneWarp = "ipv6.none_warp"
	CodeIPv6OK       = "ipv6.ok"
	CodeIPv6Stalls   = "ipv6.connect_failed"
	// foreign_vpn: names, count, on_our_ports
	CodeVPNNone  = "foreign_vpn.none"
	CodeVPNFound = "foreign_vpn.found"
	CodeVPNClash = "foreign_vpn.clash"
	// foreign_nft: table_count, rules, tables, nat_tables, ports
	CodeNftClean = "foreign_nft.clean"
	CodeNftFound = "foreign_nft.found"
	CodeNftNat   = "foreign_nft.nat"
	CodeNftHits  = "foreign_nft.hits_ports"
	CodeNftNone  = "foreign_nft.no_nft"
	CodeNftError = "foreign_nft.unreadable"
	// port_conflicts: checked, inbound_id, port, network, process, hop_from, hop_to, hop_holders
	CodePortsOK        = "port_conflicts.ok"
	CodePortsNone      = "port_conflicts.none"
	CodePortsHop       = "port_conflicts.hop"
	CodePortsTLS       = "port_conflicts.tls"
	CodePortsFailedBnd = "port_conflicts.bind_failed"
	CodePortsHeld      = "port_conflicts.held"
	CodePortsNoTable   = "port_conflicts.no_table"
	// net_baseline: differs, notes (comma separated tokens, see baselineDiff)
	CodeBaselineOK    = "net_baseline.ok"
	CodeBaselineNotes = "net_baseline.ok_notes"
	CodeBaselineDiff  = "net_baseline.differs"
	// cert_expiry: checked, reason, days_left, inbound_id, server_name
	CodeCertOK         = "cert_expiry.ok"
	CodeCertAgent      = "cert_expiry.agent"
	CodeCertInbound    = "cert_expiry.inbound"
	CodeCertUnreadable = "cert_expiry.unreadable"
	CodeCertNone       = "cert_expiry.none"
	// memory_pressure: avail_pct, swap_pct, oom_kills (a number or "unknown")
	CodeMemUsage  = "memory_pressure.usage"
	CodeMemNoInfo = "memory_pressure.no_meminfo"
	// cpu_softirq: softirq_pct, cpu_pct, samples, need
	CodeCPULoad       = "cpu_softirq.load"
	CodeCPUCollecting = "cpu_softirq.collecting"
	// kernel_headers: kernel, missing, mode (auto | kernel | userspace), virt
	CodeHeadersNoAwg     = "kernel_headers.no_awg"
	CodeHeadersContainer = "kernel_headers.container"
	CodeHeadersReady     = "kernel_headers.ready"
	CodeHeadersUserspace = "kernel_headers.userspace"
	CodeHeadersOptional  = "kernel_headers.optional"
	CodeHeadersMissing   = "kernel_headers.missing"
	// awg_backend: backend, version, mode, reason, hint
	CodeAwgNone        = "awg_backend.none"
	CodeAwgNoEngine    = "awg_backend.no_engine"
	CodeAwgRunning     = "awg_backend.running"
	CodeAwgForwardDrop = "awg_backend.forward_drop"
	CodeAwgUnavailable = "awg_backend.unavailable"
	// warp_path: state, backend, colo, inbounds, hint, error
	CodeWarpNoManager   = "warp_path.no_manager"
	CodeWarpUnused      = "warp_path.unused"
	CodeWarpNoAccount   = "warp_path.not_configured"
	CodeWarpHostClash   = "warp_path.host_clash"
	CodeWarpUp          = "warp_path.up"
	CodeWarpCheckFailed = "warp_path.check_failed"
	CodeWarpStarting    = "warp_path.starting"
	CodeWarpNoBackend   = "warp_path.no_backend"
	CodeWarpPausedUsed  = "warp_path.paused_used"
	CodeWarpPaused      = "warp_path.paused"
	CodeWarpDown        = "warp_path.down"
	CodeWarpUnknown     = "warp_path.unknown_state"
	// Any check: why it did not run. skip.unsupported has reason (English, from the host probe).
	CodeSkipUnsupported = "skip.unsupported"
	CodeSkipTimeout     = "skip.timeout"
	CodeSkipInternal    = "skip.internal"
	CodeSkipUnknown     = "skip.unknown_check"
)

Detail codes: the stable name of the fact line of a Result ("<check id>.<variant>", agent.proto DoctorResult.detail_code). The admin UI writes a localized sentence per code from Result.Params (the English Detail stays for logs, old panels and codes the UI does not know). A code is never renamed; add new ones. Params named in the comments are what the sentence of that code uses; numbers are plain decimal strings.

View Source
const (
	CheckDiskSpace      = "disk_space"
	CheckJournaldSize   = "journald_size"
	CheckDstateTasks    = "dstate_tasks"
	CheckTimeSync       = "time_sync"
	CheckResolver       = "resolver"
	CheckIPv6           = "ipv6"
	CheckForeignVPN     = "foreign_vpn"
	CheckForeignNft     = "foreign_nft"
	CheckPortConflicts  = "port_conflicts"
	CheckNetBaseline    = "net_baseline"
	CheckCertExpiry     = "cert_expiry"
	CheckMemoryPressure = "memory_pressure"
	CheckCPUSoftirq     = "cpu_softirq"
	CheckKernelHeaders  = "kernel_headers"
	CheckAwgBackend     = "awg_backend"
	CheckWarpPath       = "warp_path"
)

Check ids, in the order a full report lists them (agent.proto "CHECK IDS"). Append only.

View Source
const (
	FixJournaldVacuum = "journald_vacuum"
	FixApplyBaseline  = "apply_baseline"
	FixRestartInbound = "restart_inbound"
	FixSetResolver    = "set_resolver"
	FixReconnectWarp  = "reconnect_warp"
)

Fix ids (agent.proto "FIX IDS"). Only these five exist.

View Source
const (
	ErrUnknownFix      = "unknown_fix"
	ErrBadParams       = "bad_params"
	ErrNotApplicable   = "not_applicable"
	ErrUnsupportedHost = "unsupported_host"
	ErrFixBusy         = "busy"
)

The fix vocabulary of CommandResult.error for ApplyFix (agent.proto "DOCTOR").

Variables

Codes lists every detail code, for the test that keeps the admin UI's wording in step.

View Source
var ErrBusy = errors.New("busy")

ErrBusy is returned by Run while another run is in progress.

Functions

func CheckIDs

func CheckIDs() []string

CheckIDs returns every check id in report order.

func FixIDs

func FixIDs() []string

FixIDs returns the five fix ids.

func RecheckIDs

func RecheckIDs(fixID string) []string

RecheckIDs returns the checks to re-run after a fix, nil for an unknown fix id.

func ResolverTargets

func ResolverTargets(s Settings) []string

ResolverTargets is what set_resolver configures: the usable (IP, optionally host:port) entries of NodeSettings.dns_resolvers, else the default for the country.

Types

type AwgBackend

type AwgBackend struct {
	Mode      string // what NodeSettings.awg_backend asked: auto | kernel | userspace
	Name      string // "kernel" | "userspace"; "" when unavailable
	Version   string
	Available bool
	Reason    string // when unavailable: a short English fact
}

AwgBackend is the choice of the AmneziaWG backend as the engine made it (awg.BackendStatus).

type Container

type Container struct {
	Names []string
	Image string
	Ports []int // published host ports
}

Container is a docker container as far as foreign_vpn cares.

type Doctor

type Doctor struct {
	// contains filtered or unexported fields
}

Doctor runs the checks and the fixes. Create it with New.

func New

func New(env Env) *Doctor

New builds a doctor over env. Nil function fields in env get safe defaults.

func (*Doctor) Apply

func (d *Doctor) Apply(ctx context.Context, fixID string, dryRun bool, params map[string]string) FixOutcome

Apply runs one of the five fixes. The id is compared against a compiled list and never reaches a shell; params are validated (an inbound id must be one this agent runs). dryRun changes nothing: it only reads and describes. One fix at a time.

func (*Doctor) Run

func (d *Doctor) Run(ctx context.Context, ids []string) (*Report, error)

Run executes the checks in ids (empty = all, a full report) and returns one Result per requested id, in report order for a full run and in request order otherwise. An unknown id gives SKIP "unknown check". It returns ErrBusy while another run is in progress.

type Env

type Env struct {
	// Root is prefixed to every absolute path the checks read (/proc/..., /etc/..., /var/log/...); "" = the
	// real root. Commands and syscalls are not redirected: they go through Run, Statfs, ... below.
	Root string
	// StateDir is the agent state directory; its volume is checked for free space too.
	StateDir string
	// Virt is systemd-detect-virt style ("kvm", "openvz", "lxc", "none", "unknown", "").
	Virt string
	// CPUs is the logical CPU count (0 = runtime.NumCPU).
	CPUs int
	// SelfPID is the agent's pid: sockets it holds are "ours".
	SelfPID int
	// Unsupported, when non-empty, makes every check SKIP and every fix unsupported_host (not a Linux host).
	Unsupported string

	// Machine side.
	Statfs   func(path string) (FSStat, error)
	Run      func(ctx context.Context, name string, args ...string) ([]byte, error) // stdout; error carries stderr
	LookPath func(name string) (string, error)
	Readlink func(path string) (string, error) // absolute path, not rooted; nil = os.Readlink under Root
	Sleep    func(ctx context.Context, d time.Duration)
	Now      func() time.Time
	// Dial is a TCP connect attempt that is closed at once.
	Dial func(ctx context.Context, network, addr string) error
	// Lookup resolves host with the host's own resolver; LookupVia asks one server ("ip:port") directly.
	Lookup    func(ctx context.Context, host string) error
	LookupVia func(ctx context.Context, server, host string) error
	// ServedCert returns the leaf certificate a TLS listener at addr (host:port) serves for sni.
	ServedCert func(ctx context.Context, addr, sni string) (*x509.Certificate, error)
	// Docker lists the containers through the read-only socket API; an error means "no docker here".
	Docker func(ctx context.Context) ([]Container, error)

	// Agent side.
	Settings func() Settings
	Inbounds func() []Inbound
	// Samples returns the stats ring samples of the last window, oldest first.
	Samples func(window time.Duration) []Sample
	// Offset is the panel clock minus the local clock in seconds, measured at Hello.
	Offset            func() int64
	AgentCertNotAfter func() time.Time
	// OwnIface says an interface was created by the agent (nil = none is).
	OwnIface func(name string) bool
	// AwgBackend is the choice of the AmneziaWG backend (awg_backend check); nil = this build has no awg engine.
	AwgBackend func() AwgBackend
	// Warp is the WARP manager's view (warp_path check); nil = this build has no WARP manager.
	Warp func(ctx context.Context) WarpInfo
	// HostPath lists clashes of the host with the tunnel path (a routing table or rule preference another tool uses, a
	// FORWARD drop policy); nil = not checked.
	HostPath func(ctx context.Context) []PathFinding
	// UnitGen is the generation of the systemd unit the agent runs from (MISTGATE_UNIT_GEN), 0 = unknown.
	UnitGen int

	// Fix actions.
	ApplyBaseline  func(ctx context.Context) error
	RestartInbound func(ctx context.Context, inboundID string) (uint32, error)        // "" = every FAILED inbound
	ReconnectWarp  func(ctx context.Context) (bool, error)                            // true when a down tunnel was reconnected
	RecheckWarp    func(ctx context.Context) (checked, thresholdDown bool, err error) // thresholdDown also covers a scheduled check that just crossed the threshold
	Fixer          hostctl.Fixer                                                      // nil = journal/resolver fixes unsupported

	// Set by Run: the previous result of a check.
	Prev func(id string) (Result, bool)
	// contains filtered or unexported fields
}

Env is everything the checks and fixes use from the outside. Production code gets the machine side from DefaultEnv and fills the agent side; a test points Root at a temp directory and replaces the functions. Nil function fields get defaults (nothing configured, real clock) in New.

func DefaultEnv

func DefaultEnv() Env

DefaultEnv returns the machine side of an Env for this host: real commands (output capped), sockets, resolver and docker socket. The caller fills the agent side (Inbounds, Settings, ...). On a non-Linux host every check is SKIP (Unsupported is set).

type FSStat

type FSStat struct {
	BlockSize uint64
	Blocks    uint64
	Bfree     uint64
	Bavail    uint64
	Files     uint64
	Ffree     uint64
}

FSStat is what statfs says about a mount.

type FixOutcome

type FixOutcome struct {
	OK       bool
	Affected uint32
	Detail   string // short English fact line: what would happen / what was done
	Params   map[string]string
	Err      string // "" when OK; else one of the Err* words or "failed: <message>"
}

FixOutcome is the answer to Apply; the agent turns it into a CommandResult.

type Inbound

type Inbound struct {
	ID       string
	Protocol string
	Network  string // "udp" | "tcp"
	Port     int
	HopFrom  int // 0 = no hop range
	HopTo    int
	Enabled  bool
	Egress   string // "direct" | "warp"
	TLSMode  string // "acme_domain" | "acme_ip" | "self_signed" | ""
	// ServerName is the TLS server name (or IP for acme_ip).
	ServerName string
	State      string // "starting" | "running" | "failed" | "stopped"
	Error      string // why it is not running
	// CertNotAfter is what the engine reported when the inbound was last applied; zero = unknown. It can be
	// stale for ACME (renewal happens later), so it is only trusted for self-signed certificates.
	CertNotAfter time.Time
	// TLSPort is the TCP port of the inbound's HTTPS listener (decoy and ACME), 0 = none. The served certificate
	// is read there, but only if the listener is ours (see TLSDown and the socket table).
	TLSPort int
	// TLSDown is why the engine says that listener is not up ("masq_tcp: ... address already in use"), "" = up.
	TLSDown string
}

Inbound is one inbound as the doctor sees it.

type PathFinding

type PathFinding struct{ ID, Detail string }

PathFinding is one clash of the host with the tunnel path (warp.Finding): "table_in_use" | "rule_pref_in_use" | "interface_in_use" | "forward_drop".

type Report

type Report struct {
	Results  []Result
	Partial  bool // only a subset of the checks ran
	Duration time.Duration
}

Report is the outcome of Run.

type Result

type Result struct {
	ID     string
	Status Status
	// Detail is a short English fact line (at most 200 bytes).
	Detail string
	// Code names the fact line for the UI (codes.go): it writes the localized sentence from Code and Params.
	Code string
	// Params fill i18n placeholders; numbers are plain decimal strings, lists are comma separated.
	Params map[string]string
	// FixID is the fix offered (only with WARN/FAIL); empty = none.
	FixID    string
	Measured time.Time
}

Result is one check's outcome; it becomes one DoctorResult.

func (Result) TitleKey

func (r Result) TitleKey() string

TitleKey is the i18n key of the one-line title.

type Ring

type Ring struct {
	// contains filtered or unexported fields
}

Ring keeps the last ringSize host samples for cpu_softirq and the idle-load rule. Safe for concurrent use.

func (*Ring) Add

func (r *Ring) Add(s Sample)

Add records a sample (the agent calls it once per stats interval).

func (*Ring) Since

func (r *Ring) Since(now time.Time, window time.Duration) []Sample

Since returns the samples taken at or after now-window, oldest first.

type Sample

type Sample struct {
	At      time.Time
	CPU     float64 // total busy %
	Softirq float64 // softirq %
	Load1   float64
}

Sample is one stats-interval host sample kept by the agent (Ring).

type Settings

type Settings struct {
	Country   string   // ISO 3166-1 alpha-2, "" = unknown
	Resolvers []string // NodeSettings.dns_resolvers
}

Settings is the part of NodeSettings the doctor needs.

type Status

type Status int

Status mirrors agent.v1.DoctorStatus (values 1..4), so the agent converts with a plain cast.

const (
	OK   Status = 1
	Warn Status = 2
	Fail Status = 3
	Skip Status = 4
)

func (Status) String

func (s Status) String() string

type WarpInfo

type WarpInfo struct {
	Configured bool // the node has a WarpSpec (paused included)
	// State: "none" | "unavailable" | "starting" | "up" | "down" | "disabled" (warp.State.String()).
	State         string
	Backend       string
	Endpoint      string
	Colo          string
	LastError     string
	LastHandshake time.Time
}

WarpInfo is the WARP manager's view at the time of the check.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL