mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-20 09:59:09 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29f1c68bea |
+1
-54
@@ -130,12 +130,7 @@ def setup_logging(
|
|||||||
# Console handler (always add)
|
# Console handler (always add)
|
||||||
console_handler = logging.StreamHandler(sys.stdout)
|
console_handler = logging.StreamHandler(sys.stdout)
|
||||||
console_handler.setLevel(level)
|
console_handler.setLevel(level)
|
||||||
# Under systemd, tag each line so the journal records the real severity
|
console_handler.setFormatter(formatter)
|
||||||
# rather than filing everything as informational. The file handler below
|
|
||||||
# keeps the plain formatter: the prefix is meaningful to journald and noise
|
|
||||||
# anywhere else.
|
|
||||||
console_handler.setFormatter(
|
|
||||||
JournalPriorityFormatter(formatter) if _under_systemd() else formatter)
|
|
||||||
root_logger.addHandler(console_handler)
|
root_logger.addHandler(console_handler)
|
||||||
|
|
||||||
# File handler (if specified)
|
# File handler (if specified)
|
||||||
@@ -150,54 +145,6 @@ def setup_logging(
|
|||||||
sys.stderr.write(f"Warning: Could not set up file logging to {log_file}: {e}\n")
|
sys.stderr.write(f"Warning: Could not set up file logging to {log_file}: {e}\n")
|
||||||
|
|
||||||
|
|
||||||
#: syslog priorities, which is what systemd parses from a "<N>" prefix on
|
|
||||||
#: stdout. Mapped from Python's levels.
|
|
||||||
_SYSLOG_PRIORITY = {
|
|
||||||
logging.CRITICAL: 2, # LOG_CRIT
|
|
||||||
logging.ERROR: 3, # LOG_ERR
|
|
||||||
logging.WARNING: 4, # LOG_WARNING
|
|
||||||
logging.INFO: 6, # LOG_INFO
|
|
||||||
logging.DEBUG: 7, # LOG_DEBUG
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class JournalPriorityFormatter(logging.Formatter):
|
|
||||||
"""Wraps a formatter, prefixing each line with its syslog priority.
|
|
||||||
|
|
||||||
Under systemd everything this process writes to stdout lands in the journal
|
|
||||||
as PRIORITY=6, whatever the Python level was. Measured on a live rig: 55
|
|
||||||
ERROR lines and 13 WARNING lines in a day, every one of them recorded as
|
|
||||||
informational, so `journalctl -p err -u ledmatrix` returned nothing at all
|
|
||||||
while errors were being logged. Anyone triaging has to grep the message
|
|
||||||
text instead, which is both slower and wrong -- a search for "oom" matches
|
|
||||||
the radar logging "zoom=9".
|
|
||||||
|
|
||||||
systemd reads a leading "<N>" on each line and uses it as the priority
|
|
||||||
(sd-daemon(3)), so this needs no extra dependency. Multi-line records get
|
|
||||||
the prefix on every line, since the journal splits them and an unprefixed
|
|
||||||
continuation would fall back to the default.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, inner: logging.Formatter):
|
|
||||||
super().__init__()
|
|
||||||
self._inner = inner
|
|
||||||
|
|
||||||
def format(self, record: logging.LogRecord) -> str:
|
|
||||||
text = self._inner.format(record)
|
|
||||||
prefix = f"<{_SYSLOG_PRIORITY.get(record.levelno, 6)}>"
|
|
||||||
return "\n".join(prefix + line for line in text.split("\n"))
|
|
||||||
|
|
||||||
|
|
||||||
def _under_systemd() -> bool:
|
|
||||||
"""True when stdout is the journal.
|
|
||||||
|
|
||||||
systemd sets JOURNAL_STREAM for services whose output it captures. Without
|
|
||||||
this check the "<N>" prefixes would show up as literal noise when the
|
|
||||||
program is run from a terminal, in the emulator, or in tests.
|
|
||||||
"""
|
|
||||||
return bool(os.environ.get("JOURNAL_STREAM"))
|
|
||||||
|
|
||||||
|
|
||||||
class PluginLoggerAdapter(logging.LoggerAdapter):
|
class PluginLoggerAdapter(logging.LoggerAdapter):
|
||||||
"""LoggerAdapter that stamps every record with its plugin_id.
|
"""LoggerAdapter that stamps every record with its plugin_id.
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import time
|
|||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
from typing import Dict, Optional, Any, Callable
|
from typing import Dict, Optional, Any, Callable
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field, fields
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import psutil
|
import psutil
|
||||||
@@ -102,6 +102,50 @@ class PluginResourceMonitor:
|
|||||||
"psutil not available - resource monitoring will be limited to execution time only"
|
"psutil not available - resource monitoring will be limited to execution time only"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _metrics_from_cache(self, plugin_id: str, cached: Any) -> "ResourceMetrics":
|
||||||
|
"""Build metrics from a cached record, ignoring anything unrecognised.
|
||||||
|
|
||||||
|
ResourceMetrics(**cached) raises TypeError on a single unexpected key,
|
||||||
|
and that exception escapes into plugin_manager, which reports it as
|
||||||
|
"plugin <id> operation failed". Every plugin fails, and the plugin
|
||||||
|
system never finishes initialising.
|
||||||
|
|
||||||
|
Seen on a live rig: every plugin failing with
|
||||||
|
|
||||||
|
ResourceMetrics.__init__() got an unexpected keyword argument
|
||||||
|
'consecutive_failures'
|
||||||
|
|
||||||
|
which is a plugin_health field, not a metrics one. How a health-shaped
|
||||||
|
record came to sit under a plugin_metrics key on that machine is not
|
||||||
|
established -- a restored backup that mixed two machines' caches is the
|
||||||
|
likeliest explanation -- but the loader should not be brittle enough for
|
||||||
|
it to matter. plugin_health already repairs its records field by field
|
||||||
|
rather than trusting whatever is on disk; this does the same.
|
||||||
|
|
||||||
|
Unknown keys are dropped and named once, so a genuine schema change is
|
||||||
|
visible in the log instead of silently discarded.
|
||||||
|
"""
|
||||||
|
if not isinstance(cached, dict):
|
||||||
|
self.logger.warning(
|
||||||
|
"Ignoring cached metrics for %s: expected a mapping, got %s",
|
||||||
|
plugin_id, type(cached).__name__)
|
||||||
|
return ResourceMetrics()
|
||||||
|
|
||||||
|
known = {f.name for f in fields(ResourceMetrics)}
|
||||||
|
unknown = sorted(set(cached) - known)
|
||||||
|
if unknown:
|
||||||
|
self.logger.warning(
|
||||||
|
"Dropping unrecognised field(s) from cached metrics for %s: %s",
|
||||||
|
plugin_id, ", ".join(unknown))
|
||||||
|
usable = {k: v for k, v in cached.items() if k in known}
|
||||||
|
try:
|
||||||
|
return ResourceMetrics(**usable)
|
||||||
|
except (TypeError, ValueError) as e:
|
||||||
|
self.logger.warning(
|
||||||
|
"Cached metrics for %s unusable (%s); starting fresh",
|
||||||
|
plugin_id, e)
|
||||||
|
return ResourceMetrics()
|
||||||
|
|
||||||
def _get_metrics_key(self, plugin_id: str) -> str:
|
def _get_metrics_key(self, plugin_id: str) -> str:
|
||||||
"""Get cache key for plugin metrics."""
|
"""Get cache key for plugin metrics."""
|
||||||
return f"plugin_metrics:{plugin_id}"
|
return f"plugin_metrics:{plugin_id}"
|
||||||
@@ -126,7 +170,7 @@ class PluginResourceMonitor:
|
|||||||
cache_key, max_age=None, memory_ttl=0 if force_reload else None
|
cache_key, max_age=None, memory_ttl=0 if force_reload else None
|
||||||
)
|
)
|
||||||
if cached:
|
if cached:
|
||||||
metrics = ResourceMetrics(**cached)
|
metrics = self._metrics_from_cache(plugin_id, cached)
|
||||||
else:
|
else:
|
||||||
metrics = ResourceMetrics()
|
metrics = ResourceMetrics()
|
||||||
self._metrics[plugin_id] = metrics
|
self._metrics[plugin_id] = metrics
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
"""Log lines must reach the journal with their real severity.
|
|
||||||
|
|
||||||
Everything this process writes to stdout lands in the journal as PRIORITY=6,
|
|
||||||
whatever the Python level was, because journald has no other signal. Measured
|
|
||||||
on a live rig over 24 hours: 55 lines containing " - ERROR - " and 13
|
|
||||||
containing " - WARNING - ", every one of them recorded as informational. So
|
|
||||||
|
|
||||||
journalctl -p err -u ledmatrix
|
|
||||||
|
|
||||||
returned nothing while errors were being logged, and anyone triaging has to
|
|
||||||
grep the message text instead. That is slower and it is wrong: a search for
|
|
||||||
"oom" also matches the radar logging "zoom=9", which is exactly the false
|
|
||||||
positive it produced during this audit.
|
|
||||||
|
|
||||||
systemd reads a leading "<N>" on each stdout line and uses it as the priority
|
|
||||||
(sd-daemon(3)), so this needs no extra dependency -- and it must only be
|
|
||||||
applied when systemd is actually reading, or the prefixes become literal noise
|
|
||||||
in a terminal, the emulator, and test output.
|
|
||||||
"""
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from src.logging_config import JournalPriorityFormatter, _SYSLOG_PRIORITY, _under_systemd
|
|
||||||
|
|
||||||
|
|
||||||
class _Plain(logging.Formatter):
|
|
||||||
def format(self, record):
|
|
||||||
return record.getMessage()
|
|
||||||
|
|
||||||
|
|
||||||
def _record(level, msg="hello"):
|
|
||||||
return logging.LogRecord("t", level, "f.py", 1, msg, None, None)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("level,expected", [
|
|
||||||
(logging.CRITICAL, 2),
|
|
||||||
(logging.ERROR, 3),
|
|
||||||
(logging.WARNING, 4),
|
|
||||||
(logging.INFO, 6),
|
|
||||||
(logging.DEBUG, 7),
|
|
||||||
])
|
|
||||||
def test_each_level_maps_to_its_syslog_priority(level, expected):
|
|
||||||
out = JournalPriorityFormatter(_Plain()).format(_record(level))
|
|
||||||
assert out.startswith(f"<{expected}>"), out
|
|
||||||
assert _SYSLOG_PRIORITY[level] == expected
|
|
||||||
|
|
||||||
|
|
||||||
def test_error_and_info_are_distinguishable():
|
|
||||||
"""The whole point: journalctl -p err must be able to tell them apart."""
|
|
||||||
fmt = JournalPriorityFormatter(_Plain())
|
|
||||||
assert fmt.format(_record(logging.ERROR))[:3] != fmt.format(_record(logging.INFO))[:3]
|
|
||||||
|
|
||||||
|
|
||||||
def test_every_line_of_a_multiline_record_is_tagged():
|
|
||||||
"""The journal splits them, and an untagged continuation loses its level.
|
|
||||||
|
|
||||||
A traceback is the case that matters -- it is the most important thing in
|
|
||||||
the log and the longest.
|
|
||||||
"""
|
|
||||||
out = JournalPriorityFormatter(_Plain()).format(
|
|
||||||
_record(logging.ERROR, "Traceback:\nline one\nline two"))
|
|
||||||
lines = out.split("\n")
|
|
||||||
assert len(lines) == 3
|
|
||||||
assert all(line.startswith("<3>") for line in lines), lines
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_message_survives_intact():
|
|
||||||
out = JournalPriorityFormatter(_Plain()).format(_record(logging.WARNING, "disk full"))
|
|
||||||
assert out == "<4>disk full"
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_unknown_level_falls_back_to_info():
|
|
||||||
out = JournalPriorityFormatter(_Plain()).format(_record(25))
|
|
||||||
assert out.startswith("<6>")
|
|
||||||
|
|
||||||
|
|
||||||
def test_prefixing_is_off_outside_systemd():
|
|
||||||
"""Otherwise a terminal run, the emulator and pytest all show `<6>`."""
|
|
||||||
with patch.dict(os.environ, {}, clear=True):
|
|
||||||
assert not _under_systemd()
|
|
||||||
with patch.dict(os.environ, {"JOURNAL_STREAM": "8:12345"}):
|
|
||||||
assert _under_systemd()
|
|
||||||
|
|
||||||
|
|
||||||
def test_setup_uses_the_wrapper_only_under_systemd():
|
|
||||||
from src.logging_config import setup_logging
|
|
||||||
|
|
||||||
for env, expect_wrapped in (({}, False), ({"JOURNAL_STREAM": "8:1"}, True)):
|
|
||||||
with patch.dict(os.environ, env, clear=True):
|
|
||||||
setup_logging()
|
|
||||||
handlers = [h for h in logging.getLogger().handlers
|
|
||||||
if isinstance(h, logging.StreamHandler)]
|
|
||||||
assert handlers, "no stream handler installed"
|
|
||||||
wrapped = any(isinstance(h.formatter, JournalPriorityFormatter)
|
|
||||||
for h in handlers)
|
|
||||||
assert wrapped is expect_wrapped, (
|
|
||||||
f"JOURNAL_STREAM={env}: wrapped={wrapped}, expected {expect_wrapped}")
|
|
||||||
logging.getLogger().handlers.clear()
|
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""A malformed metrics cache entry must not take every plugin down with it.
|
||||||
|
|
||||||
|
`ResourceMetrics(**cached)` raises TypeError on a single unexpected key, and
|
||||||
|
that exception escapes into plugin_manager, which reports it per plugin as
|
||||||
|
"plugin <id> operation failed". Every plugin fails and the plugin system never
|
||||||
|
finishes initialising -- the health endpoint reports
|
||||||
|
`plugin_system: not_initialized` while the display itself keeps running.
|
||||||
|
|
||||||
|
Seen on a live rig, once per plugin, continuously:
|
||||||
|
|
||||||
|
ERROR - src.plugin_system.plugin_manager - plugin geochron operation failed:
|
||||||
|
ResourceMetrics.__init__() got an unexpected keyword argument
|
||||||
|
'consecutive_failures'
|
||||||
|
|
||||||
|
`consecutive_failures` belongs to plugin_health, not to metrics. How a
|
||||||
|
health-shaped record came to sit under a plugin_metrics key on that machine is
|
||||||
|
not established -- a restored backup that mixed two machines' caches is the
|
||||||
|
likeliest explanation, and the same rig had one restored onto it -- but a
|
||||||
|
loader that turns one bad cache entry into a total outage is the part worth
|
||||||
|
fixing. plugin_health already repairs its own records field by field rather
|
||||||
|
than trusting what is on disk.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
from dataclasses import fields
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.plugin_system.resource_monitor import PluginResourceMonitor, ResourceMetrics
|
||||||
|
|
||||||
|
|
||||||
|
class _Cache:
|
||||||
|
def __init__(self, payload=None):
|
||||||
|
self.payload = payload
|
||||||
|
|
||||||
|
def get(self, key, max_age=None, memory_ttl=None, **kwargs):
|
||||||
|
return self.payload
|
||||||
|
|
||||||
|
def set(self, key, data, ttl=None, **kwargs):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _monitor(payload):
|
||||||
|
m = PluginResourceMonitor(cache_manager=_Cache(payload))
|
||||||
|
m.logger = logging.getLogger("test")
|
||||||
|
return m
|
||||||
|
|
||||||
|
|
||||||
|
#: What the rig actually had under the metrics key.
|
||||||
|
HEALTH_SHAPED = {
|
||||||
|
"consecutive_failures": 0, "circuit_state": "closed",
|
||||||
|
"circuit_opened_time": None, "half_open_start_time": None,
|
||||||
|
"last_error": None, "last_failure_time": None,
|
||||||
|
"last_success_time": 1_700_000_000.0, "total_failures": 0,
|
||||||
|
"total_successes": 42,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_health_record_under_the_metrics_key_does_not_raise():
|
||||||
|
"""The exact failure: it must degrade, not take the plugin system down."""
|
||||||
|
monitor = _monitor(HEALTH_SHAPED)
|
||||||
|
metrics = monitor.get_metrics(" plugin-a".strip())
|
||||||
|
assert isinstance(metrics, ResourceMetrics)
|
||||||
|
|
||||||
|
|
||||||
|
def test_recognised_fields_in_a_mixed_record_are_kept():
|
||||||
|
"""Dropping the record wholesale would lose real history unnecessarily."""
|
||||||
|
mixed = dict(HEALTH_SHAPED, call_count=7, memory_mb=12.5)
|
||||||
|
metrics = _monitor(mixed).get_metrics("plugin-b")
|
||||||
|
assert metrics.call_count == 7
|
||||||
|
assert metrics.memory_mb == 12.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_clean_record_still_loads_unchanged():
|
||||||
|
clean = {f.name: 3 for f in fields(ResourceMetrics)}
|
||||||
|
metrics = _monitor(clean).get_metrics("plugin-c")
|
||||||
|
for name in (f.name for f in fields(ResourceMetrics)):
|
||||||
|
assert getattr(metrics, name) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_fields_are_named_in_the_log(caplog):
|
||||||
|
"""Silently discarding them would hide a real schema change."""
|
||||||
|
with caplog.at_level(logging.WARNING):
|
||||||
|
_monitor(HEALTH_SHAPED).get_metrics("plugin-d")
|
||||||
|
# getMessage(), not .message: the latter is only populated once a handler
|
||||||
|
# formats the record, so the obvious spelling silently never matches.
|
||||||
|
assert any("consecutive_failures" in r.getMessage() for r in caplog.records), \
|
||||||
|
caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", ["a string", 42, ["a", "list"]])
|
||||||
|
def test_a_non_mapping_cache_entry_does_not_raise(payload):
|
||||||
|
metrics = _monitor(payload).get_metrics("plugin-e")
|
||||||
|
assert isinstance(metrics, ResourceMetrics)
|
||||||
|
|
||||||
|
|
||||||
|
def test_values_of_the_wrong_type_do_not_raise():
|
||||||
|
"""A dataclass will accept these, but a later float() on them would not."""
|
||||||
|
metrics = _monitor({"call_count": "not a number"}).get_metrics("plugin-f")
|
||||||
|
assert isinstance(metrics, ResourceMetrics)
|
||||||
Reference in New Issue
Block a user