Add authenticated Gateway system updates with rollback
This commit is contained in:
1 parent
198b1d7b78
commit
4e35a3a557
9 files changed
+423
-1
No files matched your search
@@ -11,6 +11,10 @@
|
||||
bacnet.deviceInstance = 23;
|
||||
bacnet.ipPort = 47808;
|
||||
webPort = 8088;
|
||||
updates = {
|
||||
enable = true;
|
||||
remote = "https://git.portal.se-cloud.de/Hannes/SE-UGW";
|
||||
};
|
||||
openFirewall = true;
|
||||
trends = {
|
||||
enable = true;
|
||||
|
||||
@@ -12,6 +12,25 @@ let
|
||||
&& !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}";
|
||||
updateSocket = "/run/seiugw-update/request.sock";
|
||||
updateWorker = pkgs.writeShellScript "seiugw-system-update" ''
|
||||
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin
|
||||
export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"}
|
||||
export SEIUGW_UPDATE_REPO=${escapeShellArg cfg.updates.checkout}
|
||||
export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote}
|
||||
export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch}
|
||||
export SEIUGW_UPDATE_DATA=${escapeShellArg cfg.dataDir}
|
||||
export SEIUGW_UPDATE_HEALTH=${escapeShellArg "http://127.0.0.1:${toString cfg.webPort}"}
|
||||
${builtins.readFile ./system-update.sh}
|
||||
'';
|
||||
updateTrigger = pkgs.writeShellScript "seiugw-request-update" ''
|
||||
if ${pkgs.systemd}/bin/systemd-run --quiet --collect --unit=seiugw-update-worker \
|
||||
--property=Type=exec ${updateWorker} >&2; then
|
||||
printf 'accepted\n'
|
||||
else
|
||||
printf 'unavailable\n'
|
||||
fi
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.services.seiugw = {
|
||||
@@ -47,6 +66,25 @@ in
|
||||
description = "Open the configured web and BACnet/IP ports in the NixOS firewall.";
|
||||
};
|
||||
|
||||
updates = {
|
||||
enable = mkEnableOption "local-root system updates requested by the Gateway administrator";
|
||||
checkout = mkOption {
|
||||
type = types.str;
|
||||
default = "/etc/nixos/seiugw";
|
||||
description = "Root-owned checkout already used by the NixOS host configuration.";
|
||||
};
|
||||
remote = mkOption {
|
||||
type = types.str;
|
||||
default = "";
|
||||
description = "Trusted HTTPS Git URL used by the update worker.";
|
||||
};
|
||||
branch = mkOption {
|
||||
type = types.str;
|
||||
default = "main";
|
||||
description = "Branch allowed for fast-forward gateway updates.";
|
||||
};
|
||||
};
|
||||
|
||||
bacnet = {
|
||||
interface = mkOption {
|
||||
type = types.str;
|
||||
@@ -133,6 +171,13 @@ in
|
||||
};
|
||||
|
||||
config = mkIf cfg.enable {
|
||||
assertions = optionals cfg.updates.enable [
|
||||
{
|
||||
assertion = builtins.match "https://[^/@]+/[^?#]+" cfg.updates.remote != null;
|
||||
message = "Gateway system updates require an HTTPS Git remote without embedded credentials.";
|
||||
}
|
||||
];
|
||||
|
||||
users.groups.seiugw = { };
|
||||
users.groups.dialout = { };
|
||||
users.users.seiugw = {
|
||||
@@ -151,8 +196,33 @@ in
|
||||
"d /var/lib/seiugw-network 0700 root root -"
|
||||
] ++ optionals cfg.komari.enable [
|
||||
"d ${cfg.komari.installDir} 0750 root root -"
|
||||
] ++ optionals cfg.updates.enable [
|
||||
"d /var/lib/seiugw-updater 0755 root root -"
|
||||
];
|
||||
|
||||
systemd.sockets.seiugw-update = mkIf cfg.updates.enable {
|
||||
description = "Local Gateway system update requests";
|
||||
wantedBy = [ "sockets.target" ];
|
||||
socketConfig = {
|
||||
ListenStream = updateSocket;
|
||||
SocketUser = "root";
|
||||
SocketGroup = "seiugw";
|
||||
SocketMode = "0660";
|
||||
Accept = true;
|
||||
RemoveOnStop = true;
|
||||
};
|
||||
};
|
||||
|
||||
systemd.services."seiugw-update@" = mkIf cfg.updates.enable {
|
||||
description = "Start the independent Gateway update worker";
|
||||
serviceConfig = {
|
||||
ExecStart = updateTrigger;
|
||||
StandardInput = "socket";
|
||||
StandardOutput = "socket";
|
||||
StandardError = "journal";
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall = mkIf cfg.openFirewall {
|
||||
allowedTCPPorts = [ cfg.webPort cfg.opcUa.port ] ++ cfg.modbusTcpPorts;
|
||||
allowedUDPPorts = [ cfg.bacnet.ipPort ];
|
||||
@@ -240,6 +310,9 @@ in
|
||||
Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance;
|
||||
Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort;
|
||||
Gateway__OpcUa__Port = toString cfg.opcUa.port;
|
||||
} // lib.optionalAttrs cfg.updates.enable {
|
||||
Gateway__UpdateSocketPath = updateSocket;
|
||||
Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json";
|
||||
};
|
||||
|
||||
serviceConfig = {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
|
||||
state=/var/lib/seiugw-updater
|
||||
repo="$SEIUGW_UPDATE_REPO"
|
||||
profile=/nix/var/nix/profiles/system
|
||||
database="$SEIUGW_UPDATE_DATA/seiugw.db"
|
||||
gateway_units=(seiugw.service seiugw-bacnet.service)
|
||||
commit=""
|
||||
previous_commit=""
|
||||
target=""
|
||||
step="Vorprüfung"
|
||||
checkout_changed=0
|
||||
services_stopped=0
|
||||
activation_started=0
|
||||
snapshot_ready=0
|
||||
|
||||
exec 9>"$state/lock"
|
||||
flock -n 9
|
||||
work=$(mktemp -d "$state/run.XXXXXX")
|
||||
cd "$work"
|
||||
|
||||
git_gateway() {
|
||||
git -C "$repo" -c core.hooksPath=/dev/null "$@"
|
||||
}
|
||||
|
||||
status() {
|
||||
jq -n --arg phase "$1" --arg message "$2" --arg commit "$commit" --arg target "$target" \
|
||||
--arg updatedAt "$(date --iso-8601=seconds)" --arg runId "${work##*/}" \
|
||||
'{phase:$phase,message:$message,commit:$commit,target:$target,updatedAt:$updatedAt,runId:$runId}' >"$work/status.json"
|
||||
chmod 0644 "$work/status.json"
|
||||
mv -f "$work/status.json" "$state/status.json"
|
||||
}
|
||||
|
||||
healthy() {
|
||||
local attempt consecutive=0 heartbeat now
|
||||
for ((attempt=0; attempt<30; attempt++)); do
|
||||
now=$(date +%s%3N)
|
||||
heartbeat=$(runuser -u seiugw -- sqlite3 -readonly -cmd '.timeout 1000' "$database" \
|
||||
'SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1' 2>/dev/null) || heartbeat=""
|
||||
if systemctl is-active --quiet seiugw.service &&
|
||||
systemctl is-active --quiet seiugw-bacnet.service &&
|
||||
[[ $heartbeat =~ ^[0-9]{13}$ ]] && ((now - heartbeat < 5000)) &&
|
||||
curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/api/health" |
|
||||
jq -e '.status == "ok" and .adminConfigured == true' >/dev/null &&
|
||||
curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/" -o /dev/null; then
|
||||
((consecutive+=1))
|
||||
if ((consecutive >= 3)); then return 0; fi
|
||||
else
|
||||
consecutive=0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
finish() {
|
||||
local code=$? restored=1
|
||||
trap - EXIT
|
||||
trap '' HUP INT TERM
|
||||
if ((code != 0)); then
|
||||
echo "Gateway update failed during $step (exit $code)." >&2
|
||||
if ((checkout_changed || services_stopped)); then
|
||||
status rollingBack "Fehler bei $step. Die vorherige Version wird wiederhergestellt." || true
|
||||
if ((services_stopped)); then
|
||||
if systemctl stop "${gateway_units[@]}"; then
|
||||
if ((snapshot_ready)); then
|
||||
runuser -u seiugw -- sqlite3 -bail "$database" ".restore '$work/gateway.db'" || restored=0
|
||||
fi
|
||||
else
|
||||
restored=0
|
||||
fi
|
||||
fi
|
||||
if ((checkout_changed)); then git_gateway reset --keep "$previous_commit" || restored=0; fi
|
||||
commit=$previous_commit
|
||||
if ((activation_started)); then
|
||||
if [[ $(readlink -f "$profile") != "$previous_system" ]]; then
|
||||
nix-env --profile "$profile" --set "$previous_system" || restored=0
|
||||
fi
|
||||
"$previous_system/bin/switch-to-configuration" switch || restored=0
|
||||
fi
|
||||
if ((services_stopped)); then
|
||||
if ! systemctl start "${gateway_units[@]}" || ! healthy; then restored=0; fi
|
||||
fi
|
||||
if ((restored)); then
|
||||
status rolledBack "Fehler bei $step. Die vorherige Version wurde wiederhergestellt." || true
|
||||
else
|
||||
status rollbackFailed "Fehler bei $step. Die Wiederherstellung konnte nicht bestätigt werden." || true
|
||||
echo "Recovery files kept in $work." >&2
|
||||
exit "$code"
|
||||
fi
|
||||
else
|
||||
status failed "Fehler bei $step. Die installierte Version läuft weiter." || true
|
||||
fi
|
||||
fi
|
||||
rm -f -- "$work/result" "$work/gateway.db" "$work/gateway.db-wal" "$work/gateway.db-shm" "$work/status.json"
|
||||
rmdir -- "$work"
|
||||
exit "$code"
|
||||
}
|
||||
trap finish EXIT
|
||||
trap 'exit 130' HUP INT TERM
|
||||
|
||||
status checking "Der Repository- und Systemstand wird geprüft."
|
||||
[[ $(git_gateway rev-parse --show-toplevel) == "$repo" ]]
|
||||
commit=$(git_gateway rev-parse HEAD)
|
||||
previous_commit=$commit
|
||||
[[ $(git_gateway symbolic-ref --short HEAD) == "$SEIUGW_UPDATE_BRANCH" ]]
|
||||
[[ -z $(git_gateway status --porcelain --untracked-files=all) ]]
|
||||
previous_system=$(readlink -f /run/current-system)
|
||||
[[ $(readlink -f "$profile") == "$previous_system" ]]
|
||||
|
||||
step="Git-Abruf"
|
||||
status fetching "Neue Version wird aus Git abgerufen."
|
||||
timeout 120 git -C "$repo" -c core.hooksPath=/dev/null -c credential.helper= \
|
||||
fetch --no-tags -- "$SEIUGW_UPDATE_REMOTE" "refs/heads/$SEIUGW_UPDATE_BRANCH"
|
||||
target=$(git_gateway rev-parse FETCH_HEAD)
|
||||
if [[ $commit == "$target" ]]; then
|
||||
status current "Das Gateway ist bereits auf dem aktuellen Stand."
|
||||
exit 0
|
||||
fi
|
||||
if git_gateway merge-base --is-ancestor "$target" "$commit"; then
|
||||
status unpublished "Die installierte Version ist neuer als der veröffentlichte Stand."
|
||||
exit 0
|
||||
fi
|
||||
git_gateway merge-base --is-ancestor "$commit" "$target"
|
||||
|
||||
step="Systembau"
|
||||
status building "Die neue NixOS-Generation wird gebaut."
|
||||
checkout_changed=1
|
||||
git_gateway merge --ff-only "$target"
|
||||
timeout --kill-after=30s 60m nixos-rebuild build
|
||||
candidate=$(readlink -f result)
|
||||
[[ -x $candidate/bin/switch-to-configuration ]]
|
||||
|
||||
step="Datenbanksicherung"
|
||||
status activating "Das Gateway wird kurz angehalten. Die Datenbank wird gesichert."
|
||||
services_stopped=1
|
||||
systemctl stop "${gateway_units[@]}"
|
||||
[[ -f $database ]]
|
||||
chgrp seiugw "$work"
|
||||
chmod 0710 "$work"
|
||||
install -o seiugw -g seiugw -m 0600 /dev/null "$work/gateway.db"
|
||||
runuser -u seiugw -- sqlite3 -bail "$database" ".backup '$work/gateway.db'"
|
||||
[[ $(sqlite3 -bail "$work/gateway.db" 'PRAGMA quick_check') == ok ]]
|
||||
snapshot_ready=1
|
||||
|
||||
step="Aktivierung"
|
||||
status activating "Die neue Version wird aktiviert und geprüft."
|
||||
activation_started=1
|
||||
"$candidate/bin/switch-to-configuration" test
|
||||
[[ $(readlink -f /run/current-system) == "$candidate" ]]
|
||||
systemctl restart "${gateway_units[@]}"
|
||||
step="Funktionsprüfung"
|
||||
healthy
|
||||
|
||||
step="Boot-Konfiguration"
|
||||
nix-env --profile "$profile" --set "$candidate"
|
||||
"$candidate/bin/switch-to-configuration" boot
|
||||
[[ $(readlink -f "$profile") == "$candidate" ]]
|
||||
commit=$target
|
||||
status succeeded "Die neue Version ist aktiv und für den nächsten Start eingestellt."
|
||||
Reference in new issue
Block a user