Add live VPS CPU, memory and disk widgets
This commit is contained in:
1 parent
b854d3a001
commit
4c525b8f77
5 files changed
+558
No files matched your search
@@ -0,0 +1,51 @@
|
|||||||
|
# Виджеты ресурсов VPS (v111)
|
||||||
|
|
||||||
|
Три карточки ЦП, ОЗУ и ДИСК находятся над кнопками «Рестарт Xray VPS»,
|
||||||
|
профилем и выходом. На ПК ширина и высота совпадают с кнопками под ними.
|
||||||
|
На мобильном карточки видны над кнопкой открытия меню хаба.
|
||||||
|
|
||||||
|
Панель запрашивает `/api/vps/resources` сразу и каждые 3 секунды.
|
||||||
|
ЦП — общая загрузка процессоров по разнице счётчиков `/proc/stat`.
|
||||||
|
ОЗУ — занятая память, рассчитанная как `MemTotal - MemAvailable`.
|
||||||
|
ДИСК — занятое место файловой системы `/`. В подсказках указаны число
|
||||||
|
vCPU и объёмы занятой/общей памяти и диска.
|
||||||
|
|
||||||
|
Доступ требует входа в Hub. Показания общие для всех вкладок и кешируются
|
||||||
|
на 3 секунды. Сбор не открывает SQLite и не запускает внешние команды.
|
||||||
|
Опрос приостанавливается в скрытой вкладке; после возвращения возобновляется.
|
||||||
|
При ошибке связи вместо устаревших чисел показывается «—».
|
||||||
|
|
||||||
|
## Установка и откат с Windows 11
|
||||||
|
|
||||||
|
В PowerShell, из любого каталога:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-vps-widgets.ps1" -Vps "root@193.233.82.38" -Action Install
|
||||||
|
```
|
||||||
|
|
||||||
|
После `VPS_WIDGETS_V111_Install_OK` обновите страницу через Ctrl+F5.
|
||||||
|
Скрипт загружает локальный файл, проверяет его до замены, перезапускает
|
||||||
|
службу и проверяет health. При ошибке после замены восстанавливает файл
|
||||||
|
перед текущей попыткой. База данных и настройки не заменяются.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-vps-widgets.ps1" -Vps "root@193.233.82.38" -Action Rollback
|
||||||
|
```
|
||||||
|
|
||||||
|
Откат использует неизменяемую копию первого состояния до установки:
|
||||||
|
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v111`.
|
||||||
|
Успешное завершение: `VPS_WIDGETS_V111_Rollback_OK`.
|
||||||
|
|
||||||
|
## Локальные проверки
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python tests/test_vps_resources.py -v
|
||||||
|
python tests/test_vps_resources.py --export-preview .test-output/vps-widgets
|
||||||
|
node --check .test-output/vps-widgets/dashboard.js
|
||||||
|
node tests/test_vps_resources_ui.cjs .test-output/vps-widgets/dashboard.js
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверяются вычисления, совместный кеш при одновременных запросах,
|
||||||
|
ошибки чтения, авторизация HTTP и отсутствие доступа к SQLite.
|
||||||
|
JS-проверки охватывают обновление обеих версий панели, отсутствие
|
||||||
|
параллельных запросов, таймауты, восстановление связи и скрытие вкладки.
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""VPS metrics, shared sampling and authenticated HTTP regression checks."""
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
SOURCE = Path(os.environ.get("OWRT_VPS_WIDGETS_HUB_SOURCE", Path(__file__).resolve().parents[1] / "vps/owrt-remote-hub.py"))
|
||||||
|
STATE = tempfile.TemporaryDirectory(prefix="owrt-vps-widgets-")
|
||||||
|
spec = importlib.util.spec_from_file_location("vps_widgets_hub", SOURCE)
|
||||||
|
hub = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[spec.name] = hub
|
||||||
|
with mock.patch.dict(os.environ, {"OWRT_REMOTE_STATE_DIR": STATE.name}):
|
||||||
|
spec.loader.exec_module(hub)
|
||||||
|
|
||||||
|
|
||||||
|
class ResourceSampleTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory(dir=STATE.name)
|
||||||
|
self.addCleanup(self.tmp.cleanup)
|
||||||
|
self.proc = Path(self.tmp.name)
|
||||||
|
self.proc.joinpath("stat").write_text("cpu 100 20 30 500 50 10 10 10 40 20\n")
|
||||||
|
self.proc.joinpath("meminfo").write_text("MemTotal: 1000 kB\nMemAvailable: 600 kB\nMemFree: 100 kB\nCached: 500 kB\n")
|
||||||
|
self.monitor = hub.VpsResourceMonitor(self.proc)
|
||||||
|
|
||||||
|
def test_cpu_uses_interval_delta_without_double_counting_guest_ticks(self):
|
||||||
|
# 100 total ticks, 70 idle+iowait ticks; guest counters are duplicated.
|
||||||
|
self.proc.joinpath("stat").write_text("cpu 110 20 40 550 70 15 15 10 45 20\n")
|
||||||
|
self.assertEqual(self.monitor.cpu_usage()["percent"], 30.0)
|
||||||
|
self.assertIsNone(self.monitor.cpu_usage()["percent"], "zero interval must not invent a CPU reading")
|
||||||
|
self.proc.joinpath("stat").write_text("cpu 1 0 0 1\n")
|
||||||
|
self.assertIsNone(self.monitor.cpu_usage()["percent"], "reset counters must not give negative load")
|
||||||
|
|
||||||
|
def test_memory_counts_available_cache_as_available_ram(self):
|
||||||
|
memory = self.monitor.memory_usage()
|
||||||
|
self.assertEqual(memory["percent"], 40.0)
|
||||||
|
self.assertEqual(memory["used_bytes"], 400 * 1024)
|
||||||
|
self.assertEqual(memory["available_bytes"], 600 * 1024)
|
||||||
|
|
||||||
|
def test_memory_fallback_and_bounds(self):
|
||||||
|
self.proc.joinpath("meminfo").write_text("MemTotal: 1000 kB\nMemFree: 100 kB\nBuffers: 50 kB\nCached: 200 kB\nSReclaimable: 100 kB\nShmem: 50 kB\n")
|
||||||
|
self.assertEqual(self.monitor.memory_usage()["percent"], 60.0)
|
||||||
|
self.proc.joinpath("meminfo").write_text("MemTotal: 1000 kB\nMemAvailable: 2000 kB\n")
|
||||||
|
self.assertEqual(self.monitor.memory_usage()["percent"], 0.0)
|
||||||
|
|
||||||
|
def test_disk_reports_root_filesystem_used_free_and_total(self):
|
||||||
|
with mock.patch.object(hub.shutil, "disk_usage", return_value=SimpleNamespace(total=1000, used=250, free=750)) as disk:
|
||||||
|
metric = self.monitor.disk_usage()
|
||||||
|
disk.assert_called_once_with("/")
|
||||||
|
self.assertEqual(metric, {"percent": 25.0, "used_bytes": 250, "total_bytes": 1000, "free_bytes": 750, "path": "/"})
|
||||||
|
|
||||||
|
def test_shared_cache_samples_once_for_concurrent_viewers_then_refreshes(self):
|
||||||
|
with mock.patch.object(hub.time, "monotonic", return_value=10) as clock, mock.patch.object(self.monitor, "cpu_usage", return_value={"percent": 30, "cores": 2}) as cpu:
|
||||||
|
results = []
|
||||||
|
threads = [threading.Thread(target=lambda: results.append(self.monitor.snapshot())) for _ in range(8)]
|
||||||
|
for thread in threads: thread.start()
|
||||||
|
for thread in threads: thread.join(timeout=5)
|
||||||
|
self.assertEqual(len(results), 8)
|
||||||
|
self.assertEqual(cpu.call_count, 1)
|
||||||
|
clock.return_value = 12.99
|
||||||
|
self.monitor.snapshot()
|
||||||
|
self.assertEqual(cpu.call_count, 1)
|
||||||
|
clock.return_value = 13
|
||||||
|
self.monitor.snapshot()
|
||||||
|
self.assertEqual(cpu.call_count, 2)
|
||||||
|
|
||||||
|
def test_unavailable_proc_files_do_not_break_disk_or_response(self):
|
||||||
|
self.proc.joinpath("stat").write_text("invalid stat\n")
|
||||||
|
self.proc.joinpath("meminfo").write_text("MemTotal: invalid\n")
|
||||||
|
with mock.patch.object(hub.shutil, "disk_usage", return_value=SimpleNamespace(total=1000, used=250, free=750)):
|
||||||
|
result = self.monitor.snapshot()
|
||||||
|
self.assertIsNone(result["cpu"]["percent"])
|
||||||
|
self.assertIsNone(result["memory"])
|
||||||
|
self.assertEqual(result["disk"]["percent"], 25)
|
||||||
|
with mock.patch.object(hub.shutil, "disk_usage", side_effect=OSError("unavailable")):
|
||||||
|
self.assertIsNone(self.monitor.disk_usage())
|
||||||
|
|
||||||
|
|
||||||
|
class QuietHandler(hub.Handler):
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ResourceHttpTests(unittest.TestCase):
|
||||||
|
def test_metrics_require_hub_login_and_never_open_router_database(self):
|
||||||
|
app = hub.App(Path(STATE.name) / "unused.db", "test-session", "test-agent", "")
|
||||||
|
server = hub.HubHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||||
|
server.app = app
|
||||||
|
server.is_tls = False
|
||||||
|
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
url = f"http://127.0.0.1:{server.server_port}/api/vps/resources"
|
||||||
|
try:
|
||||||
|
with mock.patch.object(app, "conn", side_effect=AssertionError("metrics must not access SQLite")):
|
||||||
|
for headers in ({}, {"Authorization": "Bearer test-agent"}):
|
||||||
|
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||||
|
urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=5)
|
||||||
|
with error.exception as response:
|
||||||
|
self.assertEqual(response.code, 401)
|
||||||
|
self.assertFalse(json.load(response)["ok"])
|
||||||
|
request = urllib.request.Request(url, headers={"Cookie": "owrt_remote_session=test-session"})
|
||||||
|
with urllib.request.urlopen(request, timeout=5) as response:
|
||||||
|
self.assertEqual(response.headers["Cache-Control"], "no-store")
|
||||||
|
data = json.load(response)
|
||||||
|
self.assertTrue(data["ok"])
|
||||||
|
self.assertEqual(set(data), {"ok", "cpu", "memory", "disk", "sampled_at"})
|
||||||
|
self.assertGreater(data["disk"]["total_bytes"], 0)
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
thread.join(timeout=5)
|
||||||
|
|
||||||
|
|
||||||
|
def export_preview(output):
|
||||||
|
output.mkdir(parents=True, exist_ok=True)
|
||||||
|
with mock.patch.object(hub, "web_push_backend_status", return_value={"ready": False}):
|
||||||
|
page = hub.dashboard_html([], "root", auth_bootstrap={"is_owner": True, "can_add_router": True})
|
||||||
|
output.joinpath("dashboard.html").write_text(page, encoding="utf-8")
|
||||||
|
output.joinpath("dashboard.js").write_text("\n".join(re.findall(r"<script>(.*?)</script>", page, re.S)), encoding="utf-8")
|
||||||
|
print(f"Exported preview: {output}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
|
||||||
|
export_preview(Path(sys.argv[2]))
|
||||||
|
else:
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// node tests/test_vps_resources_ui.cjs <exported-dashboard.js>
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const source = fs.readFileSync(process.argv[2], 'utf8').replace(/\r\n/g, '\n');
|
||||||
|
const begin = source.indexOf('function initVpsResourceWidgets() {');
|
||||||
|
const end = source.indexOf('\nsetInterval(loadRouters, 5000);', begin);
|
||||||
|
assert(begin >= 0 && end > begin);
|
||||||
|
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); };
|
||||||
|
|
||||||
|
function fixture() {
|
||||||
|
const timers = new Map(), documentEvents = {}, windowEvents = {}, calls = [];
|
||||||
|
let nextId = 1;
|
||||||
|
const widgets = ['cpu', 'memory', 'disk', 'cpu', 'memory', 'disk'].map(key => ({
|
||||||
|
dataset: {vpsResource: key}, label: {textContent: {cpu: 'ЦП', memory: 'ОЗУ', disk: 'ДИСК'}[key]},
|
||||||
|
value: {textContent: '—'}, title: '',
|
||||||
|
querySelector(selector) { return selector === 'span' ? this.label : this.value; },
|
||||||
|
setAttribute(key, value) { this[key] = value; },
|
||||||
|
}));
|
||||||
|
const metrics = {ok: true, cpu: {percent: 25, cores: 2}, memory: {percent: 40, used_bytes: 1024, total_bytes: 2048}, disk: {percent: 60, used_bytes: 2048, total_bytes: 4096}};
|
||||||
|
const context = {
|
||||||
|
Intl, AbortController,
|
||||||
|
document: {hidden: false, querySelectorAll() { return widgets; }, addEventListener(key, fn) { documentEvents[key] = fn; }},
|
||||||
|
window: {addEventListener(key, fn) { windowEvents[key] = fn; }},
|
||||||
|
setInterval(fn, ms) { const id = nextId++; timers.set(id, {fn, ms, interval: true}); return id; },
|
||||||
|
setTimeout(fn, ms) { const id = nextId++; timers.set(id, {fn, ms}); return id; },
|
||||||
|
clearInterval(id) { timers.delete(id); }, clearTimeout(id) { timers.delete(id); },
|
||||||
|
fetch(url, options) { calls.push({url, options}); return context.respond(url, options); },
|
||||||
|
respond: async () => ({ok: true, status: 200, json: async () => metrics}),
|
||||||
|
};
|
||||||
|
vm.createContext(context);
|
||||||
|
vm.runInContext(source.slice(begin, end), context);
|
||||||
|
return {context, timers, calls, widgets, documentEvents, windowEvents,
|
||||||
|
tick() { const timer = [...timers.values()].find(t => t.interval); assert(timer); return timer.fn(); },
|
||||||
|
intervals() { return [...timers.values()].filter(t => t.interval); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const f = fixture();
|
||||||
|
await flush();
|
||||||
|
assert.equal(f.calls.length, 1, 'first update starts immediately');
|
||||||
|
assert.equal(f.intervals().length, 1);
|
||||||
|
assert.equal(f.intervals()[0].ms, 3000);
|
||||||
|
assert.equal(f.calls[0].url, '/api/vps/resources');
|
||||||
|
assert.equal(f.calls[0].options.cache, 'no-store');
|
||||||
|
assert.equal(f.widgets[0].value.textContent, '25%');
|
||||||
|
assert.equal(f.widgets[3].value.textContent, '25%');
|
||||||
|
assert(f.widgets[1].title.includes('1 КиБ из 2 КиБ'));
|
||||||
|
assert(f.widgets[2].title.includes('раздел /'));
|
||||||
|
|
||||||
|
let finish;
|
||||||
|
f.context.respond = () => new Promise(resolve => { finish = resolve; });
|
||||||
|
f.tick(); f.tick();
|
||||||
|
assert.equal(f.calls.length, 2, 'slow requests must not overlap');
|
||||||
|
finish({ok: true, status: 200, json: async () => ({ok: true, cpu: {percent: 50, cores: 2}, memory: null, disk: null})});
|
||||||
|
await flush();
|
||||||
|
assert.equal(f.widgets[0].value.textContent, '50%');
|
||||||
|
assert.equal(f.widgets[1].value.textContent, '—');
|
||||||
|
|
||||||
|
f.context.respond = async () => { throw new Error('offline'); };
|
||||||
|
f.tick(); await flush();
|
||||||
|
assert.equal(f.widgets[0].value.textContent, '—', 'failed fetch must not pretend old numbers are live');
|
||||||
|
assert.equal(f.widgets[0].dataset.stale, 'true');
|
||||||
|
f.context.respond = async () => ({ok: true, status: 200, json: async () => ({ok: true, cpu: {percent: 0, cores: 1}})});
|
||||||
|
f.tick(); await flush();
|
||||||
|
assert.equal(f.widgets[0].value.textContent, '0%');
|
||||||
|
assert.equal(f.widgets[0].dataset.stale, 'false');
|
||||||
|
|
||||||
|
f.context.document.hidden = true;
|
||||||
|
f.documentEvents.visibilitychange();
|
||||||
|
assert.equal(f.intervals().length, 0);
|
||||||
|
f.context.document.hidden = false;
|
||||||
|
f.documentEvents.visibilitychange(); await flush();
|
||||||
|
assert.equal(f.intervals().length, 1);
|
||||||
|
f.windowEvents.pagehide();
|
||||||
|
assert.equal(f.intervals().length, 0);
|
||||||
|
f.windowEvents.pageshow(); await flush();
|
||||||
|
assert.equal(f.intervals().length, 1, 'BFCache restore must resume once');
|
||||||
|
|
||||||
|
f.context.respond = async () => ({ok: false, status: 401});
|
||||||
|
f.tick(); await flush();
|
||||||
|
assert.equal(f.intervals().length, 0, 'expired sessions stop polling');
|
||||||
|
const count = f.calls.length;
|
||||||
|
f.documentEvents.visibilitychange(); await flush();
|
||||||
|
assert.equal(f.calls.length, count);
|
||||||
|
|
||||||
|
const g = fixture(); await flush();
|
||||||
|
g.context.respond = (url, options) => new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('timeout'))));
|
||||||
|
g.tick();
|
||||||
|
const timeout = [...g.timers.values()].find(timer => !timer.interval);
|
||||||
|
assert.equal(timeout.ms, 2500);
|
||||||
|
timeout.fn(); await flush();
|
||||||
|
assert(g.calls.at(-1).options.signal.aborted);
|
||||||
|
assert.equal(g.widgets[0].dataset.stale, 'true');
|
||||||
|
g.windowEvents.pagehide();
|
||||||
|
console.log('VPS_WIDGETS_UI_OK: immediate/3s updates, no overlaps, desktop/mobile, errors, timeout, pause/resume and session expiry');
|
||||||
|
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
|
||||||
|
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
|
||||||
|
[switch]$PrepareOnly
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$RepoRoot = Split-Path -Parent $PSScriptRoot
|
||||||
|
$UploadName = 'owrt-vps-widgets-' + [guid]::NewGuid().ToString('N')
|
||||||
|
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
|
||||||
|
$Utf8 = [System.Text.UTF8Encoding]::new($false)
|
||||||
|
$RemoteScript = @'
|
||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
stage=/tmp/__UPLOAD_NAME__
|
||||||
|
target=/opt/owrt-remote/owrt-remote-hub.py
|
||||||
|
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-vps-widgets-v111
|
||||||
|
candidate=$target.new-__UPLOAD_NAME__
|
||||||
|
changed=0
|
||||||
|
cleanup() {
|
||||||
|
code=$?
|
||||||
|
trap - EXIT
|
||||||
|
if [ "$code" -ne 0 ] && [ "$changed" = 1 ]; then
|
||||||
|
echo 'Operation failed; restoring the file from this attempt.' >&2
|
||||||
|
journalctl -u owrt-remote -n 30 --no-pager >&2 || true
|
||||||
|
cp -p "$stage/previous.py" "$candidate"
|
||||||
|
mv -f "$candidate" "$target"
|
||||||
|
systemctl restart owrt-remote || true
|
||||||
|
fi
|
||||||
|
rm -f "$candidate"
|
||||||
|
rm -rf "$stage"
|
||||||
|
exit "$code"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
test -s "$target"
|
||||||
|
python_bin=/opt/owrt-remote/venv/bin/python
|
||||||
|
[ -x "$python_bin" ] || python_bin=python3
|
||||||
|
if [ '__ACTION__' = Install ]; then
|
||||||
|
test -s "$stage/hub.py"
|
||||||
|
"$python_bin" -m py_compile "$stage/hub.py"
|
||||||
|
OWRT_VPS_WIDGETS_HUB_SOURCE="$stage/hub.py" "$python_bin" "$stage/tests.py" -v
|
||||||
|
if [ ! -e "$backup" ]; then cp -p "$target" "$backup"; fi
|
||||||
|
test -s "$backup"
|
||||||
|
source_file="$stage/hub.py"
|
||||||
|
else
|
||||||
|
test -s "$backup"
|
||||||
|
"$python_bin" -m py_compile "$backup"
|
||||||
|
source_file="$backup"
|
||||||
|
fi
|
||||||
|
printf 'Backup: %s\n' "$backup"
|
||||||
|
cp -p "$target" "$stage/previous.py"
|
||||||
|
cp "$source_file" "$candidate"
|
||||||
|
chmod 755 "$candidate"
|
||||||
|
changed=1
|
||||||
|
mv -f "$candidate" "$target"
|
||||||
|
systemctl restart owrt-remote
|
||||||
|
healthy=0
|
||||||
|
for attempt in 1 2 3 4 5 6 7 8 9 10; do
|
||||||
|
if systemctl is-active --quiet owrt-remote && curl -fsS --max-time 5 http://127.0.0.1:8088/health; then healthy=1; break; fi
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
test "$healthy" = 1
|
||||||
|
cmp "$source_file" "$target"
|
||||||
|
if [ '__ACTION__' = Install ]; then
|
||||||
|
# Without a Hub login this endpoint must refuse access, rather than leak metrics.
|
||||||
|
code=$(curl -sS --max-time 5 -o "$stage/response.json" -w '%{http_code}' http://127.0.0.1:8088/api/vps/resources)
|
||||||
|
test "$code" = 401
|
||||||
|
fi
|
||||||
|
printf '\nVPS_WIDGETS_V111_%s_OK\n' '__ACTION__'
|
||||||
|
'@
|
||||||
|
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
|
||||||
|
try {
|
||||||
|
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
|
||||||
|
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
|
||||||
|
if ($Action -eq 'Install') {
|
||||||
|
$Payloads = @{
|
||||||
|
'hub.py' = 'vps\owrt-remote-hub.py'
|
||||||
|
'tests.py' = 'tests\test_vps_resources.py'
|
||||||
|
}
|
||||||
|
foreach ($Item in $Payloads.GetEnumerator()) {
|
||||||
|
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
|
||||||
|
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
|
||||||
|
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Installation has not started.' }
|
||||||
|
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
|
||||||
|
Write-Host "VPS widgets $Action finished successfully."
|
||||||
|
} finally {
|
||||||
|
if (-not $PrepareOnly) {
|
||||||
|
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
|
||||||
|
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
|
||||||
|
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
|
||||||
|
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4668,6 +4668,16 @@ def parse_resize_payload(payload):
|
|||||||
return message.get("rows"), message.get("cols")
|
return message.get("rows"), message.get("cols")
|
||||||
|
|
||||||
|
|
||||||
|
def vps_resource_widgets_html(mobile=False):
|
||||||
|
kind = "mobile" if mobile else "desktop"
|
||||||
|
widgets = "".join(
|
||||||
|
f'<div class="vpsResource badge" data-vps-resource="{key}" title="{label}: ожидаем данные VPS">'
|
||||||
|
f'<span>{label}</span><strong data-vps-resource-value>—</strong></div>'
|
||||||
|
for key, label in (("cpu", "ЦП"), ("memory", "ОЗУ"), ("disk", "ДИСК"))
|
||||||
|
)
|
||||||
|
return f'<div class="vpsResources vpsResources-{kind}" role="group" aria-label="Ресурсы VPS">{widgets}</div>'
|
||||||
|
|
||||||
|
|
||||||
def dashboard_html(routers, username, sessions=None, notifications=None, auth_bootstrap=None):
|
def dashboard_html(routers, username, sessions=None, notifications=None, auth_bootstrap=None):
|
||||||
routers_json = json.dumps(routers, ensure_ascii=False)
|
routers_json = json.dumps(routers, ensure_ascii=False)
|
||||||
sessions_json = json.dumps(sessions or [], ensure_ascii=False)
|
sessions_json = json.dumps(sessions or [], ensure_ascii=False)
|
||||||
@@ -4730,6 +4740,22 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
|||||||
@media(max-width:680px){{.trafficPanel{{width:min(100%,332px);padding:9px 9px 8px;border-radius:10px}}.trafficControls{{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:6px}}.trafficPanel .wolField{{gap:4px;font-size:11px}}.trafficPanel .wolField input{{min-height:32px;padding:0 9px;font-size:12.5px}}.trafficStatusField .wolMeta{{min-height:32px;font-size:11px;line-height:1.18}}.trafficPanel .btn{{min-height:32px;padding:6px 7px;font-size:11px}}.trafficSummaryChip{{min-height:20px;padding:0 7px;font-size:9px}}.trafficViewport{{max-height:min(42svh,350px)}}.trafficIdentity{{text-align:center!important}}.trafficName{{font-size:12px;text-align:center!important}}.trafficMetaLine{{font-size:10px;line-height:1.28;text-align:center!important}}.trafficTotalBadge{{display:grid;width:fit-content;min-width:130px;max-width:180px;justify-self:center!important;margin:0 auto;place-self:center;padding:6px 10px;text-align:center!important}}.trafficTotalBadge strong{{font-size:11px}}.trafficStat{{padding:6px 5px}}.trafficStat strong{{font-size:11px}}}}
|
@media(max-width:680px){{.trafficPanel{{width:min(100%,332px);padding:9px 9px 8px;border-radius:10px}}.trafficControls{{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:6px}}.trafficPanel .wolField{{gap:4px;font-size:11px}}.trafficPanel .wolField input{{min-height:32px;padding:0 9px;font-size:12.5px}}.trafficStatusField .wolMeta{{min-height:32px;font-size:11px;line-height:1.18}}.trafficPanel .btn{{min-height:32px;padding:6px 7px;font-size:11px}}.trafficSummaryChip{{min-height:20px;padding:0 7px;font-size:9px}}.trafficViewport{{max-height:min(42svh,350px)}}.trafficIdentity{{text-align:center!important}}.trafficName{{font-size:12px;text-align:center!important}}.trafficMetaLine{{font-size:10px;line-height:1.28;text-align:center!important}}.trafficTotalBadge{{display:grid;width:fit-content;min-width:130px;max-width:180px;justify-self:center!important;margin:0 auto;place-self:center;padding:6px 10px;text-align:center!important}}.trafficTotalBadge strong{{font-size:11px}}.trafficStat{{padding:6px 5px}}.trafficStat strong{{font-size:11px}}}}
|
||||||
@media(max-width:420px){{.trafficPanel{{width:100%}}.trafficControls{{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:5px}}.trafficStatusField,.trafficPasswordField{{grid-column:auto}}.trafficStatusField .wolMeta{{padding:6px 8px}}.trafficTotalBadge{{min-width:118px;max-width:168px}}}}
|
@media(max-width:420px){{.trafficPanel{{width:100%}}.trafficControls{{grid-template-columns:repeat(2,minmax(0,1fr))!important;gap:5px}}.trafficStatusField,.trafficPasswordField{{grid-column:auto}}.trafficStatusField .wolMeta{{padding:6px 8px}}.trafficTotalBadge{{min-width:118px;max-width:168px}}}}
|
||||||
@media(max-width:680px){{.routerCardGroup{{margin-top:10px;padding:5px 0;gap:6px}}.routerGroupPickerHead{{min-height:30px}}.routerGroupPickerToggle{{min-height:30px;padding:6px 14px;font-size:11px}}.routerGroupPickerOptions{{width:100%;box-sizing:border-box;grid-template-columns:1fr;gap:6px;padding:6px}}.routerGroupChoice{{min-height:32px;padding:7px 8px;font-size:11px}}}}#diagnosticBuild,.btn[data-diagnose]{{display:none!important}}
|
@media(max-width:680px){{.routerCardGroup{{margin-top:10px;padding:5px 0;gap:6px}}.routerGroupPickerHead{{min-height:30px}}.routerGroupPickerToggle{{min-height:30px;padding:6px 14px;font-size:11px}}.routerGroupPickerOptions{{width:100%;box-sizing:border-box;grid-template-columns:1fr;gap:6px;padding:6px}}.routerGroupChoice{{min-height:32px;padding:7px 8px;font-size:11px}}}}#diagnosticBuild,.btn[data-diagnose]{{display:none!important}}
|
||||||
|
.desktopHeaderTop{{grid-template-columns:var(--hdr-col-1) var(--hdr-col-2) var(--hdr-col-3) var(--hdr-col-4) var(--hdr-col-5) var(--hdr-col-6) var(--hdr-col-7) var(--hdr-col-8);width:100%}}
|
||||||
|
.desktopHeaderTop>.appBanner{{grid-column:1/span 2;width:100%;min-width:0;max-width:none}}
|
||||||
|
.desktopHeaderTop>.routerSearchDock{{grid-column:3/span 2;width:100%;min-width:0;max-width:none}}
|
||||||
|
.desktopHeaderTop>#seasonDock{{grid-column:5;width:100%;min-width:0;max-width:none}}
|
||||||
|
.vpsResources{{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;min-width:0;width:100%}}
|
||||||
|
.vpsResources-desktop{{grid-column:6/span 3}}
|
||||||
|
.vpsResources-mobile{{display:none}}
|
||||||
|
.vpsResource.badge{{min-width:0;width:100%;height:36px;min-height:36px;padding:8px 10px;font-size:12px;gap:6px;cursor:default}}
|
||||||
|
.vpsResource span{{color:var(--muted);font-weight:800}}
|
||||||
|
.vpsResource strong{{font-size:12px;font-weight:900;font-variant-numeric:tabular-nums;color:var(--cyan)}}
|
||||||
|
.vpsResource[data-vps-resource="memory"] strong{{color:#86efac}}
|
||||||
|
.vpsResource[data-vps-resource="disk"] strong{{color:#fde68a}}
|
||||||
|
.vpsResource[data-stale="true"] strong{{color:var(--muted)}}
|
||||||
|
@media(min-width:681px) and (max-width:980px){{.vpsResource.badge{{padding:8px 4px;font-size:11px;gap:4px}}.vpsResource strong{{font-size:11px}}}}
|
||||||
|
@media(min-width:681px) and (max-width:800px){{.vpsResource.badge{{padding:8px 2px;gap:2px}}.vpsResource.badge,.vpsResource strong{{font-size:10px}}}}
|
||||||
|
@media(max-width:680px){{.vpsResources-mobile{{display:grid;margin:8px 0 3px}}.vpsResource.badge{{padding:8px 6px;font-size:11px}}.vpsResource strong{{font-size:11px}}}}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="preload-mobile-panels">
|
<body class="preload-mobile-panels">
|
||||||
@@ -4785,6 +4811,7 @@ input,select{{min-width:0;border:1px solid var(--line);border-radius:8px;padding
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
{vps_resource_widgets_html()}
|
||||||
</div>
|
</div>
|
||||||
<div class="desktopHeaderBottom">
|
<div class="desktopHeaderBottom">
|
||||||
<div class="links">
|
<div class="links">
|
||||||
@@ -5136,6 +5163,7 @@ systemctl restart owrt-remote-xray</pre>
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
{vps_resource_widgets_html(mobile=True)}
|
||||||
<button class="mobilePanelToggle primary" id="hubMenuToggle" type="button" hidden>Открыть меню хаба</button>
|
<button class="mobilePanelToggle primary" id="hubMenuToggle" type="button" hidden>Открыть меню хаба</button>
|
||||||
<div id="hubMenuPanelHost"></div>
|
<div id="hubMenuPanelHost"></div>
|
||||||
<div class="mobileOwnerTools" id="mobileOwnerTools" hidden>
|
<div class="mobileOwnerTools" id="mobileOwnerTools" hidden>
|
||||||
@@ -11504,6 +11532,71 @@ syncRouterSearchToggleState();
|
|||||||
requestRouterRender();
|
requestRouterRender();
|
||||||
fillRouterForm(true);
|
fillRouterForm(true);
|
||||||
waitNotificationsLoop();
|
waitNotificationsLoop();
|
||||||
|
function initVpsResourceWidgets() {{
|
||||||
|
const widgets = Array.from(document.querySelectorAll('[data-vps-resource]'));
|
||||||
|
if (!widgets.length) return;
|
||||||
|
let timer = null;
|
||||||
|
let request = null;
|
||||||
|
let stopped = false;
|
||||||
|
const percentText = (value) => typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? new Intl.NumberFormat('ru-RU', {{maximumFractionDigits: 1}}).format(value) + '%' : '—';
|
||||||
|
const bytesText = (value) => {{
|
||||||
|
if (typeof value !== 'number' || !Number.isFinite(value)) return '—';
|
||||||
|
const units = ['Б', 'КиБ', 'МиБ', 'ГиБ', 'ТиБ'];
|
||||||
|
let unit = 0;
|
||||||
|
while (value >= 1024 && unit < units.length - 1) {{ value /= 1024; unit++; }}
|
||||||
|
return new Intl.NumberFormat('ru-RU', {{maximumFractionDigits: 1}}).format(value) + ' ' + units[unit];
|
||||||
|
}};
|
||||||
|
const show = (data, failed = false) => widgets.forEach((widget) => {{
|
||||||
|
const key = widget.dataset.vpsResource;
|
||||||
|
const metric = data && data[key];
|
||||||
|
const label = widget.querySelector('span').textContent;
|
||||||
|
widget.querySelector('[data-vps-resource-value]').textContent = percentText(metric && metric.percent);
|
||||||
|
widget.dataset.stale = failed ? 'true' : 'false';
|
||||||
|
let detail = failed ? 'нет связи с VPS' : 'данные пока недоступны';
|
||||||
|
if (metric && typeof metric.percent === 'number') {{
|
||||||
|
detail = key === 'cpu' ? 'нагрузка ' + percentText(metric.percent) + ', vCPU: ' + metric.cores
|
||||||
|
: 'занято ' + bytesText(metric.used_bytes) + ' из ' + bytesText(metric.total_bytes);
|
||||||
|
if (key === 'disk') detail += ' (раздел /)';
|
||||||
|
}}
|
||||||
|
widget.title = label + ': ' + detail;
|
||||||
|
widget.setAttribute('aria-label', widget.title);
|
||||||
|
}});
|
||||||
|
const load = async () => {{
|
||||||
|
if (stopped || document.hidden || request) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
request = controller;
|
||||||
|
const timeout = setTimeout(() => controller.abort(), 2500);
|
||||||
|
try {{
|
||||||
|
const response = await fetch('/api/vps/resources', {{cache: 'no-store', signal: controller.signal}});
|
||||||
|
if (response.status === 401 || response.status === 403) {{ stopped = true; clearInterval(timer); }}
|
||||||
|
if (!response.ok) throw new Error('VPS resources unavailable');
|
||||||
|
const data = await response.json();
|
||||||
|
if (!data.ok) throw new Error('Invalid VPS resources');
|
||||||
|
if (!document.hidden && !stopped) show(data);
|
||||||
|
}} catch (error) {{
|
||||||
|
if (!document.hidden) show(null, true);
|
||||||
|
}} finally {{
|
||||||
|
clearTimeout(timeout);
|
||||||
|
request = null;
|
||||||
|
}}
|
||||||
|
}};
|
||||||
|
const pause = () => {{
|
||||||
|
clearInterval(timer); timer = null;
|
||||||
|
if (request) request.abort();
|
||||||
|
}};
|
||||||
|
const resume = () => {{
|
||||||
|
pause();
|
||||||
|
if (stopped || document.hidden) return;
|
||||||
|
load();
|
||||||
|
timer = setInterval(load, 3000);
|
||||||
|
}};
|
||||||
|
document.addEventListener('visibilitychange', resume);
|
||||||
|
window.addEventListener('pagehide', pause);
|
||||||
|
window.addEventListener('pageshow', resume);
|
||||||
|
resume();
|
||||||
|
}}
|
||||||
|
initVpsResourceWidgets();
|
||||||
setInterval(loadRouters, 5000);
|
setInterval(loadRouters, 5000);
|
||||||
setInterval(() => loadNotifications(), 30000);
|
setInterval(() => loadNotifications(), 30000);
|
||||||
window.addEventListener('beforeunload', () => {{
|
window.addEventListener('beforeunload', () => {{
|
||||||
@@ -13963,6 +14056,82 @@ def login_html(error=""):
|
|||||||
return page
|
return page
|
||||||
|
|
||||||
|
|
||||||
|
class VpsResourceMonitor:
|
||||||
|
"""Shared, nonblocking Linux samples; never spawn commands per browser poll."""
|
||||||
|
|
||||||
|
interval = 3.0
|
||||||
|
|
||||||
|
def __init__(self, proc_dir="/proc", disk_path="/"):
|
||||||
|
self.proc_dir = Path(proc_dir)
|
||||||
|
self.disk_path = disk_path
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.last_sample = None
|
||||||
|
self.cached = None
|
||||||
|
self.cpu_previous = self.read_cpu()
|
||||||
|
|
||||||
|
def read_cpu(self):
|
||||||
|
try:
|
||||||
|
with (self.proc_dir / "stat").open(encoding="ascii") as source:
|
||||||
|
values = source.readline().split()
|
||||||
|
if not values or values[0] != "cpu" or len(values) < 5:
|
||||||
|
return None
|
||||||
|
ticks = [int(value) for value in values[1:9]]
|
||||||
|
# guest/guest_nice are already included in user/nice; do not sum twice.
|
||||||
|
return sum(ticks), ticks[3] + (ticks[4] if len(ticks) > 4 else 0)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def cpu_usage(self):
|
||||||
|
current = self.read_cpu()
|
||||||
|
previous, self.cpu_previous = self.cpu_previous, current
|
||||||
|
percent = None
|
||||||
|
if current is not None and previous is not None:
|
||||||
|
total, idle = current[0] - previous[0], current[1] - previous[1]
|
||||||
|
if total > 0 and idle >= 0:
|
||||||
|
percent = round(max(0.0, min(100.0, 100 * (total - idle) / total)), 1)
|
||||||
|
return {"percent": percent, "cores": os.cpu_count() or 1}
|
||||||
|
|
||||||
|
def memory_usage(self):
|
||||||
|
try:
|
||||||
|
with (self.proc_dir / "meminfo").open(encoding="ascii") as source:
|
||||||
|
values = {key: int(value.split()[0]) * 1024 for key, value in
|
||||||
|
(line.split(":", 1) for line in source if ":" in line)}
|
||||||
|
total = values["MemTotal"]
|
||||||
|
available = values.get("MemAvailable")
|
||||||
|
if available is None:
|
||||||
|
available = (values.get("MemFree", 0) + values.get("Buffers", 0) +
|
||||||
|
values.get("Cached", 0) + values.get("SReclaimable", 0) -
|
||||||
|
values.get("Shmem", 0))
|
||||||
|
if total <= 0:
|
||||||
|
return None
|
||||||
|
available = max(0, min(total, available))
|
||||||
|
used = total - available
|
||||||
|
return {"percent": round(used * 100 / total, 1), "used_bytes": used,
|
||||||
|
"total_bytes": total, "available_bytes": available}
|
||||||
|
except (OSError, ValueError, KeyError, IndexError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def disk_usage(self):
|
||||||
|
try:
|
||||||
|
usage = shutil.disk_usage(self.disk_path)
|
||||||
|
if usage.total <= 0:
|
||||||
|
return None
|
||||||
|
return {"percent": round(usage.used * 100 / usage.total, 1),
|
||||||
|
"used_bytes": usage.used, "total_bytes": usage.total,
|
||||||
|
"free_bytes": usage.free, "path": self.disk_path}
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def snapshot(self):
|
||||||
|
with self.lock:
|
||||||
|
now = time.monotonic()
|
||||||
|
if self.cached is None or now - self.last_sample >= self.interval:
|
||||||
|
self.cached = {"cpu": self.cpu_usage(), "memory": self.memory_usage(),
|
||||||
|
"disk": self.disk_usage(), "sampled_at": time.time()}
|
||||||
|
self.last_sample = now
|
||||||
|
return self.cached
|
||||||
|
|
||||||
|
|
||||||
class App:
|
class App:
|
||||||
def __init__(self, db_path, session, agent, public_url):
|
def __init__(self, db_path, session, agent, public_url):
|
||||||
self.db_path = Path(db_path)
|
self.db_path = Path(db_path)
|
||||||
@@ -13973,6 +14142,7 @@ class App:
|
|||||||
self.router_state_snapshot = {}
|
self.router_state_snapshot = {}
|
||||||
self.router_monitor_stop = threading.Event()
|
self.router_monitor_stop = threading.Event()
|
||||||
self.router_monitor_thread = None
|
self.router_monitor_thread = None
|
||||||
|
self.vps_resources = VpsResourceMonitor()
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def conn(self):
|
def conn(self):
|
||||||
@@ -16955,6 +17125,12 @@ exit 127
|
|||||||
if path == "/health":
|
if path == "/health":
|
||||||
self.send_json(200, {"ok": True})
|
self.send_json(200, {"ok": True})
|
||||||
return
|
return
|
||||||
|
if path == "/api/vps/resources":
|
||||||
|
if not self.admin_ok():
|
||||||
|
self.send_json(401, {"ok": False, "error": "not authorized"})
|
||||||
|
return
|
||||||
|
self.send_json(200, {"ok": True, **self.app.vps_resources.snapshot()})
|
||||||
|
return
|
||||||
if path == "/favicon.ico":
|
if path == "/favicon.ico":
|
||||||
self.send_local_asset(FAVICON_ICO_FILE, "image/x-icon")
|
self.send_local_asset(FAVICON_ICO_FILE, "image/x-icon")
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in new issue
Block a user