Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions internal/inventory/inventory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,11 @@ name = "db"
"[[host]]\nname = \"db\"\n[[host]]\nname = \"db\"": "db is there twice",
"": "no machines",
} {
if _, err := load(content); err == nil || !strings.Contains(err.Error(), wantErr) {
t.Errorf("%q: got %v, want %q", content, err, wantErr)
}
t.Run(wantErr, func(t *testing.T) {
if _, err := load(content); err == nil || !strings.Contains(err.Error(), wantErr) {
t.Errorf("%q: got %v, want %q", content, err, wantErr)
}
})
}
}

Expand All @@ -102,15 +104,17 @@ func TestSelectFind(t *testing.T) {
"-1": `"-1" matches 2 machines`, // ambiguous
"mail": `no machine matches "mail"`,
} {
i, err := Find(hosts, name)

got := fmt.Sprint(i)
if err != nil {
got = err.Error()
}

if got != want {
t.Errorf("find %q: got %s, want %s", name, got, want)
}
t.Run("find "+name, func(t *testing.T) {
i, err := Find(hosts, name)

got := fmt.Sprint(i)
if err != nil {
got = err.Error()
}

if got != want {
t.Errorf("got %s, want %s", got, want)
}
})
}
}
71 changes: 35 additions & 36 deletions internal/swarm/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,52 +34,49 @@ func TestCommandQuoting(t *testing.T) {
"DescribeStack": Docker("docker").DescribeStack(name),
"DescribeContainer": Docker("docker").DescribeContainer(name),
} {
dir := t.TempDir()
t.Run(what, func(t *testing.T) {
dir := t.TempDir()

c := exec.CommandContext(t.Context(), "sh", "-c", cmd)
c.Dir = dir
c := exec.CommandContext(t.Context(), "sh", "-c", cmd)
c.Dir = dir

out, _ := c.CombinedOutput() // describe's sections may fail on fakes: only the arguments matter
if !strings.Contains(string(out), "["+name+"]") && !strings.Contains(string(out), "label=com.docker.compose.project="+name+"]") {
t.Errorf("%s: the name isn't one argument:\n%s\nran: %s", what, out, cmd)
}
out, _ := c.CombinedOutput() // describe's sections may fail on fakes: only the arguments matter
if !strings.Contains(string(out), "["+name+"]") && !strings.Contains(string(out), "label=com.docker.compose.project="+name+"]") {
t.Errorf("the name isn't one argument:\n%s\nran: %s", out, cmd)
}

if _, err := os.Stat(filepath.Join(dir, "pwned")); err == nil {
t.Errorf("%s: the name ran a command", what)
}
if _, err := os.Stat(filepath.Join(dir, "pwned")); err == nil {
t.Error("the name ran a command")
}
})
}
}

// Stream runs a one-shot command under a time limit, and follows a logs command with
// -f and a terminal; a failure ends the stream with a line saying so.
// -f and a terminal.
func TestStream(t *testing.T) {
testutil.FakeBin(t, "ssh", `for a; do last=$a; done
case "$*" in *-tt*) echo tty ;; esac
echo "ran: $last"; echo oops >&2
case "$last" in *fail*) exit 3 ;; esac`)

h := inventory.Host{Address: "h"}

lines := func(follow bool, cmd string) string {
var got []string
for l := range Stream(t.Context(), h, cmd, follow) {
got = append(got, l)
}

return strings.Join(got, "|")
}
echo "ran: $last"; echo oops >&2`)

for _, tt := range []struct {
name string
follow bool
cmd, want string
}{
{false, "logs", "ran: timeout 30 sh -c 'logs'|oops"},
{true, "logs", "tty|ran: logs -f|oops"},
{false, "fail", "ran: timeout 30 sh -c 'fail'|oops|[exit status 3]"},
{"one-shot", false, "logs", "ran: timeout 30 sh -c 'logs'|oops"},
{"followed", true, "logs", "tty|ran: logs -f|oops"},
} {
if got := lines(tt.follow, tt.cmd); got != tt.want {
t.Errorf("Stream %q, follow %v:\n got %s\nwant %s", tt.cmd, tt.follow, got, tt.want)
}
t.Run(tt.name, func(t *testing.T) {
var lines []string
for l := range Stream(t.Context(), inventory.Host{Address: "h"}, tt.cmd, tt.follow) {
lines = append(lines, l)
}

if got := strings.Join(lines, "|"); got != tt.want {
t.Errorf("Stream %q, follow %v:\n got %s\nwant %s", tt.cmd, tt.follow, got, tt.want)
}
})
}
}

Expand All @@ -91,12 +88,14 @@ func TestUnitAction(t *testing.T) {
testutil.FakeBin(t, "systemctl", `echo "systemctl $*"; exit 1`)

for uid, want := range map[string]string{"0": "systemctl --no-block restart it's", "1000": "sudo systemctl --no-block restart it's"} {
t.Setenv("FAKE_UID", uid)

out, err := exec.CommandContext(t.Context(), "bash", "-c", UnitAction(Restart, "it's")).CombinedOutput()
if err == nil || strings.TrimSpace(string(out)) != want {
t.Errorf("uid %s: %v, ran %q, want %q once", uid, err, out, want)
}
t.Run("uid "+uid, func(t *testing.T) {
t.Setenv("FAKE_UID", uid)

out, err := exec.CommandContext(t.Context(), "bash", "-c", UnitAction(Restart, "it's")).CombinedOutput()
if err == nil || strings.TrimSpace(string(out)) != want {
t.Errorf("%v, ran %q, want %q once", err, out, want)
}
})
}
}

Expand Down
72 changes: 65 additions & 7 deletions internal/swarm/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net"
"path"
"slices"
"strconv"
"strings"
Expand Down Expand Up @@ -42,7 +43,8 @@ type Machine struct {
MemTotal, MemAvailable, SwapTotal, SwapFree uint64 // bytes

Disks []Disk
Processes []Process // the busiest, from top
Sensors []Sensor // the TopN hottest temperatures, hottest first; none in VMs and containers
Processes []Process // the TopN busiest, from top
}

// Disk is a mounted filesystem, in bytes.
Expand All @@ -51,18 +53,25 @@ type Disk struct {
Size, Used, Free uint64
}

// Sensor is a temperature sensor: its chip (coretemp, nvme...), its label, in °C.
type Sensor struct {
Chip, Label string
Temp float64
}

// Process is one of top's processes; CPU and Mem in percent.
type Process struct {
PID, User, Command string
CPU, Mem float64
}

// TopN is how many of top elements to show at most in tables on a machine's card.
const TopN = 5

// DescribeMachine is the describe command of a machine, for ParseMachine. top's
// first frame averages since boot: the second covers the last second. A home that
// doesn't exist keeps the user's top settings (~/.toprc: a line per CPU, other
// columns...) out of the format parseTop reads. df leaves out
// pseudo filesystems, container layers and snaps. lscpu runs in the C locale, so
// that its field names are the ones sed looks for.
// top: values in the last second, its second frame, whole.
// temps: grep -H prints each hwmon file as path:value, for parseSensors.
// disks: df leaves out pseudo filesystems, container layers and snaps.
func DescribeMachine() string {
return inSections(
[2]string{"system", `echo "os=$(. /etc/os-release && echo "$PRETTY_NAME")"
Expand All @@ -75,7 +84,8 @@ echo "uptime=$(cut -d' ' -f1 /proc/uptime)"
echo "load=$(cut -d' ' -f1-3 /proc/loadavg)"`},
[2]string{"memory", "grep -E '^(MemTotal|MemAvailable|SwapTotal|SwapFree):' /proc/meminfo"},
[2]string{"disks", "df -P -k -x tmpfs -x devtmpfs -x overlay -x squashfs -x efivarfs"},
[2]string{"top", "HOME=/nonexistent XDG_CONFIG_HOME=/nonexistent LC_ALL=C top -b -n 2 -d 1 -w 512 | awk '/^top -/ {n++} n == 2' | head -n 12"},
[2]string{"temps", "grep -H . /sys/class/hwmon/hwmon*/name /sys/class/hwmon/hwmon*/temp*_label /sys/class/hwmon/hwmon*/temp*_input 2>/dev/null"},
[2]string{"top", "HOME=/nonexistent XDG_CONFIG_HOME=/nonexistent LC_ALL=C top -b -n 2 -d 1 -w 512 | awk '/^top -/ {n++} n == 2'"},
)
}

Expand Down Expand Up @@ -119,7 +129,9 @@ func ParseMachine(out string) (Machine, error) {
}

m.Disks = parseDisks(sec["disks"])
m.Sensors = parseSensors(sec["temps"])
m.CPUBusy, m.Processes = parseTop(sec["top"])
m.Sensors, m.Processes = m.Sensors[:min(len(m.Sensors), TopN)], m.Processes[:min(len(m.Processes), TopN)]

return m, nil
}
Expand Down Expand Up @@ -147,6 +159,52 @@ func parseDisks(raw string) []Disk {
return disks
}

// maxTemp is the temperature, in °C, from which a sensor is taken for an unconnected input.
const maxTemp = 125

// parseSensors reads hwmon's files as grep -H prints them (path:value).
// A sensor without a label is named after its file.
// Each sensor has 3 files: name, label and input:
// .../hwmon0/name:nvme <- Chip
// .../hwmon0/temp2_label:Sensor 1 <- Label
// .../hwmon0/temp2_input:33850 <- Temp (milliC)
func parseSensors(raw string) []Sensor {
values := map[string]string{} // by path
var inputs []string

for line := range strings.SplitSeq(raw, "\n") {
file, value, ok := strings.Cut(line, ":")
if !ok {
continue
}

values[file] = value
if strings.HasSuffix(file, "_input") {
inputs = append(inputs, file)
}
}

var sensors []Sensor

for _, in := range inputs {
temp := number(values[in]) / 1000
if temp <= 0 || temp >= maxTemp {
continue
}

sensor := strings.TrimSuffix(in, "_input")
sensors = append(sensors, Sensor{
Chip: values[path.Dir(in)+"/name"],
Label: cmp.Or(values[sensor+"_label"], path.Base(sensor)),
Temp: temp,
})
}

slices.SortStableFunc(sensors, func(a, b Sensor) int { return cmp.Compare(b.Temp, a.Temp) })

return sensors
}

// parseTop reads top's frame: the CPUs' busy percent, from the idle one on the
// %Cpu(s) line, and the processes under the PID header line. busy is nil without it.
// That line's values are 5 wide, with no space of their own: a full one touches
Expand Down
11 changes: 11 additions & 0 deletions internal/swarm/describe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,21 @@ func TestParseMachine(t *testing.T) {
t.Errorf("top: %v %+v", m.CPUBusy, m.Processes)
}

if len(m.Sensors) != 3 || m.Sensors[0] != (Sensor{Chip: "nvme", Label: "Sensor 2", Temp: 87.85}) {
t.Errorf("sensors: %+v", m.Sensors)
}

if _, err := ParseMachine(sshError); err == nil {
t.Error("ssh's error parsed as a machine")
}

// Without a label, a sensor is named after its file; an unconnected input is left out.
sensors := parseSensors("/sys/class/hwmon/hwmon1/name:cpu_thermal\n/sys/class/hwmon/hwmon1/temp1_input:49173\n" +
"/sys/class/hwmon/hwmon2/name:nct6798\n/sys/class/hwmon/hwmon2/temp7_input:127000")
if len(sensors) != 1 || sensors[0] != (Sensor{Chip: "cpu_thermal", Label: "temp1", Temp: 49.173}) {
t.Errorf("sensors: %+v", sensors)
}

// An idle machine's 100.0 touches the comma before it: still idle, not busy.
if busy, _ := parseTop("%Cpu(s): 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st"); busy == nil || *busy != 0 {
t.Errorf("an idle machine is %v%% busy", busy)
Expand Down
4 changes: 4 additions & 0 deletions internal/swarm/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Report struct {
Load *float64 // percent, nil if unknown: the 1-minute load per CPU, past 100 when tasks wait
Memory *float64 // percent in use (not available to programs), nil if unknown
Disk *float64 // percent used of the fullest local disk, nil if unknown
Temp *float64 // °C of the hottest sensor, nil if none (VMs, containers)
Revision string // NixOS: the git commit the system was built from, if set
Units []Unit
Docker Docker // "" without docker
Expand Down Expand Up @@ -236,6 +237,9 @@ func (s Stack) Bad() []Container {
// FullDisk is the use, in percent, from which the fullest disk is a problem.
const FullDisk = 90

// HotTemp is the temperature, in °C, from which the hottest sensor needs attention.
const HotTemp = 85

// Problems lists what's wrong: the host is down, or failed commands, a disk nearly
// full, failed units, broken containers, and what just restarted on its own.
func (r Report) Problems() []string {
Expand Down
64 changes: 35 additions & 29 deletions internal/swarm/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,46 +10,52 @@ import (
// docker words it, plays no part.
func TestContainerCondition(t *testing.T) {
for _, tt := range []struct {
state, health string
code int
want Condition
name, state, health string
code int
want Condition
}{
{"running", "", 0, Fine},
{"running", "healthy", 0, Fine},
{"running", "starting", 0, Warning},
{"running", "unhealthy", 0, Broken},
{"exited", "", 0, Fine},
{"exited", "", 137, Broken},
{"restarting", "", 1, Broken},
{"created", "", 0, Warning},
{"paused", "healthy", 0, Warning},
{"removing", "", 0, Warning},
{"dead", "", 0, Broken},
{"running", "running", "", 0, Fine},
{"health starting", "running", "starting", 0, Warning},
{"unhealthy", "running", "unhealthy", 0, Broken},
{"init container done", "exited", "", 0, Fine},
{"crashed", "exited", "", 137, Broken},
{"crash loop", "restarting", "", 1, Broken},
{"created", "created", "", 0, Warning},
} {
c := Container{State: tt.state, Health: tt.health, ExitCode: tt.code, Status: "Up 2 hours (unhealthy)"}
if got := c.Condition(); got != tt.want {
t.Errorf("%s, health %q, exit %d: %v, want %v", tt.state, tt.health, tt.code, got, tt.want)
}
t.Run(tt.name, func(t *testing.T) {
c := Container{State: tt.state, Health: tt.health, ExitCode: tt.code, Status: "Up 2 hours (unhealthy)"}
if got := c.Condition(); got != tt.want {
t.Errorf("%s, health %q, exit %d: %v, want %v", tt.state, tt.health, tt.code, got, tt.want)
}
})
}
}

// A unit is broken failed, a warning changing, fine active, and else idle; a
// machine is broken down, a warning with problems, else fine.
func TestCondition(t *testing.T) {
for active, want := range map[string]Condition{"failed": Broken, "activating": Warning, "active": Fine, "inactive": Idle} {
if got := (Unit{Active: active}).Condition(); got != want {
t.Errorf("unit %s: %v, want %v", active, got, want)
}
t.Run("unit "+active, func(t *testing.T) {
if got := (Unit{Active: active}).Condition(); got != want {
t.Errorf("%v, want %v", got, want)
}
})
}

for r, want := range map[*Report]Condition{
{Err: errors.New("refused")}: Broken,
{Errors: []string{"x: oops"}}: Warning,
{Disk: new(float64(FullDisk))}: Warning,
{Disk: new(12.0)}: Fine,
for _, tt := range []struct {
name string
r Report
want Condition
}{
{"machine down", Report{Err: errors.New("refused")}, Broken},
{"machine with a failed command", Report{Errors: []string{"x: oops"}}, Warning},
{"machine with a full disk", Report{Disk: new(float64(FullDisk))}, Warning},
{"machine fine", Report{Disk: new(12.0)}, Fine},
} {
if got := r.Condition(); got != want {
t.Errorf("%+v: %v, want %v", *r, got, want)
}
t.Run(tt.name, func(t *testing.T) {
if got := tt.r.Condition(); got != tt.want {
t.Errorf("%+v: %v, want %v", tt.r, got, tt.want)
}
})
}
}
Loading