2024-02-21 23:10:28 +03:00
|
|
|
"""Utilities for stats."""
|
|
|
|
|
|
2022-11-29 04:24:20 +03:00
|
|
|
import asyncio
|
2023-05-29 13:31:17 +03:00
|
|
|
import os
|
|
|
|
|
import shutil
|
2021-01-04 02:35:58 +03:00
|
|
|
import time
|
2024-08-15 04:41:41 +03:00
|
|
|
from json import JSONDecodeError
|
Use Fork-Server As Spawn Method (#18682)
* Set runtime
* Use count correctly
* Don't assume camera sizes
* Use separate zmq proxy for object detection
* Correct order
* Use forkserver
* Only store PID instead of entire process reference
* Cleanup
* Catch correct errors
* Fix typing
* Remove before_run from process util
The before_run never actually ran because:
You're right to suspect an issue with before_run not being called and a potential deadlock. The way you've implemented the run_wrapper using __getattribute__ for the run method of BaseProcess is a common pitfall in Python's multiprocessing, especially when combined with how multiprocessing.Process works internally.
Here's a breakdown of why before_run isn't being called and why you might be experiencing a deadlock:
The Problem: __getattribute__ and Process Serialization
When you create a multiprocessing.Process object and call start(), the multiprocessing module needs to serialize the process object (or at least enough of it to re-create the process in the new interpreter). It then pickles this serialized object and sends it to the newly spawned process.
The issue with your __getattribute__ implementation for run is that:
run is retrieved during serialization: When multiprocessing tries to pickle your Process object to send to the new process, it will likely access the run attribute. This triggers your __getattribute__ wrapper, which then tries to bind run_wrapper to self.
run_wrapper is bound to the parent process's self: The run_wrapper closure, when created in the parent process, captures the self (the Process instance) from the parent's memory space.
Deserialization creates a new object: In the child process, a new Process object is created by deserializing the pickled data. However, the run_wrapper method that was pickled still holds a reference to the self from the parent process. This is a subtle but critical distinction.
The child's run is not your wrapped run: When the child process starts, it internally calls its own run method. Because of the serialization and deserialization process, the run method that's ultimately executed in the child process is the original multiprocessing.Process.run or the Process.run if you had directly overridden it. Your __getattribute__ magic, which wraps run, isn't correctly applied to the Process object within the child's context.
* Cleanup
* Logging bugfix (#18465)
* use mp Manager to handle logging queues
A Python bug (https://github.com/python/cpython/issues/91555) was preventing logs from the embeddings maintainer process from printing. The bug is fixed in Python 3.14, but a viable workaround is to use the multiprocessing Manager, which better manages mp queues and causes the logging to work correctly.
* consolidate
* fix typing
* Fix typing
* Use global log queue
* Move to using process for logging
* Convert camera tracking to process
* Add more processes
* Finalize process
* Cleanup
* Cleanup typing
* Formatting
* Remove daemon
---------
Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2025-06-12 21:12:34 +03:00
|
|
|
from multiprocessing.managers import DictProxy
|
2023-05-29 13:31:17 +03:00
|
|
|
from typing import Any, Optional
|
|
|
|
|
|
2022-04-11 15:10:19 +03:00
|
|
|
import requests
|
2023-05-29 13:31:17 +03:00
|
|
|
from requests.exceptions import RequestException
|
2021-01-04 02:35:58 +03:00
|
|
|
|
|
|
|
|
from frigate.config import FrigateConfig
|
2024-02-21 02:21:54 +03:00
|
|
|
from frigate.const import CACHE_DIR, CLIPS_DIR, RECORD_DIR
|
2025-01-10 22:44:30 +03:00
|
|
|
from frigate.data_processing.types import DataProcessorMetrics
|
2025-04-15 16:55:38 +03:00
|
|
|
from frigate.object_detection.base import ObjectDetectProcess
|
2024-09-27 15:53:23 +03:00
|
|
|
from frigate.types import StatsTrackingTypes
|
2023-07-06 17:28:50 +03:00
|
|
|
from frigate.util.services import (
|
2025-08-22 22:48:27 +03:00
|
|
|
calculate_shm_requirements,
|
2023-05-29 13:31:17 +03:00
|
|
|
get_amd_gpu_stats,
|
2026-03-27 14:07:07 +03:00
|
|
|
get_axcl_npu_stats,
|
2023-05-29 13:31:17 +03:00
|
|
|
get_bandwidth_stats,
|
|
|
|
|
get_cpu_stats,
|
2025-08-22 22:48:27 +03:00
|
|
|
get_fs_type,
|
2025-12-22 18:25:38 +03:00
|
|
|
get_hailo_temps,
|
2023-05-29 13:31:17 +03:00
|
|
|
get_intel_gpu_stats,
|
2023-07-26 13:50:41 +03:00
|
|
|
get_jetson_stats,
|
2023-05-29 13:31:17 +03:00
|
|
|
get_nvidia_gpu_stats,
|
2025-10-17 16:06:41 +03:00
|
|
|
get_openvino_npu_stats,
|
2025-04-20 00:34:05 +03:00
|
|
|
get_rockchip_gpu_stats,
|
2025-04-19 17:20:22 +03:00
|
|
|
get_rockchip_npu_stats,
|
2024-02-21 02:21:54 +03:00
|
|
|
is_vaapi_amd_driver,
|
2023-05-29 13:31:17 +03:00
|
|
|
)
|
|
|
|
|
from frigate.version import VERSION
|
2021-01-04 02:35:58 +03:00
|
|
|
|
2021-02-17 16:23:32 +03:00
|
|
|
|
2023-01-26 03:36:26 +03:00
|
|
|
def get_latest_version(config: FrigateConfig) -> str:
|
|
|
|
|
if not config.telemetry.version_check:
|
|
|
|
|
return "disabled"
|
|
|
|
|
|
2022-05-26 18:04:33 +03:00
|
|
|
try:
|
|
|
|
|
request = requests.get(
|
2022-10-01 16:58:23 +03:00
|
|
|
"https://api.github.com/repos/blakeblackshear/frigate/releases/latest",
|
|
|
|
|
timeout=10,
|
2022-05-26 18:04:33 +03:00
|
|
|
)
|
2025-12-24 17:03:09 +03:00
|
|
|
response = request.json()
|
2024-08-15 04:41:41 +03:00
|
|
|
except (RequestException, JSONDecodeError):
|
2022-05-26 18:04:33 +03:00
|
|
|
return "unknown"
|
|
|
|
|
|
2022-04-16 18:40:04 +03:00
|
|
|
if request.ok and response and "tag_name" in response:
|
|
|
|
|
return str(response.get("tag_name").replace("v", ""))
|
2022-04-11 15:10:19 +03:00
|
|
|
else:
|
|
|
|
|
return "unknown"
|
|
|
|
|
|
|
|
|
|
|
2022-04-16 18:40:04 +03:00
|
|
|
def stats_init(
|
2023-01-26 03:36:26 +03:00
|
|
|
config: FrigateConfig,
|
Use Fork-Server As Spawn Method (#18682)
* Set runtime
* Use count correctly
* Don't assume camera sizes
* Use separate zmq proxy for object detection
* Correct order
* Use forkserver
* Only store PID instead of entire process reference
* Cleanup
* Catch correct errors
* Fix typing
* Remove before_run from process util
The before_run never actually ran because:
You're right to suspect an issue with before_run not being called and a potential deadlock. The way you've implemented the run_wrapper using __getattribute__ for the run method of BaseProcess is a common pitfall in Python's multiprocessing, especially when combined with how multiprocessing.Process works internally.
Here's a breakdown of why before_run isn't being called and why you might be experiencing a deadlock:
The Problem: __getattribute__ and Process Serialization
When you create a multiprocessing.Process object and call start(), the multiprocessing module needs to serialize the process object (or at least enough of it to re-create the process in the new interpreter). It then pickles this serialized object and sends it to the newly spawned process.
The issue with your __getattribute__ implementation for run is that:
run is retrieved during serialization: When multiprocessing tries to pickle your Process object to send to the new process, it will likely access the run attribute. This triggers your __getattribute__ wrapper, which then tries to bind run_wrapper to self.
run_wrapper is bound to the parent process's self: The run_wrapper closure, when created in the parent process, captures the self (the Process instance) from the parent's memory space.
Deserialization creates a new object: In the child process, a new Process object is created by deserializing the pickled data. However, the run_wrapper method that was pickled still holds a reference to the self from the parent process. This is a subtle but critical distinction.
The child's run is not your wrapped run: When the child process starts, it internally calls its own run method. Because of the serialization and deserialization process, the run method that's ultimately executed in the child process is the original multiprocessing.Process.run or the Process.run if you had directly overridden it. Your __getattribute__ magic, which wraps run, isn't correctly applied to the Process object within the child's context.
* Cleanup
* Logging bugfix (#18465)
* use mp Manager to handle logging queues
A Python bug (https://github.com/python/cpython/issues/91555) was preventing logs from the embeddings maintainer process from printing. The bug is fixed in Python 3.14, but a viable workaround is to use the multiprocessing Manager, which better manages mp queues and causes the logging to work correctly.
* consolidate
* fix typing
* Fix typing
* Use global log queue
* Move to using process for logging
* Convert camera tracking to process
* Add more processes
* Finalize process
* Cleanup
* Cleanup typing
* Formatting
* Remove daemon
---------
Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2025-06-12 21:12:34 +03:00
|
|
|
camera_metrics: DictProxy,
|
2025-01-10 22:44:30 +03:00
|
|
|
embeddings_metrics: DataProcessorMetrics | None,
|
2022-11-04 05:23:09 +03:00
|
|
|
detectors: dict[str, ObjectDetectProcess],
|
2023-05-05 01:58:59 +03:00
|
|
|
processes: dict[str, int],
|
2022-04-16 18:40:04 +03:00
|
|
|
) -> StatsTrackingTypes:
|
|
|
|
|
stats_tracking: StatsTrackingTypes = {
|
2021-02-17 16:23:32 +03:00
|
|
|
"camera_metrics": camera_metrics,
|
2025-01-05 17:47:57 +03:00
|
|
|
"embeddings_metrics": embeddings_metrics,
|
2021-02-17 16:23:32 +03:00
|
|
|
"detectors": detectors,
|
|
|
|
|
"started": int(time.time()),
|
2023-01-26 03:36:26 +03:00
|
|
|
"latest_frigate_version": get_latest_version(config),
|
2023-01-27 15:20:41 +03:00
|
|
|
"last_updated": int(time.time()),
|
2023-05-05 01:58:59 +03:00
|
|
|
"processes": processes,
|
2021-01-04 02:35:58 +03:00
|
|
|
}
|
|
|
|
|
return stats_tracking
|
|
|
|
|
|
2021-02-17 16:23:32 +03:00
|
|
|
|
2022-04-16 18:40:04 +03:00
|
|
|
def read_temperature(path: str) -> Optional[float]:
|
2021-11-30 00:52:58 +03:00
|
|
|
if os.path.isfile(path):
|
|
|
|
|
with open(path) as f:
|
2021-12-12 19:27:01 +03:00
|
|
|
line = f.readline().strip()
|
|
|
|
|
return int(line) / 1000
|
2021-11-30 00:52:58 +03:00
|
|
|
return None
|
|
|
|
|
|
2021-12-12 19:27:01 +03:00
|
|
|
|
2022-04-16 18:40:04 +03:00
|
|
|
def get_temperatures() -> dict[str, float]:
|
2021-12-12 19:27:01 +03:00
|
|
|
temps = {}
|
2021-11-30 00:52:58 +03:00
|
|
|
|
|
|
|
|
# Get temperatures for all attached Corals
|
2021-12-12 19:27:01 +03:00
|
|
|
base = "/sys/class/apex/"
|
|
|
|
|
if os.path.isdir(base):
|
|
|
|
|
for apex in os.listdir(base):
|
|
|
|
|
temp = read_temperature(os.path.join(base, apex, "temp"))
|
|
|
|
|
if temp is not None:
|
|
|
|
|
temps[apex] = temp
|
2021-11-30 00:52:58 +03:00
|
|
|
|
2025-12-22 18:25:38 +03:00
|
|
|
# Get temperatures for Hailo devices
|
|
|
|
|
temps.update(get_hailo_temps())
|
|
|
|
|
|
2021-11-30 00:52:58 +03:00
|
|
|
return temps
|
2021-02-17 16:23:32 +03:00
|
|
|
|
2021-12-12 19:27:01 +03:00
|
|
|
|
2025-12-22 18:25:38 +03:00
|
|
|
def get_detector_temperature(
|
|
|
|
|
detector_type: str,
|
|
|
|
|
detector_index_by_type: dict[str, int],
|
|
|
|
|
) -> Optional[float]:
|
|
|
|
|
"""Get temperature for a specific detector based on its type."""
|
|
|
|
|
if detector_type == "edgetpu":
|
|
|
|
|
# Get temperatures for all attached Corals
|
|
|
|
|
base = "/sys/class/apex/"
|
|
|
|
|
if os.path.isdir(base):
|
|
|
|
|
apex_devices = sorted(os.listdir(base))
|
|
|
|
|
index = detector_index_by_type.get("edgetpu", 0)
|
|
|
|
|
if index < len(apex_devices):
|
|
|
|
|
apex_name = apex_devices[index]
|
|
|
|
|
temp = read_temperature(os.path.join(base, apex_name, "temp"))
|
|
|
|
|
if temp is not None:
|
|
|
|
|
return temp
|
|
|
|
|
elif detector_type == "hailo8l":
|
|
|
|
|
# Get temperatures for Hailo devices
|
|
|
|
|
hailo_temps = get_hailo_temps()
|
|
|
|
|
if hailo_temps:
|
|
|
|
|
hailo_device_names = sorted(hailo_temps.keys())
|
|
|
|
|
index = detector_index_by_type.get("hailo8l", 0)
|
|
|
|
|
if index < len(hailo_device_names):
|
|
|
|
|
device_name = hailo_device_names[index]
|
|
|
|
|
return hailo_temps[device_name]
|
2025-12-31 23:32:07 +03:00
|
|
|
elif detector_type == "rknn":
|
|
|
|
|
# Rockchip temperatures are handled by the GPU / NPU stats
|
|
|
|
|
# as there are not detector specific temperatures
|
|
|
|
|
pass
|
2025-12-22 18:25:38 +03:00
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_detector_stats(
|
|
|
|
|
stats_tracking: StatsTrackingTypes,
|
|
|
|
|
) -> dict[str, dict[str, Any]]:
|
|
|
|
|
"""Get stats for all detectors, including temperatures based on detector type."""
|
|
|
|
|
detector_stats: dict[str, dict[str, Any]] = {}
|
|
|
|
|
detector_type_indices: dict[str, int] = {}
|
|
|
|
|
|
|
|
|
|
for name, detector in stats_tracking["detectors"].items():
|
|
|
|
|
pid = detector.detect_process.pid if detector.detect_process else None
|
|
|
|
|
detector_type = detector.detector_config.type
|
|
|
|
|
|
|
|
|
|
# Keep track of the index for each detector type to match temperatures correctly
|
|
|
|
|
current_index = detector_type_indices.get(detector_type, 0)
|
|
|
|
|
detector_type_indices[detector_type] = current_index + 1
|
|
|
|
|
|
|
|
|
|
detector_stat = {
|
|
|
|
|
"inference_speed": round(detector.avg_inference_speed.value * 1000, 2), # type: ignore[attr-defined]
|
|
|
|
|
# issue https://github.com/python/typeshed/issues/8799
|
|
|
|
|
# from mypy 0.981 onwards
|
|
|
|
|
"detection_start": detector.detection_start.value, # type: ignore[attr-defined]
|
|
|
|
|
# issue https://github.com/python/typeshed/issues/8799
|
|
|
|
|
# from mypy 0.981 onwards
|
|
|
|
|
"pid": pid,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
temp = get_detector_temperature(detector_type, {detector_type: current_index})
|
|
|
|
|
|
|
|
|
|
if temp is not None:
|
|
|
|
|
detector_stat["temperature"] = round(temp, 1)
|
|
|
|
|
|
|
|
|
|
detector_stats[name] = detector_stat
|
|
|
|
|
|
|
|
|
|
return detector_stats
|
|
|
|
|
|
|
|
|
|
|
2023-01-05 03:12:51 +03:00
|
|
|
def get_processing_stats(
|
|
|
|
|
config: FrigateConfig, stats: dict[str, str], hwaccel_errors: list[str]
|
|
|
|
|
) -> None:
|
2022-11-29 04:24:20 +03:00
|
|
|
"""Get stats for cpu / gpu."""
|
|
|
|
|
|
|
|
|
|
async def run_tasks() -> None:
|
2023-06-11 16:26:34 +03:00
|
|
|
stats_tasks = [
|
|
|
|
|
asyncio.create_task(set_gpu_stats(config, stats, hwaccel_errors)),
|
|
|
|
|
asyncio.create_task(set_cpu_stats(stats)),
|
2025-04-19 17:20:22 +03:00
|
|
|
asyncio.create_task(set_npu_usages(config, stats)),
|
2023-06-11 16:26:34 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
if config.telemetry.stats.network_bandwidth:
|
|
|
|
|
stats_tasks.append(asyncio.create_task(set_bandwidth_stats(config, stats)))
|
|
|
|
|
|
|
|
|
|
await asyncio.wait(stats_tasks)
|
2022-11-29 04:24:20 +03:00
|
|
|
|
|
|
|
|
loop = asyncio.new_event_loop()
|
|
|
|
|
asyncio.set_event_loop(loop)
|
|
|
|
|
loop.run_until_complete(run_tasks())
|
|
|
|
|
loop.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def set_cpu_stats(all_stats: dict[str, Any]) -> None:
|
|
|
|
|
"""Set cpu usage from top."""
|
|
|
|
|
cpu_stats = get_cpu_stats()
|
|
|
|
|
|
|
|
|
|
if cpu_stats:
|
|
|
|
|
all_stats["cpu_usages"] = cpu_stats
|
|
|
|
|
|
|
|
|
|
|
2023-06-11 15:34:03 +03:00
|
|
|
async def set_bandwidth_stats(config: FrigateConfig, all_stats: dict[str, Any]) -> None:
|
2023-05-18 04:01:56 +03:00
|
|
|
"""Set bandwidth from nethogs."""
|
2023-06-11 15:34:03 +03:00
|
|
|
bandwidth_stats = get_bandwidth_stats(config)
|
2023-05-18 04:01:56 +03:00
|
|
|
|
|
|
|
|
if bandwidth_stats:
|
|
|
|
|
all_stats["bandwidth_usages"] = bandwidth_stats
|
|
|
|
|
|
|
|
|
|
|
2023-01-05 03:12:51 +03:00
|
|
|
async def set_gpu_stats(
|
|
|
|
|
config: FrigateConfig, all_stats: dict[str, Any], hwaccel_errors: list[str]
|
|
|
|
|
) -> None:
|
2022-11-29 04:24:20 +03:00
|
|
|
"""Parse GPUs from hwaccel args and use for stats."""
|
|
|
|
|
hwaccel_args = []
|
|
|
|
|
|
|
|
|
|
for camera in config.cameras.values():
|
|
|
|
|
args = camera.ffmpeg.hwaccel_args
|
|
|
|
|
|
|
|
|
|
if isinstance(args, list):
|
|
|
|
|
args = " ".join(args)
|
|
|
|
|
|
2023-01-07 04:31:25 +03:00
|
|
|
if args and args not in hwaccel_args:
|
2022-11-29 04:24:20 +03:00
|
|
|
hwaccel_args.append(args)
|
|
|
|
|
|
2023-01-04 16:37:42 +03:00
|
|
|
for stream_input in camera.ffmpeg.inputs:
|
|
|
|
|
args = stream_input.hwaccel_args
|
|
|
|
|
|
|
|
|
|
if isinstance(args, list):
|
|
|
|
|
args = " ".join(args)
|
|
|
|
|
|
|
|
|
|
if args and args not in hwaccel_args:
|
|
|
|
|
hwaccel_args.append(args)
|
|
|
|
|
|
2022-11-29 04:24:20 +03:00
|
|
|
stats: dict[str, dict] = {}
|
2026-05-14 00:12:48 +03:00
|
|
|
intel_gpu_collected = False
|
2022-11-29 04:24:20 +03:00
|
|
|
|
|
|
|
|
for args in hwaccel_args:
|
2023-01-07 04:31:25 +03:00
|
|
|
if args in hwaccel_errors:
|
|
|
|
|
# known erroring args should automatically return as error
|
2024-04-27 19:26:51 +03:00
|
|
|
stats["error-gpu"] = {"gpu": "", "mem": ""}
|
2023-01-07 04:31:25 +03:00
|
|
|
elif "cuvid" in args or "nvidia" in args:
|
2022-11-29 04:24:20 +03:00
|
|
|
# nvidia GPU
|
|
|
|
|
nvidia_usage = get_nvidia_gpu_stats()
|
|
|
|
|
|
|
|
|
|
if nvidia_usage:
|
2023-05-05 02:02:01 +03:00
|
|
|
for i in range(len(nvidia_usage)):
|
|
|
|
|
stats[nvidia_usage[i]["name"]] = {
|
2026-05-14 00:12:48 +03:00
|
|
|
"vendor": "nvidia",
|
2023-05-05 02:02:01 +03:00
|
|
|
"gpu": str(round(float(nvidia_usage[i]["gpu"]), 2)) + "%",
|
|
|
|
|
"mem": str(round(float(nvidia_usage[i]["mem"]), 2)) + "%",
|
2023-10-13 17:44:18 +03:00
|
|
|
"enc": str(round(float(nvidia_usage[i]["enc"]), 2)) + "%",
|
|
|
|
|
"dec": str(round(float(nvidia_usage[i]["dec"]), 2)) + "%",
|
2025-12-31 23:32:07 +03:00
|
|
|
"temp": str(nvidia_usage[i]["temp"]),
|
2023-05-05 02:02:01 +03:00
|
|
|
}
|
|
|
|
|
|
2022-11-29 04:24:20 +03:00
|
|
|
else:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["nvidia-gpu"] = {"vendor": "nvidia", "gpu": "", "mem": ""}
|
2023-01-05 03:12:51 +03:00
|
|
|
hwaccel_errors.append(args)
|
2023-07-26 13:50:41 +03:00
|
|
|
elif "nvmpi" in args or "jetson" in args:
|
|
|
|
|
# nvidia Jetson
|
|
|
|
|
jetson_usage = get_jetson_stats()
|
|
|
|
|
|
|
|
|
|
if jetson_usage:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["jetson-gpu"] = {"vendor": "nvidia", **jetson_usage}
|
2023-07-26 13:50:41 +03:00
|
|
|
else:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["jetson-gpu"] = {"vendor": "nvidia", "gpu": "", "mem": ""}
|
2023-07-26 13:50:41 +03:00
|
|
|
hwaccel_errors.append(args)
|
2026-03-29 20:09:02 +03:00
|
|
|
elif "qsv" in args or ("vaapi" in args and not is_vaapi_amd_driver()):
|
2023-06-11 16:26:34 +03:00
|
|
|
if not config.telemetry.stats.intel_gpu_stats:
|
|
|
|
|
continue
|
|
|
|
|
|
2026-05-14 00:12:48 +03:00
|
|
|
if not intel_gpu_collected:
|
2026-03-29 20:09:02 +03:00
|
|
|
# intel GPU (QSV or VAAPI both use the same physical GPU)
|
2026-05-14 00:12:48 +03:00
|
|
|
intel_gpu_collected = True
|
2025-07-14 15:11:25 +03:00
|
|
|
intel_usage = get_intel_gpu_stats(
|
|
|
|
|
config.telemetry.stats.intel_gpu_device
|
|
|
|
|
)
|
2022-11-29 04:24:20 +03:00
|
|
|
|
2026-05-14 00:12:48 +03:00
|
|
|
if intel_usage:
|
|
|
|
|
for entry in intel_usage.values():
|
|
|
|
|
name = entry.pop("name")
|
|
|
|
|
stats[name] = entry
|
2022-11-29 04:24:20 +03:00
|
|
|
else:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["intel-gpu"] = {"vendor": "intel", "gpu": "", "mem": ""}
|
2023-01-05 03:12:51 +03:00
|
|
|
hwaccel_errors.append(args)
|
2026-03-29 20:09:02 +03:00
|
|
|
elif "vaapi" in args:
|
|
|
|
|
if not config.telemetry.stats.amd_gpu_stats:
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# AMD VAAPI GPU
|
|
|
|
|
amd_usage = get_amd_gpu_stats()
|
|
|
|
|
|
|
|
|
|
if amd_usage:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["amd-vaapi"] = {"vendor": "amd", **amd_usage}
|
2026-03-29 20:09:02 +03:00
|
|
|
else:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["amd-vaapi"] = {"vendor": "amd", "gpu": "", "mem": ""}
|
2026-03-29 20:09:02 +03:00
|
|
|
hwaccel_errors.append(args)
|
2025-04-20 00:34:05 +03:00
|
|
|
elif "preset-rk" in args:
|
|
|
|
|
rga_usage = get_rockchip_gpu_stats()
|
|
|
|
|
|
|
|
|
|
if rga_usage:
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["rockchip"] = {"vendor": "rockchip", **rga_usage}
|
2022-11-30 04:56:01 +03:00
|
|
|
elif "v4l2m2m" in args or "rpi" in args:
|
2022-11-29 04:24:20 +03:00
|
|
|
# RPi v4l2m2m is currently not able to get usage stats
|
2026-05-14 00:12:48 +03:00
|
|
|
stats["rpi-v4l2m2m"] = {"vendor": "rpi", "gpu": "", "mem": ""}
|
2022-11-29 04:24:20 +03:00
|
|
|
|
|
|
|
|
if stats:
|
|
|
|
|
all_stats["gpu_usages"] = stats
|
2025-04-19 17:20:22 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def set_npu_usages(config: FrigateConfig, all_stats: dict[str, Any]) -> None:
|
|
|
|
|
stats: dict[str, dict] = {}
|
|
|
|
|
|
|
|
|
|
for detector in config.detectors.values():
|
|
|
|
|
if detector.type == "rknn":
|
|
|
|
|
# Rockchip NPU usage
|
|
|
|
|
rk_usage = get_rockchip_npu_stats()
|
|
|
|
|
stats["rockchip"] = rk_usage
|
2025-10-17 16:06:41 +03:00
|
|
|
elif detector.type == "openvino" and detector.device == "NPU":
|
|
|
|
|
# OpenVINO NPU usage
|
|
|
|
|
ov_usage = get_openvino_npu_stats()
|
|
|
|
|
stats["openvino"] = ov_usage
|
2026-03-27 14:07:07 +03:00
|
|
|
elif detector.type == "axengine":
|
|
|
|
|
# AXERA NPU usage
|
|
|
|
|
axcl_usage = get_axcl_npu_stats()
|
|
|
|
|
stats["axengine"] = axcl_usage
|
2025-04-19 17:20:22 +03:00
|
|
|
|
|
|
|
|
if stats:
|
|
|
|
|
all_stats["npu_usages"] = stats
|
2022-11-29 04:24:20 +03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def stats_snapshot(
|
2023-01-05 03:12:51 +03:00
|
|
|
config: FrigateConfig, stats_tracking: StatsTrackingTypes, hwaccel_errors: list[str]
|
2022-11-29 04:24:20 +03:00
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
"""Get a snapshot of the current stats that are being tracked."""
|
2021-02-17 16:23:32 +03:00
|
|
|
camera_metrics = stats_tracking["camera_metrics"]
|
2022-04-16 18:40:04 +03:00
|
|
|
stats: dict[str, Any] = {}
|
2021-01-04 02:35:58 +03:00
|
|
|
|
2025-08-12 19:49:53 +03:00
|
|
|
total_camera_fps = total_process_fps = total_skipped_fps = total_detection_fps = 0
|
2021-01-04 02:35:58 +03:00
|
|
|
|
2023-10-20 01:15:47 +03:00
|
|
|
stats["cameras"] = {}
|
2021-01-04 02:35:58 +03:00
|
|
|
for name, camera_stats in camera_metrics.items():
|
2026-03-04 19:07:34 +03:00
|
|
|
if name not in config.cameras:
|
|
|
|
|
continue
|
|
|
|
|
|
2025-08-12 19:49:53 +03:00
|
|
|
total_camera_fps += camera_stats.camera_fps.value
|
|
|
|
|
total_process_fps += camera_stats.process_fps.value
|
|
|
|
|
total_skipped_fps += camera_stats.skipped_fps.value
|
2024-09-27 15:53:23 +03:00
|
|
|
total_detection_fps += camera_stats.detection_fps.value
|
Use Fork-Server As Spawn Method (#18682)
* Set runtime
* Use count correctly
* Don't assume camera sizes
* Use separate zmq proxy for object detection
* Correct order
* Use forkserver
* Only store PID instead of entire process reference
* Cleanup
* Catch correct errors
* Fix typing
* Remove before_run from process util
The before_run never actually ran because:
You're right to suspect an issue with before_run not being called and a potential deadlock. The way you've implemented the run_wrapper using __getattribute__ for the run method of BaseProcess is a common pitfall in Python's multiprocessing, especially when combined with how multiprocessing.Process works internally.
Here's a breakdown of why before_run isn't being called and why you might be experiencing a deadlock:
The Problem: __getattribute__ and Process Serialization
When you create a multiprocessing.Process object and call start(), the multiprocessing module needs to serialize the process object (or at least enough of it to re-create the process in the new interpreter). It then pickles this serialized object and sends it to the newly spawned process.
The issue with your __getattribute__ implementation for run is that:
run is retrieved during serialization: When multiprocessing tries to pickle your Process object to send to the new process, it will likely access the run attribute. This triggers your __getattribute__ wrapper, which then tries to bind run_wrapper to self.
run_wrapper is bound to the parent process's self: The run_wrapper closure, when created in the parent process, captures the self (the Process instance) from the parent's memory space.
Deserialization creates a new object: In the child process, a new Process object is created by deserializing the pickled data. However, the run_wrapper method that was pickled still holds a reference to the self from the parent process. This is a subtle but critical distinction.
The child's run is not your wrapped run: When the child process starts, it internally calls its own run method. Because of the serialization and deserialization process, the run method that's ultimately executed in the child process is the original multiprocessing.Process.run or the Process.run if you had directly overridden it. Your __getattribute__ magic, which wraps run, isn't correctly applied to the Process object within the child's context.
* Cleanup
* Logging bugfix (#18465)
* use mp Manager to handle logging queues
A Python bug (https://github.com/python/cpython/issues/91555) was preventing logs from the embeddings maintainer process from printing. The bug is fixed in Python 3.14, but a viable workaround is to use the multiprocessing Manager, which better manages mp queues and causes the logging to work correctly.
* consolidate
* fix typing
* Fix typing
* Use global log queue
* Move to using process for logging
* Convert camera tracking to process
* Add more processes
* Finalize process
* Cleanup
* Cleanup typing
* Formatting
* Remove daemon
---------
Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2025-06-12 21:12:34 +03:00
|
|
|
pid = camera_stats.process_pid.value if camera_stats.process_pid.value else None
|
2024-09-27 15:53:23 +03:00
|
|
|
ffmpeg_pid = camera_stats.ffmpeg_pid.value if camera_stats.ffmpeg_pid else None
|
2024-09-17 18:41:46 +03:00
|
|
|
capture_pid = (
|
Use Fork-Server As Spawn Method (#18682)
* Set runtime
* Use count correctly
* Don't assume camera sizes
* Use separate zmq proxy for object detection
* Correct order
* Use forkserver
* Only store PID instead of entire process reference
* Cleanup
* Catch correct errors
* Fix typing
* Remove before_run from process util
The before_run never actually ran because:
You're right to suspect an issue with before_run not being called and a potential deadlock. The way you've implemented the run_wrapper using __getattribute__ for the run method of BaseProcess is a common pitfall in Python's multiprocessing, especially when combined with how multiprocessing.Process works internally.
Here's a breakdown of why before_run isn't being called and why you might be experiencing a deadlock:
The Problem: __getattribute__ and Process Serialization
When you create a multiprocessing.Process object and call start(), the multiprocessing module needs to serialize the process object (or at least enough of it to re-create the process in the new interpreter). It then pickles this serialized object and sends it to the newly spawned process.
The issue with your __getattribute__ implementation for run is that:
run is retrieved during serialization: When multiprocessing tries to pickle your Process object to send to the new process, it will likely access the run attribute. This triggers your __getattribute__ wrapper, which then tries to bind run_wrapper to self.
run_wrapper is bound to the parent process's self: The run_wrapper closure, when created in the parent process, captures the self (the Process instance) from the parent's memory space.
Deserialization creates a new object: In the child process, a new Process object is created by deserializing the pickled data. However, the run_wrapper method that was pickled still holds a reference to the self from the parent process. This is a subtle but critical distinction.
The child's run is not your wrapped run: When the child process starts, it internally calls its own run method. Because of the serialization and deserialization process, the run method that's ultimately executed in the child process is the original multiprocessing.Process.run or the Process.run if you had directly overridden it. Your __getattribute__ magic, which wraps run, isn't correctly applied to the Process object within the child's context.
* Cleanup
* Logging bugfix (#18465)
* use mp Manager to handle logging queues
A Python bug (https://github.com/python/cpython/issues/91555) was preventing logs from the embeddings maintainer process from printing. The bug is fixed in Python 3.14, but a viable workaround is to use the multiprocessing Manager, which better manages mp queues and causes the logging to work correctly.
* consolidate
* fix typing
* Fix typing
* Use global log queue
* Move to using process for logging
* Convert camera tracking to process
* Add more processes
* Finalize process
* Cleanup
* Cleanup typing
* Formatting
* Remove daemon
---------
Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
2025-06-12 21:12:34 +03:00
|
|
|
camera_stats.capture_process_pid.value
|
|
|
|
|
if camera_stats.capture_process_pid.value
|
|
|
|
|
else None
|
2022-04-16 18:40:04 +03:00
|
|
|
)
|
2025-12-16 00:02:03 +03:00
|
|
|
# Calculate connection quality based on current state
|
|
|
|
|
# This is computed at stats-collection time so offline cameras
|
|
|
|
|
# correctly show as unusable rather than excellent
|
|
|
|
|
expected_fps = config.cameras[name].detect.fps
|
|
|
|
|
current_fps = camera_stats.camera_fps.value
|
|
|
|
|
reconnects = camera_stats.reconnects_last_hour.value
|
|
|
|
|
stalls = camera_stats.stalls_last_hour.value
|
|
|
|
|
|
|
|
|
|
if current_fps < 0.1:
|
|
|
|
|
quality_str = "unusable"
|
|
|
|
|
elif reconnects == 0 and current_fps >= 0.9 * expected_fps and stalls < 5:
|
|
|
|
|
quality_str = "excellent"
|
|
|
|
|
elif reconnects <= 2 and current_fps >= 0.6 * expected_fps:
|
|
|
|
|
quality_str = "fair"
|
|
|
|
|
elif reconnects > 10 or current_fps < 1.0 or stalls > 100:
|
|
|
|
|
quality_str = "unusable"
|
|
|
|
|
else:
|
|
|
|
|
quality_str = "poor"
|
|
|
|
|
|
|
|
|
|
connection_quality = {
|
|
|
|
|
"connection_quality": quality_str,
|
|
|
|
|
"expected_fps": expected_fps,
|
|
|
|
|
"reconnects_last_hour": reconnects,
|
|
|
|
|
"stalls_last_hour": stalls,
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-20 01:15:47 +03:00
|
|
|
stats["cameras"][name] = {
|
2024-09-27 15:53:23 +03:00
|
|
|
"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),
|
|
|
|
|
"detection_fps": round(camera_stats.detection_fps.value, 2),
|
2024-02-19 16:26:59 +03:00
|
|
|
"detection_enabled": config.cameras[name].detect.enabled,
|
2022-04-16 18:40:04 +03:00
|
|
|
"pid": pid,
|
2024-09-17 18:41:46 +03:00
|
|
|
"capture_pid": capture_pid,
|
2022-11-13 21:48:14 +03:00
|
|
|
"ffmpeg_pid": ffmpeg_pid,
|
2024-09-27 15:53:23 +03:00
|
|
|
"audio_rms": round(camera_stats.audio_rms.value, 4),
|
|
|
|
|
"audio_dBFS": round(camera_stats.audio_dBFS.value, 4),
|
2025-12-16 00:02:03 +03:00
|
|
|
**connection_quality,
|
2021-01-04 02:35:58 +03:00
|
|
|
}
|
|
|
|
|
|
2025-12-22 18:25:38 +03:00
|
|
|
stats["detectors"] = get_detector_stats(stats_tracking)
|
2025-08-12 19:49:53 +03:00
|
|
|
stats["camera_fps"] = round(total_camera_fps, 2)
|
|
|
|
|
stats["process_fps"] = round(total_process_fps, 2)
|
|
|
|
|
stats["skipped_fps"] = round(total_skipped_fps, 2)
|
2021-02-17 16:23:32 +03:00
|
|
|
stats["detection_fps"] = round(total_detection_fps, 2)
|
2021-01-04 02:35:58 +03:00
|
|
|
|
2025-02-28 21:43:08 +03:00
|
|
|
stats["embeddings"] = {}
|
|
|
|
|
|
|
|
|
|
# Get metrics if available
|
|
|
|
|
embeddings_metrics = stats_tracking.get("embeddings_metrics")
|
|
|
|
|
|
|
|
|
|
if embeddings_metrics:
|
|
|
|
|
# Add metrics based on what's enabled
|
|
|
|
|
if config.semantic_search.enabled:
|
|
|
|
|
stats["embeddings"].update(
|
|
|
|
|
{
|
|
|
|
|
"image_embedding_speed": round(
|
2025-03-29 02:13:35 +03:00
|
|
|
embeddings_metrics.image_embeddings_speed.value * 1000, 2
|
|
|
|
|
),
|
|
|
|
|
"image_embedding": round(
|
|
|
|
|
embeddings_metrics.image_embeddings_eps.value, 2
|
2025-02-28 21:43:08 +03:00
|
|
|
),
|
|
|
|
|
"text_embedding_speed": round(
|
2025-03-29 02:13:35 +03:00
|
|
|
embeddings_metrics.text_embeddings_speed.value * 1000, 2
|
|
|
|
|
),
|
|
|
|
|
"text_embedding": round(
|
|
|
|
|
embeddings_metrics.text_embeddings_eps.value, 2
|
2025-02-28 21:43:08 +03:00
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
)
|
2025-01-05 17:47:57 +03:00
|
|
|
|
|
|
|
|
if config.face_recognition.enabled:
|
|
|
|
|
stats["embeddings"]["face_recognition_speed"] = round(
|
2025-03-29 02:13:35 +03:00
|
|
|
embeddings_metrics.face_rec_speed.value * 1000, 2
|
|
|
|
|
)
|
|
|
|
|
stats["embeddings"]["face_recognition"] = round(
|
|
|
|
|
embeddings_metrics.face_rec_fps.value, 2
|
2025-01-05 17:47:57 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if config.lpr.enabled:
|
|
|
|
|
stats["embeddings"]["plate_recognition_speed"] = round(
|
2025-03-29 02:13:35 +03:00
|
|
|
embeddings_metrics.alpr_speed.value * 1000, 2
|
|
|
|
|
)
|
|
|
|
|
stats["embeddings"]["plate_recognition"] = round(
|
|
|
|
|
embeddings_metrics.alpr_pps.value, 2
|
2025-01-05 17:47:57 +03:00
|
|
|
)
|
2025-02-28 21:43:08 +03:00
|
|
|
|
2025-03-29 02:13:35 +03:00
|
|
|
if embeddings_metrics.yolov9_lpr_pps.value > 0.0:
|
2025-02-26 17:29:34 +03:00
|
|
|
stats["embeddings"]["yolov9_plate_detection_speed"] = round(
|
2025-03-29 02:13:35 +03:00
|
|
|
embeddings_metrics.yolov9_lpr_speed.value * 1000, 2
|
|
|
|
|
)
|
|
|
|
|
stats["embeddings"]["yolov9_plate_detection"] = round(
|
|
|
|
|
embeddings_metrics.yolov9_lpr_pps.value, 2
|
2025-02-26 17:29:34 +03:00
|
|
|
)
|
2025-01-05 17:47:57 +03:00
|
|
|
|
2025-08-10 19:24:08 +03:00
|
|
|
if embeddings_metrics.review_desc_speed.value > 0.0:
|
2025-08-10 14:57:54 +03:00
|
|
|
stats["embeddings"]["review_description_speed"] = round(
|
|
|
|
|
embeddings_metrics.review_desc_speed.value * 1000, 2
|
|
|
|
|
)
|
2025-11-21 02:50:17 +03:00
|
|
|
stats["embeddings"]["review_description_events_per_second"] = round(
|
2025-08-10 14:57:54 +03:00
|
|
|
embeddings_metrics.review_desc_dps.value, 2
|
|
|
|
|
)
|
|
|
|
|
|
2025-10-02 21:48:11 +03:00
|
|
|
if embeddings_metrics.object_desc_speed.value > 0.0:
|
|
|
|
|
stats["embeddings"]["object_description_speed"] = round(
|
|
|
|
|
embeddings_metrics.object_desc_speed.value * 1000, 2
|
|
|
|
|
)
|
2025-11-21 02:50:17 +03:00
|
|
|
stats["embeddings"]["object_description_events_per_second"] = round(
|
2025-10-02 21:48:11 +03:00
|
|
|
embeddings_metrics.object_desc_dps.value, 2
|
|
|
|
|
)
|
|
|
|
|
|
2025-06-06 19:29:44 +03:00
|
|
|
for key in embeddings_metrics.classification_speeds.keys():
|
|
|
|
|
stats["embeddings"][f"{key}_classification_speed"] = round(
|
|
|
|
|
embeddings_metrics.classification_speeds[key].value * 1000, 2
|
|
|
|
|
)
|
2025-11-21 02:50:17 +03:00
|
|
|
stats["embeddings"][f"{key}_classification_events_per_second"] = round(
|
2025-06-06 19:29:44 +03:00
|
|
|
embeddings_metrics.classification_cps[key].value, 2
|
|
|
|
|
)
|
|
|
|
|
|
2023-01-05 03:12:51 +03:00
|
|
|
get_processing_stats(config, stats, hwaccel_errors)
|
2022-11-13 21:48:14 +03:00
|
|
|
|
2021-02-17 16:23:32 +03:00
|
|
|
stats["service"] = {
|
|
|
|
|
"uptime": (int(time.time()) - stats_tracking["started"]),
|
|
|
|
|
"version": VERSION,
|
2022-04-11 15:10:19 +03:00
|
|
|
"latest_version": stats_tracking["latest_frigate_version"],
|
2021-02-17 16:23:32 +03:00
|
|
|
"storage": {},
|
2023-01-27 15:20:41 +03:00
|
|
|
"last_updated": int(time.time()),
|
2021-01-04 02:35:58 +03:00
|
|
|
}
|
|
|
|
|
|
2025-08-22 22:48:27 +03:00
|
|
|
for path in [RECORD_DIR, CLIPS_DIR, CACHE_DIR]:
|
2023-01-13 16:22:47 +03:00
|
|
|
try:
|
|
|
|
|
storage_stats = shutil.disk_usage(path)
|
2024-12-19 02:45:08 +03:00
|
|
|
except (FileNotFoundError, OSError):
|
2023-01-13 16:22:47 +03:00
|
|
|
stats["service"]["storage"][path] = {}
|
2023-10-22 21:35:19 +03:00
|
|
|
continue
|
2023-01-13 16:22:47 +03:00
|
|
|
|
2021-02-17 16:23:32 +03:00
|
|
|
stats["service"]["storage"][path] = {
|
2023-06-11 22:49:13 +03:00
|
|
|
"total": round(storage_stats.total / pow(2, 20), 1),
|
|
|
|
|
"used": round(storage_stats.used / pow(2, 20), 1),
|
|
|
|
|
"free": round(storage_stats.free / pow(2, 20), 1),
|
2021-02-17 16:23:32 +03:00
|
|
|
"mount_type": get_fs_type(path),
|
2021-02-03 15:36:13 +03:00
|
|
|
}
|
|
|
|
|
|
2025-08-22 22:48:27 +03:00
|
|
|
stats["service"]["storage"]["/dev/shm"] = calculate_shm_requirements(config)
|
|
|
|
|
|
2023-05-05 01:58:59 +03:00
|
|
|
stats["processes"] = {}
|
|
|
|
|
for name, pid in stats_tracking["processes"].items():
|
|
|
|
|
stats["processes"][name] = {
|
|
|
|
|
"pid": pid,
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-29 20:58:47 +03:00
|
|
|
# Embed cpu/mem stats into detectors, cameras, and processes
|
|
|
|
|
# so history consumers don't need the full cpu_usages dict
|
|
|
|
|
cpu_usages = stats.get("cpu_usages", {})
|
|
|
|
|
|
|
|
|
|
for det_stats in stats["detectors"].values():
|
|
|
|
|
pid_str = str(det_stats.get("pid", ""))
|
|
|
|
|
usage = cpu_usages.get(pid_str, {})
|
|
|
|
|
det_stats["cpu"] = usage.get("cpu")
|
|
|
|
|
det_stats["mem"] = usage.get("mem")
|
|
|
|
|
|
|
|
|
|
for cam_stats in stats["cameras"].values():
|
|
|
|
|
for pid_key, field in [
|
|
|
|
|
("ffmpeg_pid", "ffmpeg_cpu"),
|
|
|
|
|
("capture_pid", "capture_cpu"),
|
|
|
|
|
("pid", "detect_cpu"),
|
|
|
|
|
]:
|
|
|
|
|
pid_str = str(cam_stats.get(pid_key, ""))
|
|
|
|
|
usage = cpu_usages.get(pid_str, {})
|
|
|
|
|
cam_stats[field] = usage.get("cpu")
|
|
|
|
|
|
|
|
|
|
for proc_stats in stats["processes"].values():
|
|
|
|
|
pid_str = str(proc_stats.get("pid", ""))
|
|
|
|
|
usage = cpu_usages.get(pid_str, {})
|
|
|
|
|
proc_stats["cpu"] = usage.get("cpu")
|
|
|
|
|
proc_stats["mem"] = usage.get("mem")
|
|
|
|
|
|
2021-01-04 02:35:58 +03:00
|
|
|
return stats
|