diff --git a/README.md b/README.md index df0ad7b..d4f5c5b 100644 --- a/README.md +++ b/README.md @@ -243,11 +243,14 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0). - **Alerts** (off until you turn them on): a systemd timer on the server checks it every few minutes, even when your computer is off, for failed `matrix-*` services, the homeserver not answering, a - certificate expiring within 14 days and a disk over 90% full, and + certificate expiring within 14 days, a disk over 90% full and a mirror + (registry, packages, playbook) not answering, and sends a message when that changes (once when something breaks, once when it's fixed) to an ntfy topic, or as `{"text": …}` to a webhook such as a Hookshot room, Slack, Discord or Mattermost. Applying sends - a test message. + a test message. Once a day it also looks at the playbook's changelog + and sends the entries newer than your last update, marking with ★ + those about your homeserver or enabled components. - **Users** (Synapse): totals at the top (people, active in the last 30 days, admins, new, rooms, media), then everyone with how recently they were seen; the one selected opens into a card with when they diff --git a/internal/deploy/alerts.go b/internal/deploy/alerts.go index 993d3c7..4a725ec 100644 --- a/internal/deploy/alerts.go +++ b/internal/deploy/alerts.go @@ -7,6 +7,11 @@ import ( "net/url" "os" "path/filepath" + "slices" + "strings" + + "interzone/internal/catalog" + "interzone/internal/config" ) // The server checks itself on a timer, as scheduled backups do, so alerts @@ -19,7 +24,7 @@ const alertsScript = `#!/bin/bash # Written by interzone: checks this Matrix server and sends a message when # what's wrong changes. "interzone-alerts test" sends a test message. set -uo pipefail -. "${IZ_ENV:-/etc/interzone-alerts.env}" +set -a; . "${IZ_ENV:-/etc/interzone-alerts.env}"; set +a state=${IZ_STATE:-/var/lib/interzone-alerts.state} send() { @@ -53,6 +58,49 @@ while read -r use mount; do problems+=("$mount is $use full") fi done < <(df -P / /matrix 2>/dev/null | awk 'NR > 1 && !seen[$6]++ { print $5, $6 }') +# Mirrors only have to answer: a registry says 401, a repository root 403. +for m in ${IZ_MIRRORS:-}; do + code=$(curl -sS -m 20 -o /dev/null -r 0-0 -w '%{http_code}' "$m" 2>/dev/null) + if [ "${code:-000}" -lt 200 ] || [ "$code" -ge 500 ]; then + problems+=("the mirror $m doesn't answer") + fi +done + +# Once a day, the playbook's changelog: entries newer than the titles in +# $news are sent, those about this server's components first. +news=${IZ_NEWS:-/var/lib/interzone-alerts.news} +if [ -n "${IZ_PLAYBOOK:-}" ] && [ -s "$news" ] && [ -z "$(find "$news" -mmin -1380 2>/dev/null)" ]; then + tmp=$(mktemp -d) + if git clone -q --depth 1 --filter=blob:none --no-checkout "$IZ_PLAYBOOK" "$tmp/p" 2>/dev/null && + git -C "$tmp/p" show HEAD:CHANGELOG.md > "$tmp/CHANGELOG.md" 2>/dev/null; then + msg=$(python3 - "$news" "$tmp/CHANGELOG.md" <<'PY' +import os, re, sys +seen = set(l.strip() for l in open(sys.argv[1])) +hs = os.environ.get("IZ_HOMESERVER", "").lower() +words = [w for w in os.environ.get("IZ_WATCH", "").lower().split("|") if w] +new = [] +for l in open(sys.argv[2]): + if l.startswith("## "): + if l[3:].strip() in seen: + break + new.append([l[3:].strip(), ""]) + elif new: + new[-1][1] += l.lower() +# by title for the homeserver: nearly every entry mentions Synapse in passing +yours = lambda t, b: bool(hs and hs in t.lower()) or any(w in b or w in t.lower() for w in words) +new.sort(key=lambda n: not yours(*n)) +if new: + print("%d new in the Matrix playbook's changelog (interzone's Updates shows them):" % len(new)) +for t, b in new: + print(("★ " if yours(t, b) else "• ") + re.sub(r"\[([^]]*)\]\([^)]*\)", r"\1", t)) +PY +) + if [ -z "$msg" ] || send "$msg"; then + sed -n 's/^## //p' "$tmp/CHANGELOG.md" > "$news" + fi + fi + rm -rf "$tmp" +fi now=$(printf '%s\n' "${problems[@]+"${problems[@]}"}") before=$(cat "$state" 2>/dev/null || true) @@ -78,9 +126,9 @@ const alertsPlay = `- name: Set up alerts changed_when: false when: interzone_enabled | bool - - name: Install curl and openssl + - name: Install curl, openssl, git and python3 ansible.builtin.package: - name: [curl, openssl] + name: [curl, openssl, git, python3] state: present when: interzone_enabled | bool @@ -95,9 +143,21 @@ const alertsPlay = `- name: Set up alerts IZ_PORT={{ interzone_port | quote }} IZ_URL={{ interzone_url | quote }} IZ_JSON={{ interzone_json | bool | lower }} + IZ_MIRRORS={{ interzone_mirrors | join(' ') | quote }} + IZ_PLAYBOOK={{ interzone_playbook | quote }} + IZ_HOMESERVER={{ interzone_homeserver | quote }} + IZ_WATCH={{ interzone_watch | join('|') | quote }} no_log: true when: interzone_enabled | bool + - name: Note the changelog entries already known + ansible.builtin.copy: + dest: /var/lib/interzone-alerts.news + content: "{{ interzone_seen }}" + force: false + mode: "0644" + when: interzone_enabled | bool and interzone_seen != "" + - name: Install the check ansible.builtin.copy: dest: /usr/local/bin/interzone-alerts @@ -165,9 +225,63 @@ const alertsPlay = `- name: Set up alerts - /usr/local/bin/interzone-alerts - /etc/interzone-alerts.env - /var/lib/interzone-alerts.state + - /var/lib/interzone-alerts.news when: not interzone_enabled | bool ` +// alertMirrors are the mirrors the server installs and updates from. +func alertMirrors(c *config.Config) []string { + s := c.Sources + var out []string + if s.UseRegistry && s.RegistryPrefix != "" { + host, _, _ := strings.Cut(s.RegistryPrefix, "/") + out = append(out, "https://"+host+"/v2/") + } + for _, u := range []string{s.APTMirror, s.DockerPackageURL, s.PlaybookGit, s.RolesGitBase} { + if u != "" && !slices.Contains(out, u) { + out = append(out, u) + } + } + return out +} + +// watchWords tie a changelog entry to this server, as markYours does: +// the doc pages of enabled components and the words in mentions. +func watchWords(c *config.Config) []string { + var out []string + for _, comp := range catalog.Components { + if c.Enabled(comp) { + if comp.Doc != "" { + out = append(out, strings.ToLower(comp.Doc)) + } + out = append(out, mentions[comp.ID]...) + } + } + return out +} + +func hsName(id string) string { + for _, h := range catalog.Homeservers { + if h.ID == id { + return h.Name + } + } + return "" +} + +// seenTitles are the entries of the local playbook's changelog, which the +// server starts from so only later ones are sent. +func seenTitles(c *config.Config) string { + b, _ := os.ReadFile(filepath.Join(c.PlaybookDir, "CHANGELOG.md")) + var out strings.Builder + for _, l := range strings.Split(string(b), "\n") { + if t, ok := strings.CutPrefix(l, "## "); ok { + out.WriteString(strings.TrimSpace(t) + "\n") + } + } + return out.String() +} + // AlertsURLProblem says what's wrong with an alerts URL, or "". func AlertsURLProblem(u string) string { p, err := url.Parse(u) @@ -197,7 +311,9 @@ func (r *Runner) alerts(ctx context.Context) error { vars, _ := json.Marshal(map[string]any{"interzone_enabled": a.Enabled, "interzone_every": a.Every, "interzone_url": a.URL, "interzone_json": a.JSON, "interzone_domain": r.cfg.Domain, "interzone_host": r.cfg.HostName(), "interzone_scheme": scheme, "interzone_port": port, - "interzone_script": alertsScript}) + "interzone_script": alertsScript, "interzone_mirrors": alertMirrors(r.cfg), + "interzone_playbook": r.cfg.Sources.PlaybookGit, "interzone_homeserver": hsName(r.cfg.Homeserver), + "interzone_watch": watchWords(r.cfg), "interzone_seen": seenTitles(r.cfg)}) dir := filepath.Join(r.cfg.PlaybookDir, "inventory") varsFile := filepath.Join(dir, "interzone-alerts-vars.json") if err := os.WriteFile(varsFile, vars, 0o600); err != nil { diff --git a/internal/deploy/alerts_test.go b/internal/deploy/alerts_test.go index 8990e94..47c190e 100644 --- a/internal/deploy/alerts_test.go +++ b/internal/deploy/alerts_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) // The alert script sends once when problems appear, nothing while they @@ -29,18 +30,19 @@ func TestAlertsScript(t *testing.T) { sent := filepath.Join(dir, "sent") stub("systemctl", `[ -f "$IZ_DIR/failing" ] && echo "matrix-synapse.service loaded failed failed Synapse"; true`) stub("df", `echo "Filesystem 1024-blocks Used Available Capacity Mounted"; echo "/dev/sda 100 50 50 50% /"`) - stub("curl", `for a; do [ "$a" = --resolve ] && { [ -f "$IZ_DIR/failing" ] && exit 22; exit 0; }; done + stub("curl", `for a; do [ "$a" = '%{http_code}' ] && { [ -f "$IZ_DIR/failing" ] && echo 000 || echo 401; exit 0; }; done +for a; do [ "$a" = --resolve ] && { [ -f "$IZ_DIR/failing" ] && exit 22; exit 0; }; done for a; do [ "$a" = @- ] && { cat >> "$IZ_DIR/sent"; echo >> "$IZ_DIR/sent"; exit 0; }; done printf '%s\n' "${@: -2:1}" >> "$IZ_DIR/sent"`) env := filepath.Join(dir, "env") - _ = os.WriteFile(env, []byte("IZ_DOMAIN=example.org\nIZ_HOST=matrix.example.org\nIZ_SCHEME=http\nIZ_PORT=80\nIZ_URL=https://ntfy.example/t\nIZ_JSON=false\n"), 0o600) + _ = os.WriteFile(env, []byte("IZ_DOMAIN=example.org\nIZ_HOST=matrix.example.org\nIZ_SCHEME=http\nIZ_PORT=80\nIZ_URL=https://ntfy.example/t\nIZ_JSON=false\nIZ_MIRRORS=https://reg.example/v2/\n"), 0o600) script := filepath.Join(dir, "interzone-alerts") _ = os.WriteFile(script, []byte(alertsScript), 0o755) run := func(args ...string) string { cmd := exec.Command("bash", append([]string{script}, args...)...) cmd.Env = append(os.Environ(), "PATH="+filepath.Join(dir, "bin")+":"+os.Getenv("PATH"), "IZ_DIR="+dir, - "IZ_ENV="+env, "IZ_STATE="+filepath.Join(dir, "state")) + "IZ_ENV="+env, "IZ_STATE="+filepath.Join(dir, "state"), "IZ_NEWS="+filepath.Join(dir, "news")) if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("%v: %s", err, out) } @@ -53,7 +55,8 @@ printf '%s\n' "${@: -2:1}" >> "$IZ_DIR/sent"`) } _ = os.WriteFile(filepath.Join(dir, "failing"), nil, 0o644) got := run() - if !strings.Contains(got, "matrix-synapse.service has failed") || !strings.Contains(got, "http://matrix.example.org doesn't answer") { + if !strings.Contains(got, "matrix-synapse.service has failed") || !strings.Contains(got, "http://matrix.example.org doesn't answer") || + !strings.Contains(got, "the mirror https://reg.example/v2/ doesn't answer") { t.Errorf("problems sent as %q", got) } if got := run(); got != "" { @@ -63,6 +66,23 @@ printf '%s\n' "${@: -2:1}" >> "$IZ_DIR/sent"`) if got := run(); !strings.Contains(got, "fine again") { t.Errorf("recovery sent as %q", got) } + + // A day after the last look, new changelog entries are sent, this + // server's first, and only once. + stub("git", `[ "$1" = clone ] && exit 0 +printf '# 2026-10-28\n\n## Something about Jitsi\n\nOther.\n\n## Bridges: see [docs](docs/configuring-playbook-bridge-mautrix-telegram.md)\n\n## Old one\n'`) + news := filepath.Join(dir, "news") + _ = os.WriteFile(news, []byte("Old one\n"), 0o644) + _ = os.Chtimes(news, time.Now().Add(-25*time.Hour), time.Now().Add(-25*time.Hour)) + _ = os.WriteFile(env, []byte("IZ_DOMAIN=example.org\nIZ_HOST=matrix.example.org\nIZ_SCHEME=http\nIZ_PORT=80\nIZ_URL=https://ntfy.example/t\nIZ_JSON=false\n"+ + "IZ_PLAYBOOK=https://git.example/mdad\nIZ_HOMESERVER=Synapse\nIZ_WATCH=configuring-playbook-bridge-mautrix-telegram.md\n"), 0o600) + got = run() + if !strings.Contains(got, "2 new") || !strings.Contains(got, "★ Bridges: see docs\n• Something about Jitsi") { + t.Errorf("news sent as %q", got) + } + if got := run(); got != "" { + t.Errorf("news sent again: %q", got) + } _ = os.WriteFile(env, []byte("IZ_DOMAIN=example.org\nIZ_HOST=matrix.example.org\nIZ_SCHEME=http\nIZ_PORT=80\nIZ_URL=https://hook.example/x\nIZ_JSON=true\n"), 0o600) if got := run("test"); !strings.Contains(got, `"text": "interzone alerts are on for example.org`) { t.Errorf("JSON test message sent as %q", got) diff --git a/internal/ui/alerts.go b/internal/ui/alerts.go index de255f3..81d5445 100644 --- a/internal/ui/alerts.go +++ b/internal/ui/alerts.go @@ -49,7 +49,7 @@ func (s *alertsScreen) enter(c *config.Config) tea.Cmd { } s.form = newForm( toggleField("on", "Send alerts", a.Enabled, - "The server checks itself, even when this computer is off: failed services, the homeserver not answering, a certificate expiring within 14 days, a disk over 90% full."), + "The server checks itself, even when this computer is off: failed services, the homeserver not answering, a certificate expiring within 14 days, a disk over 90% full, a mirror not answering. Once a day, new entries in the playbook's changelog too."), textField("url", "Send them to", a.URL, example, "An ntfy topic (subscribe to it in the ntfy app), or a webhook: a Hookshot room webhook, Slack, Discord or Mattermost. Anyone who knows an ntfy topic can read it, so make it long and random."), choiceField("format", "Message format", []string{"text", "json"},