keep event cleanup running and fix storage usage keys

- Event cleanup ran with no exception handling inside its loop, so one error (a camera added or removed while it iterated the shared cameras dict, a DB error, a thumbnail unlink failure) ended event and snapshot retention until restart. Each cycle is now guarded, camera iterations use a snapshot, and thumbnail unlink errors are caught
- Camera keys were captured once at startup, so a camera added at runtime also matched the removed-camera branch and its events could expire early under the global retention. The keys are refreshed each cycle and the removed-camera label cache resets when they change
- Clip expiry had no has_clip filter and redid every past expiration each cycle. The queries now skip events already expired, and the dead clip unlink block is removed
- Storage usage was keyed by friendly name, so cameras sharing one merged into a single row. It is keyed by camera id and the storage graph resolves the display name
This commit is contained in:
Josh Hawkins
2026-11-23 15:54:35 -06:00
parent d20d6dcf72
commit 565328499c
6 changed files with 246 additions and 90 deletions
+25 -45
View File
@@ -2,14 +2,11 @@
import datetime import datetime
import logging import logging
import os
import threading import threading
from multiprocessing.synchronize import Event as MpEvent from multiprocessing.synchronize import Event as MpEvent
from pathlib import Path
from typing import Any from typing import Any
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR
from frigate.db.sqlitevecq import SqliteVecQueueDatabase from frigate.db.sqlitevecq import SqliteVecQueueDatabase
from frigate.models import Event, Timeline from frigate.models import Event, Timeline
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
@@ -143,7 +140,7 @@ class EventCleanup(threading.Thread):
events_to_update = [] events_to_update = []
## Expire events from cameras based on the camera config ## Expire events from cameras based on the camera config
for name, camera in self.config.cameras.items(): for name, camera in list(self.config.cameras.items()):
retain_config = camera.snapshots.retain retain_config = camera.snapshots.retain
# get distinct objects in database for this camera # get distinct objects in database for this camera
@@ -205,54 +202,18 @@ class EventCleanup(threading.Thread):
self.config.record.effective_alert_days, self.config.record.effective_alert_days,
self.config.record.effective_detection_days, self.config.record.effective_detection_days,
) )
file_extension = None # mp4 clips are no longer stored in /clips
update_params = {"has_clip": False} update_params = {"has_clip": False}
# get expiration time for this label
expire_after = ( expire_after = (
datetime.datetime.now() - datetime.timedelta(days=expire_days) datetime.datetime.now() - datetime.timedelta(days=expire_days)
).timestamp() ).timestamp()
# grab all events after specific time
expired_events: list[Event] = list(
Event.select(
Event.id,
Event.camera,
)
.where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
.namedtuples()
.iterator()
)
logger.debug(f"{len(expired_events)} events can be expired")
# delete the media from disk
for expired in expired_events:
media_name = f"{expired.camera}-{expired.id}"
media_path = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
try:
media_path.unlink(missing_ok=True)
if file_extension == "jpg":
media_path = Path( # type: ignore[unreachable]
f"{os.path.join(CLIPS_DIR, media_name)}-clean.webp"
)
media_path.unlink(missing_ok=True)
# Also delete clean.png (legacy) for backward compatibility
media_path = Path(
f"{os.path.join(CLIPS_DIR, media_name)}-clean.png"
)
media_path.unlink(missing_ok=True)
except OSError as e:
logger.warning(f"Unable to delete event images: {e}")
# update the clips attribute for the db entry # update the clips attribute for the db entry
query = Event.select(Event.id).where( query = Event.select(Event.id).where(
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.retain_indefinitely == False, Event.retain_indefinitely == False,
Event.has_clip == True,
) )
events_to_update = [] events_to_update = []
@@ -280,7 +241,7 @@ class EventCleanup(threading.Thread):
now = datetime.datetime.now() now = datetime.datetime.now()
## Expire events from cameras based on the camera config ## Expire events from cameras based on the camera config
for name, camera in self.config.cameras.items(): for name, camera in list(self.config.cameras.items()):
# effective days cover the sub window, keeping tracked objects # effective days cover the sub window, keeping tracked objects
# in Explore while sub recordings and review items still exist # in Explore while sub recordings and review items still exist
alert_expire_date = ( alert_expire_date = (
@@ -298,6 +259,7 @@ class EventCleanup(threading.Thread):
.where( .where(
Event.camera == name, Event.camera == name,
Event.retain_indefinitely == False, Event.retain_indefinitely == False,
Event.has_clip == True,
( (
( (
(Event.data["max_severity"] != "detection") (Event.data["max_severity"] != "detection")
@@ -335,6 +297,23 @@ class EventCleanup(threading.Thread):
# only expire events every 5 minutes # only expire events every 5 minutes
while not self.stop_event.wait(300): while not self.stop_event.wait(300):
try:
self.expire_events()
except Exception:
logger.exception("Event cleanup failed, retrying next cycle")
logger.info("Exiting event cleanup...")
def refresh_camera_keys(self) -> None:
"""Track cameras added or removed at runtime."""
camera_keys = list(self.config.cameras)
if set(camera_keys) != set(self.camera_keys):
self.camera_keys = camera_keys
self.removed_camera_labels = None
def expire_events(self) -> None:
self.refresh_camera_keys()
events_with_expired_clips = self.expire_clips() events_with_expired_clips = self.expire_clips()
# delete timeline entries for events that have expired recordings # delete timeline entries for events that have expired recordings
@@ -357,7 +336,10 @@ class EventCleanup(threading.Thread):
events_to_delete: list[Event] = [e for e in events] events_to_delete: list[Event] = [e for e in events]
for e in events_to_delete: for e in events_to_delete:
delete_event_thumbnail(e) if not delete_event_thumbnail(e):
logger.warning(
f"Unable to delete event thumbnail for {e.camera}: {e.id}"
)
logger.debug(f"Found {len(events_to_delete)} events that can be expired") logger.debug(f"Found {len(events_to_delete)} events that can be expired")
if len(events_to_delete) > 0: if len(events_to_delete) > 0:
@@ -373,5 +355,3 @@ class EventCleanup(threading.Thread):
self.db.delete_embeddings_description(event_ids=chunk) self.db.delete_embeddings_description(event_ids=chunk)
self.db.delete_embeddings_thumbnail(event_ids=chunk) self.db.delete_embeddings_thumbnail(event_ids=chunk)
logger.debug(f"Deleted {len(chunk)} embeddings") logger.debug(f"Deleted {len(chunk)} embeddings")
logger.info("Exiting event cleanup...")
+3 -6
View File
@@ -137,7 +137,7 @@ class StorageMaintainer(threading.Thread):
def calculate_camera_bandwidth(self) -> None: def calculate_camera_bandwidth(self) -> None:
"""Calculate an average MB/hr for each camera.""" """Calculate an average MB/hr for each camera."""
for camera in self.config.cameras.keys(): for camera in list(self.config.cameras):
# Skip replay cameras # Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX): if camera.startswith(REPLAY_CAMERA_PREFIX):
continue continue
@@ -186,7 +186,7 @@ class StorageMaintainer(threading.Thread):
"""Calculate the storage usage of each camera.""" """Calculate the storage usage of each camera."""
usages: dict[str, dict] = {} usages: dict[str, dict] = {}
for camera in self.config.cameras.keys(): for camera in list(self.config.cameras):
# Skip replay cameras # Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX): if camera.startswith(REPLAY_CAMERA_PREFIX):
continue continue
@@ -208,10 +208,7 @@ class StorageMaintainer(threading.Thread):
"bandwidth_by_stream", {} "bandwidth_by_stream", {}
) )
camera_key = ( usages[camera] = {
getattr(self.config.cameras[camera], "friendly_name", None) or camera
)
usages[camera_key] = {
"usage": sum(stream_usages.values()), "usage": sum(stream_usages.values()),
"bandwidth": self.camera_storage_stats.get(camera, {}).get( "bandwidth": self.camera_storage_stats.get(camera, {}).get(
"bandwidth", 0 "bandwidth", 0
+141
View File
@@ -0,0 +1,141 @@
"""Tests for the event cleanup cycle and runtime camera changes."""
import datetime
import unittest
from unittest.mock import MagicMock, patch
from peewee import SqliteDatabase
from frigate.config import FrigateConfig
from frigate.events.cleanup import EventCleanup
from frigate.models import Event, Timeline
from frigate.util.file import delete_event_thumbnail
def _camera(path: str, record_days: int) -> dict:
return {
"ffmpeg": {"inputs": [{"path": path, "roles": ["detect", "record"]}]},
"record": {
"enabled": True,
"alerts": {"retain": {"days": record_days}},
"detections": {"retain": {"days": record_days}},
},
}
class TestEventCleanup(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase(":memory:")
models = [Event, Timeline]
self.db.bind(models)
self.db.create_tables(models)
config = FrigateConfig(
**{
"mqtt": {"host": "mqtt"},
"record": {
"alerts": {"retain": {"days": 10}},
"detections": {"retain": {"days": 10}},
},
"cameras": {"front_door": _camera("rtsp://10.0.0.1:554/video", 10)},
}
)
self.config = config
self.cleanup = EventCleanup(config, MagicMock(), MagicMock())
def tearDown(self):
self.db.close()
def _insert_event(
self, id: str, camera: str, age_days: float, has_clip: bool = True
) -> None:
end_time = (
datetime.datetime.now() - datetime.timedelta(days=age_days)
).timestamp()
Event.create(
id=id,
label="person",
camera=camera,
start_time=end_time - 10,
end_time=end_time,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=has_clip,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
plus_id="",
model_hash="",
detector_type="cpu",
model_type="ssd",
data={"max_severity": "alert"},
)
def test_runtime_added_camera_keeps_its_own_retention(self):
added = FrigateConfig(
**{
"mqtt": {"host": "mqtt"},
"cameras": {"garage": _camera("rtsp://10.0.0.2:554/video", 30)},
}
).cameras["garage"]
self.config.cameras["garage"] = added
self._insert_event("garage-event", "garage", age_days=20)
self.cleanup.expire_events()
assert Event.get(Event.id == "garage-event").has_clip is True
def test_runtime_removed_camera_gets_global_retention(self):
self._insert_event("front-event", "front_door", age_days=20)
self.cleanup.camera_keys = ["front_door"]
self.cleanup.removed_camera_labels = []
del self.config.cameras["front_door"]
self.cleanup.expire_events()
# clip and snapshot both expire under the global retention
assert self.cleanup.camera_keys == []
assert not Event.select().where(Event.id == "front-event").exists()
def test_expired_clips_are_only_selected_once(self):
self._insert_event("pending", "front_door", age_days=20)
self._insert_event("expired", "front_door", age_days=20, has_clip=False)
self._insert_event("removed-pending", "removed", age_days=20)
self._insert_event("removed-expired", "removed", age_days=20, has_clip=False)
assert self.cleanup.expire_clips() == ["pending"]
assert not Event.select().where(Event.has_clip == True).exists()
with patch.object(Event, "update", wraps=Event.update) as update:
assert self.cleanup.expire_clips() == []
update.assert_not_called()
def test_cycle_failure_does_not_stop_the_thread(self):
self.cleanup.stop_event.wait.side_effect = [False, False, True]
with patch.object(
self.cleanup, "expire_events", side_effect=[RuntimeError, None]
) as expire_events:
self.cleanup.run()
assert expire_events.call_count == 2
def test_thumbnail_unlink_error_is_reported(self):
event = MagicMock(thumbnail="", camera="front_door", id="e1")
with patch(
"frigate.util.file.Path.unlink", side_effect=PermissionError
) as unlink:
assert delete_event_thumbnail(event) is False
unlink.assert_called_once()
if __name__ == "__main__":
unittest.main()
+30
View File
@@ -440,6 +440,36 @@ class TestHttp(unittest.TestCase):
assert usages["front_door"]["usage"] == 0 assert usages["front_door"]["usage"] == 0
assert usages["front_door"]["streams"] == {} assert usages["front_door"]["streams"] == {}
def test_camera_usages_keyed_by_camera_id(self):
"""Cameras sharing a friendly name keep separate usage entries."""
self.double_cam_config["cameras"]["front_door"]["friendly_name"] = "Door"
self.double_cam_config["cameras"]["back_door"]["friendly_name"] = "Door"
config = FrigateConfig(**self.double_cam_config)
storage = StorageMaintainer(config, MagicMock())
time_keep = datetime.datetime.now().timestamp()
_insert_mock_recording(
"1234567.frontdoor",
os.path.join(self.test_dir, "front.tmp"),
time_keep,
time_keep + 10,
seg_size=20,
)
_insert_mock_recording(
"1234568.backdoor",
os.path.join(self.test_dir, "back.tmp"),
time_keep,
time_keep + 10,
camera="back_door",
seg_size=5,
)
storage.calculate_camera_bandwidth()
usages = storage.calculate_camera_usages()
assert usages["front_door"]["usage"] == 20
assert usages["back_door"]["usage"] == 5
def test_storage_cleanup(self): def test_storage_cleanup(self):
"""Ensure that all recordings are cleaned up when necessary.""" """Ensure that all recordings are cleaned up when necessary."""
config = FrigateConfig(**self.minimal_config) config = FrigateConfig(**self.minimal_config)
+5 -1
View File
@@ -262,10 +262,14 @@ def delete_event_snapshot(event: Event) -> bool:
def delete_event_thumbnail(event: Event) -> bool: def delete_event_thumbnail(event: Event) -> bool:
if event.thumbnail: if event.thumbnail:
return True return True
else:
try:
Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink( Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink(
missing_ok=True missing_ok=True
) )
except OSError:
return False
return True return True
@@ -18,6 +18,9 @@ import {
} from "@/components/ui/popover"; } from "@/components/ui/popover";
import { getUnitSize } from "@/utils/storageUtil"; import { getUnitSize } from "@/utils/storageUtil";
import { CameraStorage, StreamStorage } from "@/types/stats"; import { CameraStorage, StreamStorage } from "@/types/stats";
import { FrigateConfig } from "@/types/frigateConfig";
import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
import useSWR from "swr";
import { CiCircleAlert } from "react-icons/ci"; import { CiCircleAlert } from "react-icons/ci";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -51,6 +54,7 @@ export function CombinedStorageGraph({
}: CombinedStorageGraphProps) { }: CombinedStorageGraphProps) {
const { t } = useTranslation(["views/system", "components/player"]); const { t } = useTranslation(["views/system", "components/player"]);
const { data: config } = useSWR<FrigateConfig>("config");
const { theme, systemTheme } = useTheme(); const { theme, systemTheme } = useTheme();
const isDark = (systemTheme || theme) == "dark"; const isDark = (systemTheme || theme) == "dark";
@@ -197,10 +201,10 @@ export function CombinedStorageGraph({
} else if (name == "Other") { } else if (name == "Other") {
return t("label.other", { ns: "common" }); return t("label.other", { ns: "common" });
} else { } else {
return name.replaceAll("_", " "); return resolveCameraName(config, name);
} }
}, },
[t], [t, config],
); );
const getStreamSplit = useCallback( const getStreamSplit = useCallback(