Files
WebAisMap/state.py
T
Grigo 03075f1ef1 Initial import: WebAisMap
Closes TG-4

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-04 07:56:45 +03:00

50 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import threading
# Все структуры AIS-данных (vessels/base_stations/buoys/stats/slots/...) вынесены в
# централизованный процесс ais_hub (localhost:8081). Здесь остаётся только функция
# измерения загрузки CPU для эндпоинта /api/sysinfo — ais_hub системные метрики не отдаёт.
_cpu_prev_jiffies = None
_cpu_jiffy_lock = threading.Lock()
def _read_cpu_aggregated_jiffies():
"""Суммарные jiffies по всем ядрам: первая строка cpu в /proc/stat."""
with open("/proc/stat", "r") as f:
line = f.readline()
parts = line.split()
if not parts or parts[0] != "cpu":
return None
nums = [int(x) for x in parts[1:]]
idle = nums[3] + nums[4] # idle + iowait
total = sum(nums)
return total, idle
def get_cpu_usage_percent():
"""
Загрузка CPU в % (0100), как в htop: разница двух замеров /proc/stat.
Первый запрос после старта может вернуть None — ещё нет предыдущего замера.
"""
global _cpu_prev_jiffies
try:
cur = _read_cpu_aggregated_jiffies()
if cur is None:
return None
total, idle = cur
with _cpu_jiffy_lock:
prev = _cpu_prev_jiffies
_cpu_prev_jiffies = (total, idle)
if prev is None:
return None
p_total, p_idle = prev
dt = total - p_total
di = idle - p_idle
if dt <= 0:
return None
busy = dt - di
pct = max(0.0, min(100.0, 100.0 * busy / dt))
return round(pct, 1)
except Exception:
return None