Fix Edge heartbeat routing and preserve MQTT registration on upgrade
This commit is contained in:
parent
ce85458ee9
commit
cc80ccaa1c
|
|
@ -146,7 +146,6 @@ MQTT_CLEANUP_FILES=(
|
|||
/etc/mosquitto/conf.d/60-iomatex-bridge.conf
|
||||
/etc/mosquitto/conf.d/99-iomatex-debug.conf
|
||||
/etc/mosquitto/conf.d/zz-iomatex-bridge.conf
|
||||
/etc/iomatex/mqtt_bridge.env
|
||||
/usr/local/sbin/iomatex-mqtt-apply
|
||||
/usr/local/sbin/iomatex-mqtt-remote-set
|
||||
/usr/local/sbin/iomatex-mqtt-health.sh
|
||||
|
|
@ -159,13 +158,12 @@ MQTT_CLEANUP_FILES=(
|
|||
/etc/systemd/system/iomatex-mqtt-health.service
|
||||
/etc/systemd/system/iomatex-mqtt-health.timer
|
||||
/etc/sudoers.d/90-iomatex-mqtt-apply
|
||||
/var/lib/mosquitto/mosquitto.db
|
||||
/run/iomatex-mqtt-apply.sha
|
||||
/var/log/mosquitto/mosquitto.log
|
||||
/var/log/iomatex-stage1-mqtt.log
|
||||
)
|
||||
|
||||
step "Full cleanup of previous MQTT/IOMATEX artifacts"
|
||||
step "Replace MQTT tools while preserving registration and broker persistence"
|
||||
for unit in "${MQTT_STOP_UNITS[@]}"; do
|
||||
safe_systemctl stop "$unit"
|
||||
done
|
||||
|
|
@ -182,7 +180,7 @@ remove_if_exists /var/lib/mosquitto/*.db
|
|||
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
touch "$LOG" >/dev/null 2>&1 || true
|
||||
log "OK: cleaned mosquitto configs, iomatex tools/env, mosquitto DB, systemd units, and logs. Ready for clean install."
|
||||
log "OK: replaced generated MQTT artifacts; retained bridge credentials/settings and mosquitto persistence."
|
||||
|
||||
step "Install Mosquitto broker + clients"
|
||||
log "RUN: dpkg --configure -a || true"
|
||||
|
|
@ -194,6 +192,7 @@ apt_noninteractive install netcat-openbsd >/dev/null 2>&1 || true
|
|||
|
||||
step "Create directories and base env file"
|
||||
mkdir -p /etc/iomatex
|
||||
if [[ ! -f "$ENV_FILE" ]]; then
|
||||
cat >"$ENV_FILE" <<__IOMATEX_ENV__
|
||||
# IOMATEX MQTT bridge settings (parsed as key=value, NOT sourced)
|
||||
# ASCII recommended. No spaces around '='. Values may contain spaces (we do not source this file).
|
||||
|
|
@ -207,6 +206,7 @@ REMOTE_CLIENTID=${HOSTNAME_SHORT}
|
|||
LEGACY_ITSCREEN_TREE=1
|
||||
BRIDGE_BASE_TOPIC=v1/edge
|
||||
__IOMATEX_ENV__
|
||||
fi
|
||||
chmod 600 "$ENV_FILE"
|
||||
chown root:root "$ENV_FILE"
|
||||
|
||||
|
|
@ -394,6 +394,33 @@ check_remote(){
|
|||
log "Remote reachable OK"
|
||||
}
|
||||
|
||||
# Resolve the platform destination from the registered client's configuration.
|
||||
# Only use it for the same broker; during a server switch the previous prefix
|
||||
# must never be routed to the new cloud. No credentials are printed or sourced.
|
||||
platform_health_prefix(){
|
||||
python3 - "$REMOTE_HOST" "$REMOTE_PORT" "$REMOTE_TLS" <<'__PLATFORM_HEALTH_PREFIX__'
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
values = {}
|
||||
try:
|
||||
for line in Path("/var/lib/itscreen/config/it-screen/it-screen.conf").read_text().splitlines():
|
||||
key, sep, value = line.partition("=")
|
||||
if sep:
|
||||
values[key.strip()] = value.strip()
|
||||
except (OSError, UnicodeError):
|
||||
pass
|
||||
prefix = values.get("mqttPrefix", "").strip("/")
|
||||
host = values.get("mqttHost", "").lower().rstrip(".")
|
||||
if (host == sys.argv[1].lower().rstrip(".")
|
||||
and values.get("mqttPort") == sys.argv[2]
|
||||
and values.get("mqttTls", "0") == sys.argv[3]
|
||||
and re.fullmatch(r"[A-Za-z0-9_.:-]+(?:/[A-Za-z0-9_.:-]+)*", prefix)):
|
||||
print(prefix)
|
||||
__PLATFORM_HEALTH_PREFIX__
|
||||
}
|
||||
|
||||
write_bridge_conf(){
|
||||
rm -f "$BRIDGE_CONF" || true
|
||||
|
||||
|
|
@ -480,6 +507,16 @@ topic iomatex/+/client/sub/action/frames/# in 0 "" ""
|
|||
topic iomatex/+/client/sub/action/playlist/# in 0 "" ""
|
||||
__MAP__
|
||||
|
||||
# Keep the installed service/command namespace intact. Forward the same
|
||||
# heartbeat to the platform namespace. Explicit topics avoid overlapping
|
||||
# Mosquitto remap subscriptions swallowing one of the destinations.
|
||||
local platform_prefix
|
||||
platform_prefix="$(platform_health_prefix)"
|
||||
if [[ -n "$platform_prefix" && "$platform_prefix" != "$BRIDGE_BASE_TOPIC" ]]; then
|
||||
printf 'topic %s/health/%s out 1 "" ""\n' \
|
||||
"$platform_prefix" "$DEVICE_ID" >>"$BRIDGE_CONF"
|
||||
fi
|
||||
|
||||
if [[ "${LEGACY_ITSCREEN_TREE}" == "1" ]]; then
|
||||
cat >>"$BRIDGE_CONF" <<__LEGACY_ITSCREEN__
|
||||
|
||||
|
|
@ -570,6 +607,7 @@ report(){
|
|||
echo "Bridge enabled : ${ENABLE_BRIDGE:-0}"
|
||||
echo "Legacy it-screen: ${LEGACY_ITSCREEN_TREE:-0}"
|
||||
echo "Base topic : ${BRIDGE_BASE_TOPIC:-v1/edge}"
|
||||
echo "Platform health : $(platform_health_prefix)"
|
||||
echo
|
||||
echo "Bridge policy:"
|
||||
echo " OUT: ${BRIDGE_BASE_TOPIC}/health/${DEVICE_ID}"
|
||||
|
|
@ -823,6 +861,10 @@ if ! systemctl is-active --quiet mosquitto; then
|
|||
systemctl start mosquitto || systemctl restart mosquitto || true
|
||||
fi
|
||||
|
||||
# The shared apply owner reconciles the heartbeat route after client registration
|
||||
# changes, even when an older client does not track the bridge topic prefix.
|
||||
bridge_report="$(/usr/local/sbin/iomatex-mqtt-apply --print)"
|
||||
platform_prefix="$(printf '%s\n' "$bridge_report" | sed -n 's/^Platform health : //p')"
|
||||
h="$(resolve_edge_name)"
|
||||
BRIDGE_BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BRIDGE_BASE_TOPIC:=v1/edge}"
|
||||
boot_id="$(tr -d '\n\r' < /proc/sys/kernel/random/boot_id 2>/dev/null || true)"
|
||||
|
|
@ -886,6 +928,9 @@ __IOMATEX_HEALTH_JSON__
|
|||
topic="${BRIDGE_BASE_TOPIC}/health/${h}"
|
||||
|
||||
mosquitto_pub -h 127.0.0.1 -p 1883 -q 1 -r -t "${topic}" -m "${payload}"
|
||||
if [[ -n "$platform_prefix" && "$platform_prefix" != "$BRIDGE_BASE_TOPIC" ]]; then
|
||||
mosquitto_pub -h 127.0.0.1 -p 1883 -q 1 -r -t "${platform_prefix}/health/${h}" -m "${payload}"
|
||||
fi
|
||||
|
||||
finished_at_ms="$(date +%s%3N)"
|
||||
duration_ms="$((finished_at_ms - started_at_ms))"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,94 @@
|
|||
"""Execute the generated apply owner's real routing functions in an isolated FS."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).with_name('stage_mqtt_install.sh').read_text()
|
||||
APPLY = SOURCE.split("<<'__IOMATEX_APPLY__'\n", 1)[1].split('\n__IOMATEX_APPLY__', 1)[0]
|
||||
FUNCTIONS = APPLY[:APPLY.index('\nmain(){')]
|
||||
|
||||
|
||||
class HealthRouteTest(unittest.TestCase):
|
||||
def route(self, host='dev.iomatex.com', prefix='it-screen/dev', base='v1/edge', config_host=None, port='1883', config_port=None):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
config = Path(tmp) / 'client.conf'
|
||||
bridge = Path(tmp) / 'bridge.conf'
|
||||
config.write_text(f'mqttHost={config_host or host}\nmqttPrefix={prefix}\nmqttPort={config_port or port}\nmqttTls=0\n')
|
||||
code = FUNCTIONS.replace('/var/lib/itscreen/config/it-screen/it-screen.conf', str(config))
|
||||
code += '''
|
||||
chown(){ :; }
|
||||
chmod(){ :; }
|
||||
REMOTE_HOST="$AUDIT_HOST"
|
||||
REMOTE_PORT="$AUDIT_PORT"
|
||||
REMOTE_TLS=0
|
||||
REMOTE_USERNAME=test
|
||||
REMOTE_PASSWORD=test
|
||||
REMOTE_CLIENTID=g-box-deadbeef
|
||||
DEVICE_ID=g-box-deadbeef
|
||||
ENABLE_BRIDGE=1
|
||||
LEGACY_ITSCREEN_TREE=1
|
||||
BRIDGE_BASE_TOPIC="$AUDIT_BASE"
|
||||
BRIDGE_CONF="$AUDIT_BRIDGE"
|
||||
write_bridge_conf
|
||||
'''
|
||||
env = dict(os.environ, AUDIT_HOST=host, AUDIT_PORT=port, AUDIT_BASE=base, AUDIT_BRIDGE=str(bridge))
|
||||
subprocess.run(['bash'], input=code, text=True, env=env, check=True, capture_output=True)
|
||||
return bridge.read_text()
|
||||
|
||||
def test_default_service_namespace_routes_to_dev(self):
|
||||
text = self.route()
|
||||
self.assertIn('topic it-screen/dev/health/g-box-deadbeef out 1 "" ""', text)
|
||||
self.assertIn('topic v1/edge/command/g-box-deadbeef/# in 0', text)
|
||||
self.assertIn('topic it-screen/$devices/settings/g-box-deadbeef/sub in 0', text)
|
||||
self.assertIn('topic it-screen/+/$devices/settings/g-box-deadbeef/sub in 0', text)
|
||||
self.assertIn('topic it-screen/+/client/pub/component/notify/g-box-deadbeef/# out 0', text)
|
||||
|
||||
def test_console_already_selected_platform_has_no_duplicate(self):
|
||||
text = self.route(base='it-screen/dev')
|
||||
self.assertEqual(1, text.count('/health/g-box-deadbeef out 1'))
|
||||
self.assertIn('topic it-screen/dev/health/g-box-deadbeef out 1', text)
|
||||
|
||||
def test_new_cloud_uses_its_own_prefix(self):
|
||||
text = self.route(host='uae.iomatex.com', prefix='iomatex/ae')
|
||||
self.assertIn('topic iomatex/ae/health/g-box-deadbeef out 1', text)
|
||||
self.assertNotIn('topic it-screen/dev/health/', text)
|
||||
|
||||
def test_mid_switch_does_not_route_old_prefix_to_new_broker(self):
|
||||
self.assertNotIn('topic it-screen/dev/health/', self.route(host='uae.iomatex.com', config_host='dev.iomatex.com'))
|
||||
self.assertNotIn('topic it-screen/dev/health/', self.route(port='11883', config_port='1883'))
|
||||
|
||||
def test_invalid_and_unregistered_prefix_never_adds_wildcards(self):
|
||||
for prefix in ['', 'it-screen/+', 'it-screen/#', 'bad prefix']:
|
||||
with self.subTest(prefix=prefix):
|
||||
self.assertNotIn('topic it-screen/dev/health/', self.route(prefix=prefix))
|
||||
|
||||
def test_upgrade_preserves_registration_and_retained_store(self):
|
||||
cleanup = SOURCE.split('MQTT_CLEANUP_FILES=(', 1)[1].split('\n)', 1)[0]
|
||||
self.assertNotIn('/etc/iomatex/mqtt_bridge.env', cleanup)
|
||||
self.assertNotIn('/var/lib/mosquitto/mosquitto.db', cleanup)
|
||||
self.assertIn('if [[ ! -f "$ENV_FILE" ]]; then\ncat >"$ENV_FILE" <<__IOMATEX_ENV__', SOURCE)
|
||||
|
||||
def test_upgrade_executes_without_resetting_existing_env(self):
|
||||
block = SOURCE.split('step "Create directories and base env file"', 1)[1].split('step "Ensure mosquitto.conf', 1)[0]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
env_file = Path(tmp) / 'mqtt_bridge.env'
|
||||
original = 'ENABLE_BRIDGE=1\nREMOTE_HOST=dev.iomatex.com\nBRIDGE_BASE_TOPIC=it-screen/dev\nREMOTE_PASSWORD=test-secret\n'
|
||||
env_file.write_text(original)
|
||||
block = block.replace('mkdir -p /etc/iomatex', ':').replace('chown root:root "$ENV_FILE"', ':')
|
||||
subprocess.run(['bash'], input=block, text=True, check=True,
|
||||
env=dict(os.environ, ENV_FILE=str(env_file), HOSTNAME_SHORT='g-box-deadbeef'))
|
||||
self.assertEqual(original, env_file.read_text())
|
||||
env_file.unlink()
|
||||
subprocess.run(['bash'], input=block, text=True, check=True,
|
||||
env=dict(os.environ, ENV_FILE=str(env_file), HOSTNAME_SHORT='g-box-deadbeef'))
|
||||
self.assertIn('BRIDGE_BASE_TOPIC=v1/edge', env_file.read_text())
|
||||
|
||||
def test_heartbeat_reconciles_route_before_publishing(self):
|
||||
health = SOURCE.split("<<'__IOMATEX_HEALTH_SH__'\n", 1)[1].split('\n__IOMATEX_HEALTH_SH__', 1)[0]
|
||||
self.assertLess(health.index('/usr/local/sbin/iomatex-mqtt-apply --print'), health.index('mosquitto_pub'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue