From da5e800e6c524dc001648d8dd52e3d81670a78ba Mon Sep 17 00:00:00 2001 From: Nick Mowen Date: Wed, 9 Nov 2022 13:43:00 -0700 Subject: [PATCH] Add support for cpu usage stats --- frigate/stats.py | 3 +++ frigate/util.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/frigate/stats.py b/frigate/stats.py index 36a467574..99f37aea2 100644 --- a/frigate/stats.py +++ b/frigate/stats.py @@ -14,6 +14,7 @@ from frigate.config import FrigateConfig from frigate.const import RECORD_DIR, CLIPS_DIR, CACHE_DIR from frigate.types import StatsTrackingTypes, CameraMetricsTypes from frigate.version import VERSION +from frigate.util import get_cpu_stats from frigate.object_detection import ObjectDetectProcess logger = logging.getLogger(__name__) @@ -116,6 +117,8 @@ def stats_snapshot(stats_tracking: StatsTrackingTypes) -> dict[str, Any]: } stats["detection_fps"] = round(total_detection_fps, 2) + stats["cpu_usages"] = get_cpu_stats() + stats["service"] = { "uptime": (int(time.time()) - stats_tracking["started"]), "version": VERSION, diff --git a/frigate/util.py b/frigate/util.py index 8b3703891..6d14010b4 100755 --- a/frigate/util.py +++ b/frigate/util.py @@ -1,6 +1,8 @@ import copy import datetime import logging +import subprocess as sp +import json import re import signal import traceback @@ -679,6 +681,36 @@ def escape_special_characters(path: str) -> str: return path +def get_cpu_stats() -> dict[str, dict]: + """Get cpu usages for each process id""" + usages = {} + top_command = ["top", "-b", "-n", "1"] + + p = sp.run( + top_command, + encoding="ascii", + capture_output=True, + ) + + if p.returncode != 0: + logger.error(p.stderr) + return usages + else: + lines = p.stdout.split("\n") + + for line in lines: + stats = list(filter(lambda a: a != "", line.strip().split(" "))) + try: + usages[stats[0]] = { + "cpu": stats[8], + "mem": stats[9], + } + except: + continue + + return usages + + class FrameManager(ABC): @abstractmethod def create(self, name, size) -> AnyStr: