Automate Edge reverse tunnel enrollment

This commit is contained in:
Andrei Smaliak 2026-09-05 17:49:39 +02:00
parent 92d25b9439
commit 1e2e8d79d5
9 changed files with 246 additions and 22 deletions

View File

@ -46,7 +46,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 2.2.79"
UI_VERSION = "V 2.2.80"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -1996,6 +1996,7 @@ def systemd_unit(unit_name):
"Result",
"ExecMainStatus",
"FragmentPath",
"MainPID",
]
cmd = ["systemctl", "show", unit_name, "--no-page"]
for prop in properties:
@ -2010,6 +2011,7 @@ def systemd_unit(unit_name):
"result": "",
"exec_main_status": "",
"fragment_path": "",
"main_pid": 0,
"installed": False,
"active": False,
"raw_error": stderr if rc != 0 else "",
@ -2035,6 +2037,8 @@ def systemd_unit(unit_name):
data["exec_main_status"] = value
elif key == "FragmentPath":
data["fragment_path"] = value
elif key == "MainPID":
data["main_pid"] = int(value) if value.isdigit() else 0
data["installed"] = data["load_state"] != "not-found" or bool(data["fragment_path"])
data["active"] = data["active_state"] == "active"
return data
@ -3015,15 +3019,21 @@ def terminate_process(proc):
def restart_service_card(service_id):
allowed_units = {
"zigbee2mqtt": "zigbee2mqtt.service",
"reverse_tunnel": (
"iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service",
"iomatex-rt-webui.service",
),
}
service_id = str(service_id or "").strip()
unit_name = allowed_units.get(service_id)
if not unit_name:
raise ValueError("Unsupported service")
rc, _, stderr = run(["systemctl", "restart", unit_name], timeout=20)
unit_names = list(unit_name) if isinstance(unit_name, tuple) else [unit_name]
rc, _, stderr = run(["systemctl", "restart", *unit_names], timeout=20)
if rc != 0:
raise RuntimeError(stderr or f"Failed to restart {unit_name}")
raise RuntimeError(stderr or f"Failed to restart {service_id}")
invalidate_cache()
payload = find_service_card(service_id)

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
import json
import ipaddress
import base64
import os
import queue
import re
@ -9,7 +10,10 @@ import tempfile
import threading
import time
import uuid
from urllib.parse import urlparse, urlunparse
import subprocess
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse, urlunparse
from urllib.request import Request, urlopen
try:
import paho.mqtt.client as mqtt
@ -33,6 +37,7 @@ DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
SETTINGS_CATEGORY = "server"
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
REGISTRATION_STORE_PATH = "/var/lib/itscreen/data/it-screen/it-screen/registration.ini"
REVERSE_TUNNEL_CONFIG_PATH = "/etc/iomatex/reverse-tunnel.env"
MQTT_TOPIC_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$")
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
_REGISTRATION_LOCK = threading.Lock()
@ -399,6 +404,82 @@ def _same_registration_host(left, right):
return _truncate_empty(left).lower().rstrip("/") == _truncate_empty(right).lower().rstrip("/")
def _reverse_tunnel_public_key(device_id):
candidates = (
f"/home/iomatex/.ssh/iomatex-{device_id}.pub",
"/home/iomatex/.ssh/id_ed25519.pub",
)
for path in candidates:
try:
with open(path, "r", encoding="utf-8") as stream:
value = " ".join(stream.read().strip().split())
if value.startswith("ssh-ed25519 "):
return value
except OSError:
continue
raise RuntimeError("Reverse tunnel SSH public key was not found")
def _enroll_reverse_tunnel(state):
host = validate_host(state.get("host", ""))
username = _truncate_empty(state.get("username")) or _device_identity()["device_id"]
password = _truncate_empty(state.get("password"))
if not password:
stored = _read_simple_key_value_file(REGISTRATION_STORE_PATH)
password = _truncate_empty(stored.get("password"))
if not password:
raise RuntimeError("Device registration password is unavailable")
base_url = host if "://" in host else f"http://{host}"
endpoint = base_url.rstrip("/") + "/v2/device/reverse-tunnel"
body = urlencode({"public_key": _reverse_tunnel_public_key(state.get("device_id", ""))}).encode("utf-8")
authorization = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
request = Request(endpoint, data=body, method="POST", headers={
"Authorization": f"Basic {authorization}",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
})
try:
with urlopen(request, timeout=8) as response:
payload = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
raise RuntimeError(f"Environment rejected reverse tunnel enrollment (HTTP {exc.code})") from exc
except (URLError, OSError, ValueError, json.JSONDecodeError) as exc:
raise RuntimeError("Reverse tunnel enrollment request failed") from exc
tunnel = payload.get("reverse_tunnel") if isinstance(payload, dict) else None
if not isinstance(tunnel, dict) or not isinstance(tunnel.get("ports"), dict):
raise RuntimeError("Environment returned an invalid reverse tunnel configuration")
ssh_host = _truncate_empty(tunnel.get("ssh_host"))
ssh_port = int(tunnel.get("ssh_port") or 22)
ssh_user = _truncate_empty(tunnel.get("ssh_user")) or "iomatex-tunnel"
if not ssh_host or not 1 <= ssh_port <= 65535:
raise RuntimeError("Environment returned an invalid SSH gateway")
directory = os.path.dirname(REVERSE_TUNNEL_CONFIG_PATH)
os.makedirs(directory, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix="reverse-tunnel.", suffix=".env", dir=directory, text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as stream:
stream.write(f"TUNNEL_HOST={ssh_host}\nTUNNEL_PORT={ssh_port}\n")
stream.write("TUNNEL_OPERATOR_USER=builder\n")
stream.write(f"TUNNEL_SSH_USER={ssh_user}\n")
os.chmod(temporary, 0o644)
os.replace(temporary, REVERSE_TUNNEL_CONFIG_PATH)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
subprocess.run([
"systemctl", "restart",
"iomatex-rt-cockpit.service",
"iomatex-rt-z2m.service",
"iomatex-rt-webui.service",
], check=True, timeout=20)
return tunnel
def _registration_transport_interrupted(exc):
text = str(exc or "").lower()
return isinstance(exc, TimeoutError) or any(marker in text for marker in (
@ -1200,8 +1281,16 @@ def _register_device_once(host, token=""):
"status": str(event.get("status", "") or ""),
"timestamp": _event_timestamp(),
}
enrollment_warning = ""
reverse_tunnel = None
if merged.get("registered"):
try:
reverse_tunnel = _enroll_reverse_tunnel(merged)
except Exception as exc:
enrollment_warning = _truncate_empty(str(exc)) or "Reverse tunnel enrollment failed"
_debug(f"reverse-tunnel enrollment warning: {enrollment_warning}")
save_state(merged)
return {
result = {
"ok": True,
"status": "already_active" if flow.get("already_active") else ("registered" if merged.get("registered") else "error"),
"message": (
@ -1211,6 +1300,11 @@ def _register_device_once(host, token=""):
),
"data": _build_public_status(merged),
}
if reverse_tunnel:
result["reverse_tunnel"] = reverse_tunnel
if enrollment_warning:
result["warning"] = enrollment_warning
return result
except TimeoutError as exc:
working["status"] = "error"
save_state(working)

View File

@ -10,6 +10,30 @@ SPEC.loader.exec_module(provider)
class ReverseTunnelBootstrapTest(unittest.TestCase):
def test_tunnel_is_active_only_when_ssh_child_has_established_connection(self):
unit = {"active": True, "active_state": "active", "main_pid": 100}
responses = {
("pgrep", "-P", "100", "ssh"): (0, "101\n", ""),
("ss", "-Htnp", "state", "established"): (
0,
'0 0 192.168.0.100:40000 192.168.0.102:2222 users:(("ssh",pid=101,fd=3))\n',
"",
),
}
context = {"run": lambda command, timeout=4: responses.get(tuple(command), (1, "", ""))}
self.assertTrue(provider._reverse_tunnel_connected(context, unit))
state, label, active = provider._reverse_tunnel_item_state(True, True, unit, True)
self.assertEqual(("active", "Active", True), (state, label, active))
def test_running_autossh_without_established_child_is_connecting(self):
unit = {"active": True, "main_pid": 100, "active_state": "active"}
context = {"run": lambda command, timeout=4: (1, "", "")}
self.assertFalse(provider._reverse_tunnel_connected(context, unit))
state, label, active = provider._reverse_tunnel_item_state(True, True, unit, False)
self.assertEqual(("connecting", "Connecting", False), (state, label, active))
def test_mqtt_bridge_card_keeps_remote_port_without_network_probe(self):
unit = {
"active": True,
@ -53,13 +77,21 @@ class ReverseTunnelBootstrapTest(unittest.TestCase):
return 1, "", "unexpected command"
context = {"read_text": lambda path: files.get(path, ""), "run": run}
command = provider._reverse_tunnel_bootstrap_command(context)
command = provider._reverse_tunnel_bootstrap_command(context, "uae.iomatex.com")
self.assertNotIn("api.ipify.org", command)
self.assertIn("reverse-tunnel-service register", command)
self.assertIn("--device g-box-12345678", command)
self.assertEqual([["getent", "passwd", "iomatex"]], commands)
def test_bootstrap_is_hidden_until_tunnel_host_is_known(self):
context = {
"read_text": lambda path: "g-box-12345678\n" if path == "/etc/hostname" else "ssh-ed25519 AAAA edge\n",
"run": lambda command, timeout=4: (0, "iomatex:x:1001:1001::/home/iomatex:/bin/bash", ""),
}
self.assertEqual("", provider._reverse_tunnel_bootstrap_command(context, ""))
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,30 @@
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
class ReverseTunnelActionsContractTest(unittest.TestCase):
def test_card_restarts_all_units_and_exposes_local_service_links(self):
backend = (ROOT / "backend" / "app.py").read_text(encoding="utf-8")
frontend = (ROOT / "frontend" / "console.js").read_text(encoding="utf-8")
stylesheet = (ROOT / "frontend" / "console.css").read_text(encoding="utf-8")
index = (ROOT / "frontend" / "index.html").read_text(encoding="utf-8")
provider = (ROOT / "providers" / "00_core_services.py").read_text(encoding="utf-8")
self.assertIn('"reverse_tunnel": (', backend)
self.assertIn('"iomatex-rt-cockpit.service"', backend)
self.assertIn('"iomatex-rt-z2m.service"', backend)
self.assertIn('"iomatex-rt-webui.service"', backend)
self.assertIn('href: `https://${host}:9090`', frontend)
self.assertIn('href: `http://${host}:8081`', frontend)
self.assertIn('href: `http://${host}:8099`', frontend)
self.assertIn('restartable=installed', provider)
self.assertIn('.reverseTunnelCommand{\n margin-top:14px;', stylesheet)
self.assertIn('grid-template-columns:minmax(110px,42%) minmax(0,1fr)', stylesheet)
self.assertIn('console.css?v=2.2.80', index)
if __name__ == "__main__":
unittest.main()

View File

@ -397,7 +397,8 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.dot.ok{background:var(--accent)}
.dot.warn{background:var(--warn)}
.dot.error{background:var(--error)}
.meta{display:grid;grid-template-columns:140px 1fr;gap:8px 10px;margin-top:16px;font-size:13px}
.meta{display:grid;grid-template-columns:minmax(110px,42%) minmax(0,1fr);gap:8px 10px;margin-top:16px;font-size:13px}
.meta > div:not(.key){min-width:0;overflow-wrap:anywhere}
.compactMeta{margin-top:0}
.splitMeta{
display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:18px;margin-top:16px;
@ -569,7 +570,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
padding-top:10px;
}
.reverseTunnelCommand{
margin-top:10px;
margin-top:14px;
}
html[dir="rtl"] .menuToggleBtn{left:18px;right:auto}
html[dir="rtl"] .actionMenu{left:18px;right:auto}

View File

@ -54,6 +54,7 @@
"Configured": "Настроено",
"Active": "Активно",
"Inactive": "Неактивно",
"Connecting": "Подключение",
"Loading": "Загрузка",
"Registration": "Регистрация",
"Registration in progress": "Выполняется регистрация",
@ -222,6 +223,7 @@
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel нужен для удалённого доступа извне локальной сети. Если у вас уже открыт этот UI, значит вы уже находитесь в одной сети с устройством Edge, и Reverse Tunnel обычно не нужен. Если он понадобится позже, откройте Web UI, перейдите в Devices, выберите своё устройство Edge и откройте вкладку SSH в настройках устройства. Там есть нужные ссылки и полная инструкция из 2 шагов.",
"Command to configure VPS access": "Команда для настройки доступа к VPS",
"Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "Подключитесь к SSH-шлюзу текущего окружения, затем скопируйте, вставьте и выполните приведённую ниже команду регистрации.",
"Run this command with root privileges on the Edge registration server:": "Выполните эту команду с правами root на сервере регистрации Edge:",
"Copy command": "Скопировать команду",
"VPS bootstrap command copied": "Команда настройки VPS скопирована",
"Bootstrap command is unavailable": "Команда настройки недоступна",
@ -546,6 +548,7 @@
"Installed": "Zainstalowano",
"Configured": "Skonfigurowano",
"Inactive": "Nieaktywne",
"Connecting": "Łączenie",
"Running": "Uruchomione",
"Stopped": "Zatrzymane",
"Registration": "Rejestracja",
@ -599,6 +602,7 @@
"VPS bootstrap command copied": "Polecenie bootstrap VPS zostało skopiowane",
"Failed to copy VPS bootstrap command": "Nie udało się skopiować polecenia bootstrap VPS",
"Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "Połącz się z bramą SSH bieżącego środowiska, a następnie skopiuj, wklej i uruchom poniższe polecenie rejestracji.",
"Run this command with root privileges on the Edge registration server:": "Uruchom to polecenie z uprawnieniami root na serwerze rejestracji Edge:",
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel jest potrzebny do zdalnego dostępu spoza sieci lokalnej. Jeśli masz już dostęp do tego UI, jesteś już w tej samej sieci co urządzenie Edge, więc Reverse Tunnel zwykle nie jest potrzebny. Aby użyć go później, otwórz Web UI, przejdź do Devices, wybierz swoje urządzenie Edge, a następnie otwórz kartę SSH w ustawieniach urządzenia. Znajdziesz tam wymagane linki i pełną instrukcję w 2 krokach.",
"Success": "Sukces",
"Available": "Dostępne",
@ -997,6 +1001,7 @@
"Clipboard is unavailable": "الحافظة غير متاحة",
"Loading": "جار التحميل",
"Inactive": "غير نشط",
"Connecting": "جارٍ الاتصال",
"Registration": "التسجيل",
"Ready": "جاهز",
"Actions": "الإجراءات",
@ -1216,6 +1221,7 @@
,"VPS bootstrap command copied": "تم نسخ أمر التهيئة الأولية لـ VPS"
,"Failed to copy VPS bootstrap command": "فشل نسخ أمر التهيئة الأولية لـ VPS"
,"Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "اتصل ببوابة SSH الخاصة بهذه البيئة، ثم انسخ أمر التسجيل أدناه والصقه وشغّله."
,"Run this command with root privileges on the Edge registration server:": "شغّل هذا الأمر بصلاحيات root على خادم تسجيل Edge:"
,"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "يلزم Reverse Tunnel للوصول عن بُعد من خارج الشبكة المحلية. إذا كان لديك وصول إلى هذا الـ UI بالفعل، فأنت ضمن نفس الشبكة مع جهاز Edge، لذلك غالباً لا تكون هناك حاجة إليه. لاستخدامه لاحقاً، افتح Web UI ثم اذهب إلى Devices واختر جهاز Edge الخاص بك وافتح تبويب SSH في إعدادات الجهاز. ستجد هناك الروابط المطلوبة والتعليمات الكاملة من خطوتين."
,"Account security": "أمان الحساب"
,"Change the WEB UI login password for the local iomatex user.": "تغيير كلمة مرور تسجيل الدخول إلى WEB UI للمستخدم المحلي iomatex."
@ -1461,6 +1467,7 @@
"Active": "सक्रिय",
"Loading": "लोड हो रहा है",
"Inactive": "निष्क्रिय",
"Connecting": "कनेक्ट हो रहा है",
"Failed": "विफल",
"Registration": "पंजीकरण",
"Running": "चल रहा है",
@ -1508,6 +1515,7 @@
"VPS bootstrap command copied": "VPS bootstrap command कॉपी हो गया",
"Failed to copy VPS bootstrap command": "VPS bootstrap command कॉपी नहीं हो सका",
"Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "इस environment के SSH gateway से कनेक्ट करें, फिर नीचे दिया registration command कॉपी, पेस्ट और चलाएँ।",
"Run this command with root privileges on the Edge registration server:": "यह कमांड Edge registration server पर root अधिकारों के साथ चलाएँ:",
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel लोकल नेटवर्क के बाहर से remote access के लिए चाहिए। अगर यह UI पहले से खुल रहा है, तो आप Edge डिवाइस के उसी नेटवर्क में हैं, इसलिए आमतौर पर Reverse Tunnel की जरूरत नहीं है। बाद में उपयोग करना हो तो Web UI में Devices खोलें, अपना Edge चुनें, फिर device settings में SSH tab खोलें। वहाँ जरूरी links और 2-step instructions मिल जाएँगी।",
"Display": "डिस्प्ले",
"Display status": "डिस्प्ले स्थिति",

View File

@ -48,7 +48,7 @@
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" }
];
const UI_VERSION = "V 2.2.79";
const UI_VERSION = "V 2.2.80";
const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250;
@ -90,6 +90,7 @@
ok: "OK",
degraded: "Degraded",
running: "Running",
connecting: "Connecting",
stopped: "Stopped",
loading: "Loading",
paused: "Paused",
@ -1307,7 +1308,15 @@
];
const overallRow = { label: t("Overall"), value: card.active ? t("OK") : t("Degraded") };
const bootstrapCommand = textValue(card.bootstrap_command, "");
const bootstrapHost = textValue(card.bootstrap_host, "");
const bootstrapOpen = !!state.reverseTunnelUi.bootstrapOpen;
const host = currentAccessHost();
const tunnelLinks = [
{ name: "cockpit", label: "Cockpit", href: `https://${host}:9090` },
{ name: "z2m", label: "Zigbee2MQTT", href: `http://${host}:8081` },
{ name: "webui", label: "Edge WEB UI", href: `http://${host}:8099` }
];
const restartBusy = !!state.serviceActions.busyById[card.id];
return `
<article class="panel card serviceCard reverseTunnelCard">
@ -1355,7 +1364,8 @@
</button>
<div class="tunnelAccordionBody" ${bootstrapOpen ? "" : "hidden"}>
<div class="formHint">
${esc(t("Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below."))}
${esc(t("Run this command with root privileges on the Edge registration server:"))}
<strong>${esc(bootstrapHost)}</strong>
</div>
<div class="actionRow">
<button class="actionBtn secondary" type="button" onclick="window.__copyReverseTunnelBootstrap()">
@ -1367,7 +1377,20 @@
</div>
</div>
` : ""}
${renderServiceActions(card)}
<div class="list">
<div class="listTitle">${esc(t("Actions"))}</div>
<div class="actionRow serviceActionRow">
<button class="actionBtn secondary" type="button" ${restartBusy ? "disabled" : ""} onclick="window.__restartService('${esc(card.id)}')">
${esc(restartBusy ? t("Restarting...") : t("Restart"))}
</button>
${tunnelLinks.map((link) => {
const tunnel = tunnels.find((item) => item.name === link.name);
return tunnel && tunnel.active
? `<a class="actionBtn" href="${esc(link.href)}" target="_blank" rel="noopener noreferrer">${esc(t(link.label))}</a>`
: `<button class="actionBtn" type="button" disabled>${esc(t(link.label))}</button>`;
}).join("")}
</div>
</div>
${warnings.length ? `<div class="list"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${warnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
${errors.length ? `<div class="list"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${errors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
</article>

View File

@ -23,7 +23,7 @@
} catch (error) {}
})();
</script>
<link rel="stylesheet" href="/console.css?v=2.2.79">
<link rel="stylesheet" href="/console.css?v=2.2.80">
</head>
<body>
<main class="shell">
@ -108,7 +108,7 @@
</main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js?v=2.2.79"></script>
<script src="/console.js?v=2.2.79"></script>
<script src="/console.i18n.js?v=2.2.80"></script>
<script src="/console.js?v=2.2.80"></script>
</body>
</html>

View File

@ -9,7 +9,7 @@ DRM_ROOT = "/sys/class/drm"
REVERSE_TUNNEL_SERVICES = (
{"name": "cockpit", "unit": "iomatex-rt-cockpit.service", "local_port": 9090},
{"name": "z2m", "unit": "iomatex-rt-z2m.service", "local_port": 8081},
{"name": "webui", "unit": "iomatex-rt-webui.service", "local_port": 80},
{"name": "webui", "unit": "iomatex-rt-webui.service", "local_port": 8099},
)
@ -691,22 +691,38 @@ def _reverse_tunnel_key_paths(ctx):
return paths
def _reverse_tunnel_item_state(installed, configured, unit):
active = bool(installed and configured and unit["active"])
def _reverse_tunnel_connected(ctx, unit):
main_pid = int(unit.get("main_pid", 0) or 0)
if not unit.get("active") or main_pid <= 0:
return False
rc, stdout, _ = ctx["run"](["pgrep", "-P", str(main_pid), "ssh"])
if rc != 0 or not stdout.strip():
return False
child_pids = {value for value in stdout.split() if value.isdigit()}
rc, stdout, _ = ctx["run"](["ss", "-Htnp", "state", "established"])
if rc != 0:
return False
return any(f"pid={pid}," in stdout for pid in child_pids)
def _reverse_tunnel_item_state(installed, configured, unit, connected):
active = bool(installed and configured and unit["active"] and connected)
if not installed:
return "not installed", "Not installed", active
if unit["active_state"] == "failed":
return "failed", "Failed", active
if active:
return "active", "Active", active
if configured and unit["active"]:
return "connecting", "Connecting", active
if not configured:
return "installed_not_configured", "Not configured", active
return "inactive", "Inactive", active
def _reverse_tunnel_bootstrap_command(ctx):
def _reverse_tunnel_bootstrap_command(ctx, tunnel_host=""):
hostname = _read_trimmed(ctx, "/etc/hostname").split(".", 1)[0]
if not hostname:
if not hostname or not tunnel_host:
return ""
public_key_line = ""
@ -747,7 +763,8 @@ def reverse_tunnel_card(ctx):
has_unit = any(path and ctx["file_exists"](path) for path in unit_file_candidates) or unit["installed"]
has_script = ctx["file_exists"](script_path)
configured = bool(has_script and key_present)
item_state, item_status_text, is_active = _reverse_tunnel_item_state(has_unit or has_script, configured, unit)
connected = _reverse_tunnel_connected(ctx, unit)
item_state, item_status_text, is_active = _reverse_tunnel_item_state(has_unit or has_script, configured, unit, connected)
installed_checks.append(has_unit or has_script)
configured_checks.append(configured)
@ -758,6 +775,8 @@ def reverse_tunnel_card(ctx):
"installed": has_unit or has_script,
"configured": configured,
"active": is_active,
"unit_running": bool(unit["active"]),
"connected": connected,
"enabled": unit["unit_file_state"] in ("enabled", "static", "generated", "linked", "linked-runtime", "alias"),
"state": item_state,
"status_text": item_status_text,
@ -773,6 +792,7 @@ def reverse_tunnel_card(ctx):
installed = any(installed_checks)
configured = all(configured_checks) if installed else False
active_count = sum(1 for item in service_states if item["active"])
running_count = sum(1 for item in service_states if item["unit_running"])
total = len(service_states)
active = active_count == total and total > 0
@ -785,6 +805,9 @@ def reverse_tunnel_card(ctx):
elif active_count > 0:
state = "degraded"
status_text = f"Partial ({active_count}/{total})"
elif running_count > 0:
state = "connecting"
status_text = f"Connecting ({active_count}/{total})"
elif configured:
state = "inactive"
status_text = "Inactive"
@ -802,10 +825,11 @@ def reverse_tunnel_card(ctx):
)
tunnel_env = ctx["read_env_file"]("/etc/iomatex/reverse-tunnel.env")
tunnel_host = tunnel_env.get("TUNNEL_HOST", "").strip()
details = [
{"label": "SSH key", "value": "Present" if key_present else "Missing"},
{"label": "Active tunnels", "value": f"{active_count}/{total}" if total else "0/0"},
{"label": "Tunnel host", "value": tunnel_env.get("TUNNEL_HOST", "Not configured")},
{"label": "Tunnel host", "value": tunnel_host or "Not configured"},
]
return _service_card(
@ -821,7 +845,9 @@ def reverse_tunnel_card(ctx):
warnings[:3],
details=details,
tunnels=service_states,
bootstrap_command=_reverse_tunnel_bootstrap_command(ctx),
restartable=installed,
bootstrap_host=tunnel_host,
bootstrap_command=_reverse_tunnel_bootstrap_command(ctx, tunnel_host),
)