From 97f259490620e431942120584abbb463bd5d7de5 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Tue, 8 Sep 2026 09:46:22 +0200 Subject: [PATCH] Install reverse tunnels before cloud registration --- local_installer.sh | 2 +- .../stage_reverse_tunnels_install.sh | 51 +++++++--- .../test_dynamic_environment_contract.py | 1 + .../test_installer_lifecycle.py | 96 +++++++++++++++++++ 4 files changed, 138 insertions(+), 12 deletions(-) create mode 100644 stage_reverse_tunnels/test_installer_lifecycle.py diff --git a/local_installer.sh b/local_installer.sh index 021f2ce..694ab59 100755 --- a/local_installer.sh +++ b/local_installer.sh @@ -1435,7 +1435,7 @@ print_summary() { echo " - after reboot the installer resumes via systemd and opens lxterminal on DISPLAY=:0" echo " - final reboot is recommended after the full run" echo " - stage_avahi and stage_cockpit are optional and do not block the main Edge install" - echo " - stage_reverse_tunnels is intentionally last because it requires manual completion" + echo " - stage_reverse_tunnels installs local services; cloud registration enrolls and starts tunnels" echo " - engineer-facing entrypoints are install_iomatex_edge.sh and install_iomatex_z2m.sh" echo "============================================================" } diff --git a/stage_reverse_tunnels/stage_reverse_tunnels_install.sh b/stage_reverse_tunnels/stage_reverse_tunnels_install.sh index 4e23750..fd05696 100644 --- a/stage_reverse_tunnels/stage_reverse_tunnels_install.sh +++ b/stage_reverse_tunnels/stage_reverse_tunnels_install.sh @@ -18,9 +18,9 @@ EDGE_USER="${EDGE_USER:-iomatex}" REGISTRATION_SERVER="${REGISTRATION_SERVER:-}" TUNNEL_HOST="${TUNNEL_HOST:-${VPS_HOST:-}}" -TUNNEL_PORT="${TUNNEL_PORT:-${VPS_PORT:-22}}" -TUNNEL_OPERATOR_USER="${TUNNEL_OPERATOR_USER:-builder}" -TUNNEL_SSH_USER="${TUNNEL_SSH_USER:-iomatex-tunnel}" +TUNNEL_PORT="${TUNNEL_PORT:-${VPS_PORT:-}}" +TUNNEL_OPERATOR_USER="${TUNNEL_OPERATOR_USER:-}" +TUNNEL_SSH_USER="${TUNNEL_SSH_USER:-}" COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}" Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}" @@ -102,6 +102,24 @@ validate_settings() { (( max_remote_port <= 65535 )) || die "Computed remote port range exceeds 65535: ${PORT_BASE}..${max_remote_port}" } +load_environment_config() { + local name value + # Read data, never execute an existing environment file as shell code. + # Explicit installer overrides win over saved enrollment settings. + if [[ -f "$CONFIG_FILE" ]]; then + while IFS='=' read -r name value || [[ -n "$name" ]]; do + case "$name" in + TUNNEL_HOST|TUNNEL_PORT|TUNNEL_OPERATOR_USER|TUNNEL_SSH_USER) + [[ -n "${!name}" ]] || printf -v "$name" '%s' "$value" + ;; + esac + done <"$CONFIG_FILE" + fi + TUNNEL_PORT="${TUNNEL_PORT:-22}" + TUNNEL_OPERATOR_USER="${TUNNEL_OPERATOR_USER:-builder}" + TUNNEL_SSH_USER="${TUNNEL_SSH_USER:-iomatex-tunnel}" +} + normalize_host() { local value="$1" value="${value#http://}" @@ -115,6 +133,7 @@ discover_registration_server() { local candidate value [[ -n "$REGISTRATION_SERVER" ]] && { normalize_host "$REGISTRATION_SERVER"; return; } for candidate in \ + "/var/lib/itscreen/data/it-screen/it-screen/registration.ini" \ "/userdata/itscreen/data/it-screen/it-screen/registration.ini" \ "/home/${EDGE_USER}/.local/share/it-screen/it-screen/registration.ini" \ "/home/${EDGE_USER}/.local/share/it-screen/registration.ini"; do @@ -130,7 +149,10 @@ resolve_tunnel_host() { if [[ -n "$TUNNEL_HOST" ]]; then TUNNEL_HOST="$(normalize_host "$TUNNEL_HOST")" else - registration_host="$(discover_registration_server)" || die "Cannot discover registration server; pass REGISTRATION_SERVER or TUNNEL_HOST" + if ! registration_host="$(discover_registration_server)"; then + log "Registration server is not configured yet; installing tunnels pending cloud registration." + return 0 + fi # By default the environment host itself is the SSH gateway. Deployments # may override this with tunnel. without reinstalling units. TUNNEL_HOST="$registration_host" @@ -235,7 +257,7 @@ exec autossh -M 0 -N \\ -i "${key}" \\ -p "\${TUNNEL_PORT}" \\ -R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\ - "${vps_user}@\${TUNNEL_HOST}" + "\${TUNNEL_SSH_USER}@\${TUNNEL_HOST}" EOF chmod 0755 "$wrapper_path" @@ -250,16 +272,17 @@ write_unit() { Description=IOMATEX Reverse Tunnel (${name}) %H After=network-online.target Wants=network-online.target +StartLimitIntervalSec=0 [Service] User=${EDGE_USER} EnvironmentFile=${CONFIG_FILE} Environment=AUTOSSH_GATETIME=0 Environment=AUTOSSH_POLL=30 +ExecCondition=/usr/bin/test -n "\${TUNNEL_HOST}" ExecStart=${WRAPPER_DIR}/iomatex-rt-${name}.sh Restart=always RestartSec=15 -StartLimitIntervalSec=0 [Install] WantedBy=multi-user.target @@ -286,7 +309,13 @@ print_summary() { echo echo "============================================================" - echo "EDGE READY (TUNNELS START AFTER REBOOT)" + echo "REVERSE TUNNEL COMPONENTS INSTALLED" + if [[ -z "$TUNNEL_HOST" ]]; then + echo "Status: waiting for cloud registration (services will skip startup until configured)." + echo "Register the device in Edge Console to enroll and start the tunnels automatically." + echo "============================================================" + return 0 + fi echo echo "HOSTNAME: ${hostname_value}" echo "EDGE IP: ${edge_ip}" @@ -302,14 +331,13 @@ print_summary() { echo "SSH PUBLIC KEY:" echo "$public_key_line" echo - echo "RUN THIS ON VPS:" + echo "MANUAL VPS ENROLLMENT FALLBACK:" echo echo "$vps_bootstrap_cmd" echo echo "IMPORTANT:" - echo "1. Run the VPS command above" - echo "2. Reboot EDGE" - echo "3. Reverse tunnels will start automatically" + echo "Register/reconnect the device in Edge Console to enroll and start tunnels automatically." + echo "For manual enrollment, run the VPS command above, then restart the tunnel services or reboot EDGE." echo "============================================================" } @@ -321,6 +349,7 @@ main() { require_root preflight_checks + load_environment_config validate_settings resolve_tunnel_host write_environment_config diff --git a/stage_reverse_tunnels/test_dynamic_environment_contract.py b/stage_reverse_tunnels/test_dynamic_environment_contract.py index 8ea85b7..dd9941c 100644 --- a/stage_reverse_tunnels/test_dynamic_environment_contract.py +++ b/stage_reverse_tunnels/test_dynamic_environment_contract.py @@ -13,6 +13,7 @@ class DynamicEnvironmentContractTest(unittest.TestCase): self.assertIn('reverse-tunnel.env', source) self.assertIn("discover_registration_server", source) self.assertIn("/userdata/itscreen/data/it-screen/it-screen/registration.ini", source) + self.assertIn("/var/lib/itscreen/data/it-screen/it-screen/registration.ini", source) self.assertIn("EnvironmentFile=${CONFIG_FILE}", source) def test_operator_helper_requires_environment_host(self): diff --git a/stage_reverse_tunnels/test_installer_lifecycle.py b/stage_reverse_tunnels/test_installer_lifecycle.py new file mode 100644 index 0000000..cce886e --- /dev/null +++ b/stage_reverse_tunnels/test_installer_lifecycle.py @@ -0,0 +1,96 @@ +import os +import pathlib +import subprocess +import tempfile +import unittest + + +ROOT = pathlib.Path(__file__).parent + + +class InstallerLifecycleTest(unittest.TestCase): + def run_installer(self, saved_config="", explicit_host="", registration_host=""): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + config = root / "reverse-tunnel.env" + if saved_config: + config.write_text(saved_config) + source = (ROOT / "stage_reverse_tunnels_install.sh").read_text() + # Execute the actual installer functions; isolate machine mutations. + functions = source[source.index("log() {"):source.rindex('main "$@"')] + harness = r''' +set -euo pipefail +EDGE_USER=iomatex +REGISTRATION_SERVER="" +TUNNEL_HOST="$EXPLICIT_HOST" +TUNNEL_PORT="" +TUNNEL_OPERATOR_USER="" +TUNNEL_SSH_USER="" +COCKPIT_LOCAL_PORT=9090 +Z2M_LOCAL_PORT=8081 +WEBUI_LOCAL_PORT=8099 +PORT_BASE=20000 +PORT_SLOTS=4000 +CONFIG_DIR="$TEST_ROOT" +CONFIG_FILE="$TEST_ROOT/reverse-tunnel.env" +WRAPPER_DIR="$TEST_ROOT" +SYSTEMD_DIR="$TEST_ROOT" +''' + harness += functions + r''' +require_root() { :; } +preflight_checks() { :; } +ensure_autossh_installed() { touch "$TEST_ROOT/autossh-installed"; } +discover_registration_server() { + [[ -n "$REGISTRATION_HOST" ]] || return 1 + printf '%s' "$REGISTRATION_HOST" +} +hostname() { echo edge-test; } +ensure_key() { + touch "$TEST_ROOT/key" + echo 'ssh-ed25519 test edge-test' > "$TEST_ROOT/key.pub" + printf '%s|%s|%s\n' "$TEST_ROOT" "$TEST_ROOT/key" "$TEST_ROOT/key.pub" +} +systemctl() { echo "$*" >> "$TEST_ROOT/systemctl-calls"; } +main +''' + env = dict(os.environ, TEST_ROOT=directory, EXPLICIT_HOST=explicit_host, + REGISTRATION_HOST=registration_host) + result = subprocess.run(["bash", "-c", harness], env=env, text=True, + capture_output=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue((root / "key.pub").exists()) + self.assertTrue((root / "autossh-installed").exists()) + calls = (root / "systemctl-calls").read_text() + self.assertNotIn("restart", calls) + for name in ("cockpit", "z2m", "webui"): + self.assertIn(f"enable iomatex-rt-{name}.service", calls) + unit = (root / f"iomatex-rt-{name}.service").read_text() + self.assertIn('ExecCondition=/usr/bin/test -n "${TUNNEL_HOST}"', unit) + wrapper = root / f"iomatex-rt-{name}.sh" + subprocess.run(["bash", "-n", str(wrapper)], check=True) + self.assertIn('${TUNNEL_SSH_USER}@${TUNNEL_HOST}', wrapper.read_text()) + return config.read_text(), result.stdout + + def test_fresh_install_waits_for_registration(self): + config, output = self.run_installer() + self.assertIn("TUNNEL_HOST=\n", config) + self.assertIn("waiting for cloud registration", output) + + def test_reinstall_preserves_enrolled_gateway(self): + saved = ("TUNNEL_HOST=ssh.example.test\nTUNNEL_PORT=2222\n" + "TUNNEL_OPERATOR_USER=operator\nTUNNEL_SSH_USER=custom-tunnel\n") + config, _ = self.run_installer(saved, registration_host="app.example.test") + self.assertEqual(config, saved) + + def test_explicit_host_overrides_saved_gateway(self): + config, _ = self.run_installer("TUNNEL_HOST=old.example.test\n", + explicit_host="new.example.test") + self.assertIn("TUNNEL_HOST=new.example.test\n", config) + + def test_existing_registration_is_discovered(self): + config, _ = self.run_installer(registration_host="app.example.test") + self.assertIn("TUNNEL_HOST=app.example.test\n", config) + + +if __name__ == "__main__": + unittest.main()