mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-12-03 02:37:06 +03:00
Refactor Notices and System Health pane (#24243)
* refactor notices * show startup message for enrichments in health pane * tweaks
This commit is contained in:
committed by
Nicolas Mowen
parent
5cef6823a6
commit
7bc32fd4c9
+91
-10
@@ -11,7 +11,7 @@ from typing import Any
|
||||
from frigate.comms.inter_process import InterProcessRequestor
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import FREQUENCY_STATS_POINTS
|
||||
from frigate.notices.registry import NoticeRegistry
|
||||
from frigate.notices import flush_notices, raise_notice, resolve_kind, resolve_notice
|
||||
from frigate.stats.hardware import HardwareStats
|
||||
from frigate.stats.prometheus import update_metrics
|
||||
from frigate.stats.util import get_latest_version, is_newer_version, stats_snapshot
|
||||
@@ -26,6 +26,46 @@ MAX_STATS_POINTS = 80
|
||||
# how often to ask GitHub for the latest release
|
||||
VERSION_REFRESH_S = 24 * 60 * 60
|
||||
|
||||
# a camera skipping at least this percent of its frames is falling behind
|
||||
SKIPPED_DETECTIONS_PCT = 5
|
||||
|
||||
# for at least this long before it becomes a notice
|
||||
SKIPPED_DETECTIONS_HOLD_S = 60
|
||||
|
||||
# detectors warm up after a start; the status bar waits this long too
|
||||
STARTUP_GRACE_S = 120
|
||||
|
||||
|
||||
class SkippedDetectionsTracker:
|
||||
"""Finds cameras whose skipped share stays high long enough for a notice."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._since: dict[str, float] = {}
|
||||
self._raised: set[str] = set()
|
||||
|
||||
def update(self, cameras: dict[str, dict[str, Any]], now: float) -> list[str]:
|
||||
"""Return the cameras whose episode qualified on this sample."""
|
||||
qualified: list[str] = []
|
||||
|
||||
# a removed camera that comes back starts a new episode
|
||||
for camera in self._since.keys() - cameras.keys():
|
||||
self._since.pop(camera)
|
||||
self._raised.discard(camera)
|
||||
|
||||
for camera, camera_stats in cameras.items():
|
||||
if camera_stats["skipped_pct"] < SKIPPED_DETECTIONS_PCT:
|
||||
self._since.pop(camera, None)
|
||||
self._raised.discard(camera)
|
||||
continue
|
||||
|
||||
since = self._since.setdefault(camera, now)
|
||||
|
||||
if camera not in self._raised and now - since >= SKIPPED_DETECTIONS_HOLD_S:
|
||||
self._raised.add(camera)
|
||||
qualified.append(camera)
|
||||
|
||||
return qualified
|
||||
|
||||
|
||||
class StatsEmitter(threading.Thread):
|
||||
def __init__(
|
||||
@@ -33,15 +73,18 @@ class StatsEmitter(threading.Thread):
|
||||
config: FrigateConfig,
|
||||
stats_tracking: StatsTrackingTypes,
|
||||
stop_event: MpEvent,
|
||||
notice_registry: NoticeRegistry | None = None,
|
||||
):
|
||||
super().__init__(name="frigate_stats_emitter")
|
||||
self.config = config
|
||||
self.stats_tracking = stats_tracking
|
||||
self.stop_event = stop_event
|
||||
self.notice_registry = notice_registry
|
||||
self.hardware_stats = HardwareStats(config)
|
||||
self.stats_history: list[dict[str, Any]] = []
|
||||
self.skipped_detections = SkippedDetectionsTracker()
|
||||
|
||||
# the shm notice's params as last sent, so only a change is written
|
||||
self._shm_checked = False
|
||||
self._shm_params: dict[str, Any] | None = None
|
||||
|
||||
# create communication for stats
|
||||
self.requestor = InterProcessRequestor()
|
||||
@@ -134,9 +177,6 @@ class StatsEmitter(threading.Thread):
|
||||
|
||||
def _check_update_notice(self) -> None:
|
||||
"""Raise or resolve the update notice from the tracked latest version."""
|
||||
if self.notice_registry is None:
|
||||
return
|
||||
|
||||
latest = self.stats_tracking["latest_frigate_version"]
|
||||
|
||||
# a failed lookup says nothing about whether an update exists
|
||||
@@ -144,11 +184,9 @@ class StatsEmitter(threading.Thread):
|
||||
return
|
||||
|
||||
if is_newer_version(VERSION, latest):
|
||||
self.notice_registry.raise_notice(
|
||||
"update_available", params={"version": latest}
|
||||
)
|
||||
raise_notice("update_available", scope=latest, params={"version": latest})
|
||||
else:
|
||||
self.notice_registry.resolve("update_available")
|
||||
resolve_kind("update_available")
|
||||
|
||||
def _refresh_latest_version(self) -> None:
|
||||
"""Refresh the latest release on a daemon thread so the request never stalls stats."""
|
||||
@@ -166,6 +204,46 @@ class StatsEmitter(threading.Thread):
|
||||
target=refresh, name="frigate_version_check", daemon=True
|
||||
).start()
|
||||
|
||||
def _update_shm_notice(self, shm: dict[str, Any]) -> None:
|
||||
"""Raise the shm notice while /dev/shm is smaller than the cameras need."""
|
||||
params = (
|
||||
{"total": shm["total"], "min": shm["min_shm"]}
|
||||
if shm and shm["total"] < shm["min_shm"]
|
||||
else None
|
||||
)
|
||||
|
||||
# the first tick always sends, so a row the last run left is raised
|
||||
# again or cleared
|
||||
if self._shm_checked and params == self._shm_params:
|
||||
return
|
||||
|
||||
self._shm_checked = True
|
||||
self._shm_params = params
|
||||
|
||||
if params is None:
|
||||
resolve_notice("shm_too_low")
|
||||
else:
|
||||
raise_notice("shm_too_low", params=params)
|
||||
|
||||
def _update_notices(self, stats: dict[str, Any], now: float) -> None:
|
||||
"""Update notices based on current stats or time."""
|
||||
# skipped detections
|
||||
if stats["service"]["uptime"] >= STARTUP_GRACE_S:
|
||||
for camera in self.skipped_detections.update(stats["cameras"], now):
|
||||
raise_notice(
|
||||
"skipped_detections",
|
||||
scope=camera,
|
||||
params={"pct": stats["cameras"][camera]["skipped_pct"]},
|
||||
)
|
||||
|
||||
# shm too small for the cameras
|
||||
self._update_shm_notice(stats["service"]["storage"]["/dev/shm"])
|
||||
|
||||
# repeats of batched kinds, such as failed logins
|
||||
flush_notices()
|
||||
|
||||
# add any additional notice types here
|
||||
|
||||
def run(self) -> None:
|
||||
time.sleep(10)
|
||||
self._check_update_notice()
|
||||
@@ -186,11 +264,14 @@ class StatsEmitter(threading.Thread):
|
||||
)
|
||||
self.stats_history.append(stats)
|
||||
self.stats_history = self.stats_history[-MAX_STATS_POINTS:]
|
||||
self._update_notices(stats, time.time())
|
||||
|
||||
if counter == 0:
|
||||
self.requestor.send_data("stats", json.dumps(stats))
|
||||
|
||||
logger.debug("Finished stats collection")
|
||||
|
||||
# write the repeats held back since the last tick
|
||||
flush_notices()
|
||||
self.hardware_stats.stop()
|
||||
logger.info("Exiting stats emitter...")
|
||||
|
||||
+28
-1
@@ -6,7 +6,7 @@ import shutil
|
||||
import time
|
||||
from json import JSONDecodeError
|
||||
from multiprocessing.managers import DictProxy
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import requests
|
||||
from requests.exceptions import RequestException
|
||||
@@ -24,6 +24,9 @@ from frigate.util.services import (
|
||||
)
|
||||
from frigate.version import VERSION
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from frigate.storage import StorageMaintainer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -88,6 +91,7 @@ def stats_init(
|
||||
embeddings_metrics: DataProcessorMetrics,
|
||||
detectors: dict[str, ObjectDetectProcess],
|
||||
processes: dict[str, int],
|
||||
storage_maintainer: "StorageMaintainer | None" = None,
|
||||
) -> StatsTrackingTypes:
|
||||
stats_tracking: StatsTrackingTypes = {
|
||||
"camera_metrics": camera_metrics,
|
||||
@@ -97,6 +101,7 @@ def stats_init(
|
||||
"latest_frigate_version": get_latest_version(config),
|
||||
"last_updated": int(time.time()),
|
||||
"processes": processes,
|
||||
"storage_maintainer": storage_maintainer,
|
||||
}
|
||||
return stats_tracking
|
||||
|
||||
@@ -216,6 +221,18 @@ def embeddings_stats(
|
||||
return stats
|
||||
|
||||
|
||||
def skipped_percent(skipped_fps: float, camera_fps: float, enabled: bool) -> float:
|
||||
"""Percent of a camera's frames dropped before detection.
|
||||
|
||||
camera_fps counts the dropped frames too. A disabled camera keeps its last
|
||||
readings, so it reports zero.
|
||||
"""
|
||||
if not enabled or camera_fps <= 0:
|
||||
return 0.0
|
||||
|
||||
return round(skipped_fps / camera_fps * 100, 1)
|
||||
|
||||
|
||||
def stats_snapshot(
|
||||
config: FrigateConfig,
|
||||
stats_tracking: StatsTrackingTypes,
|
||||
@@ -273,6 +290,11 @@ def stats_snapshot(
|
||||
"camera_fps": round(camera_stats.camera_fps.value, 2),
|
||||
"process_fps": round(camera_stats.process_fps.value, 2),
|
||||
"skipped_fps": round(camera_stats.skipped_fps.value, 2),
|
||||
"skipped_pct": skipped_percent(
|
||||
camera_stats.skipped_fps.value,
|
||||
current_fps,
|
||||
config.cameras[name].enabled,
|
||||
),
|
||||
"detection_fps": round(camera_stats.detection_fps.value, 2),
|
||||
"detection_enabled": config.cameras[name].detect.enabled,
|
||||
"pid": pid,
|
||||
@@ -301,12 +323,17 @@ def stats_snapshot(
|
||||
if bandwidth_stats:
|
||||
stats["bandwidth_usages"] = bandwidth_stats
|
||||
|
||||
storage_maintainer = stats_tracking.get("storage_maintainer")
|
||||
|
||||
stats["service"] = {
|
||||
"uptime": (int(time.time()) - stats_tracking["started"]),
|
||||
"version": VERSION,
|
||||
"latest_version": stats_tracking["latest_frigate_version"],
|
||||
"storage": {},
|
||||
"last_updated": int(time.time()),
|
||||
"retention_unmet": bool(
|
||||
storage_maintainer and storage_maintainer.retention_unmet
|
||||
),
|
||||
}
|
||||
|
||||
for path in [RECORD_DIR, CLIPS_DIR, CACHE_DIR]:
|
||||
|
||||
Reference in New Issue
Block a user