Add comprehensive smoke and feature tests for Gateway API
- Introduced LtdFeatureTests to validate BACnet and OPC UA point updates, trend logging, and alarm rule functionality. - Added OpcUaClientTests to ensure proper OPC UA client configuration, point value synchronization, and session management. - Created OpcUaFeatureTests to test OPC UA server capabilities, including browsing, reading, writing, and subscription notifications. - Implemented native_bacnet_test.py for isolated BACnet wire testing, covering discovery, read/write operations, and command processing. - Added ui-theme-tabs.test.cjs to verify theme switching, tab interactions, and protocol form accessibility in the UI.
This commit is contained in:
1 parent
d9165a60ff
commit
98c48d9d78
80 files changed
+11120
-315
No files matched your search
@@ -0,0 +1,50 @@
|
||||
{ stdenv, fetchzip, cmake, perl, sqlite }:
|
||||
stdenv.mkDerivation {
|
||||
pname = "seiugw-bacnet";
|
||||
version = "1.7.0-0bfe656";
|
||||
src = fetchzip {
|
||||
extension = "tar.gz";
|
||||
url = "https://codeload.github.com/bacnet-stack/bacnet-stack/tar.gz/0bfe65645ff7238e15121a6727870f96413ac22e";
|
||||
sha256 = "1yjdj0brziizrxqxf14z25yl6hgqjn07jci2d080llj391vyzxhi";
|
||||
};
|
||||
nativeBuildInputs = [ cmake perl ];
|
||||
buildInputs = [ sqlite ];
|
||||
postPatch = ''
|
||||
cp ${../native/bacnet/gateway_bridge.c} apps/server/gateway_bridge.c
|
||||
cp ${../native/bacnet/gateway_bridge.h} apps/server/gateway_bridge.h
|
||||
substituteInPlace apps/server/main.c \
|
||||
--replace-fail '#include <stdio.h>' '#include <stdio.h>
|
||||
#include "gateway_bridge.h"' \
|
||||
--replace-fail 'Device_Init(NULL);' 'Gateway_Init();' \
|
||||
--replace-fail 'dlenv_init();' 'Gateway_Configure(); dlenv_init(); Gateway_Network_Ready();' \
|
||||
--replace-fail 'Device_Timer(elapsed_milliseconds);' 'Device_Timer(elapsed_milliseconds); Gateway_Tick();'
|
||||
perl -0pi -e 's@ /\* create some dynamically created objects as examples \*/.*?(?= /\* set up our confirmed)@@s or die "example block missing"' apps/server/main.c
|
||||
# Object lifecycle belongs to the gateway DB, not the example Create/Delete service.
|
||||
perl -0pi -e 's@ apdu_set_confirmed_handler\(\s*SERVICE_CONFIRMED_(CREATE|DELETE)_OBJECT, handler_(create|delete)_object\);@@g' apps/server/main.c
|
||||
substituteInPlace src/bacnet/basic/bbmd/h_bbmd.c \
|
||||
--replace-fail '#include <stdio.h>' '#include <stdlib.h>
|
||||
#include <stdio.h>' \
|
||||
--replace-fail 'return bvlc_bbmd_enabled_handler(addr, src, npdu, npdu_len);' 'if (getenv("SEIUGW_BBMD_MODE") && strcmp(getenv("SEIUGW_BBMD_MODE"), "Bbmd")) return bvlc_bbmd_disabled_handler(addr, src, npdu, npdu_len);
|
||||
return bvlc_bbmd_enabled_handler(addr, src, npdu, npdu_len);'
|
||||
substituteInPlace CMakeLists.txt \
|
||||
--replace-fail 'add_executable(server apps/server/main.c)' 'add_executable(server apps/server/main.c apps/server/gateway_bridge.c)
|
||||
target_link_libraries(server PRIVATE sqlite3)'
|
||||
'';
|
||||
cmakeFlags = [
|
||||
"-DBACDL_BIP6=OFF" "-DBAC_ROUTING=OFF"
|
||||
"-DCMAKE_C_FLAGS=-DBACNET_OBJECT_ANALOG_VALUE_COMMANDABLE=1 -DBACNET_OBJECT_BINARY_VALUE_COMMANDABLE=1 -DBACNET_OBJECT_MULTISTATE_VALUE_COMMANDABLE=1 -DBACNET_ADDRESS_CACHE_FILE=1"
|
||||
];
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
cmake --build . --target server readprop writeprop scov whois --parallel $NIX_BUILD_CORES
|
||||
runHook postBuild
|
||||
'';
|
||||
installPhase = ''
|
||||
mkdir -p $out/bin
|
||||
install -m755 server $out/bin/bacserv
|
||||
install -m755 readprop $out/bin/bacrp
|
||||
install -m755 writeprop $out/bin/bacwp
|
||||
install -m755 scov $out/bin/bacscov
|
||||
install -m755 whois $out/bin/bacwi
|
||||
'';
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Minimal persistent NixOS base system used before the gateway module is added.
|
||||
{ pkgs, ... }:
|
||||
|
||||
{
|
||||
imports = [ ./hardware-configuration.nix ];
|
||||
|
||||
boot.loader.systemd-boot.enable = true;
|
||||
boot.loader.efi.canTouchEfiVariables = true;
|
||||
|
||||
networking.hostName = "seiugw-bootstrap";
|
||||
networking.useDHCP = true;
|
||||
networking.firewall.allowedTCPPorts = [ 22 ];
|
||||
|
||||
time.timeZone = "Europe/Berlin";
|
||||
i18n.defaultLocale = "de_DE.UTF-8";
|
||||
console.keyMap = "de";
|
||||
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
settings = {
|
||||
PermitRootLogin = "yes";
|
||||
PasswordAuthentication = true;
|
||||
KbdInteractiveAuthentication = false;
|
||||
};
|
||||
};
|
||||
|
||||
environment.systemPackages = with pkgs; [ git curl vim ];
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
|
||||
system.stateVersion = "26.05";
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Hardware profile for the initial Hyper-V deployment. Filesystems use labels so
|
||||
# the installation remains independent of the virtual disk's UUIDs.
|
||||
{ lib, ... }:
|
||||
|
||||
{
|
||||
boot.initrd.availableKernelModules = [ "sd_mod" "sr_mod" ];
|
||||
|
||||
fileSystems."/" = {
|
||||
device = "/dev/disk/by-label/nixos";
|
||||
fsType = "ext4";
|
||||
};
|
||||
|
||||
fileSystems."/boot" = {
|
||||
device = "/dev/disk/by-label/EFI";
|
||||
fsType = "vfat";
|
||||
options = [ "fmask=0022" "dmask=0022" ];
|
||||
};
|
||||
|
||||
swapDevices = [ { device = "/dev/disk/by-label/swap"; } ];
|
||||
|
||||
nixpkgs.hostPlatform = lib.mkDefault "x86_64-linux";
|
||||
virtualisation.hypervGuest.enable = true;
|
||||
}
|
||||
+145
@@ -14,6 +14,16 @@
|
||||
"version": "5.2.0.1603",
|
||||
"hash": "sha256-w5T7ekYwVGg+Zs8uolvcWFyY+r9duni0qIigxgHgIdw="
|
||||
},
|
||||
{
|
||||
"pname": "NModbus",
|
||||
"version": "3.0.83",
|
||||
"hash": "sha256-V9+Bnt+b4yqRJNPXrDrhOKUqtEllcGPVicqKrthrpgk="
|
||||
},
|
||||
{
|
||||
"pname": "NModbus.Serial",
|
||||
"version": "3.0.83",
|
||||
"hash": "sha256-Z6Yk8IozblLq3obdx/GXTqT/hSMTaTf8UkleJpcNYwQ="
|
||||
},
|
||||
{
|
||||
"pname": "SQLitePCLRaw.bundle_e_sqlite3",
|
||||
"version": "2.1.12",
|
||||
@@ -38,5 +48,140 @@
|
||||
"pname": "System.Memory",
|
||||
"version": "4.5.3",
|
||||
"hash": "sha256-Cvl7RbRbRu9qKzeRBWjavUkseT2jhZBUWV1SPipUWFk="
|
||||
},
|
||||
{
|
||||
"pname": "System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-G8j9c0erBzZfJAVlW08XoE58gPhiNWJE78sFaBV2e4Q="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-BqExVU/zHj7o++mzOpY9y+i9yZZVbcGmO/D4mRzigY8="
|
||||
},
|
||||
{
|
||||
"pname": "BitFaster.Caching",
|
||||
"version": "2.6.0",
|
||||
"hash": "sha256-cF3SDKbopdWPiZ7Wrx5Uh7PXxohUoVPAVCkmjeBwPPw="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.DependencyInjection",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-eKex/vpm5A4o2WV6sJyjqKPydWhekJFO6wrH0V7RyBY="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.DependencyInjection.Abstractions",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-HV30fu+lF/GYkeVP+Yq/EU1FzgdMqwqlepCpvxUgugE="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.Logging",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-wcnZWJDQGe6iTd7SIvcbyZLO+Lyc3zCKWlYYP8ovA44="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.Logging.Abstractions",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-VruWNhGycjxU2+BxiE++Aw2Tzv50lARcslDp66ImCDE="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.Options",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-KHcgAMsOPgjK0ly34mAt3/1hPA4XDSltXUNrEjSNnh8="
|
||||
},
|
||||
{
|
||||
"pname": "Microsoft.Extensions.Primitives",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-LJFzI1nODfakvP3owQn8xwVKliRxIYs6nl19xAbxKOc="
|
||||
},
|
||||
{
|
||||
"pname": "Newtonsoft.Json",
|
||||
"version": "13.0.4",
|
||||
"hash": "sha256-8JCB1FdAW681qXP6DFDWvycu1oPyVoxaYgpJ2pUvZSk="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Client",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-/UD3bbZC4fDNUvR5pP12NxsnFrzASdxho2I2kDqNZqw="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Configuration",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-T71KTHoti4q4hphw/SGFVl8FipOE/MSVXDnTWIz+ee4="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Core",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-Uxk7j7t65dez3rbOiTYQj5FljT7DxLqUs7pwtF4n1pw="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Security.Certificates",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-8SCA9p/Wp1x3hP3wQbAi2jcj+fCcBjlZ6tsLNRLUNSc="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Server",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-wiaT8XHzRaWoH487f4ulJoMZB4rdBoAyOxjlCLrs5ZQ="
|
||||
},
|
||||
{
|
||||
"pname": "OPCFoundation.NetStandard.Opc.Ua.Types",
|
||||
"version": "1.5.378.182",
|
||||
"hash": "sha256-3f14kZ6NffAXLT+tcpSfHW0KeIeHp0wGZdBhgsW2IEA="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.linux-arm.runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-m5+od7ZhlzImwSE9E7Qq1nH3A3muXwCnsvrVUoJ7+WE="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.linux-arm64.runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-IgbG3HT3A0VItWl5asE7Hk0zaQjQneKQS9f65cQAjLI="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.linux-x64.runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-44oujSHhc0Nl2WCvLYkScrAyqNAlbGfOnlzPwCofwlA="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.osx-arm64.runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-oFMF60yyTy3fXwLlXJkNUtzdRz4EyxevAUIcfcVESCE="
|
||||
},
|
||||
{
|
||||
"pname": "runtime.osx-x64.runtime.native.System.IO.Ports",
|
||||
"version": "8.0.0",
|
||||
"hash": "sha256-b2J9DcunMtChpuyNC0XN39Z01Wr738HI/syJW1n9bfE="
|
||||
},
|
||||
{
|
||||
"pname": "System.Collections.Immutable",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-HTsGt7wf5O54IXUvy3UeIrzJn+ICRlRbwU60d5YH33I="
|
||||
},
|
||||
{
|
||||
"pname": "System.Diagnostics.DiagnosticSource",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-WUukX2DEBYxDiJVcGosDMfq16sarrbDGtzq7p5WC7EE="
|
||||
},
|
||||
{
|
||||
"pname": "System.Formats.Asn1",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-WPATl+pz3/qYhOtp6GQNlWlZpkwUgBpEYPc9taU1VYg="
|
||||
},
|
||||
{
|
||||
"pname": "System.IO.Pipelines",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-/7LqBohsw/Z6/2tDUKoLjQyR8mEbvk4vU2t83EcB2ag="
|
||||
},
|
||||
{
|
||||
"pname": "System.Text.Encodings.Web",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-HGgwNazFJc8PPhjA3p4P3Zgc/Zg8KOk+0uruWPHuo3M="
|
||||
},
|
||||
{
|
||||
"pname": "System.Text.Json",
|
||||
"version": "10.0.8",
|
||||
"hash": "sha256-RTXz0xPQalhyyRLXiu6reSl+dsUXE58GzjYmPP9+hYU="
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
{ ... }:
|
||||
|
||||
{
|
||||
imports = [
|
||||
(builtins.getFlake "path:/etc/nixos/seiugw").nixosModules.default
|
||||
];
|
||||
|
||||
services.seiugw = {
|
||||
enable = true;
|
||||
bacnet.interface = "eth0";
|
||||
bacnet.deviceInstance = 23;
|
||||
bacnet.ipPort = 47808;
|
||||
webPort = 8088;
|
||||
openFirewall = true;
|
||||
trends = {
|
||||
enable = true;
|
||||
databaseName = "wago";
|
||||
};
|
||||
komari = {
|
||||
enable = true;
|
||||
endpoint = "https://komari.cloud.se-inno.de";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
"""Apply and confirm per-interface IPv4 profiles using the existing dhcpcd unit."""
|
||||
|
||||
import fnmatch
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
BASE = Path(sys.argv[2])
|
||||
IP = sys.argv[3]
|
||||
SYSTEMCTL = sys.argv[4]
|
||||
STATE = Path("/var/lib/seiugw-network")
|
||||
RUN = Path("/run/seiugw-network")
|
||||
CONFIRMED = STATE / "profiles.json"
|
||||
EFFECTIVE = RUN / "dhcpcd.conf"
|
||||
TRIAL = RUN / "trial"
|
||||
TRIAL_SECONDS = 120
|
||||
|
||||
|
||||
def atomic_write(path, content, mode=0o600):
|
||||
temporary = path.with_suffix(".tmp")
|
||||
with temporary.open("w", encoding="utf-8") as output:
|
||||
os.fchmod(output.fileno(), mode)
|
||||
output.write(content)
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
temporary.replace(path)
|
||||
directory = os.open(path.parent, os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def configuration(profiles):
|
||||
lines = [BASE.read_text(), "# IPv4 profiles managed by SE-Inno Universalgateway"]
|
||||
for name, profile in sorted(profiles.items()):
|
||||
lines.extend(["", f"interface {name}", f"metric {profile['metric']}"])
|
||||
if profile["mode"] == "static":
|
||||
lines.append(f"static ip_address={profile['address']}/{profile['prefixLength']}")
|
||||
if profile["gateway"]:
|
||||
lines.append(f"static routers={profile['gateway']}")
|
||||
if profile["dns"]:
|
||||
lines.append("static domain_name_servers=" + " ".join(profile["dns"]))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def install(profiles):
|
||||
atomic_write(EFFECTIVE, configuration(profiles), 0o644)
|
||||
|
||||
|
||||
def configured_profiles():
|
||||
return json.loads(CONFIRMED.read_text()) if CONFIRMED.exists() else {}
|
||||
|
||||
|
||||
def ip_json(*args):
|
||||
return json.loads(subprocess.check_output([IP, "-j", "-4", *args], timeout=3))
|
||||
|
||||
|
||||
def inventory():
|
||||
settings = {}
|
||||
for line in BASE.read_text().splitlines():
|
||||
words = line.partition("#")[0].split()
|
||||
if words and words[0] in ("allowinterfaces", "denyinterfaces"):
|
||||
settings.setdefault(words[0], []).extend(words[1:])
|
||||
allowed = settings.get("allowinterfaces", [])
|
||||
denied = settings.get("denyinterfaces", [])
|
||||
routes = ip_json("route", "show", "default")
|
||||
cards = {}
|
||||
for link in ip_json("address", "show"):
|
||||
name = link["ifname"]
|
||||
device = Path("/sys/class/net") / name
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith("-"):
|
||||
continue
|
||||
if not (device / "device").exists() or (device / "type").read_text().strip() != "1":
|
||||
continue
|
||||
if any(fnmatch.fnmatchcase(name, pattern) for pattern in denied):
|
||||
continue
|
||||
if allowed and not any(fnmatch.fnmatchcase(name, pattern) for pattern in allowed):
|
||||
continue
|
||||
ipv4 = [{"address": info["local"], "prefixLength": info["prefixlen"],
|
||||
"dynamic": info.get("dynamic", False)}
|
||||
for info in link["addr_info"] if info["family"] == "inet" and info.get("scope") == "global"]
|
||||
cards[name] = {"name": name, "macAddress": (device / "address").read_text().strip(),
|
||||
"addresses": ipv4, "routes": [route for route in routes if route.get("dev") == name]}
|
||||
return cards
|
||||
|
||||
|
||||
def unicast(value):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError("Eine gültige IPv4-Adresse ist erforderlich.")
|
||||
address = ipaddress.IPv4Address(value)
|
||||
if address.is_unspecified or address.is_multicast or address.is_loopback or address.is_reserved:
|
||||
raise ValueError("Eine nutzbare IPv4-Adresse ist erforderlich.")
|
||||
return address
|
||||
|
||||
|
||||
def validate(profile, cards, profiles):
|
||||
name = profile.get("interface")
|
||||
if not isinstance(name, str) or name not in cards:
|
||||
raise ValueError("Diese Netzwerkkarte kann nicht verwaltet werden.")
|
||||
mode = profile.get("mode")
|
||||
metric = profile.get("metric")
|
||||
if mode not in ("dhcp", "static") or type(metric) is not int or not 1 <= metric <= 65535:
|
||||
raise ValueError("Bitte Modus und Routenmetrik (1–65535) prüfen.")
|
||||
result = {"interface": name, "mode": mode, "metric": metric, "address": None,
|
||||
"prefixLength": None, "gateway": None, "dns": []}
|
||||
if mode == "dhcp":
|
||||
return result
|
||||
|
||||
address = unicast(profile.get("address"))
|
||||
prefix = profile.get("prefixLength")
|
||||
if type(prefix) is not int or not 1 <= prefix <= 32:
|
||||
raise ValueError("Die Präfixlänge muss zwischen 1 und 32 liegen.")
|
||||
subnet = ipaddress.IPv4Network((address, prefix), strict=False)
|
||||
if prefix <= 30 and address in (subnet.network_address, subnet.broadcast_address):
|
||||
raise ValueError("Die Adresse darf keine Netz- oder Broadcast-Adresse sein.")
|
||||
gateway = unicast(profile["gateway"]) if profile.get("gateway") else None
|
||||
if gateway is not None and (gateway not in subnet or gateway == address or
|
||||
(prefix <= 30 and gateway in (subnet.network_address, subnet.broadcast_address))):
|
||||
raise ValueError("Das Standardgateway muss eine andere nutzbare Adresse im selben Subnetz sein.")
|
||||
dns = profile.get("dns") or []
|
||||
if not isinstance(dns, list) or len(dns) > 4:
|
||||
raise ValueError("Bis zu vier IPv4-DNS-Server sind zulässig.")
|
||||
if any(other != name and (any(item["address"] == str(address) for item in card["addresses"]) or
|
||||
profiles.get(other, {}).get("address") == str(address)) for other, card in cards.items()):
|
||||
raise ValueError("Die Adresse ist bereits einer anderen Netzwerkkarte zugeordnet.")
|
||||
result.update(address=str(address), prefixLength=prefix, gateway=str(gateway) if gateway else None,
|
||||
dns=list(dict.fromkeys(str(unicast(item)) for item in dns)))
|
||||
return result
|
||||
|
||||
|
||||
def restart_dhcp():
|
||||
return subprocess.Popen([SYSTEMCTL, "restart", "dhcpcd.service"])
|
||||
|
||||
|
||||
class NetworkControl:
|
||||
def __init__(self):
|
||||
self.profiles = configured_profiles()
|
||||
self.change = None
|
||||
self.job = None
|
||||
self.notice = None
|
||||
if TRIAL.exists():
|
||||
self.revert("Nicht bestätigte Netzwerkeinstellungen wurden zurückgesetzt.")
|
||||
|
||||
def revert(self, notice):
|
||||
install(self.profiles)
|
||||
# Queue another restart even if a previous systemctl client is still waiting.
|
||||
self.job = restart_dhcp()
|
||||
self.change = None
|
||||
self.notice = notice
|
||||
|
||||
def tick(self):
|
||||
now = time.monotonic()
|
||||
if self.job is not None and self.job.poll() is not None:
|
||||
success = self.job.returncode == 0
|
||||
self.job = None
|
||||
if self.change and not success:
|
||||
self.revert("Der Netzwerkdienst konnte die Änderung nicht laden. Vorheriges Profil wiederhergestellt.")
|
||||
elif not self.change:
|
||||
if success:
|
||||
TRIAL.unlink(missing_ok=True)
|
||||
else:
|
||||
self.notice = "Rücksetzen gespeichert. Der DHCP-Dienst meldet einen Startfehler."
|
||||
if self.change is None:
|
||||
return
|
||||
if now >= self.change["deadline"]:
|
||||
self.revert("Zeit abgelaufen. Vorheriges Profil wiederhergestellt.")
|
||||
elif not self.change["started"] and now >= self.change["start"]:
|
||||
self.change["started"] = True
|
||||
try:
|
||||
install(self.profiles | {self.change["profile"]["interface"]: self.change["profile"]})
|
||||
self.job = restart_dhcp()
|
||||
except OSError:
|
||||
self.revert("Netzwerkeinstellungen konnten nicht angewendet werden.")
|
||||
|
||||
def status(self, cards):
|
||||
pending = None
|
||||
if self.change:
|
||||
change = self.change
|
||||
profile = change["profile"]
|
||||
card = cards.get(profile["interface"], {})
|
||||
addresses = card.get("addresses", [])
|
||||
ready = change["started"] and self.job is None and any(
|
||||
candidate["dynamic"] if profile["mode"] == "dhcp" else
|
||||
candidate["address"] == profile["address"] and candidate["prefixLength"] == profile["prefixLength"]
|
||||
for candidate in addresses)
|
||||
pending = {"id": change["id"], "profile": profile, "ready": ready,
|
||||
"secondsLeft": max(0, round(change["deadline"] - time.monotonic()))}
|
||||
return {"interfaces": list(cards.values()), "profiles": self.profiles, "pending": pending,
|
||||
"busy": self.job is not None, "notice": self.notice}
|
||||
|
||||
def handle(self, request):
|
||||
if not isinstance(request, dict):
|
||||
raise ValueError("Ungültige Netzwerk-Anfrage.")
|
||||
action = request.get("action")
|
||||
cards = inventory()
|
||||
if action == "apply":
|
||||
if self.change or self.job:
|
||||
raise ValueError("Es läuft bereits eine Netzwerkänderung.")
|
||||
profile = request.get("profile")
|
||||
if not isinstance(profile, dict):
|
||||
raise ValueError("Das Netzwerkprofil fehlt.")
|
||||
profile = validate(profile, cards, self.profiles)
|
||||
now = time.monotonic()
|
||||
atomic_write(TRIAL, "pending\n")
|
||||
self.change = {"id": uuid.uuid4().hex, "profile": profile, "start": now + 2,
|
||||
"deadline": now + TRIAL_SECONDS, "started": False}
|
||||
self.notice = None
|
||||
elif action in ("confirm", "revert"):
|
||||
if not self.change or self.change["id"] != request.get("id"):
|
||||
raise ValueError("Diese Netzwerkänderung ist nicht mehr offen.")
|
||||
if action == "revert":
|
||||
self.revert("Vorheriges Profil wiederhergestellt.")
|
||||
else:
|
||||
if not self.status(cards)["pending"]["ready"]:
|
||||
raise ValueError("Die neue Adresse ist noch nicht aktiv.")
|
||||
profile = self.change["profile"]
|
||||
profiles = self.profiles | {profile["interface"]: profile}
|
||||
atomic_write(CONFIRMED, json.dumps(profiles))
|
||||
self.profiles, self.change = profiles, None
|
||||
TRIAL.unlink(missing_ok=True)
|
||||
self.notice = "Netzwerkeinstellungen gespeichert."
|
||||
elif action != "status":
|
||||
raise ValueError("Ungültige Netzwerkaktion.")
|
||||
return self.status(cards)
|
||||
|
||||
|
||||
def serve():
|
||||
control = NetworkControl()
|
||||
listener = socket.socket(fileno=3) # systemd ListenStream
|
||||
listener.settimeout(0.5)
|
||||
while True:
|
||||
control.tick()
|
||||
try:
|
||||
client, _ = listener.accept()
|
||||
except TimeoutError:
|
||||
continue
|
||||
with client:
|
||||
client.settimeout(2)
|
||||
try:
|
||||
request = client.makefile("rb").read(8193)
|
||||
if len(request) > 8192:
|
||||
raise ValueError("Netzwerk-Anfrage zu groß.")
|
||||
result = control.handle(json.loads(request))
|
||||
except ValueError as error:
|
||||
result = {"error": str(error)}
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
print(error, file=sys.stderr, flush=True)
|
||||
result = {"error": "Der Netzwerkdienst konnte die Anfrage nicht verarbeiten."}
|
||||
try:
|
||||
client.sendall(json.dumps(result).encode())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1] == "prepare":
|
||||
# A tentative change exists only in /run; a reboot loads the confirmed profiles.
|
||||
install(configured_profiles())
|
||||
else:
|
||||
serve()
|
||||
@@ -0,0 +1,35 @@
|
||||
# Persistent Hyper-V host configuration after the SEIU Gateway source has been
|
||||
# placed in /etc/nixos/seiugw.
|
||||
{ pkgs, ... }:
|
||||
|
||||
{
|
||||
imports = [
|
||||
./hardware-configuration.nix
|
||||
./seiugw-host.nix
|
||||
];
|
||||
|
||||
boot.loader.systemd-boot.enable = true;
|
||||
boot.loader.efi.canTouchEfiVariables = true;
|
||||
|
||||
networking.hostName = "seiugw-bootstrap";
|
||||
networking.useDHCP = true;
|
||||
networking.firewall.allowedTCPPorts = [ 22 ];
|
||||
|
||||
time.timeZone = "Europe/Berlin";
|
||||
i18n.defaultLocale = "de_DE.UTF-8";
|
||||
console.keyMap = "de";
|
||||
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
settings = {
|
||||
PermitRootLogin = "yes";
|
||||
PasswordAuthentication = true;
|
||||
KbdInteractiveAuthentication = false;
|
||||
};
|
||||
};
|
||||
|
||||
environment.systemPackages = with pkgs; [ git curl vim ];
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
|
||||
system.stateVersion = "26.05";
|
||||
}
|
||||
+164
-19
@@ -6,6 +6,12 @@ let
|
||||
cfg = config.services.seiugw;
|
||||
hostProvisioningRequest = "${cfg.dataDir}/provisioning/host.json";
|
||||
komariInstalledMarker = "${cfg.dataDir}/provisioning/komari-installed";
|
||||
komariRuntimeToken = "/run/seiugw-komari/token";
|
||||
bacnetStackServer = pkgs.callPackage ./bacnet.nix { };
|
||||
manageHostNetwork = config.networking.useDHCP && config.networking.dhcpcd.enable
|
||||
&& !config.networking.useNetworkd && !config.networking.networkmanager.enable;
|
||||
dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart);
|
||||
networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}";
|
||||
in
|
||||
{
|
||||
options.services.seiugw = {
|
||||
@@ -67,6 +73,12 @@ in
|
||||
description = "Reserved OPC UA TCP port passed to the gateway.";
|
||||
};
|
||||
|
||||
modbusTcpPorts = mkOption {
|
||||
type = types.listOf types.port;
|
||||
default = [ 502 ];
|
||||
description = "Modbus-TCP ports opened by the NixOS firewall. Add every non-standard port used by a server instance.";
|
||||
};
|
||||
|
||||
trends = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
@@ -97,7 +109,7 @@ in
|
||||
enrollmentTokenFile = mkOption {
|
||||
type = types.str;
|
||||
default = "${cfg.dataDir}/komari-enrollment-token";
|
||||
description = "Root-readable file with the Komari one-time enrollment token. It must not be stored in Nix or Git.";
|
||||
description = "Root-only import file for a replacement Komari token. Imported into encrypted gateway storage, then removed. Never put plaintext tokens into Nix or Git.";
|
||||
};
|
||||
|
||||
installDir = mkOption {
|
||||
@@ -122,9 +134,11 @@ in
|
||||
|
||||
config = mkIf cfg.enable {
|
||||
users.groups.seiugw = { };
|
||||
users.groups.dialout = { };
|
||||
users.users.seiugw = {
|
||||
isSystemUser = true;
|
||||
group = "seiugw";
|
||||
extraGroups = [ "dialout" ];
|
||||
home = cfg.dataDir;
|
||||
createHome = true;
|
||||
};
|
||||
@@ -132,15 +146,62 @@ in
|
||||
systemd.tmpfiles.rules = [
|
||||
"d ${cfg.dataDir} 0750 seiugw seiugw -"
|
||||
"d ${cfg.dataDir}/provisioning 0750 seiugw seiugw -"
|
||||
] ++ optionals manageHostNetwork [
|
||||
"d /run/seiugw-network 0750 root seiugw -"
|
||||
"d /var/lib/seiugw-network 0700 root root -"
|
||||
] ++ optionals cfg.komari.enable [
|
||||
"d ${cfg.komari.installDir} 0750 root root -"
|
||||
];
|
||||
|
||||
networking.firewall = mkIf cfg.openFirewall {
|
||||
allowedTCPPorts = [ cfg.webPort ];
|
||||
allowedTCPPorts = [ cfg.webPort cfg.opcUa.port ] ++ cfg.modbusTcpPorts;
|
||||
allowedUDPPorts = [ cfg.bacnet.ipPort ];
|
||||
};
|
||||
|
||||
# dhcpcd sees the composed file only in its own mount namespace.
|
||||
# The NixOS base config and options remain the source for unmanaged cards.
|
||||
systemd.services.dhcpcd = mkIf manageHostNetwork {
|
||||
requires = [ "seiugw-network-prepare.service" ];
|
||||
after = [ "seiugw-network-prepare.service" ];
|
||||
serviceConfig.BindReadOnlyPaths = [ "/run/seiugw-network/dhcpcd.conf:${dhcpcdBase}" ];
|
||||
};
|
||||
|
||||
systemd.services.seiugw-network-prepare = mkIf manageHostNetwork {
|
||||
description = "Load confirmed SE-Inno IPv4 profiles";
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
ExecStart = "${networkHelper} prepare ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.sockets.seiugw-network = mkIf manageHostNetwork {
|
||||
wantedBy = [ "sockets.target" ];
|
||||
socketConfig = {
|
||||
ListenStream = "/run/seiugw-network/control.sock";
|
||||
SocketMode = "0660";
|
||||
SocketGroup = "seiugw";
|
||||
RemoveOnStop = true;
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.seiugw-network = mkIf manageHostNetwork {
|
||||
description = "SE-Inno host IPv4 control and rollback";
|
||||
after = [ "seiugw-network-prepare.service" ];
|
||||
requires = [ "seiugw-network-prepare.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${networkHelper} serve ${dhcpcdBase} ${pkgs.iproute2}/bin/ip ${pkgs.systemd}/bin/systemctl";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "1s";
|
||||
UMask = "0077";
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
NoNewPrivileges = true;
|
||||
ReadWritePaths = [ "/run/seiugw-network" "/var/lib/seiugw-network" ];
|
||||
};
|
||||
};
|
||||
|
||||
# Keep MariaDB local. The gateway process receives socket-authenticated access;
|
||||
# no database password or network-exposed database account is created.
|
||||
services.mysql = mkIf cfg.trends.enable {
|
||||
@@ -174,6 +235,7 @@ in
|
||||
environment = {
|
||||
ASPNETCORE_URLS = "http://${cfg.listenAddress}:${toString cfg.webPort}";
|
||||
Gateway__DataDirectory = cfg.dataDir;
|
||||
Gateway__ProtocolDataPlane = "native-bacnet-ip";
|
||||
Gateway__Bacnet__Interface = cfg.bacnet.interface;
|
||||
Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance;
|
||||
Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort;
|
||||
@@ -188,6 +250,56 @@ in
|
||||
UMask = "0077";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
|
||||
CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ];
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectHome = true;
|
||||
ProtectSystem = "strict";
|
||||
ReadWritePaths = [ cfg.dataDir ];
|
||||
};
|
||||
};
|
||||
|
||||
# Native BACnet/IP device. This is a separate, supervised C process from
|
||||
# the upstream BACnet stack; it owns UDP/47808 rather than relying on a
|
||||
# web process or Docker networking. Objects and durable priority slots
|
||||
# are materialised from SQLite by the native bridge.
|
||||
systemd.services.seiugw-bacnet = {
|
||||
description = "SEIU native BACnet/IP device";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
wants = [ "network-online.target" "seiugw.service" ];
|
||||
after = [ "network-online.target" "seiugw.service" ];
|
||||
|
||||
# The web unit is Type=simple: ordering alone does not mean its schema
|
||||
# migration has finished. Wait for the bridge tables on a first upgrade.
|
||||
preStart = ''
|
||||
for attempt in {1..30}; do
|
||||
if [ -f ${escapeShellArg "${cfg.dataDir}/seiugw.db"} ] && \
|
||||
[ "$(${pkgs.sqlite}/bin/sqlite3 ${escapeShellArg "${cfg.dataDir}/seiugw.db"} "SELECT (SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('bacnet_commands','bacnet_properties','bacnet_observations','bacnet_runtime','bacnet_discovery','bacnet_discovered_devices'))+(SELECT COUNT(*) FROM pragma_table_info('bacnet_discovered_devices') WHERE name IN ('network','mac'))+(SELECT COUNT(*) FROM pragma_table_info('points') WHERE name='deleted_at_utc');" 2>/dev/null)" = 9 ]; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "Gateway database schema is not ready" >&2
|
||||
exit 1
|
||||
'';
|
||||
|
||||
environment = {
|
||||
BACNET_DATALINK = "bip";
|
||||
SEIUGW_DATABASE = "${cfg.dataDir}/seiugw.db";
|
||||
BACNET_IFACE = cfg.bacnet.interface;
|
||||
BACNET_IP_PORT = toString cfg.bacnet.ipPort;
|
||||
BACNET_IP_BROADCAST_PORT = toString cfg.bacnet.ipPort;
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
ExecStart = "${bacnetStackServer}/bin/bacserv ${toString cfg.bacnet.deviceInstance} SEIU-Gateway";
|
||||
User = "seiugw";
|
||||
Group = "seiugw";
|
||||
WorkingDirectory = cfg.dataDir;
|
||||
UMask = "0077";
|
||||
Restart = "on-failure";
|
||||
RestartSec = "5s";
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectHome = true;
|
||||
@@ -202,9 +314,12 @@ in
|
||||
# re-applied after every later boot without changing NixOS configuration.
|
||||
systemd.services.seiugw-apply-hostname = {
|
||||
description = "Apply SEIU Gateway commissioning hostname";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig.Type = "oneshot";
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
};
|
||||
path = [ pkgs.coreutils pkgs.gnugrep pkgs.hostname pkgs.jq ];
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
@@ -225,6 +340,7 @@ in
|
||||
|
||||
host_name="SE-UGW-$project-ISP$(printf '%02d' "$isp")"
|
||||
[ "''${#host_name}" -le 63 ] || exit 0
|
||||
[ "$(${pkgs.hostname}/bin/hostname)" != "$host_name" ] || exit 0
|
||||
${pkgs.hostname}/bin/hostname "$host_name"
|
||||
'';
|
||||
};
|
||||
@@ -232,19 +348,57 @@ in
|
||||
systemd.paths.seiugw-apply-hostname = {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathExists = hostProvisioningRequest;
|
||||
PathChanged = hostProvisioningRequest;
|
||||
Unit = "seiugw-apply-hostname.service";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.seiugw-komari-token = mkIf cfg.komari.enable {
|
||||
description = "Import and materialize encrypted Komari credential";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "seiugw.service" ];
|
||||
requires = [ "seiugw.service" ];
|
||||
environment.Gateway__DataDirectory = cfg.dataDir;
|
||||
serviceConfig = { Type = "oneshot"; UMask = "0077"; Restart = "on-failure"; RestartSec = "10s"; };
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
${pkgs.coreutils}/bin/install -d -m 0700 -o seiugw -g seiugw /run/seiugw-komari
|
||||
# Stage root's input for the unprivileged database owner. Never print it.
|
||||
if [ -s ${escapeShellArg cfg.komari.enrollmentTokenFile} ]; then
|
||||
${pkgs.coreutils}/bin/install -m 0600 -o seiugw -g seiugw ${escapeShellArg cfg.komari.enrollmentTokenFile} /run/seiugw-komari/import
|
||||
${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --import-komari-token /run/seiugw-komari/import
|
||||
${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/import ${escapeShellArg cfg.komari.enrollmentTokenFile}
|
||||
fi
|
||||
if ${pkgs.util-linux}/bin/runuser -u seiugw -- ${cfg.package}/bin/Gateway.Api --materialize-komari-token /run/seiugw-komari/next; then
|
||||
if ! ${pkgs.diffutils}/bin/cmp -s /run/seiugw-komari/next ${komariRuntimeToken}; then
|
||||
${pkgs.coreutils}/bin/mv /run/seiugw-komari/next ${komariRuntimeToken}
|
||||
${pkgs.systemd}/bin/systemctl --no-block try-restart seiugw-komari-agent.service
|
||||
${pkgs.systemd}/bin/systemctl --no-block restart seiugw-komari-bootstrap.service
|
||||
else
|
||||
${pkgs.coreutils}/bin/rm -f /run/seiugw-komari/next
|
||||
fi
|
||||
fi
|
||||
'';
|
||||
};
|
||||
systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathChanged = [ "${cfg.dataDir}/provisioning/komari-token.request" cfg.komari.enrollmentTokenFile ];
|
||||
Unit = "seiugw-komari-token.service";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services.seiugw-komari-bootstrap = mkIf cfg.komari.enable {
|
||||
description = "One-time Komari agent installer for SEIU Gateway";
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
|
||||
requires = [ "seiugw-apply-hostname.service" ];
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
|
||||
requires = [ "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
# Both prerequisites are already watched by the commissioning path.
|
||||
# A completed installer must remain active; otherwise PathExists can
|
||||
# repeatedly start this successful no-op and hit systemd's start limit.
|
||||
RemainAfterExit = true;
|
||||
Restart = "on-failure";
|
||||
RestartSec = "30s";
|
||||
};
|
||||
@@ -252,7 +406,7 @@ in
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
marker=${escapeShellArg komariInstalledMarker}
|
||||
token_file=${escapeShellArg cfg.komari.enrollmentTokenFile}
|
||||
token_file=${escapeShellArg komariRuntimeToken}
|
||||
install_dir=${escapeShellArg cfg.komari.installDir}
|
||||
agent="$install_dir/agent"
|
||||
[ -e "$marker" ] && exit 0
|
||||
@@ -281,23 +435,14 @@ in
|
||||
};
|
||||
};
|
||||
|
||||
systemd.paths.seiugw-komari-token = mkIf cfg.komari.enable {
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
pathConfig = {
|
||||
PathExists = cfg.komari.enrollmentTokenFile;
|
||||
PathChanged = cfg.komari.enrollmentTokenFile;
|
||||
Unit = "seiugw-komari-bootstrap.service";
|
||||
};
|
||||
};
|
||||
|
||||
# The upstream installer deliberately does not create a NixOS unit. NixOS
|
||||
# owns this unit instead, while the binary remains in the upstream mutable
|
||||
# install directory. The enrollment token is read at service start and is
|
||||
# never placed in the Nix store.
|
||||
systemd.services.seiugw-komari-agent = mkIf cfg.komari.enable {
|
||||
description = "Komari monitoring agent";
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" ];
|
||||
wants = [ "network-online.target" ];
|
||||
after = [ "network-online.target" "seiugw-apply-hostname.service" "seiugw-komari-token.service" ];
|
||||
wants = [ "network-online.target" "seiugw-komari-token.service" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
unitConfig.ConditionPathExists = "${cfg.komari.installDir}/agent";
|
||||
serviceConfig = {
|
||||
@@ -309,7 +454,7 @@ in
|
||||
path = [ pkgs.bash pkgs.coreutils ];
|
||||
script = ''
|
||||
set -euo pipefail
|
||||
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg cfg.komari.enrollmentTokenFile})"
|
||||
token="$(${pkgs.coreutils}/bin/cat ${escapeShellArg komariRuntimeToken})"
|
||||
[ -n "$token" ]
|
||||
exec ${escapeShellArg "${cfg.komari.installDir}/agent"} -e ${escapeShellArg cfg.komari.endpoint} --auto-discovery "$token" ${lib.optionalString cfg.komari.ignoreUnsafeCertificateErrors "--ignore-unsafe-cert"}
|
||||
'';
|
||||
|
||||
Reference in new issue
Block a user