diff --git a/README.md b/README.md index d4f5c5b..c5ac6cf 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,11 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0). kernel, Docker version and uptime; load, swap, every disk and the backup timer; the containers using the most; certificate expiry for every hostname; and each container's state, health check, restarts, - CPU, memory and network traffic. Wide terminals get the cards side by + CPU, memory and network traffic. A history card draws load, memory + and disk over the last 30 days as sparklines, and says when the disk + fills up at the rate it grew this week: a small `interzone-stats` timer, + installed the first time the Dashboard opens, notes them on the server + every 10 minutes. Wide terminals get the cards side by side, the compact layout stacks them. While it's open it refreshes itself every 5 seconds (certificates every 5 minutes, or on `r`). The Dashboard, Users and the logs' service list open with what they diff --git a/internal/deploy/status.go b/internal/deploy/status.go index f6ef62b..b449c8b 100644 --- a/internal/deploy/status.go +++ b/internal/deploy/status.go @@ -37,9 +37,43 @@ type ServerStatus struct { Hosts []string // what Traefik serves for Matrix Served map[string][]string // host: the containers serving it Timer string // next scheduled backup, if any + History []Sample // the last 30 days, every 30 minutes Taken time.Time } +// Sample is the server at one time, as interzone-stats notes it every 10 +// minutes. +type Sample struct { + At time.Time + Load float64 // per CPU + MemUsed, MemTotal int64 // bytes + DiskUsed, DiskTotal int64 // bytes, of /matrix +} + +// DiskFull says when the disk fills up if it keeps growing as it did over +// the last week: zero if it doesn't grow, or there's under a day of history. +func (st *ServerStatus) DiskFull() time.Time { + h := st.History + if len(h) < 2 { + return time.Time{} + } + last := h[len(h)-1] + first := h[0] + for _, s := range h { + if last.At.Sub(s.At) <= 7*24*time.Hour { + first = s + break + } + } + span := last.At.Sub(first.At) + grew := last.DiskUsed - first.DiskUsed + if span < 24*time.Hour || grew <= 0 { + return time.Time{} + } + left := float64(last.DiskTotal-last.DiskUsed) / float64(grew) + return last.At.Add(time.Duration(left * float64(span))) +} + type Disk struct { Mount string Total, Used, Avail int64 // bytes @@ -93,6 +127,24 @@ const statusPlay = `- name: interzone status all=$(docker ps -aq --filter name=^matrix-) if [ -n "$all" ]; then docker inspect --format 'inspect={{.Name}} {{.RestartCount}} {{if .State.Health}}{{.State.Health.Status}}{{end}}' $all; fi docker ps --filter name=^matrix- --filter label=traefik.enable=true --format 'labels={{.Names}} {{.Labels}}' + if [ ! -x /usr/local/bin/interzone-stats ]; then + cat > /usr/local/bin/interzone-stats <<'EOF' + #!/bin/sh + # Written by interzone: notes load, memory and disk for its dashboard's history. + f=/var/lib/interzone-stats + echo "$(date +%s) $(cut -d' ' -f1 /proc/loadavg) $(nproc) $(awk '/^MemTotal:/{t=$2} /^MemAvailable:/{a=$2} END{print t-a, t}' /proc/meminfo) $( (df -Pk /matrix || df -Pk /) 2>/dev/null | awk 'NR==2{print $3, $2}')" >> $f + tail -n 4320 $f > $f.new && mv $f.new $f + EOF + chmod 755 /usr/local/bin/interzone-stats + printf '[Unit]\nDescription=Note load, memory and disk (interzone)\n\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/interzone-stats\n' > /etc/systemd/system/interzone-stats.service + printf '[Unit]\nDescription=Note load, memory and disk (interzone)\n\n[Timer]\nOnCalendar=*:0/10\n\n[Install]\nWantedBy=timers.target\n' > /etc/systemd/system/interzone-stats.timer + systemctl daemon-reload && systemctl enable --now interzone-stats.timer + fi >/dev/null 2>&1 + if [ "$IZ_HISTORY" = true ] && [ -f /var/lib/interzone-stats ]; then + awk '{l = $0} NR % 3 == 0 {print "hist=" $0} END {if (NR % 3) print "hist=" l}' /var/lib/interzone-stats + fi + environment: + IZ_HISTORY: "{{ interzone_history | default(false) }}" changed_when: false ` @@ -103,7 +155,8 @@ const statusPlay = `- name: interzone status // are; before anything runs behind Traefik, the usual ones are guessed. func Status(ctx context.Context, c *config.Config, certs bool) (*ServerStatus, error) { st := &ServerStatus{Taken: time.Now()} - res, err := runPlayJSON(ctx, c, "status", statusPlay, nil) + // The history is read with the certificates, every few minutes. + res, err := runPlayJSON(ctx, c, "status", statusPlay, map[string]any{"interzone_history": certs}) if err == nil { parseStatus(st, res["interzone status"].String("stdout")) } @@ -211,6 +264,17 @@ func parseStatus(st *ServerStatus, out string) { } case "timer": st.Timer = strings.TrimSpace(v) + case "hist": + if len(f) == 7 { + var n [7]float64 + for i := range f { + n[i], _ = strconv.ParseFloat(f[i], 64) + } + if n[2] > 0 { + st.History = append(st.History, Sample{At: time.Unix(int64(n[0]), 0), Load: n[1] / n[2], + MemUsed: int64(n[3]) * 1024, MemTotal: int64(n[4]) * 1024, DiskUsed: int64(n[5]) * 1024, DiskTotal: int64(n[6]) * 1024}) + } + } case "labels": st.served(v) case "ps": diff --git a/internal/deploy/status_test.go b/internal/deploy/status_test.go new file mode 100644 index 0000000..056f701 --- /dev/null +++ b/internal/deploy/status_test.go @@ -0,0 +1,66 @@ +package deploy + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "gopkg.in/yaml.v3" +) + +func TestStatusHistory(t *testing.T) { + day := int64(24 * 3600) + now := time.Now().Unix() + var out strings.Builder + // 10 GB disk, 1 GB more used each day, 8 days: 2 GB left, full in 2 days. + for i := int64(0); i <= 8; i++ { + used := i << 20 + out.WriteString("hist=" + strings.Join([]string{ + itoa(now - (8-i)*day), "1.00", "2", "1048576", "4194304", itoa(used), itoa(10 << 20)}, " ") + "\n") + } + st := &ServerStatus{} + parseStatus(st, out.String()) + if len(st.History) != 9 || st.History[0].Load != 0.5 || st.History[8].DiskUsed != 8<<30 || st.History[0].MemTotal != 4<<30 { + t.Fatalf("%+v", st.History) + } + if eta := time.Until(st.DiskFull()); eta < 47*time.Hour || eta > 49*time.Hour { + t.Errorf("full in %v, want 2 days", eta) + } + st.History = st.History[:1] + if !st.DiskFull().IsZero() { + t.Error("an estimate from one sample") + } +} + +// The stats script the status play installs runs and writes a sample. +func TestStatsScript(t *testing.T) { + var play []struct { + Tasks []struct { + Shell string `yaml:"ansible.builtin.shell"` + } + } + if err := yaml.Unmarshal([]byte(statusPlay), &play); err != nil { + t.Fatal(err) + } + sh := play[0].Tasks[0].Shell + if err := exec.Command("bash", "-n", "-c", sh).Run(); err != nil { + t.Fatal("the status shell doesn't parse:", err) + } + _, rest, _ := strings.Cut(sh, "<<'EOF'\n") + script, _, ok := strings.Cut(rest, "\nEOF\n") + if !ok { + t.Fatal("no stats script in the status play") + } + dir := t.TempDir() + script = strings.ReplaceAll(script, "/var/lib/interzone-stats", filepath.Join(dir, "stats")) + if out, err := exec.Command("sh", "-c", script).CombinedOutput(); err != nil { + t.Fatalf("%v: %s", err, out) + } + b, _ := os.ReadFile(filepath.Join(dir, "stats")) + if f := strings.Fields(string(b)); len(f) != 7 { + t.Errorf("sample %q", b) + } +} diff --git a/internal/ui/dashboard.go b/internal/ui/dashboard.go index 85901b3..70847e5 100644 --- a/internal/ui/dashboard.go +++ b/internal/ui/dashboard.go @@ -3,6 +3,8 @@ package ui import ( "context" "fmt" + "math" + "slices" "sort" "strings" "time" @@ -126,7 +128,7 @@ func (s *dashboardScreen) update(msg tea.Msg) tea.Cmd { if m.certs { s.certsAt = m.st.Taken } else if s.st != nil { - m.st.Certs = s.st.Certs + m.st.Certs, m.st.History = s.st.Certs, s.st.History } s.st = m.st saveCache("status", *m.st) @@ -257,6 +259,9 @@ func (s *dashboardScreen) view(w, h int) string { blocks = append(blocks, s.topCard(w, 0)) } } + if len(st.History) >= 2 && w >= 44 { + blocks = append(blocks, s.historyCard(w)) + } if len(st.Certs) > 0 { blocks = append(blocks, s.certCard(w)) } @@ -477,6 +482,65 @@ func (s *dashboardScreen) systemCard(w, h int) string { return card("System", lines, w, h, cFaint) } +// historyCard draws load, memory and disk over the days the server has +// noted them, and when the disk fills up at the rate it's growing. +func (s *dashboardScreen) historyCard(w int) string { + h := s.st.History + inner := w - 4 + kw := 9 + sw := max(6, inner-kw-24) + row := func(k string, f func(deploy.Sample) float64, note string) string { + vals := make([]float64, len(h)) + for i, x := range h { + vals[i] = f(x) + } + last := vals[len(vals)-1] + return lipgloss.NewStyle().Width(kw).Render(sMuted.Render(k)) + lipgloss.NewStyle().Foreground(usageColor(slices.Max(vals))).Render(sparkline(vals, sw)) + + " " + sTitle.Render(fmt.Sprintf("%4s", pct(last))) + sFaint.Render(note) + } + frac := func(a, b int64) float64 { + if b == 0 { + return 0 + } + return float64(a) / float64(b) + } + peak := func(f func(deploy.Sample) float64) string { + m := 0.0 + for _, x := range h { + m = max(m, f(x)) + } + return " peak " + pct(m) + } + load := func(x deploy.Sample) float64 { return x.Load } + mem := func(x deploy.Sample) float64 { return frac(x.MemUsed, x.MemTotal) } + disk := func(x deploy.Sample) float64 { return frac(x.DiskUsed, x.DiskTotal) } + full := " not growing" + if t := s.st.DiskFull(); !t.IsZero() { + full = fmt.Sprintf(" full in ~%d days", max(1, int(time.Until(t).Hours()/24))) + } + days := max(1, int(math.Round(h[len(h)-1].At.Sub(h[0].At).Hours()/24))) + title := fmt.Sprintf("Last %d days", days) + if days == 1 { + title = "Last day" + } + lines := []string{row("Load", load, peak(load)), row("Memory", mem, peak(mem)), row("Disk", disk, full)} + return card(title, lines, w, 0, cFaint) +} + +// sparkline draws values from 0 to 1 in w columns, each the highest of +// the values it covers. +func sparkline(vals []float64, w int) string { + const ticks = "▁▂▃▄▅▆▇█" + n := min(w, len(vals)) + var b strings.Builder + for i := range n { + m := slices.Max(vals[i*len(vals)/n : max(i*len(vals)/n+1, (i+1)*len(vals)/n)]) + t := int(math.Round(min(1, max(0, m)) * 7)) + b.WriteString(string([]rune(ticks)[t])) + } + return b.String() +} + // topCard lists what uses the most CPU and memory. func (s *dashboardScreen) topCard(w, h int) string { inner := w - 4 diff --git a/internal/ui/layout_test.go b/internal/ui/layout_test.go index 6e9b9d0..3dde56f 100644 --- a/internal/ui/layout_test.go +++ b/internal/ui/layout_test.go @@ -3,6 +3,7 @@ package ui import ( "flag" "fmt" + "math" "os" "path/filepath" "regexp" @@ -142,6 +143,13 @@ func openDashboard(a *App) { {Name: "matrix-traefik", State: "running", Status: "Up 3 days", Image: "traefik:v3.2.1", CPU: "0.20%", Mem: "60MiB / 7.8GiB", MemPerc: 0.7, Net: "2.1GB / 2.0GB"}, }} + // Two weeks every 30 minutes: a daily rhythm, the disk growing 2.4 GB a week. + for i := range 14 * 48 { + day := math.Sin(float64(i) / 48 * 2 * math.Pi) + st.History = append(st.History, deploy.Sample{At: time.Now().Add(-time.Duration(14*48-1-i) * 30 * time.Minute), + Load: 0.3 + 0.2*day, MemUsed: int64((0.55 + 0.1*day) * (8 << 30)), MemTotal: 8 << 30, + DiskUsed: (62 << 30) - int64(float64(14*48-1-i)/(7*48)*2.4*(1<<30)), DiskTotal: 80 << 30}) + } ds.st, ds.loading = st, false } diff --git a/internal/ui/testdata/layout/dashboard-120x36.txt b/internal/ui/testdata/layout/dashboard-120x36.txt index d934b88..9a36e0d 100644 --- a/internal/ui/testdata/layout/dashboard-120x36.txt +++ b/internal/ui/testdata/layout/dashboard-120x36.txt @@ -30,7 +30,7 @@ │ ││ │ synapse ██████████████ 7.6% 4.10% │ │ │ ││ │ postgres █████░░░░░░░░░ 2.7% 0.80% │ │ │ ◫ auto (wide) ctrl+l ││ │ traefik █░░░░░░░░░░░░░ 0.7% 0.20% │ │ -│ ◐ interzone ctrl+y ││ ↓ 14 more lines · ↑↓ scroll │ +│ ◐ interzone ctrl+y ││ ↓ 20 more lines · ↑↓ scroll │ │ ◂ fold ctrl+b menu ││ │ ╰────────────────────────╯╰────────────────────────────────────────────────────────────────────────────────────────────╯ r refresh · ↑↓ scroll · esc back · ctrl+c quit \ No newline at end of file diff --git a/internal/ui/testdata/layout/dashboard-180x50.txt b/internal/ui/testdata/layout/dashboard-180x50.txt index 89d32bd..c031e5c 100644 --- a/internal/ui/testdata/layout/dashboard-180x50.txt +++ b/internal/ui/testdata/layout/dashboard-180x50.txt @@ -19,8 +19,14 @@ │ ││ │ Next backup Tue 0000-00-00 00:00:00 UTC │ │ │ │ │ ▸ Mirrors ││ ╰──────────────────────────────────────────────────────────────────────╯ ╰───────────────────────────────────────────────────────────────────────╯ │ │ ││ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ -│ ▾ Servers ││ │ Certificates │ │ -│ ● example.org ││ │ ✓ Synapse matrix.example.org 60 days until 0000-00-00 · R11 │ │ +│ ▾ Servers ││ │ Last 14 days │ │ +│ ● example.org ││ │ Load ▄▄▅▄▃▂▂▃▄▅▄▄▃▂▂▃▄▅▄▄▃▂▂▃▄▅▄▃▂▂▃▄▄▅▄▃▂▂▃▄▄▅▄▃▂▂▃▄▅▄▄▃▂▂▃▄▅▄▄▃▂▃▄▄▅▄▃▂▂▃▄▄▅▄▃▂▂▃▄▅▄▄▃▂▂▃▄▅▄▄▃▂▂▃▄▅▄▃▂▂▃▄▄▅▄▃▂▂▃ 27% peak 50% │ │ +│ ││ │ Memory ▅▆▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▆▅▅▄▅▅▅▆▅▅▅▄▅▅▆▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▅▅▅▄▅▅▅▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▆▅▅▄▄▅▅▆▅▅▄▄▅▅▆▆▅▅▄▄▅ 54% peak 65% │ │ +│ ││ │ Disk ▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆▆ 78% full in ~52 days │ │ +│ ││ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │ +│ ││ ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ +│ ││ │ Certificates │ │ +│ ││ │ ✓ Synapse matrix.example.org 60 days until 0000-00-00 · R11 │ │ │ ││ │ ! Element Web element.example.org 12 days until 0000-00-00 · R11 │ │ │ ││ │ ✗ Cinny chat.other.net connection refused │ │ │ ││ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │ @@ -37,12 +43,6 @@ │ ││ │ │ ││ │ │ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ -│ ││ │ │ ◫ auto (wide) ctrl+l ││ │ │ ◐ interzone ctrl+y ││ │ │ ◂ fold ctrl+b menu ││ │ diff --git a/internal/ui/testdata/layout/dashboard-46x40.txt b/internal/ui/testdata/layout/dashboard-46x40.txt index 6ae314a..e27fca0 100644 --- a/internal/ui/testdata/layout/dashboard-46x40.txt +++ b/internal/ui/testdata/layout/dashboard-46x40.txt @@ -32,9 +32,9 @@ │ traefik █░░░░░░░░░ 0.7% 0.20% │ ╰──────────────────────────────────────────╯ ╭──────────────────────────────────────────╮ - │ Certificates │ - │ ✓ matrix.example.org │ - │ Synapse 60 days │ - │ ! element.example.org │ - ↓ 18 more lines · ↑↓ scroll + │ Last 14 days │ + │ Load ▅▅▅▅▅▅▅ 27% peak 50% │ + │ Memory ▆▆▆▆▆▆▆ 54% peak 65% │ + │ Disk ▆▆▆▆▆▆▆ 78% full in ~52 days │ + ↓ 24 more lines · ↑↓ scroll ‹ back ≡ menu ⋯ \ No newline at end of file diff --git a/internal/ui/testdata/layout/dashboard-48x20.txt b/internal/ui/testdata/layout/dashboard-48x20.txt index b604fcd..20921bd 100644 --- a/internal/ui/testdata/layout/dashboard-48x20.txt +++ b/internal/ui/testdata/layout/dashboard-48x20.txt @@ -16,5 +16,5 @@ │ ██████████████░░░░ │ │ ██████████░░░░░░░░░ │ ╰────────────────────╯ ╰─────────────────────╯ ╭────────────────────────────────────────────╮ - ↓ 37 more lines · ↑↓ scroll + ↓ 43 more lines · ↑↓ scroll ‹ back ≡ menu ⋯ \ No newline at end of file