From 010138e66697c1cd24eff2be16afb4a8dbde69df Mon Sep 17 00:00:00 2001 From: Mika Joenpera Date: Mon, 23 Oct 2023 12:39:49 +0300 Subject: [PATCH] Fix visualisation and remove phy from config - Alfred now start with own init.d - all configs done with based on the wifi interface name and phy is detected. Jira-Id: SCDI-43 Signed-off-by: Mika Joenpera --- common/scripts/mesh-11s_nats.sh | 25 +++---- .../src/nats/initd/S9011sNatsMesh | 22 +++--- .../src/nats/initd/S90Alfred | 70 +++++++++++++++++++ .../src/nats/requirements/requirements.txt | 3 +- .../src/nats/scripts/cli_settings_request.py | 5 +- .../nats/scripts/cli_settings_request_mcc.py | 29 -------- .../nats/scripts/cli_settings_request_scc.py | 29 -------- .../scripts/cli_subscribe_settings_csa.py | 56 --------------- .../src/nats/src/comms_settings.py | 18 ++--- .../src/nats/src/validation.py | 16 ++--- modules/utils/docker/entrypoint_nats.sh | 4 ++ 11 files changed, 119 insertions(+), 158 deletions(-) create mode 100644 modules/sc-mesh-secure-deployment/src/nats/initd/S90Alfred delete mode 100644 modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_mcc.py delete mode 100644 modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_scc.py delete mode 100644 modules/sc-mesh-secure-deployment/src/nats/scripts/cli_subscribe_settings_csa.py diff --git a/common/scripts/mesh-11s_nats.sh b/common/scripts/mesh-11s_nats.sh index ebbdd5243..98d4de7b2 100755 --- a/common/scripts/mesh-11s_nats.sh +++ b/common/scripts/mesh-11s_nats.sh @@ -38,6 +38,10 @@ add_network_intf_to_bridge() { _bridge_name=$1 _interfaces=$2 + _lan1=0 + if [[ "$_interfaces" == *"lan1"* ]]; then + _lan1=1 + fi # Loop through the interface names and add them to the bridge if available for _interface in $_interfaces; do # Check if the interface exists @@ -48,6 +52,11 @@ add_network_intf_to_bridge() { echo "Interface $_interface not found. Skipping." fi done + + if [ "$_lan1" -eq 1 ]; then + # Add lan1 to bridge + brctl delif "$_bridge_name" eth0 2>/dev/null + fi } fix_iface_mac_addresses() { @@ -237,17 +246,11 @@ EOF ifconfig "$bridge_name" up echo ifconfig "$bridge_name" + fix_iface_mac_addresses if [ "$routing_algo" == "batman-adv" ]; then sleep 3 # for visualisation - if ps aux | grep -q "[a]lfred -i $bridge_name -m"; then - echo "alfred is already running." - else - (alfred -i "$bridge_name" -m)& - echo "started alfred" - fi - if ps aux | grep -q "[b]atadv-vis -i $batman_iface -s"; then echo "batadv-vis is already running." else @@ -358,17 +361,11 @@ EOF ifconfig "$bridge_name" up echo ifconfig "$bridge_name" + fix_iface_mac_addresses if [ "$routing_algo" == "batman-adv" ]; then sleep 3 # for visualisation - if ps aux | grep -q "[a]lfred -i $bridge_name -m"; then - echo "alfred is already running." - else - (alfred -i "$bridge_name" -m)& - echo "started alfred" - fi - if ps aux | grep -q "[b]atadv-vis -i $batman_iface -s"; then echo "batadv-vis is already running." else diff --git a/modules/sc-mesh-secure-deployment/src/nats/initd/S9011sNatsMesh b/modules/sc-mesh-secure-deployment/src/nats/initd/S9011sNatsMesh index 4bd03236a..ded58882a 100644 --- a/modules/sc-mesh-secure-deployment/src/nats/initd/S9011sNatsMesh +++ b/modules/sc-mesh-secure-deployment/src/nats/initd/S9011sNatsMesh @@ -24,17 +24,23 @@ _MODE="${RADIO_INDEX}_MODE" PIDFILE="/var/run/${DAEMON}_${RADIO_INDEX}.pid" LOG_FILE=/opt/mesh_11s_${RADIO_INDEX}.log +SYNC_LOCK="/var/run/mesh_start.lock" + # shellcheck source=/dev/null [ -r "/etc/default/$DAEMON" ] && . "/etc/default/$DAEMON" start() { - - while [ -f "/var/run/nats.pid" ]; do - random_number=$(( (RANDOM % 5) + 1 )) - sleep $random_number - done - - echo $$ > /var/run/nats.pid + if mkdir $SYNC_LOCK 2>/dev/null; then + echo "I have a lock $RADIO_INDEX PID $$" + else + echo "Instance is already running. Waiting..." + # Wait for the lock directory to be removed, indicating the previous instance finished + while [ -d "$SYNC_LOCK" ]; do + sleep $(( (RANDOM % 5) + 1 )) + done + mkdir "$SYNC_LOCK" + echo "I have a lock $$" + fi printf 'Starting %s: ' "$DAEMON" if [ "${!_MODE}" == "ap+mesh_scc" ] || [ "${!_MODE}" == "ap+mesh_mcc" ]; then @@ -50,7 +56,7 @@ start() { echo "FAIL" fi - rm /var/run/nats.pid + rmdir "$SYNC_LOCK" return "$status" } diff --git a/modules/sc-mesh-secure-deployment/src/nats/initd/S90Alfred b/modules/sc-mesh-secure-deployment/src/nats/initd/S90Alfred new file mode 100644 index 000000000..8780331cb --- /dev/null +++ b/modules/sc-mesh-secure-deployment/src/nats/initd/S90Alfred @@ -0,0 +1,70 @@ +#!/bin/bash +### BEGIN INIT INFO +# Provides: S90Alfred +# Short-Description: alfred +# Description: Starts alfred to provide visualization data +### END INIT INFO + +DAEMON="alfred" +DIR="/usr/bin/" +PIDFILE="/var/run/$DAEMON.pid" +# shellcheck source=/dev/null +[ -r "/etc/default/$DAEMON" ] && . "/etc/default/$DAEMON" +LOG_FILE=/opt/alfred.log + +source /opt/mesh-helper.sh +# sources mesh configuration +source_configuration "id0" +bridge_name=$(echo "$BRIDGE" | cut -d' ' -f1) + +ARGS="-i $bridge_name -m" + +wait_for_bridge() { + while [ ! -d "/sys/class/net/$bridge_name" ]; do + sleep 1 + done +} + +start() { + echo "$ARGS" + printf 'Starting %s: ' "$DAEMON" + start-stop-daemon -b -m -S -q -p "$PIDFILE" -a /bin/bash -- -c "exec $DIR$DAEMON \ + $ARGS > $LOG_FILE 2>&1" + status=$? + if [ "$status" -eq 0 ]; then + echo "OK" + else + echo "FAIL" + fi + return "$status" +} +stop() { + printf 'Stopping %s: ' "$DAEMON" + start-stop-daemon -K -q -p "$PIDFILE" + status=$? + if [ "$status" -eq 0 ]; then + rm -f "$PIDFILE" + echo "OK" + else + echo "FAIL" + fi + return "$status" +} +restart() { + stop + sleep 1 + start +} +case "$1" in + start|stop|restart) + "$1";; + reload) + # Restart, since there is no true "reload" feature. + restart;; + *) + echo "Usage: $0 {start|stop|restart|reload}" + exit 1 +esac + +exit 0 + diff --git a/modules/sc-mesh-secure-deployment/src/nats/requirements/requirements.txt b/modules/sc-mesh-secure-deployment/src/nats/requirements/requirements.txt index a7d2b4b52..7ee6da723 100644 --- a/modules/sc-mesh-secure-deployment/src/nats/requirements/requirements.txt +++ b/modules/sc-mesh-secure-deployment/src/nats/requirements/requirements.txt @@ -1,4 +1,5 @@ cryptography==3.4.8 PyKCS11==1.5.11 requests==2.31.0 -pycryptodome==3.18.0 \ No newline at end of file +pycryptodome==3.18.0 +nats-py==2.1.7 \ No newline at end of file diff --git a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request.py b/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request.py index c69522e04..30cf29d5b 100644 --- a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request.py +++ b/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request.py @@ -25,7 +25,6 @@ async def main(): "tx_power": "15", "mode": "mesh", # ap+mesh_scc, mesh, halow "mesh_vif": "wlp2s0", - "phy": "phy2", # TODO: NOT_USED "batman_iface": "bat0", }, { @@ -43,7 +42,6 @@ async def main(): "tx_power": "15", "mode": "mesh", # ap+mesh_scc, mesh, halow "mesh_vif": "wlp3s0", # this needs to be correct - "phy": "phy0", # TODO: NOT_USED "batman_iface": "bat0", }, { @@ -61,11 +59,10 @@ async def main(): "tx_power": "30", "mode": "halow", # ap+mesh_scc, mesh, halow "mesh_vif": "halow1", - "phy": "phy2", # TODO: NOT_USED "batman_iface": "bat0", }, ], - "bridge": "br-lan bat0 eth1 lan1" + "bridge": "br-lan bat0 eth1 lan1 eth0 usb0" } cmd = json.dumps(cmd_dict) diff --git a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_mcc.py b/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_mcc.py deleted file mode 100644 index 841802a75..000000000 --- a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_mcc.py +++ /dev/null @@ -1,29 +0,0 @@ -import asyncio -import client -import json -import config - - -async def main(): - # Connect to NATS! - nc = await client.connect_nats() - cmd_dict = {"api_version": 1, "ssid": "test_mesh", "key": "1234567890", - "ap_mac": "00:11:22:33:44:55", "country": "FI", "frequency": "5220", - "frequency_mcc": "2412", "routing": "batman-adv", "priority": "long_range", - "ip": "192.168.1.2", "subnet": "255.255.255.0", "tx_power": "5", - "mode": "ap+mesh_mcc", "role": f"{config.MODULE_ROLE}"} - cmd = json.dumps(cmd_dict) - rep = await nc.request(f"comms.settings.{config.MODULE_IDENTITY}", - cmd.encode(), - timeout=2) - parameters = json.loads(rep.data) - print(parameters) - - await nc.close() - exit(0) - - -if __name__ == '__main__': - loop = asyncio.get_event_loop() - loop.run_until_complete(main()) - loop.close() diff --git a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_scc.py b/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_scc.py deleted file mode 100644 index 4bff03be5..000000000 --- a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_settings_request_scc.py +++ /dev/null @@ -1,29 +0,0 @@ -import asyncio -import client -import json -import config - - -async def main(): - # Connect to NATS! - nc = await client.connect_nats() - cmd_dict = {"api_version": 1, "ssid": "test_mesh", "key": "1234567890", - "ap_mac": "00:11:22:33:44:55", "country": "FI", "frequency": "5220", - "frequency_mcc": "2412", "routing": "batman-adv", "priority": "long_range", - "ip": "192.168.1.2", "subnet": "255.255.255.0", "tx_power": "5", - "mode": "ap+mesh_scc", "role": f"{config.MODULE_ROLE}"} - cmd = json.dumps(cmd_dict) - rep = await nc.request(f"comms.settings.{config.MODULE_IDENTITY}", - cmd.encode(), - timeout=2) - parameters = json.loads(rep.data) - print(parameters) - - await nc.close() - exit(0) - - -if __name__ == '__main__': - loop = asyncio.get_event_loop() - loop.run_until_complete(main()) - loop.close() diff --git a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_subscribe_settings_csa.py b/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_subscribe_settings_csa.py deleted file mode 100644 index ba3ac16a6..000000000 --- a/modules/sc-mesh-secure-deployment/src/nats/scripts/cli_subscribe_settings_csa.py +++ /dev/null @@ -1,56 +0,0 @@ -import asyncio -import signal -import json -from nats.aio.client import Client as NATS -import client - - -async def run(loop): - nc = NATS() - - async def error_cb(e): - print("Error:", e) - - async def closed_cb(): - print("Connection to NATS is closed.") - if nc.is_closed: - return - await nc.close() - - async def reconnected_cb(): - print("Connected to NATS ...") - - async def subscribe_handler(msg): - subject = msg.subject - reply = msg.reply - data = json.loads(msg.data.decode()) - print("Received a message on '{subject} {reply}': {data}".format( - subject=subject, reply=reply, data=data)) - - try: - await client.connect(nc, reconnected_cb=reconnected_cb, - closed_cb=closed_cb, - max_reconnect_attempts=-1) - except Exception as e: - print(e) - - print(f"Connected to NATS at: {nc.connected_url.netloc}") - - def signal_handler(): - if nc.is_closed: - return - print("Disconnecting...") - loop.create_task(nc.close()) - - for sig in ('SIGINT', 'SIGTERM'): - loop.add_signal_handler(getattr(signal, sig), signal_handler) - - await nc.subscribe("comms.settings_csa", "", cb=subscribe_handler) - -if __name__ == '__main__': - loop = asyncio.get_event_loop() - loop.run_until_complete(run(loop)) - try: - loop.run_forever() - finally: - loop.close() diff --git a/modules/sc-mesh-secure-deployment/src/nats/src/comms_settings.py b/modules/sc-mesh-secure-deployment/src/nats/src/comms_settings.py index 07fa8bf78..d89317418 100644 --- a/modules/sc-mesh-secure-deployment/src/nats/src/comms_settings.py +++ b/modules/sc-mesh-secure-deployment/src/nats/src/comms_settings.py @@ -40,7 +40,7 @@ def __init__(self, comms_status: [cs.CommsStatus, ...], logger): self.priority = [] self.role: str = "" self.mesh_vif = [] - self.phy = [] + # self.phy = [] self.batman_iface = [] self.bridge: str = "" self.msversion: str = "" @@ -110,9 +110,9 @@ def validate_mesh_settings(self, index: int) -> (str, str): return "FAIL", "Invalid mesh vif" self.logger.debug("validate mesh settings mesh vif ok") - if validation.validate_phy(self.phy[index]) is False: - return "FAIL", "Invalid phy" - self.logger.debug("validate mesh settings phy ok") + # if validation.validate_phy(self.phy[index]) is False: + # return "FAIL", "Invalid phy" + # self.logger.debug("validate mesh settings phy ok") if validation.validate_batman_iface(self.batman_iface[index]) is False: return "FAIL", "Invalid batman iface" @@ -138,7 +138,7 @@ def __clean_all_settings(self) -> None: self.routing = [] self.priority = [] self.mesh_vif = [] - self.phy = [] + # self.phy = [] self.batman_iface = [] def handle_mesh_settings(self, msg: str, path="/opt", @@ -173,7 +173,7 @@ def handle_mesh_settings(self, msg: str, path="/opt", self.routing.append(quote(str(parameters["routing"]))) self.priority.append(quote(str(parameters["priority"]))) self.mesh_vif.append(quote(str(parameters["mesh_vif"]))) - self.phy.append(quote(str(parameters["phy"]))) + # self.phy.append(quote(str(parameters["phy"]))) self.batman_iface.append(quote(str(parameters["batman_iface"]))) self.bridge = quote(str(parameters_set["bridge"])) @@ -223,7 +223,7 @@ def __save_settings(self, path: str, file: str, index: int) -> (str, str): mesh_conf.write(f"id{str(index)}_ROUTING={quote(self.routing[index])}\n") mesh_conf.write(f"id{str(index)}_PRIORITY={quote(self.priority[index])}\n") mesh_conf.write(f"id{str(index)}_MESH_VIF={quote(self.mesh_vif[index])}\n") - mesh_conf.write(f"id{str(index)}_PHY={quote(self.phy[index])}\n") + # mesh_conf.write(f"id{str(index)}_PHY={quote(self.phy[index])}\n") mesh_conf.write(f"id{str(index)}_BATMAN_IFACE={quote(self.batman_iface[index])}\n") mesh_conf.write(f"BRIDGE={self.bridge}\n") @@ -272,8 +272,8 @@ def __read_configs(self, mesh_conf_lines) -> None: self.priority.append(match[1]) elif name == "MESH_VIF": self.mesh_vif.append(match[1]) - elif name == "PHY": - self.phy.append(match[1]) + # elif name == "PHY": + # self.phy.append(match[1]) elif name == "BATMAN_IFACE": self.batman_iface.append(match[1]) else: diff --git a/modules/sc-mesh-secure-deployment/src/nats/src/validation.py b/modules/sc-mesh-secure-deployment/src/nats/src/validation.py index 7b313cfce..8a5084548 100644 --- a/modules/sc-mesh-secure-deployment/src/nats/src/validation.py +++ b/modules/sc-mesh-secure-deployment/src/nats/src/validation.py @@ -250,14 +250,14 @@ def validate_radio_index(radio_index: str) -> bool: except (ValueError, TypeError, AttributeError): return False -def validate_phy(phy: str) -> bool: - """ - Validates a given phy. - Returns True if the phy is valid, False otherwise. - """ - if "phy" in phy and int(phy.replace("phy", "")) >= 0: - return True - return False +# def validate_phy(phy: str) -> bool: +# """ +# Validates a given phy. +# Returns True if the phy is valid, False otherwise. +# """ +# if "phy" in phy and int(phy.replace("phy", "")) >= 0: +# return True +# return False def validate_mesh_vif(mesh_vif: str) -> bool: """ diff --git a/modules/utils/docker/entrypoint_nats.sh b/modules/utils/docker/entrypoint_nats.sh index fce15b13b..394695d26 100755 --- a/modules/utils/docker/entrypoint_nats.sh +++ b/modules/utils/docker/entrypoint_nats.sh @@ -50,6 +50,10 @@ else sleep 1 done + sleep 3 + + /opt/S90Alfred start + echo "starting provisioning agent" # blocks execution until provisioning is done or timeout (30s) # IP address and port are passed as arguments and hardcoded. TODO: mDNS