mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-21 02:19:07 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dab4b3ea57 | ||
|
|
0fd2bfae99 |
+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.
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,20 @@ class ResourceMetrics:
|
|||||||
self.total_execution_time = self.total_execution_time / self.call_count
|
self.total_execution_time = self.total_execution_time / self.call_count
|
||||||
|
|
||||||
|
|
||||||
|
#: How often a plugin's metrics are written to the cache, in seconds.
|
||||||
|
#:
|
||||||
|
#: Persisting on every call meant a small file rewritten roughly nine times a
|
||||||
|
#: minute per plugin. On a rig with fourteen active plugins that was ~126
|
||||||
|
#: writes a minute for metrics alone, and since each ~350-byte file costs a
|
||||||
|
#: 4KB block plus an ext4 journal entry, it dominated the device's write
|
||||||
|
#: volume -- on an SD card, which wears out.
|
||||||
|
#:
|
||||||
|
#: The in-memory copy stays authoritative and exact; only the cross-process
|
||||||
|
#: snapshot the web UI reads is delayed, and telemetry up to half a minute old
|
||||||
|
#: is still a fair description of a long-running plugin.
|
||||||
|
_METRICS_PERSIST_INTERVAL = 30.0
|
||||||
|
|
||||||
|
|
||||||
class PluginResourceMonitor:
|
class PluginResourceMonitor:
|
||||||
"""
|
"""
|
||||||
Monitors resource usage for plugins.
|
Monitors resource usage for plugins.
|
||||||
@@ -75,6 +89,10 @@ class PluginResourceMonitor:
|
|||||||
# Resource metrics per plugin
|
# Resource metrics per plugin
|
||||||
self._metrics: Dict[str, ResourceMetrics] = {}
|
self._metrics: Dict[str, ResourceMetrics] = {}
|
||||||
self._limits: Dict[str, ResourceLimits] = {}
|
self._limits: Dict[str, ResourceLimits] = {}
|
||||||
|
# When each plugin's metrics last reached the cache. Metrics change on
|
||||||
|
# every call, so they cannot be de-duplicated the way health state can;
|
||||||
|
# they are rate-limited instead. See _METRICS_PERSIST_INTERVAL.
|
||||||
|
self._metrics_persisted_at: Dict[str, float] = {}
|
||||||
|
|
||||||
# Thread-local storage for execution tracking
|
# Thread-local storage for execution tracking
|
||||||
self._local = threading.local()
|
self._local = threading.local()
|
||||||
@@ -232,18 +250,8 @@ class PluginResourceMonitor:
|
|||||||
# CPU is harder to measure per-call, so we track it separately
|
# CPU is harder to measure per-call, so we track it separately
|
||||||
metrics.cpu_percent = self._get_process_cpu_percent()
|
metrics.cpu_percent = self._get_process_cpu_percent()
|
||||||
|
|
||||||
# Persist metrics
|
# Persist metrics, at most once per interval per plugin.
|
||||||
cache_key = self._get_metrics_key(plugin_id)
|
self._persist_metrics(plugin_id, metrics)
|
||||||
self.cache_manager.set(cache_key, {
|
|
||||||
'memory_mb': metrics.memory_mb,
|
|
||||||
'cpu_percent': metrics.cpu_percent,
|
|
||||||
'execution_time': metrics.execution_time,
|
|
||||||
'call_count': metrics.call_count,
|
|
||||||
'total_execution_time': metrics.total_execution_time,
|
|
||||||
'max_execution_time': metrics.max_execution_time,
|
|
||||||
'min_execution_time': metrics.min_execution_time if metrics.min_execution_time != float('inf') else 0.0,
|
|
||||||
'last_update_time': metrics.last_update_time
|
|
||||||
})
|
|
||||||
|
|
||||||
# Check limits
|
# Check limits
|
||||||
if limits:
|
if limits:
|
||||||
@@ -363,6 +371,37 @@ class PluginResourceMonitor:
|
|||||||
summaries[plugin_id] = self.get_metrics_summary(plugin_id)
|
summaries[plugin_id] = self.get_metrics_summary(plugin_id)
|
||||||
return summaries
|
return summaries
|
||||||
|
|
||||||
|
def _persist_metrics(self, plugin_id: str, metrics: ResourceMetrics,
|
||||||
|
force: bool = False) -> None:
|
||||||
|
"""Write a plugin's metrics to the cache, at most once per interval.
|
||||||
|
|
||||||
|
Caller must hold ``self._lock``.
|
||||||
|
"""
|
||||||
|
# Monotonic, not wall clock: these devices have no RTC, so the clock
|
||||||
|
# jumps by however far off boot-time was the moment NTP first syncs.
|
||||||
|
# A forward jump would allow an early write, a backward one would
|
||||||
|
# stall the snapshot well past the interval.
|
||||||
|
now = time.monotonic()
|
||||||
|
if not force and now - self._metrics_persisted_at.get(plugin_id, 0.0) \
|
||||||
|
< _METRICS_PERSIST_INTERVAL:
|
||||||
|
return
|
||||||
|
cache_key = self._get_metrics_key(plugin_id)
|
||||||
|
self.cache_manager.set(cache_key, {
|
||||||
|
'memory_mb': metrics.memory_mb,
|
||||||
|
'cpu_percent': metrics.cpu_percent,
|
||||||
|
'execution_time': metrics.execution_time,
|
||||||
|
'call_count': metrics.call_count,
|
||||||
|
'total_execution_time': metrics.total_execution_time,
|
||||||
|
'max_execution_time': metrics.max_execution_time,
|
||||||
|
'min_execution_time': (metrics.min_execution_time
|
||||||
|
if metrics.min_execution_time != float('inf')
|
||||||
|
else 0.0),
|
||||||
|
'last_update_time': metrics.last_update_time,
|
||||||
|
})
|
||||||
|
# Only after the write lands. Marking it first would mean a failed
|
||||||
|
# set() bought the next interval's silence without leaving a snapshot.
|
||||||
|
self._metrics_persisted_at[plugin_id] = now
|
||||||
|
|
||||||
def reset_metrics(self, plugin_id: str) -> None:
|
def reset_metrics(self, plugin_id: str) -> None:
|
||||||
"""Reset metrics for a plugin."""
|
"""Reset metrics for a plugin."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
@@ -370,4 +409,7 @@ class PluginResourceMonitor:
|
|||||||
self._metrics[plugin_id] = ResourceMetrics()
|
self._metrics[plugin_id] = ResourceMetrics()
|
||||||
cache_key = self._get_metrics_key(plugin_id)
|
cache_key = self._get_metrics_key(plugin_id)
|
||||||
self.cache_manager.delete(cache_key)
|
self.cache_manager.delete(cache_key)
|
||||||
|
# Let the next call persist immediately rather than leaving the
|
||||||
|
# deleted key absent for the rest of the interval.
|
||||||
|
self._metrics_persisted_at.pop(plugin_id, None)
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
|
||||||
@@ -127,3 +127,67 @@ class TestForceReload:
|
|||||||
fresh = mon.get_metrics_summary("p", force_reload=True)
|
fresh = mon.get_metrics_summary("p", force_reload=True)
|
||||||
assert fresh["call_count"] == 7
|
assert fresh["call_count"] == 7
|
||||||
assert any(c.kwargs.get("memory_ttl") == 0 for c in cache.get.call_args_list)
|
assert any(c.kwargs.get("memory_ttl") == 0 for c in cache.get.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
class TestMetricsPersistenceChurn:
|
||||||
|
"""Metrics are telemetry; writing them on every call wore the SD card.
|
||||||
|
|
||||||
|
Each write is a ~350-byte file, which on ext4 costs a 4KB block plus a
|
||||||
|
journal entry. At roughly nine calls a minute per plugin across fourteen
|
||||||
|
plugins it dominated the device's write volume.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def test_repeated_calls_persist_once_per_interval(self):
|
||||||
|
cache = _cache()
|
||||||
|
mon = PluginResourceMonitor(cache, enable_monitoring=False)
|
||||||
|
for _ in range(50):
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
writes = [c for c in cache.set.call_args_list
|
||||||
|
if c.args and str(c.args[0]).startswith("plugin_metrics:")]
|
||||||
|
assert len(writes) == 1, (
|
||||||
|
f"50 calls produced {len(writes)} metric writes; expected 1")
|
||||||
|
|
||||||
|
def test_the_interval_elapsing_allows_the_next_write(self, monkeypatch):
|
||||||
|
import src.plugin_system.resource_monitor as rm
|
||||||
|
cache = _cache()
|
||||||
|
mon = PluginResourceMonitor(cache, enable_monitoring=False)
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
# pretend the interval has passed
|
||||||
|
mon._metrics_persisted_at["p"] -= rm._METRICS_PERSIST_INTERVAL + 1
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
writes = [c for c in cache.set.call_args_list
|
||||||
|
if c.args and str(c.args[0]).startswith("plugin_metrics:")]
|
||||||
|
assert len(writes) == 2
|
||||||
|
|
||||||
|
def test_in_memory_metrics_stay_exact_while_writes_are_skipped(self):
|
||||||
|
mon = PluginResourceMonitor(_cache(), enable_monitoring=False)
|
||||||
|
for _ in range(20):
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
assert mon.get_metrics("p").call_count == 20
|
||||||
|
|
||||||
|
def test_reset_lets_the_next_call_persist_immediately(self):
|
||||||
|
cache = _cache()
|
||||||
|
mon = PluginResourceMonitor(cache, enable_monitoring=False)
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
mon.reset_metrics("p")
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
writes = [c for c in cache.set.call_args_list
|
||||||
|
if c.args and str(c.args[0]).startswith("plugin_metrics:")]
|
||||||
|
assert len(writes) == 2, "reset should clear the throttle timestamp"
|
||||||
|
|
||||||
|
def test_a_failed_write_does_not_buy_the_next_interval_of_silence(self):
|
||||||
|
"""A set() that raises must not count as having persisted.
|
||||||
|
|
||||||
|
Marking the timestamp before the write would leave no snapshot in the
|
||||||
|
cache and still suppress the next 30 seconds of attempts.
|
||||||
|
"""
|
||||||
|
cache = _cache()
|
||||||
|
cache.set.side_effect = [OSError("disk full"), None]
|
||||||
|
mon = PluginResourceMonitor(cache, enable_monitoring=False)
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
# the very next call must try again rather than skip the interval
|
||||||
|
mon.monitor_call("p", lambda: None)
|
||||||
|
writes = [c for c in cache.set.call_args_list
|
||||||
|
if c.args and str(c.args[0]).startswith("plugin_metrics:")]
|
||||||
|
assert len(writes) == 2, "a failed write should be retried, not skipped"
|
||||||
|
|||||||
Reference in New Issue
Block a user