Refactor some stats function to properly handle zero values

This commit is contained in:
Sergey Krashevich 2023-06-14 18:55:40 +03:00
parent ff1b5c87aa
commit 6690183a23
No known key found for this signature in database
GPG Key ID: 625171324E7D3856

View File

@ -742,11 +742,12 @@ def clean_camera_user_pass(line: str) -> str:
def escape_special_characters(path: str) -> str:
"""Cleans reserved characters to encodings for ffmpeg."""
try:
found = re.search(REGEX_RTSP_CAMERA_USER_PASS, path).group(0)[3:-1]
match = re.search(REGEX_RTSP_CAMERA_USER_PASS, path)
if match:
found = match.group(0)[3:-1]
pw = found[(found.index(":") + 1) :]
return path.replace(pw, urllib.parse.quote_plus(pw))
except AttributeError:
else:
# path does not have user:pass
return path
@ -833,16 +834,25 @@ def get_cpu_stats() -> dict[str, dict]:
process_elapsed_sec = system_uptime_sec - process_starttime_sec
process_usage_sec = process_utime_sec + process_stime_sec
cpu_average_usage = process_usage_sec * 100 // process_elapsed_sec
cpu_average_usage = (
process_usage_sec * 100 // process_elapsed_sec
if process_elapsed_sec
else 0
)
with open(f"/proc/{pid}/statm", "r") as f:
mem_stats = f.readline().split()
if os.sysconf("SC_PAGE_SIZE"):
mem_res = int(mem_stats[1]) * os.sysconf("SC_PAGE_SIZE") / 1024
if docker_memlimit > 0:
mem_pct = round((mem_res / docker_memlimit) * 100, 1)
else:
mem_res = int(mem_stats[1])
if docker_memlimit:
mem_pct = round((mem_res / docker_memlimit) * 100, 1)
elif total_mem:
mem_pct = round((mem_res / total_mem) * 100, 1)
else:
mem_pct = 0
usages[pid] = {
"cpu": str(cpu_percent),
@ -850,8 +860,8 @@ def get_cpu_stats() -> dict[str, dict]:
"mem": f"{mem_pct}",
"cmdline": " ".join(cmdline),
}
except Exception:
continue
except Exception as e:
logger.debug(f"Unable to calculate cpu_stats: {e}")
return usages
@ -1008,7 +1018,7 @@ def get_nvidia_gpu_stats() -> dict[int, dict]:
else:
gpu_util = 0
if meminfo != "N/A":
if meminfo != "N/A" and meminfo.total:
gpu_mem_util = meminfo.used / meminfo.total * 100
else:
gpu_mem_util = -1