From dc3d30acaa87a009dbb81e5c827b8f81bc32c5d5 Mon Sep 17 00:00:00 2001 From: Prageeth Panicker Date: Fri, 16 Oct 2026 14:41:05 +0000 Subject: [PATCH 1/2] fix(sys-ctl-hlth-journalctl): skip container logs in the host journal check Problem: Every compose service logs to journald through sys-svc-container/templates/base.yml.j2. The daily journal health check grepped the whole journal for "error", so routine application errors from containers triggered the host alert (email/Telegram) and buried real host problems. Change: - Read the last day of the journal as JSON (MESSAGE, CONTAINER_ID, SYSLOG_IDENTIFIER, _SYSTEMD_UNIT) and skip every entry that carries a CONTAINER_ID field. Docker daemon and system errors are still reported. - Report each match as one readable "source: message" line instead of raw journal output. - Stream the journalctl output line by line instead of buffering a whole day of logs in memory. - Exit 2 with journalctl's stderr if journalctl itself fails, instead of silently reporting "no errors". - Rewrite the check in Python (files/python/script.py, deployed by sys-service like the other sys-ctl-hlth roles) and decode non-UTF-8 messages. - Fix the success message, which claimed "All docker containers are healthy". Impact: Container log errors no longer raise this host alert on any installation. Container health stays covered by sys-ctl-hlth-container; application log analysis belongs in a log platform such as Wazuh. system_service_suppress_flush is unchanged until a deploy confirms that no host errors remain. Tests: Unit tests run the script against a fake journalctl (8 cases): container error ignored, daemon error reported, identifier fallback, non-UTF-8 message, journalctl failure, many container lines streamed past, clean journal passes. The core cases fail against the previous script. --- roles/sys-ctl-hlth-journalctl/README.md | 10 +- .../files/python/script.py | 84 +++++++++++ .../files/shell/script.sh | 10 -- .../roles/sys-ctl-hlth-journalctl/__init__.py | 0 .../sys-ctl-hlth-journalctl/files/__init__.py | 0 .../files/test_script.py | 133 ++++++++++++++++++ 6 files changed, 224 insertions(+), 13 deletions(-) create mode 100755 roles/sys-ctl-hlth-journalctl/files/python/script.py delete mode 100644 roles/sys-ctl-hlth-journalctl/files/shell/script.sh create mode 100644 tests/unit/python/roles/sys-ctl-hlth-journalctl/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-journalctl/files/__init__.py create mode 100644 tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py diff --git a/roles/sys-ctl-hlth-journalctl/README.md b/roles/sys-ctl-hlth-journalctl/README.md index c60c77d27d..507b466be1 100644 --- a/roles/sys-ctl-hlth-journalctl/README.md +++ b/roles/sys-ctl-hlth-journalctl/README.md @@ -2,11 +2,13 @@ ## Description -Scans `journalctl` over the last day for “error” entries and alerts if any are found. +Scans `journalctl` over the last day for “error” entries outside container logs and alerts if any are found. ## Overview This role searches the systemd journal for errors over the past day and alerts if any are found. +Container output is skipped, because every compose service logs to journald and application errors would otherwise trigger the host check. +Docker daemon and system errors are still reported. ## Cosmos @@ -23,8 +25,10 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- Runs `journalctl --since '1 day ago' | grep -i error`. -- Exits non-zero on matches. +- Reads the last day of the journal as JSON and drops every entry that carries a `CONTAINER_ID` field. +- Matches the remaining messages case-insensitively against `error`. +- Prints one `source: message` line per match, naming the systemd unit or, without one, the syslog identifier, so alerts show who logged the error. +- Exits non-zero on matches, and also when `journalctl` itself fails, so a broken check never passes silently. - Scheduled via systemd timer. - Alerts via `sys-ctl-alm-compose` on detection. diff --git a/roles/sys-ctl-hlth-journalctl/files/python/script.py b/roles/sys-ctl-hlth-journalctl/files/python/script.py new file mode 100755 index 0000000000..cf0426d3ab --- /dev/null +++ b/roles/sys-ctl-hlth-journalctl/files/python/script.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +import json +import subprocess +import sys +import tempfile + +JOURNALCTL = [ + "journalctl", + "--since", + "1 day ago", + "--no-pager", + "--output=json", + "--output-fields=MESSAGE,CONTAINER_ID,SYSLOG_IDENTIFIER,_SYSTEMD_UNIT", +] + + +def message_text(value): + """Return a journal MESSAGE as one line of text. + + Args: + value: the MESSAGE field; journald encodes non-UTF-8 messages as a list of bytes. + + Returns: + The message with line breaks collapsed to spaces. + """ + if isinstance(value, list): + value = bytes(value).decode("utf-8", errors="replace") + return " ".join(str(value).splitlines()) + + +def host_errors(lines): + """Yield `source: message` for every non-container entry that mentions an error. + + Args: + lines: iterable of journalctl JSON lines, one entry per line, consumed lazily. + + Returns: + Iterator of readable error lines. + """ + for line in lines: + if not line.strip(): + continue + entry = json.loads(line) + if "CONTAINER_ID" in entry: + continue + message = message_text(entry.get("MESSAGE", "")) + if "error" not in message.lower(): + continue + source = ( + entry.get("_SYSTEMD_UNIT") or entry.get("SYSLOG_IDENTIFIER") or "unknown" + ) + yield f"{source}: {message}" + + +def main(): + print("Checking journalctl for error messages outside container logs...") + # stderr goes to a file, not a pipe: an unread stderr pipe that fills up would block journalctl while stdout is still being read. + with tempfile.TemporaryFile( + mode="w+", encoding="utf-8", errors="replace" + ) as stderr: + with subprocess.Popen( + JOURNALCTL, + stdout=subprocess.PIPE, + stderr=stderr, + encoding="utf-8", + errors="replace", + ) as journal: + errors = list(host_errors(journal.stdout)) + if journal.returncode != 0: + stderr.seek(0) + print( + f"journalctl failed with exit code {journal.returncode}: {stderr.read().strip()}" + ) + return 2 + if errors: + print("Some errors were found:") + print("\n".join(errors)) + return 1 + print("No errors found in the journal.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/sys-ctl-hlth-journalctl/files/shell/script.sh b/roles/sys-ctl-hlth-journalctl/files/shell/script.sh deleted file mode 100644 index 4903b597d1..0000000000 --- a/roles/sys-ctl-hlth-journalctl/files/shell/script.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -echo "Checking journalctl for error messages..." -journalctl_errors="$(journalctl --since '1 day ago' --no-pager | grep -i 'error')" -if [ -n "$journalctl_errors" ] -then - echo "Some errors where found: $journalctl_errors" - exit 1 -fi -echo "All docker containers are healthy." -exit 0 diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py new file mode 100644 index 0000000000..21c17f01c3 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py @@ -0,0 +1,133 @@ +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles/sys-ctl-hlth-journalctl/files/python/script.py" + +JOURNALCTL_STUB = """#!/usr/bin/env bash +printf '%s\\n' "$*" >"${STUB_DIR}/args" +cat "${STUB_DIR}/journal" +if [ "${STUB_RC}" -ne 0 ]; then +\techo "journalctl: unrecognized option '--output-fields'" >&2 +fi +exit "${STUB_RC}" +""" + +APP_ERROR = { + "MESSAGE": "ERROR: pixelfed queue failed", + "CONTAINER_ID": "0123456789ab", + "SYSLOG_IDENTIFIER": "pixelfed", + "_SYSTEMD_UNIT": "docker.service", +} +DAEMON_ERROR = { + "MESSAGE": 'level=error msg="failed to start container"', + "SYSLOG_IDENTIFIER": "dockerd", + "_SYSTEMD_UNIT": "docker.service", +} +KERNEL_ERROR = {"MESSAGE": "EXT4-fs error (device sda1)", "SYSLOG_IDENTIFIER": "kernel"} +BINARY_ERROR = { + "MESSAGE": list(b"I/O error \xff on disk"), + "_SYSTEMD_UNIT": "smartd.service", +} +SYSTEM_INFO = { + "MESSAGE": "Started Daily apt download activities.", + "_SYSTEMD_UNIT": "init.scope", +} + + +class TestHlthJournalctlScript(unittest.TestCase): + def run_script(self, *entries, rc=0): + """Run the health script against a stubbed journalctl. + + Args: + entries: journal entries the stub prints, one JSON object per line. + rc: exit code of the stubbed journalctl. + + Returns: + Tuple of the exit code, the script output, and the journalctl arguments. + """ + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) + stub = bin_dir / "journalctl" + stub.write_text(JOURNALCTL_STUB) + stub.chmod(0o755) + (bin_dir / "journal").write_text( + "".join(json.dumps(entry) + "\n" for entry in entries) + ) + env = dict(os.environ) + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_DIR"] = tmp + env["STUB_RC"] = str(rc) + done = subprocess.run( + [sys.executable, str(SCRIPT)], + env=env, + capture_output=True, + text=True, + check=False, + ) + args = (bin_dir / "args").read_text() + return done.returncode, done.stdout, args + + def test_reads_the_journal_as_json_with_the_source_fields(self): + _, _, args = self.run_script(SYSTEM_INFO) + self.assertIn("--output=json", args) + self.assertIn( + "--output-fields=MESSAGE,CONTAINER_ID,SYSLOG_IDENTIFIER,_SYSTEMD_UNIT", + args, + ) + + def test_an_application_error_from_a_container_is_ignored(self): + code, _, _ = self.run_script(APP_ERROR, SYSTEM_INFO) + self.assertEqual(code, 0) + + def test_a_docker_daemon_error_is_reported_with_its_unit(self): + code, output, _ = self.run_script(APP_ERROR, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertIn( + 'docker.service: level=error msg="failed to start container"', output + ) + self.assertNotIn("pixelfed queue failed", output) + + def test_an_entry_without_unit_is_named_by_its_identifier(self): + code, output, _ = self.run_script(KERNEL_ERROR) + self.assertEqual(code, 1) + self.assertIn("kernel: EXT4-fs error (device sda1)", output) + + def test_a_non_utf8_message_is_decoded_and_reported(self): + code, output, _ = self.run_script(BINARY_ERROR) + self.assertEqual(code, 1) + self.assertIn("smartd.service: I/O error", output) + + def test_many_container_errors_are_streamed_past_and_not_reported(self): + container_lines = [ + {**APP_ERROR, "MESSAGE": f"ERROR: pixelfed request {n} failed"} + for n in range(20000) + ] + code, output, _ = self.run_script(*container_lines, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertNotIn("pixelfed request", output) + self.assertEqual( + output.splitlines()[-1], + 'docker.service: level=error msg="failed to start container"', + ) + self.assertEqual(len(output.splitlines()), 3) + + def test_a_journal_without_errors_passes(self): + code, _, _ = self.run_script(SYSTEM_INFO) + self.assertEqual(code, 0) + + def test_a_failing_journalctl_fails_the_check(self): + code, output, _ = self.run_script(rc=1) + self.assertEqual(code, 2) + self.assertIn("journalctl failed with exit code 1", output) + self.assertIn("unrecognized option '--output-fields'", output) + + +if __name__ == "__main__": + unittest.main() From 3855b75c5f6c3667043c7f603875c51cf619f3ee Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 16 Oct 2026 22:11:09 +0200 Subject: [PATCH 2/2] fix(sys-ctl-hlth-journalctl): read long and repeated MESSAGE fields Without `--all`, `journalctl --output=json` encodes a field over 4096 bytes as `null`, so a long host error matched nothing and the check passed. A repeated `MESSAGE` field arrives as a JSON array of its values, and `bytes()` on that array raised `TypeError`, which aborted the whole check. Pass `--all`, and tell a byte array (all integers) from an array of field values, decoding each value on its own. Reproduced against the host journal: a 5000-byte error line read back as `"MESSAGE":null` and produced no match; an entry with two `MESSAGE` fields, sent over the native journal socket, read back as `["error first","error second"]` and crashed `host_errors` with `TypeError`. With the fix both are reported. Also clear the two test-lint findings of this PR: `test_comments_valid` rejects the narrative comment above the `journalctl` Popen, so it goes; the stderr-to-file choice stays, because an unread stderr pipe that fills up would block `journalctl` while stdout is still being read. `test_no_uncached_file_reads` flags the read of the stub's argument file, which lives in the test's tempdir and is written per run, so the path-keyed `utils.cache.files.read_text` could serve a stale body; the read opts out with `# nocheck: cache-read tempdir fixture`, as the other stub-driven script tests do. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/sys-ctl-hlth-journalctl/README.md | 3 ++- .../files/python/script.py | 8 +++++--- .../sys-ctl-hlth-journalctl/files/test_script.py | 16 +++++++++++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/roles/sys-ctl-hlth-journalctl/README.md b/roles/sys-ctl-hlth-journalctl/README.md index 507b466be1..6f53fb6f81 100644 --- a/roles/sys-ctl-hlth-journalctl/README.md +++ b/roles/sys-ctl-hlth-journalctl/README.md @@ -25,7 +25,8 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Features -- Reads the last day of the journal as JSON and drops every entry that carries a `CONTAINER_ID` field. +- Reads the last day of the journal as JSON with every field in full (`--all`) and drops every entry that carries a `CONTAINER_ID` field. +- Joins a repeated `MESSAGE` field into one line before matching. - Matches the remaining messages case-insensitively against `error`. - Prints one `source: message` line per match, naming the systemd unit or, without one, the syslog identifier, so alerts show who logged the error. - Exits non-zero on matches, and also when `journalctl` itself fails, so a broken check never passes silently. diff --git a/roles/sys-ctl-hlth-journalctl/files/python/script.py b/roles/sys-ctl-hlth-journalctl/files/python/script.py index cf0426d3ab..75ddf4483b 100755 --- a/roles/sys-ctl-hlth-journalctl/files/python/script.py +++ b/roles/sys-ctl-hlth-journalctl/files/python/script.py @@ -9,6 +9,7 @@ JOURNALCTL = [ "--since", "1 day ago", "--no-pager", + "--all", "--output=json", "--output-fields=MESSAGE,CONTAINER_ID,SYSLOG_IDENTIFIER,_SYSTEMD_UNIT", ] @@ -18,13 +19,15 @@ def message_text(value): """Return a journal MESSAGE as one line of text. Args: - value: the MESSAGE field; journald encodes non-UTF-8 messages as a list of bytes. + value: the MESSAGE field; journald encodes non-UTF-8 messages as a list of bytes and a repeated field as a list of its values. Returns: The message with line breaks collapsed to spaces. """ - if isinstance(value, list): + if isinstance(value, list) and all(isinstance(item, int) for item in value): value = bytes(value).decode("utf-8", errors="replace") + elif isinstance(value, list): + value = "\n".join(message_text(item) for item in value) return " ".join(str(value).splitlines()) @@ -54,7 +57,6 @@ def host_errors(lines): def main(): print("Checking journalctl for error messages outside container logs...") - # stderr goes to a file, not a pipe: an unread stderr pipe that fills up would block journalctl while stdout is still being read. with tempfile.TemporaryFile( mode="w+", encoding="utf-8", errors="replace" ) as stderr: diff --git a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py index 21c17f01c3..8a4f44007f 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-journalctl/files/test_script.py @@ -35,6 +35,10 @@ BINARY_ERROR = { "MESSAGE": list(b"I/O error \xff on disk"), "_SYSTEMD_UNIT": "smartd.service", } +REPEATED_ERROR = { + "MESSAGE": ["unit started", list(b"disk error \xff on sdb")], + "_SYSTEMD_UNIT": "zfs-import.service", +} SYSTEM_INFO = { "MESSAGE": "Started Daily apt download activities.", "_SYSTEMD_UNIT": "init.scope", @@ -71,7 +75,7 @@ class TestHlthJournalctlScript(unittest.TestCase): text=True, check=False, ) - args = (bin_dir / "args").read_text() + args = (bin_dir / "args").read_text() # nocheck: cache-read tempdir fixture return done.returncode, done.stdout, args def test_reads_the_journal_as_json_with_the_source_fields(self): @@ -82,6 +86,16 @@ class TestHlthJournalctlScript(unittest.TestCase): args, ) + def test_reads_every_field_in_full(self): + _, _, args = self.run_script(SYSTEM_INFO) + self.assertIn("--all", args.split()) + + def test_a_repeated_message_field_is_joined_and_reported(self): + code, output, _ = self.run_script(REPEATED_ERROR, DAEMON_ERROR) + self.assertEqual(code, 1) + self.assertIn("zfs-import.service: unit started disk error", output) + self.assertIn('docker.service: level=error msg="failed to start', output) + def test_an_application_error_from_a_container_is_ignored(self): code, _, _ = self.run_script(APP_ERROR, SYSTEM_INFO) self.assertEqual(code, 0)