Fix edge health latency and system resilience
This commit is contained in:
parent
4c9a2ec30c
commit
0cdf2923f1
|
|
@ -318,6 +318,113 @@ disable_userdata_swap() {
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
configure_networkmanager_dns() {
|
||||||
|
local dns_servers=""
|
||||||
|
local gateway=""
|
||||||
|
local server=""
|
||||||
|
|
||||||
|
mkdir -p /etc/NetworkManager/conf.d
|
||||||
|
write_if_changed /etc/NetworkManager/conf.d/20-iomatex-dns.conf 0644 <<'EOF'
|
||||||
|
[main]
|
||||||
|
dns=default
|
||||||
|
rc-manager=file
|
||||||
|
EOF
|
||||||
|
|
||||||
|
if have nmcli; then
|
||||||
|
nmcli general reload >/dev/null 2>&1 || true
|
||||||
|
while read -r server; do
|
||||||
|
case "$server" in
|
||||||
|
""|127.0.0.53) continue ;;
|
||||||
|
esac
|
||||||
|
if ! printf '%s\n' "$dns_servers" | grep -Fxq "$server"; then
|
||||||
|
dns_servers="${dns_servers}${server}"$'\n'
|
||||||
|
fi
|
||||||
|
done < <(nmcli -g IP4.DNS,IP6.DNS device show 2>/dev/null || true)
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -z "${dns_servers//$'\n'/}" ]; then
|
||||||
|
gateway="$(ip route show default 2>/dev/null | awk 'NR == 1 {print $3}')"
|
||||||
|
if [ -n "$gateway" ]; then
|
||||||
|
dns_servers="${gateway}"$'\n'
|
||||||
|
log "NetworkManager did not report DNS; using gateway resolver ${gateway}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "${dns_servers//$'\n'/}" ]; then
|
||||||
|
systemctl_disable_now_safe systemd-resolved.service
|
||||||
|
if [ -e /etc/resolv.conf ] || [ -L /etc/resolv.conf ]; then
|
||||||
|
backup_if_exists /etc/resolv.conf
|
||||||
|
rm -f /etc/resolv.conf
|
||||||
|
fi
|
||||||
|
{
|
||||||
|
echo "# Managed by IOMATEX NetworkManager DNS contract"
|
||||||
|
while read -r server; do
|
||||||
|
[ -n "$server" ] && printf 'nameserver %s\n' "$server"
|
||||||
|
done <<<"$dns_servers"
|
||||||
|
echo "options timeout:2 attempts:2"
|
||||||
|
} >/etc/resolv.conf
|
||||||
|
chmod 0644 /etc/resolv.conf
|
||||||
|
else
|
||||||
|
log "WARN: no DHCP DNS or default gateway available; resolver configuration was preserved"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
configure_zram_swap() {
|
||||||
|
write_if_changed /usr/local/sbin/iomatex-zram 0755 <<'EOF'
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
device=/dev/zram0
|
||||||
|
|
||||||
|
case "${1:-start}" in
|
||||||
|
start)
|
||||||
|
if swapon --show=NAME --noheadings 2>/dev/null | awk '{$1=$1};1' | grep -qx "$device"; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
modprobe zram num_devices=1 >/dev/null 2>&1 || exit 0
|
||||||
|
[ -b "$device" ] || exit 0
|
||||||
|
command -v zramctl >/dev/null 2>&1 || exit 0
|
||||||
|
mem_kib="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo)"
|
||||||
|
size_bytes=$((mem_kib * 1024 / 4))
|
||||||
|
min_bytes=$((128 * 1024 * 1024))
|
||||||
|
max_bytes=$((512 * 1024 * 1024))
|
||||||
|
[ "$size_bytes" -lt "$min_bytes" ] && size_bytes="$min_bytes"
|
||||||
|
[ "$size_bytes" -gt "$max_bytes" ] && size_bytes="$max_bytes"
|
||||||
|
zramctl --reset "$device" >/dev/null 2>&1 || true
|
||||||
|
zramctl --size "$size_bytes" "$device"
|
||||||
|
mkswap "$device" >/dev/null
|
||||||
|
swapon --priority 100 "$device"
|
||||||
|
;;
|
||||||
|
stop)
|
||||||
|
swapoff "$device" >/dev/null 2>&1 || true
|
||||||
|
zramctl --reset "$device" >/dev/null 2>&1 || true
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "usage: $0 {start|stop}" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
EOF
|
||||||
|
|
||||||
|
write_if_changed /etc/systemd/system/iomatex-zram.service 0644 <<'EOF'
|
||||||
|
[Unit]
|
||||||
|
Description=IOMATEX compressed RAM swap
|
||||||
|
After=systemd-modules-load.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
RemainAfterExit=yes
|
||||||
|
ExecStart=/usr/local/sbin/iomatex-zram start
|
||||||
|
ExecStop=/usr/local/sbin/iomatex-zram stop
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl_enable_now_safe iomatex-zram.service
|
||||||
|
}
|
||||||
|
|
||||||
userdata_has_journal() {
|
userdata_has_journal() {
|
||||||
local device
|
local device
|
||||||
device="$(readlink -f /dev/disk/by-partlabel/userdata 2>/dev/null || true)"
|
device="$(readlink -f /dev/disk/by-partlabel/userdata 2>/dev/null || true)"
|
||||||
|
|
@ -1157,6 +1264,7 @@ else
|
||||||
fi
|
fi
|
||||||
keep_pcp_logs_on_root
|
keep_pcp_logs_on_root
|
||||||
systemctl_enable_now_safe NetworkManager
|
systemctl_enable_now_safe NetworkManager
|
||||||
|
configure_networkmanager_dns
|
||||||
|
|
||||||
IP_MAIN="$(main_ipv4)"
|
IP_MAIN="$(main_ipv4)"
|
||||||
[ -n "${IP_MAIN:-}" ] || IP_MAIN="<device-ip>"
|
[ -n "${IP_MAIN:-}" ] || IP_MAIN="<device-ip>"
|
||||||
|
|
@ -1217,6 +1325,7 @@ EOF
|
||||||
# - NO fstab entries that can block boot
|
# - NO fstab entries that can block boot
|
||||||
# - /userdata is treated as optional for boot
|
# - /userdata is treated as optional for boot
|
||||||
# - NO swap on /userdata; hard power cuts can make that partition block boot on fsck
|
# - NO swap on /userdata; hard power cuts can make that partition block boot on fsck
|
||||||
|
# - compressed RAM swap is provided by iomatex-zram.service when supported
|
||||||
# - generic app log directory is created only when /userdata is already mounted
|
# - generic app log directory is created only when /userdata is already mounted
|
||||||
# -------------------------
|
# -------------------------
|
||||||
step "Userdata SAFE: non-blocking mount + generic logs + log overflow protection"
|
step "Userdata SAFE: non-blocking mount + generic logs + log overflow protection"
|
||||||
|
|
@ -1234,6 +1343,7 @@ if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
|
||||||
else
|
else
|
||||||
log "Existing Edge detected: leaving swap configuration untouched"
|
log "Existing Edge detected: leaving swap configuration untouched"
|
||||||
fi
|
fi
|
||||||
|
configure_zram_swap
|
||||||
|
|
||||||
soft_run "systemd daemon-reload (storage contract)" 20 /bin/systemctl daemon-reload
|
soft_run "systemd daemon-reload (storage contract)" 20 /bin/systemctl daemon-reload
|
||||||
soft_run "Enable iomatex-userdata-prepare.service" 20 /bin/systemctl enable iomatex-userdata-prepare.service
|
soft_run "Enable iomatex-userdata-prepare.service" 20 /bin/systemctl enable iomatex-userdata-prepare.service
|
||||||
|
|
|
||||||
|
|
@ -221,14 +221,6 @@ enable_units_only() {
|
||||||
systemctl enable iomatex-rt-webui.service
|
systemctl enable iomatex-rt-webui.service
|
||||||
}
|
}
|
||||||
|
|
||||||
fetch_public_ip() {
|
|
||||||
if ! command -v curl >/dev/null 2>&1; then
|
|
||||||
echo ""
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null || true
|
|
||||||
}
|
|
||||||
|
|
||||||
print_summary() {
|
print_summary() {
|
||||||
local hostname_value="$1"
|
local hostname_value="$1"
|
||||||
local edge_ip="$2"
|
local edge_ip="$2"
|
||||||
|
|
@ -306,9 +298,9 @@ main() {
|
||||||
# Enable but DO NOT start. Services should come up after reboot.
|
# Enable but DO NOT start. Services should come up after reboot.
|
||||||
enable_units_only
|
enable_units_only
|
||||||
|
|
||||||
edge_ip="$(fetch_public_ip)"
|
edge_ip="detected from SSH_CLIENT on VPS"
|
||||||
|
|
||||||
vps_bootstrap_cmd="EDGE_HOSTNAME=$(shell_quote "$hostname_value"); EDGE_IP=$(shell_quote "$edge_ip"); EDGE_PUBKEY_LINE=$(shell_quote "$public_key_line"); COCKPIT_REMOTE_PORT=$(shell_quote "$cockpit_remote_port"); Z2M_REMOTE_PORT=$(shell_quote "$z2m_remote_port"); WEBUI_REMOTE_PORT=$(shell_quote "$webui_remote_port"); VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
|
vps_bootstrap_cmd="EDGE_HOSTNAME=$(shell_quote "$hostname_value"); EDGE_IP=\"\${SSH_CLIENT%% *}\"; EDGE_PUBKEY_LINE=$(shell_quote "$public_key_line"); COCKPIT_REMOTE_PORT=$(shell_quote "$cockpit_remote_port"); Z2M_REMOTE_PORT=$(shell_quote "$z2m_remote_port"); WEBUI_REMOTE_PORT=$(shell_quote "$webui_remote_port"); VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; if [ -n \"\$EDGE_IP\" ]; then sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; fi; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
|
||||||
|
|
||||||
print_summary \
|
print_summary \
|
||||||
"$hostname_value" \
|
"$hostname_value" \
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,10 @@
|
||||||
parsing in the Console backend.
|
parsing in the Console backend.
|
||||||
- Load provider modules from `providers.d`.
|
- Load provider modules from `providers.d`.
|
||||||
- Cache recent status briefly to avoid repeated shell work on every page render.
|
- Cache recent status briefly to avoid repeated shell work on every page render.
|
||||||
|
- Keep `/api/status` and `/api/health/*` independent of external DNS and
|
||||||
|
network reachability. External service health belongs to background system
|
||||||
|
timers; request handlers consume their local state and never probe the
|
||||||
|
Internet synchronously.
|
||||||
|
|
||||||
## Addon responsibilities
|
## Addon responsibilities
|
||||||
- Add new service cards without changing core frontend or server flow.
|
- Add new service cards without changing core frontend or server flow.
|
||||||
|
|
|
||||||
|
|
@ -46,7 +46,7 @@ APP_DIR = "/opt/iomatex-console"
|
||||||
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||||
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||||
CONFIG_PATH = "/etc/iomatex/console.json"
|
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||||
UI_VERSION = "V 2.2.78"
|
UI_VERSION = "V 2.2.79"
|
||||||
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
|
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
|
||||||
ZONEINFO_ROOT = "/usr/share/zoneinfo"
|
ZONEINFO_ROOT = "/usr/share/zoneinfo"
|
||||||
|
|
||||||
|
|
@ -59,6 +59,8 @@ DEFAULT_CONFIG = {
|
||||||
|
|
||||||
_CACHE = {"expires_at": 0.0, "payload": None}
|
_CACHE = {"expires_at": 0.0, "payload": None}
|
||||||
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
|
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
|
||||||
|
_CACHE_LOCK = threading.Lock()
|
||||||
|
_HEALTH_SERVICES_CACHE_LOCK = threading.Lock()
|
||||||
_CPU_SAMPLE = {"total": None, "idle": None}
|
_CPU_SAMPLE = {"total": None, "idle": None}
|
||||||
_NET_SAMPLE = {}
|
_NET_SAMPLE = {}
|
||||||
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
|
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
|
||||||
|
|
@ -2324,18 +2326,22 @@ def build_status_payload():
|
||||||
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||||
return _CACHE["payload"]
|
return _CACHE["payload"]
|
||||||
|
|
||||||
cards, provider_names = collect_provider_cards(build_provider_context())
|
with _CACHE_LOCK:
|
||||||
|
now = time.time()
|
||||||
|
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||||
|
return _CACHE["payload"]
|
||||||
|
|
||||||
payload = {
|
cards, provider_names = collect_provider_cards(build_provider_context())
|
||||||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
payload = {
|
||||||
"hostname": get_system_hostname() or os.uname().nodename,
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
"identity": get_identity_payload(),
|
"hostname": get_system_hostname() or os.uname().nodename,
|
||||||
"services": cards,
|
"identity": get_identity_payload(),
|
||||||
"providers": provider_names,
|
"services": cards,
|
||||||
}
|
"providers": provider_names,
|
||||||
_CACHE["payload"] = payload
|
}
|
||||||
_CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
_CACHE["payload"] = payload
|
||||||
return payload
|
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def build_health_services_payload():
|
def build_health_services_payload():
|
||||||
|
|
@ -2344,26 +2350,31 @@ def build_health_services_payload():
|
||||||
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
|
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
|
||||||
return _HEALTH_SERVICES_CACHE["payload"]
|
return _HEALTH_SERVICES_CACHE["payload"]
|
||||||
|
|
||||||
allowed_ids = {
|
with _HEALTH_SERVICES_CACHE_LOCK:
|
||||||
"itscreen",
|
now = time.time()
|
||||||
"mosquitto",
|
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
|
||||||
"mqtt_bridge",
|
return _HEALTH_SERVICES_CACHE["payload"]
|
||||||
"zigbee2mqtt",
|
|
||||||
"cockpit",
|
allowed_ids = {
|
||||||
"reverse_tunnel",
|
"itscreen",
|
||||||
"display",
|
"mosquitto",
|
||||||
"edge_api",
|
"mqtt_bridge",
|
||||||
}
|
"zigbee2mqtt",
|
||||||
cards, _ = collect_provider_cards(build_provider_context())
|
"cockpit",
|
||||||
payload = {
|
"reverse_tunnel",
|
||||||
"ok": True,
|
"display",
|
||||||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
"edge_api",
|
||||||
"identity": get_identity_payload(),
|
}
|
||||||
"services": [card for card in cards if card.get("id") in allowed_ids],
|
cards, _ = collect_provider_cards(build_provider_context())
|
||||||
}
|
payload = {
|
||||||
_HEALTH_SERVICES_CACHE["payload"] = payload
|
"ok": True,
|
||||||
_HEALTH_SERVICES_CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
return payload
|
"identity": get_identity_payload(),
|
||||||
|
"services": [card for card in cards if card.get("id") in allowed_ids],
|
||||||
|
}
|
||||||
|
_HEALTH_SERVICES_CACHE["payload"] = payload
|
||||||
|
_HEALTH_SERVICES_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def find_service_card(service_id):
|
def find_service_card(service_id):
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
import importlib.util
|
||||||
|
import pathlib
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
|
||||||
|
PROVIDER_PATH = pathlib.Path(__file__).resolve().parents[1] / "providers" / "00_core_services.py"
|
||||||
|
SPEC = importlib.util.spec_from_file_location("core_services", PROVIDER_PATH)
|
||||||
|
provider = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(provider)
|
||||||
|
|
||||||
|
|
||||||
|
class ReverseTunnelBootstrapTest(unittest.TestCase):
|
||||||
|
def test_bootstrap_generation_never_calls_external_network(self):
|
||||||
|
files = {
|
||||||
|
"/etc/hostname": "g-box-12345678\n",
|
||||||
|
"/home/iomatex/.ssh/id_ed25519.pub": "ssh-ed25519 AAAA edge\n",
|
||||||
|
}
|
||||||
|
for name, local_port, remote_port in (
|
||||||
|
("cockpit", 9090, 19090),
|
||||||
|
("z2m", 8081, 18081),
|
||||||
|
("webui", 80, 18080),
|
||||||
|
):
|
||||||
|
files[f"/usr/local/sbin/iomatex-rt-{name}.sh"] = (
|
||||||
|
f'exec autossh -p "22" -R 127.0.0.1:{remote_port}:127.0.0.1:{local_port} "edge@gateway"'
|
||||||
|
)
|
||||||
|
|
||||||
|
commands = []
|
||||||
|
|
||||||
|
def run(command, timeout=4):
|
||||||
|
commands.append(command)
|
||||||
|
if command == ["getent", "passwd", "iomatex"]:
|
||||||
|
return 0, "iomatex:x:1001:1001::/home/iomatex:/bin/bash", ""
|
||||||
|
return 1, "", "unexpected command"
|
||||||
|
|
||||||
|
context = {"read_text": lambda path: files.get(path, ""), "run": run}
|
||||||
|
command = provider._reverse_tunnel_bootstrap_command(context)
|
||||||
|
|
||||||
|
self.assertNotIn("api.ipify.org", command)
|
||||||
|
self.assertIn("SSH_CLIENT", command)
|
||||||
|
self.assertEqual([["getent", "passwd", "iomatex"]], commands)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
import importlib.util
|
||||||
|
import pathlib
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
|
||||||
|
BACKEND_DIR = pathlib.Path(__file__).resolve().parent
|
||||||
|
sys.path.insert(0, str(BACKEND_DIR))
|
||||||
|
SPEC = importlib.util.spec_from_file_location("iomatex_console_health_app", BACKEND_DIR / "app.py")
|
||||||
|
app = importlib.util.module_from_spec(SPEC)
|
||||||
|
SPEC.loader.exec_module(app)
|
||||||
|
|
||||||
|
|
||||||
|
class HealthServicesCacheTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
app._HEALTH_SERVICES_CACHE.update({"expires_at": 0.0, "payload": None})
|
||||||
|
|
||||||
|
def test_ttl_starts_after_slow_collection_finishes(self):
|
||||||
|
clock = iter([100.0, 100.0, 110.0, 110.0])
|
||||||
|
with mock.patch.object(app.time, "time", side_effect=lambda: next(clock)), \
|
||||||
|
mock.patch.object(app, "load_config", return_value={"cache_ttl_sec": 3}), \
|
||||||
|
mock.patch.object(app, "collect_provider_cards", return_value=([{"id": "edge_api"}], [])), \
|
||||||
|
mock.patch.object(app, "get_identity_payload", return_value={}):
|
||||||
|
app.build_health_services_payload()
|
||||||
|
|
||||||
|
self.assertEqual(113.0, app._HEALTH_SERVICES_CACHE["expires_at"])
|
||||||
|
|
||||||
|
def test_concurrent_requests_share_one_collection(self):
|
||||||
|
started = threading.Event()
|
||||||
|
release = threading.Event()
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def collect(_context):
|
||||||
|
calls.append(True)
|
||||||
|
started.set()
|
||||||
|
release.wait(2)
|
||||||
|
return [{"id": "edge_api"}], []
|
||||||
|
|
||||||
|
with mock.patch.object(app, "load_config", return_value={"cache_ttl_sec": 3}), \
|
||||||
|
mock.patch.object(app, "collect_provider_cards", side_effect=collect), \
|
||||||
|
mock.patch.object(app, "get_identity_payload", return_value={}):
|
||||||
|
threads = [threading.Thread(target=app.build_health_services_payload) for _ in range(2)]
|
||||||
|
threads[0].start()
|
||||||
|
self.assertTrue(started.wait(1))
|
||||||
|
threads[1].start()
|
||||||
|
time.sleep(0.05)
|
||||||
|
release.set()
|
||||||
|
for thread in threads:
|
||||||
|
thread.join(2)
|
||||||
|
|
||||||
|
self.assertEqual(1, len(calls))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
|
|
@ -48,7 +48,7 @@
|
||||||
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
|
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
|
||||||
{ mode: "custom", label: "Custom", host: "" }
|
{ mode: "custom", label: "Custom", host: "" }
|
||||||
];
|
];
|
||||||
const UI_VERSION = "V 2.2.78";
|
const UI_VERSION = "V 2.2.79";
|
||||||
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
||||||
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
||||||
const ITSCREEN_LOG_BATCH_MS = 250;
|
const ITSCREEN_LOG_BATCH_MS = 250;
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@
|
||||||
} catch (error) {}
|
} catch (error) {}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<link rel="stylesheet" href="/console.css?v=2.2.78">
|
<link rel="stylesheet" href="/console.css?v=2.2.79">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main class="shell">
|
<main class="shell">
|
||||||
|
|
@ -108,7 +108,7 @@
|
||||||
</main>
|
</main>
|
||||||
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
||||||
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
||||||
<script src="/console.i18n.js?v=2.2.78"></script>
|
<script src="/console.i18n.js?v=2.2.79"></script>
|
||||||
<script src="/console.js?v=2.2.78"></script>
|
<script src="/console.js?v=2.2.79"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import math
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shlex
|
import shlex
|
||||||
import socket
|
|
||||||
|
|
||||||
|
|
||||||
DRM_ROOT = "/sys/class/drm"
|
DRM_ROOT = "/sys/class/drm"
|
||||||
|
|
@ -67,16 +66,6 @@ def _listening_tcp(ctx, port):
|
||||||
return any(needle in line for line in (stdout or "").splitlines())
|
return any(needle in line for line in (stdout or "").splitlines())
|
||||||
|
|
||||||
|
|
||||||
def _remote_tcp_reachable(host, port, timeout=1.0):
|
|
||||||
if not host:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
with socket.create_connection((host, int(port)), timeout=timeout):
|
|
||||||
return True
|
|
||||||
except (OSError, TypeError, ValueError):
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _fallback(value, default="Not available"):
|
def _fallback(value, default="Not available"):
|
||||||
text = str(value or "").strip()
|
text = str(value or "").strip()
|
||||||
return text if text else default
|
return text if text else default
|
||||||
|
|
@ -524,11 +513,9 @@ def mqtt_bridge_card(ctx):
|
||||||
])
|
])
|
||||||
)
|
)
|
||||||
remote_host = str(env.get("REMOTE_HOST", "")).strip()
|
remote_host = str(env.get("REMOTE_HOST", "")).strip()
|
||||||
remote_port = str(env.get("REMOTE_PORT", "1883")).strip() or "1883"
|
|
||||||
remote_reachable = _remote_tcp_reachable(remote_host, remote_port) if enabled else False
|
|
||||||
mosquitto = ctx["systemd_unit"]("mosquitto.service")
|
mosquitto = ctx["systemd_unit"]("mosquitto.service")
|
||||||
health_timer = ctx["systemd_unit"]("iomatex-mqtt-health.timer")
|
health_timer = ctx["systemd_unit"]("iomatex-mqtt-health.timer")
|
||||||
active = bool(enabled and remote_host and bridge_conf_exists and mosquitto["active"] and remote_reachable)
|
active = bool(enabled and remote_host and bridge_conf_exists and mosquitto["active"])
|
||||||
warnings = []
|
warnings = []
|
||||||
errors = []
|
errors = []
|
||||||
if installed and not enabled:
|
if installed and not enabled:
|
||||||
|
|
@ -537,8 +524,6 @@ def mqtt_bridge_card(ctx):
|
||||||
errors.append("REMOTE_HOST is empty")
|
errors.append("REMOTE_HOST is empty")
|
||||||
if installed and enabled and not bridge_conf_exists:
|
if installed and enabled and not bridge_conf_exists:
|
||||||
warnings.append("Bridge config missing")
|
warnings.append("Bridge config missing")
|
||||||
if installed and enabled and remote_host and not remote_reachable:
|
|
||||||
errors.append("Remote MQTT broker is unreachable")
|
|
||||||
state, status_text = _lifecycle(installed, configured, active, failed=mosquitto["active_state"] == "failed")
|
state, status_text = _lifecycle(installed, configured, active, failed=mosquitto["active_state"] == "failed")
|
||||||
if installed and configured and not active and not enabled:
|
if installed and configured and not active and not enabled:
|
||||||
status_text = "Disabled"
|
status_text = "Disabled"
|
||||||
|
|
@ -765,15 +750,9 @@ def _reverse_tunnel_bootstrap_command(ctx):
|
||||||
z2m = parsed["z2m"]
|
z2m = parsed["z2m"]
|
||||||
webui = parsed["webui"]
|
webui = parsed["webui"]
|
||||||
vps_user = cockpit["vps_user"]
|
vps_user = cockpit["vps_user"]
|
||||||
edge_ip = ""
|
|
||||||
|
|
||||||
rc, stdout, _ = ctx["run"](["/usr/bin/curl", "-fsS", "--max-time", "5", "https://api.ipify.org"], timeout=8)
|
|
||||||
if rc == 0:
|
|
||||||
edge_ip = (stdout or "").strip()
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
f"EDGE_HOSTNAME={shlex.quote(hostname)}; "
|
f"EDGE_HOSTNAME={shlex.quote(hostname)}; "
|
||||||
f"EDGE_IP={shlex.quote(edge_ip)}; "
|
f"EDGE_IP=\"${{SSH_CLIENT%% *}}\"; "
|
||||||
f"EDGE_PUBKEY_LINE={shlex.quote(public_key_line)}; "
|
f"EDGE_PUBKEY_LINE={shlex.quote(public_key_line)}; "
|
||||||
f"COCKPIT_REMOTE_PORT={shlex.quote(cockpit['remote_port'])}; "
|
f"COCKPIT_REMOTE_PORT={shlex.quote(cockpit['remote_port'])}; "
|
||||||
f"Z2M_REMOTE_PORT={shlex.quote(z2m['remote_port'])}; "
|
f"Z2M_REMOTE_PORT={shlex.quote(z2m['remote_port'])}; "
|
||||||
|
|
@ -785,9 +764,9 @@ def _reverse_tunnel_bootstrap_command(ctx):
|
||||||
f"\"$COCKPIT_REMOTE_PORT\" \"$Z2M_REMOTE_PORT\" \"$WEBUI_REMOTE_PORT\" \"$EDGE_PUBKEY_LINE\" | sudo tee \"/home/$VPS_USER/.ssh/authorized_keys\" >/dev/null; "
|
f"\"$COCKPIT_REMOTE_PORT\" \"$Z2M_REMOTE_PORT\" \"$WEBUI_REMOTE_PORT\" \"$EDGE_PUBKEY_LINE\" | sudo tee \"/home/$VPS_USER/.ssh/authorized_keys\" >/dev/null; "
|
||||||
f"sudo chown -R \"$VPS_USER:$VPS_USER\" \"/home/$VPS_USER/.ssh\"; "
|
f"sudo chown -R \"$VPS_USER:$VPS_USER\" \"/home/$VPS_USER/.ssh\"; "
|
||||||
f"sudo chmod 600 \"/home/$VPS_USER/.ssh/authorized_keys\"; "
|
f"sudo chmod 600 \"/home/$VPS_USER/.ssh/authorized_keys\"; "
|
||||||
f"sudo fail2ban-client set sshd unbanip \"$EDGE_IP\" 2>/dev/null || true; "
|
f"if [ -n \"$EDGE_IP\" ]; then sudo fail2ban-client set sshd unbanip \"$EDGE_IP\" 2>/dev/null || true; "
|
||||||
f"(sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& $EDGE_IP/\" /etc/fail2ban/jail.local) || "
|
f"(sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& $EDGE_IP/\" /etc/fail2ban/jail.local) || "
|
||||||
f"echo -e \"[DEFAULT]\\nignoreip = 127.0.0.1/8 $EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; "
|
f"echo -e \"[DEFAULT]\\nignoreip = 127.0.0.1/8 $EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; fi; "
|
||||||
f"sudo systemctl restart fail2ban; "
|
f"sudo systemctl restart fail2ban; "
|
||||||
f"echo \"OK: $VPS_USER ready\""
|
f"echo \"OK: $VPS_USER ready\""
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -138,9 +138,20 @@ check_base_system() {
|
||||||
local swap_total=""
|
local swap_total=""
|
||||||
swap_total="$(free -h 2>/dev/null | awk '/^Swap:/ {print $2}')"
|
swap_total="$(free -h 2>/dev/null | awk '/^Swap:/ {print $2}')"
|
||||||
if [[ -z "$swap_total" || "$swap_total" == "0B" || "$swap_total" == "0" ]]; then
|
if [[ -z "$swap_total" || "$swap_total" == "0B" || "$swap_total" == "0" ]]; then
|
||||||
warn "swap is disabled"
|
if unit_exists "iomatex-zram.service"; then
|
||||||
|
warn "iomatex-zram.service is installed but swap is unavailable"
|
||||||
|
else
|
||||||
|
warn "swap is disabled"
|
||||||
|
fi
|
||||||
else
|
else
|
||||||
pass "swap configured: ${swap_total}"
|
pass "swap configured: ${swap_total}"
|
||||||
|
if swapon --show=NAME --noheadings 2>/dev/null | awk '{$1=$1};1' | grep -qx /dev/zram0; then
|
||||||
|
pass "zram swap active on /dev/zram0"
|
||||||
|
elif swapon --show=NAME --noheadings 2>/dev/null | grep -q '^/userdata/'; then
|
||||||
|
fail "swap must not depend on /userdata"
|
||||||
|
else
|
||||||
|
warn "swap is active but not provided by iomatex zram"
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local load_text=""
|
local load_text=""
|
||||||
|
|
@ -207,6 +218,16 @@ check_network() {
|
||||||
nameserver_count="$(awk '/^nameserver / {count++} END {print count+0}' /etc/resolv.conf 2>/dev/null)"
|
nameserver_count="$(awk '/^nameserver / {count++} END {print count+0}' /etc/resolv.conf 2>/dev/null)"
|
||||||
if [[ -n "$nameserver_count" && "$nameserver_count" -gt 0 ]]; then
|
if [[ -n "$nameserver_count" && "$nameserver_count" -gt 0 ]]; then
|
||||||
pass "DNS resolver configured with ${nameserver_count} nameserver(s)"
|
pass "DNS resolver configured with ${nameserver_count} nameserver(s)"
|
||||||
|
if grep -Eq '^[[:space:]]*nameserver[[:space:]]+127\.0\.0\.53([[:space:]]|$)' /etc/resolv.conf 2>/dev/null \
|
||||||
|
&& ! unit_active systemd-resolved.service; then
|
||||||
|
fail "127.0.0.53 is configured but systemd-resolved.service is inactive"
|
||||||
|
elif awk '$1 == "nameserver" && $2 != "127.0.0.53" { found=1 } END { exit found ? 0 : 1 }' /etc/resolv.conf 2>/dev/null; then
|
||||||
|
pass "non-stub DNS resolver configured"
|
||||||
|
elif unit_active systemd-resolved.service; then
|
||||||
|
pass "systemd-resolved stub is active"
|
||||||
|
else
|
||||||
|
fail "no usable DNS resolver configured"
|
||||||
|
fi
|
||||||
if run_quick "getent ahostsv4 deb.debian.org >/dev/null" 5; then
|
if run_quick "getent ahostsv4 deb.debian.org >/dev/null" 5; then
|
||||||
pass "DNS lookup works"
|
pass "DNS lookup works"
|
||||||
else
|
else
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue