hub/internal/fleet/hostview.go
trvon 725e609949
All checks were successful
release / build (push) Successful in 4m14s
fleet: intel failing feeds, boot/reboot lines
2026-11-20 07:43:03 -07:00

467 lines
14 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
package fleet
import (
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
)
const (
// rebootGraceSeconds: a reboot pending for longer than this flags the host (exit 1).
rebootGraceSeconds = 2 * 24 * 3600
hostEventLimit = 15
hostEventFetch = 200
)
// hostMetrics are the series `hub host` draws, in order.
var hostMetrics = []string{"score", "vuln_findings", "vuln_kev", "updates_apt_pending_count"}
// changeKinds are the history event kinds that describe a state change (RS10-T).
var changeKinds = map[string]bool{
"kernel_changed": true, "reboot_required_set": true, "reboot_required_cleared": true,
"app_version_changed": true, "app_run_finished": true,
}
// failedRunStatuses are the last-run words that count as a failed run (the job's own "failed" and systemd results).
var failedRunStatuses = map[string]bool{
"failed": true, "failure": true, "error": true, "exit-code": true, "timeout": true, "signal": true,
"core-dump": true, "watchdog": true, "resources": true,
}
// degradable reports an error a secondary request may survive (the server answered badly or not at all, but the
// credentials and the route are fine).
func degradable(err error) bool {
var te *TransportError
return errors.As(err, &te)
}
func str(v any) string { s, _ := v.(string); return s }
// strList returns the strings of a JSON array; anything else is nil.
func strList(v any) []string {
list, _ := v.([]any)
var out []string
for _, it := range list {
if s, ok := it.(string); ok && s != "" {
out = append(out, s)
}
}
return out
}
// shortKernel drops a Debian "+debNN-arch" suffix for display: 7.3.4+deb14-amd64 -> 7.3.4.
func shortKernel(release string) string {
if i := strings.Index(release, "+"); i > 0 {
return release[:i]
}
return release
}
// bootView renders the "boot" line from telemetry kernel_modules (kernel/module guard) and the reasons that make the host
// need attention. An older collector sends no kernel_modules: no line, no attention.
//
// next boot 7.2.15 ok
// next boot 7.3.4 MISSING zfs
// next boot unknown, cannot confirm zfs (the next boot kernel could not be determined)
// kernel held: zfs supports <=7.2, candidate 7.3
// dpkg interrupted: linux-image-amd64
//
// Parts are joined with "; ". Missing modules or an interrupted dpkg run make `hub host` exit 1.
func bootView(h map[string]any) (line string, attention []string) {
km := obj(h["kernel_modules"])
if len(km) == 0 {
return "", nil
}
next := str(km["next_boot_kernel"])
missing := strList(km["missing_modules"])
interrupted := strList(km["dpkg_interrupted"])
hold := obj(km["kernel_hold"])
var parts []string
switch {
case next != "" && len(missing) > 0:
parts = append(parts, "next boot "+shortKernel(next)+" MISSING "+strings.Join(missing, ", "))
case next != "":
parts = append(parts, "next boot "+shortKernel(next)+" ok")
case len(missing) > 0:
parts = append(parts, "next boot unknown, cannot confirm "+strings.Join(missing, ", "))
}
if held, _ := hold["held"].(bool); held {
reason := str(hold["reason"])
if reason == "" {
reason = "held"
}
parts = append(parts, "kernel held: "+reason)
}
if len(interrupted) > 0 {
parts = append(parts, "dpkg interrupted: "+strings.Join(interrupted, ", "))
}
if len(missing) > 0 {
attention = append(attention, "next boot kernel lacks modules: "+strings.Join(missing, ", "))
}
if len(interrupted) > 0 {
attention = append(attention, "dpkg interrupted: "+strings.Join(interrupted, ", "))
}
return strings.Join(parts, "; "), attention
}
// outcomeText renders reboot_outcome as "deferred (load) at <time>"; "" when the host reports none.
func outcomeText(h map[string]any) string {
o := obj(h["reboot_outcome"])
status := str(o["status"])
if status == "" {
return ""
}
if status == "reboot_requested" {
status = "requested"
}
text := status
if reason := str(o["reason"]); reason != "" {
text += " (" + reason + ")"
}
if at := str(o["at"]); at != "" {
text += " " + at
}
return text
}
func intOrDash(v any) string {
if v == nil {
return "-"
}
return dash(v)
}
// describeEvent renders one change event as a short readable phrase.
func describeEvent(kind, label string, data map[string]any) string {
arrow := func(label string) string {
return fmt.Sprintf("%s %s -> %s", label, dash(data["from"]), dash(data["to"]))
}
switch kind {
case "kernel_changed":
return arrow("kernel")
case "app_version_changed":
return arrow(label)
case "reboot_required_cleared":
return "reboot cleared"
case "reboot_required_set":
pkgs, _ := data["pkgs"].([]any)
names := make([]string, 0, len(pkgs))
for _, p := range pkgs {
names = append(names, dash(p))
}
if len(names) == 0 {
return "reboot required"
}
return "reboot required (" + strings.Join(names, ", ") + ")"
case "app_run_finished":
out := fmt.Sprintf("%s run %s", label, dash(data["status"]))
if p := str(data["phase"]); p != "" {
out += " (" + p + ")"
}
return out
}
return kind
}
type hostEvent struct {
TS string
Text string
Raw map[string]any
}
// hostEvents keeps the change events of a /v1/history envelope (newest first), at most hostEventLimit.
func hostEvents(env *Envelope, label string) []hostEvent {
var out []hostEvent
list, _ := obj(env.Raw["data"])["events"].([]any)
for _, it := range list {
e := obj(it)
kind := str(e["kind"])
if !changeKinds[kind] {
continue
}
out = append(out, hostEvent{TS: str(e["ts"]), Text: describeEvent(kind, label, obj(e["data"])), Raw: e})
if len(out) == hostEventLimit {
break
}
}
return out
}
// HostView fetches /v1/telemetry (required), /v1/history and /v1/series (best effort: a failure becomes a note)
// and prints one screen for host. Exit 1 when the host has known-exploited culprits, a reboot pending for more
// than two days, a failed last run of the blog application's maintenance job, a next boot kernel that lacks a module the
// running kernel has, or an interrupted dpkg run; else 0.
func HostView(ctx context.Context, c *Client, w io.Writer, asJSON bool, host, since string) (int, error) {
env, err := c.Telemetry(ctx, host)
if err != nil {
return 0, err
}
data := obj(env.Raw["data"])
if status := str(data["status"]); status != "ok" {
if status == "" {
status = "unavailable"
}
return 0, &TransportError{"telemetry " + status}
}
hosts := obj(data["hosts"])
h, ok := hosts[host].(map[string]any)
if !ok {
return 0, &ConfigError{fmt.Sprintf("host %q has no telemetry", host)}
}
var notes []string
// The application's display name is runtime data; "app" when the server sends none.
label := "app"
if n := str(obj(h["app"])["name"]); n != "" {
label = n
}
var events []hostEvent
if henv, err := c.History(ctx, host, "", since, hostEventFetch); err != nil {
if !degradable(err) {
return 0, err
}
notes = append(notes, "history unavailable ("+err.Error()+"); no change events")
} else {
events = hostEvents(henv, label)
}
series := map[string][]float64{}
rawSeries := map[string]any{}
for _, m := range hostMetrics {
senv, err := c.Series(ctx, host, m, since, seriesLimit)
if err != nil {
if !degradable(err) {
return 0, err
}
notes = append(notes, "series "+m+" unavailable ("+err.Error()+")")
continue
}
series[m] = seriesValues(senv)
rawSeries[m] = obj(senv.Raw["data"])["points"]
}
// attention: the exit-1 causes
var attention []string
vulns := obj(h["vulns"])
cs := culprits(h)
if len(cs) > 0 || edrCount(vulns["kev_count"]) > 0 {
attention = append(attention, "known-exploited vulnerable packages")
}
rebootSince := str(h["reboot_required_since"])
rebootAge := int64(-1)
if req, _ := h["reboot_required"].(bool); req {
if t, ok := parseTime(rebootSince); ok {
if g, ok := parseTime(env.Raw["generated_at"]); ok {
rebootAge = int64(g.Sub(t).Seconds())
if rebootAge > rebootGraceSeconds {
attention = append(attention, "reboot required for more than 2 days")
}
}
}
}
boot, bootAttention := bootView(h)
attention = append(attention, bootAttention...)
app := obj(h["app"])
lastRun := obj(app["last_run"])
if failedRunStatuses[strings.ToLower(str(lastRun["status"]))] {
attention = append(attention, label+" last run failed")
}
code := ExitOK
if len(attention) > 0 {
code = ExitDrift
}
if asJSON {
evRaw := make([]any, 0, len(events))
for _, e := range events {
evRaw = append(evRaw, e.Raw)
}
return code, WriteJSON(w, map[string]any{
"host": host, "generated_at": env.Raw["generated_at"], "since": since, "telemetry": h, "events": evRaw,
"series": rawSeries, "attention": nonNil(attention), "notes": nonNil(notes),
})
}
// header: last report age
report := "-"
if t, ok := parseTime(h["last_report_at"]); ok {
if g, ok := parseTime(env.Raw["generated_at"]); ok {
report = fmt.Sprintf("%s ago (%s)", HumanDuration(int64(g.Sub(t).Seconds())), str(h["last_report_at"]))
}
}
fmt.Fprintf(w, "%s last report %s\n", host, report)
fmt.Fprintf(w, "%-10s %s\n", "kernel", dash(h["kernel"]))
if boot != "" {
fmt.Fprintf(w, "%-10s %s\n", "boot", boot)
}
reboot := "no"
if req, _ := h["reboot_required"].(bool); req {
reboot = "REQUIRED"
if rebootSince != "" {
reboot += " since " + rebootSince
if rebootAge >= 0 {
reboot += " (" + HumanDuration(rebootAge) + ")"
}
}
if pkgs, _ := h["reboot_required_pkgs"].([]any); len(pkgs) > 0 {
names := make([]string, 0, len(pkgs))
for _, p := range pkgs {
names = append(names, dash(p))
}
reboot += " by " + strings.Join(names, ", ")
}
}
if last := outcomeText(h); last != "" {
reboot += "; last attempt " + last
}
fmt.Fprintf(w, "%-10s %s\n", "reboot", reboot)
if len(app) == 0 {
fmt.Fprintf(w, "%-10s not reported\n", label)
} else {
line := fmt.Sprintf("%s (latest %s)", dash(app["installed_version"]), dash(app["latest_version"]))
if len(lastRun) > 0 {
line += fmt.Sprintf(" last run %s %s %s", dash(lastRun["status"]), dash(lastRun["phase"]), dash(lastRun["completed_at"]))
} else {
line += " no run recorded"
}
fmt.Fprintf(w, "%-10s %s\n", label, line)
}
up := obj(h["updates"])
fmt.Fprintf(w, "%-10s %s apt pending, %s security, %s third-party, %s kept back\n", "updates",
intOrDash(up["apt_pending_count"]), intOrDash(up["security_pending_count"]),
intOrDash(up["third_party_pending_count"]), intOrDash(up["kept_back_count"]))
if len(vulns) == 0 {
fmt.Fprintf(w, "%-10s not reported\n", "vulns")
} else {
fmt.Fprintf(w, "%-10s %s: %s findings, %s fixable, %s high urgency, %s known-exploited\n", "vulns",
dash(vulns["status"]), intOrDash(vulns["finding_count"]), intOrDash(vulns["fixable_finding_count"]),
intOrDash(vulns["high_urgency_finding_count"]), intOrDash(vulns["kev_count"]))
for _, cu := range cs {
fmt.Fprintf(w, " known-exploited %s\n", cu)
}
}
fmt.Fprintf(w, "\nchanges (since %s)\n", since)
if len(events) == 0 {
fmt.Fprintln(w, " none")
}
for _, e := range events {
fmt.Fprintf(w, " %s %s\n", dashStr(e.TS), e.Text)
}
fmt.Fprintf(w, "\ntrend (since %s)\n", since)
for _, m := range hostMetrics {
vals, ok := series[m]
if !ok {
continue
}
_, _, last, has := minMaxLast(vals)
tail := "no data"
if has {
tail = "last " + fmtNum(last)
}
fmt.Fprintf(w, " %-26s %s %s\n", m, Sparkline(vals), tail)
}
if len(attention) > 0 {
fmt.Fprintf(w, "\nattention: %s\n", strings.Join(attention, "; "))
}
for _, n := range notes {
fmt.Fprintf(w, "note: %s\n", n)
}
return code, nil
}
func nonNil(s []string) []string {
if s == nil {
return []string{}
}
return s
}
// TrendView prints one sparkline row per host for metric over since. The host list comes from /v1/telemetry
// (the pseudo host _fleet for intel_age_hours). Exit 0; a metric or since that the server would refuse is exit 2.
func TrendView(ctx context.Context, c *Client, w io.Writer, asJSON bool, metric, since string) (int, error) {
if !ValidMetric(metric) {
return 0, &ConfigError{fmt.Sprintf("unknown metric %q (one of: %s)", metric, strings.Join(MetricNames, ", "))}
}
if !ValidSince(since) {
return 0, &ConfigError{fmt.Sprintf("bad --since %q (use 12h or 7d)", since)}
}
names := []string{FleetHost}
if metric != "intel_age_hours" {
env, err := c.Telemetry(ctx, "")
if err != nil {
return 0, err
}
data := obj(env.Raw["data"])
if status := str(data["status"]); status != "ok" {
if status == "" {
status = "unavailable"
}
return 0, &TransportError{"telemetry " + status}
}
names = sortedKeys(obj(data["hosts"]))
}
type row struct {
name string
vals []float64
raw any
err error
}
rows := make([]row, 0, len(names))
for _, n := range names {
env, err := c.Series(ctx, n, metric, since, seriesLimit)
if err != nil {
if !degradable(err) {
return 0, err
}
rows = append(rows, row{name: n, err: err})
continue
}
rows = append(rows, row{name: n, vals: seriesValues(env), raw: obj(env.Raw["data"])["points"]})
}
sort.SliceStable(rows, func(i, j int) bool { return rows[i].name < rows[j].name })
if asJSON {
out := map[string]any{}
for _, r := range rows {
if r.err != nil {
out[r.name] = map[string]any{"error": r.err.Error()}
continue
}
out[r.name] = r.raw
}
return ExitOK, WriteJSON(w, map[string]any{"metric": metric, "since": since, "hosts": out})
}
width := 0
for _, r := range rows {
if len(r.name) > width {
width = len(r.name)
}
}
fmt.Fprintf(w, "%s since %s\n", metric, since)
if len(rows) == 0 {
fmt.Fprintln(w, " no hosts")
}
for _, r := range rows {
if r.err != nil {
fmt.Fprintf(w, "%-*s unavailable (%v)\n", width, r.name, r.err)
continue
}
lo, hi, last, ok := minMaxLast(r.vals)
if !ok {
fmt.Fprintf(w, "%-*s %s no data\n", width, r.name, Sparkline(nil))
continue
}
fmt.Fprintf(w, "%-*s %s min %s max %s last %s\n", width, r.name, Sparkline(r.vals), fmtNum(lo), fmtNum(hi), fmtNum(last))
}
return ExitOK, nil
}