From 2218c4c2fe597a79a054e443563b38c37c615f5c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:07:07 +0100 Subject: [PATCH 01/16] feat(common): read the devices file of a port as a top-level array The runner now accepts the devices file as a top-level JSON array. The legacy {"devices": [...]} object is still read until no node writes it. Before the MQTT client is built, the runner exits with code 2 when the port package energy_node_ha_ is not installed. Co-Authored-By: Claude Sonnet 5.5 --- .../src/energy_node_common/ha/README.md | 32 +++++++++-------- .../src/energy_node_common/ha/__main__.py | 31 +++++++++++----- .../tests/ha/test_runner.py | 35 +++++++++++++++++++ 3 files changed, 74 insertions(+), 24 deletions(-) diff --git a/libs/energy_node_common/src/energy_node_common/ha/README.md b/libs/energy_node_common/src/energy_node_common/ha/README.md index 16b1f546..9e682e6f 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/README.md +++ b/libs/energy_node_common/src/energy_node_common/ha/README.md @@ -50,24 +50,24 @@ with `strings.json` as the last fallback. Entity names come from `entity...name`, placeholders included. The configuration lives in `ha__devices.json` in the devices directory. -Each record mirrors a Home Assistant config entry: +It is a top-level array, and each record mirrors a Home Assistant config entry: ```json -{ - "devices": [ - { - "id": "home", - "name": "Home", - "data": {"latitude": 52.5, "longitude": 13.4}, - "options": {}, - "subentries": [ - {"type": "plane", "title": "South roof", "data": {"declination": 30}} - ] - } - ] -} +[ + { + "id": "home", + "name": "Home", + "data": {"latitude": 52.5, "longitude": 13.4}, + "options": {}, + "subentries": [ + {"type": "plane", "title": "South roof", "data": {"declination": 30}} + ] + } +] ``` +The older `{"devices": [...]}` object is still read, but new files use the array. + Subentries get the IDs `_0`, `_1` and so on. ## Running @@ -82,7 +82,9 @@ The systemd template `energy-node-ha@.service` runs it as `energy-node-ha@.service` and restarts it after a failure. If setup fails, for example because the API is not reachable, the runner reports the service offline with the reason and exits with code 1. Without configured -devices, or with a devices file it cannot read, it exits with code 2. +devices, with a devices file it cannot read, or when the port package +`energy_node_ha_` is not installed, it exits with code 2 before it +connects to MQTT. ## Topics diff --git a/libs/energy_node_common/src/energy_node_common/ha/__main__.py b/libs/energy_node_common/src/energy_node_common/ha/__main__.py index 2530d43c..63f85541 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/__main__.py +++ b/libs/energy_node_common/src/energy_node_common/ha/__main__.py @@ -2,15 +2,17 @@ Usage: ``python3 -m energy_node_common.ha [--config PATH] [--language de]`` -The devices file ``/ha__devices.json`` holds -``{"devices": [...]}``, one record per device. Each record becomes one config -entry of the integration. Follows the Home Assistant API surface. +The devices file ``/ha__devices.json`` holds a top-level +array with one record per device. Each record becomes one config entry of the +integration. The older ``{"devices": [...]}`` object is still read until no +node writes it any more. Follows the Home Assistant API surface. """ from __future__ import annotations import argparse import asyncio +import importlib.util import json import logging import signal @@ -45,18 +47,25 @@ def service_name(domain: str) -> str: def _load_devices(path: Path) -> list: - """Return the device records; raise ValueError naming the problem.""" + """Return the device records; raise ValueError naming the problem. + + The file is a top-level array. Das Altformat ``{"devices": [...]}`` wird + entfernt, sobald kein Node es mehr hat. + """ if not path.exists(): return [] try: document = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as exc: raise ValueError(f"kein gueltiges JSON ({exc})") from exc - if not isinstance(document, dict): - raise ValueError("erwartet ein Objekt mit dem Schluessel 'devices'") - devices = document.get("devices", []) - if not isinstance(devices, list): - raise ValueError("'devices' ist keine Liste") + if isinstance(document, dict): + devices = document.get("devices", []) + if not isinstance(devices, list): + raise ValueError("'devices' ist keine Liste") + elif isinstance(document, list): + devices = document + else: + raise ValueError("erwartet eine Liste von Geräten (oder das Altformat mit 'devices')") for index, rec in enumerate(devices): if not isinstance(rec, dict) or "id" not in rec: raise ValueError(f"Gerät {index} ohne 'id'") @@ -84,6 +93,10 @@ async def run(args: argparse.Namespace, client_factory=common_mqtt.build_client) if not devices: print(f"{devices_path}: keine Geräte konfiguriert", file=sys.stderr) return 2 + if importlib.util.find_spec(package_for(args.domain)) is None: + print(f"Port {args.domain} ist nicht installiert " + f"(Paket {package_for(args.domain)} fehlt)", file=sys.stderr) + return 2 outstation = f"outstation/{service}" client = client_factory( diff --git a/libs/energy_node_common/tests/ha/test_runner.py b/libs/energy_node_common/tests/ha/test_runner.py index 08c01593..a8fd8dcf 100644 --- a/libs/energy_node_common/tests/ha/test_runner.py +++ b/libs/energy_node_common/tests/ha/test_runner.py @@ -12,6 +12,8 @@ import sys from pathlib import Path +import pytest + sys.path.insert(0, str(Path(__file__).parent)) import fake_port # noqa: E402 @@ -52,6 +54,39 @@ def write_devices(tmp_path: Path, data: dict) -> None: (tmp_path / "ha_fake_devices.json").write_text(json.dumps(devices), encoding="utf-8") +def test_load_devices_top_level_array(tmp_path): + path = tmp_path / "ha_fake_devices.json" + path.write_text(json.dumps([{"id": "node1", "data": {}}]), encoding="utf-8") + assert runner._load_devices(path) == [{"id": "node1", "data": {}}] + + +def test_load_devices_legacy_object_still_works(tmp_path): + path = tmp_path / "ha_fake_devices.json" + path.write_text(json.dumps({"devices": [{"id": "node1"}]}), encoding="utf-8") + assert runner._load_devices(path) == [{"id": "node1"}] + + +def test_load_devices_rejects_scalar(tmp_path): + path = tmp_path / "ha_fake_devices.json" + path.write_text(json.dumps("x"), encoding="utf-8") + with pytest.raises(ValueError, match="erwartet eine Liste"): + runner._load_devices(path) + + +def test_run_exits_2_when_port_missing(tmp_path, capsys): + config = write_config(tmp_path) + args = runner.parse_args(["does_not_exist", "--config", str(config)]) + (tmp_path / "ha_does_not_exist_devices.json").write_text( + json.dumps([{"id": "node1", "data": {}}]), encoding="utf-8") + + def no_client(**kwargs): + raise AssertionError("MQTT client must not be built without the port") + + code = asyncio.run(runner.run(args, client_factory=no_client)) + assert code == 2 + assert "Port does_not_exist ist nicht installiert (Paket energy_node_ha_does_not_exist fehlt)" in capsys.readouterr().err + + def _values(**extra) -> dict: data = {"values": {"energy": 12.5, "power": 1400, "alarm": True}} data.update(extra) From ee1f54cd4f691b6ef0ba4d75cf6e6dcb343fa298 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:07:24 +0100 Subject: [PATCH 02/16] fix(common): use English in the devices loader docstring Co-Authored-By: Claude Sonnet 5.5 --- libs/energy_node_common/src/energy_node_common/ha/__main__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/energy_node_common/src/energy_node_common/ha/__main__.py b/libs/energy_node_common/src/energy_node_common/ha/__main__.py index 63f85541..432f6fd4 100644 --- a/libs/energy_node_common/src/energy_node_common/ha/__main__.py +++ b/libs/energy_node_common/src/energy_node_common/ha/__main__.py @@ -49,8 +49,8 @@ def service_name(domain: str) -> str: def _load_devices(path: Path) -> list: """Return the device records; raise ValueError naming the problem. - The file is a top-level array. Das Altformat ``{"devices": [...]}`` wird - entfernt, sobald kein Node es mehr hat. + The file is a top-level array. The legacy format ``{"devices": [...]}`` is + removed once no node has it any more. """ if not path.exists(): return [] From adb2e5d1b5b65fa2a0e319e7d1e93013a39360f1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:07:35 +0100 Subject: [PATCH 03/16] chore(bootstrap): add the Home Assistant ports signing key Co-Authored-By: Claude Sonnet 5.5 --- scripts/bootstrap/keys/ha_ports_signing_key.pub.pem | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 scripts/bootstrap/keys/ha_ports_signing_key.pub.pem diff --git a/scripts/bootstrap/keys/ha_ports_signing_key.pub.pem b/scripts/bootstrap/keys/ha_ports_signing_key.pub.pem new file mode 100644 index 00000000..9ade6746 --- /dev/null +++ b/scripts/bootstrap/keys/ha_ports_signing_key.pub.pem @@ -0,0 +1,3 @@ +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEAAy6U8DkFlAEjtqsjQNG+WH6u4uiRV9qG196247GllCs= +-----END PUBLIC KEY----- From 02c1387bc292a6079317aab66bed7e17cae12609 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:09:54 +0100 Subject: [PATCH 04/16] feat(dashboard): allow Home Assistant port sections in the config schema The core schema accepts services.ha_ sections through patternProperties, with service_id as the only field. The config validator now evaluates patternProperties, so matching keys are no longer rejected by additionalProperties false, and unsupported keywords inside those subschemas are refused like the rest. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/schemagen/core.schema.json | 13 +++++- .../internal/appconfig/appconfig_test.go | 27 ++++++++++++ .../internal/appconfig/config.schema.json | 18 ++++++++ dashboard/internal/config/config.go | 44 ++++++++++++++++++- dashboard/internal/config/config_test.go | 23 ++++++++++ 5 files changed, 123 insertions(+), 2 deletions(-) diff --git a/dashboard/cmd/schemagen/core.schema.json b/dashboard/cmd/schemagen/core.schema.json index 12e9c7e4..6f630b69 100644 --- a/dashboard/cmd/schemagen/core.schema.json +++ b/dashboard/cmd/schemagen/core.schema.json @@ -42,7 +42,18 @@ "title": "Services", "additionalProperties": false, "required": [], - "properties": {} + "properties": {}, + "patternProperties": { + "^ha_[a-z0-9_]+$": { + "title": "Home Assistant port", + "type": "object", + "additionalProperties": false, + "required": ["service_id"], + "properties": { + "service_id": {"type": "string", "pattern": "^ha_[a-z0-9_]+$", "title": "Service ID", "description": "Identifies the port in its MQTT topics."} + } + } + } }, "installed_services": { "type": "object", diff --git a/dashboard/internal/appconfig/appconfig_test.go b/dashboard/internal/appconfig/appconfig_test.go index 53b8271b..9b228452 100644 --- a/dashboard/internal/appconfig/appconfig_test.go +++ b/dashboard/internal/appconfig/appconfig_test.go @@ -380,3 +380,30 @@ func TestSchemaAcceptsConfigWithoutRuntimeDir(t *testing.T) { t.Fatalf("Load ohne runtime_dir: %v", err) } } + +func TestSchemaAcceptsHAPortSection(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["ha_nordpool"] = map[string]any{"service_id": "ha_nordpool"} + if _, err := appconfig.Load(writeConfig(t, document)); err != nil { + t.Fatalf("Load mit HA-Port-Abschnitt: %v", err) + } +} + +func TestSchemaRejectsUnknownService(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["foo"] = map[string]any{"service_id": "foo"} + if _, err := appconfig.Load(writeConfig(t, document)); err == nil { + t.Fatal("erwartete einen Schema-Fehler fuer den unbekannten Dienst foo") + } +} + +func TestSchemaRejectsHAPortExtraField(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["ha_nordpool"] = map[string]any{ + "service_id": "ha_nordpool", + "poll_interval_s": 60, + } + if _, err := appconfig.Load(writeConfig(t, document)); err == nil { + t.Fatal("erwartete einen Schema-Fehler fuer ein Zusatzfeld in einem HA-Port-Abschnitt") + } +} diff --git a/dashboard/internal/appconfig/config.schema.json b/dashboard/internal/appconfig/config.schema.json index 2669155a..0aaf62a3 100644 --- a/dashboard/internal/appconfig/config.schema.json +++ b/dashboard/internal/appconfig/config.schema.json @@ -270,6 +270,24 @@ }, "services": { "additionalProperties": false, + "patternProperties": { + "^ha_[a-z0-9_]+$": { + "additionalProperties": false, + "properties": { + "service_id": { + "description": "Identifies the port in its MQTT topics.", + "pattern": "^ha_[a-z0-9_]+$", + "title": "Service ID", + "type": "string" + } + }, + "required": [ + "service_id" + ], + "title": "Home Assistant port", + "type": "object" + } + }, "properties": { "apsystems": { "additionalProperties": false, diff --git a/dashboard/internal/config/config.go b/dashboard/internal/config/config.go index b697840d..612d11db 100644 --- a/dashboard/internal/config/config.go +++ b/dashboard/internal/config/config.go @@ -534,6 +534,13 @@ func checkSchemaKeywords(raw any, path string) error { } } } + if patterns, ok := schema["patternProperties"].(map[string]any); ok { + for key, child := range patterns { + if err := checkSchemaKeywords(child, path+".patternProperties."+key); err != nil { + return err + } + } + } for _, keyword := range []string{"items", "if", "then", "else"} { if child, ok := schema[keyword]; ok { if err := checkSchemaKeywords(child, path+"."+keyword); err != nil { @@ -666,9 +673,17 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return nil, fmt.Errorf("%s.%s is required", path, required) } } + patterns, _ := schema["patternProperties"].(map[string]any) if additional, ok := schema["additionalProperties"].(bool); ok && !additional { for _, key := range sortedKeys(object) { - if _, exists := properties[key]; !exists { + if _, exists := properties[key]; exists { + continue + } + matched, err := matchingPatternSchemas(patterns, key) + if err != nil { + return nil, err + } + if len(matched) == 0 { return nil, fmt.Errorf("%s.%s is not allowed", path, key) } } @@ -680,6 +695,16 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return nil, err } } + matched, err := matchingPatternSchemas(patterns, key) + if err != nil { + return nil, err + } + for _, sub := range matched { + evaluated[key] = true + if err := validateValue(object[key], sub, path+"."+key); err != nil { + return nil, err + } + } } } if all, ok := schema["allOf"].([]any); ok { @@ -739,6 +764,23 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return evaluated, nil } +// matchingPatternSchemas returns the patternProperties subschemas whose +// regular expression matches key, in pattern order. An invalid pattern is an +// error, so a broken schema cannot silently accept keys. +func matchingPatternSchemas(patterns map[string]any, key string) ([]any, error) { + var matched []any + for _, pattern := range sortedKeys(patterns) { + expr, err := compiledPattern(pattern) + if err != nil { + return nil, fmt.Errorf("invalid patternProperties pattern %q", pattern) + } + if expr.MatchString(key) { + matched = append(matched, patterns[pattern]) + } + } + return matched, nil +} + // branchDeclarations collects the properties of every then/else branch, // active or not, the first declaration winning (as allProperties in // schema-form.js). Deviating from JSON Schema on purpose: a field of an diff --git a/dashboard/internal/config/config_test.go b/dashboard/internal/config/config_test.go index aa17211d..d7544b4f 100644 --- a/dashboard/internal/config/config_test.go +++ b/dashboard/internal/config/config_test.go @@ -496,3 +496,26 @@ func TestAutomationRulesSchemaPatternAcceptsCustomCategories(t *testing.T) { t.Fatal("custom:Sauna accepted") } } + +const patternPropertiesSchema = `{"type":"object","additionalProperties":false,"properties":{"services":{"type":"object","additionalProperties":false,"properties":{},"patternProperties":{"^ha_[a-z0-9_]+$":{"type":"object","additionalProperties":false,"required":["service_id"],"properties":{"service_id":{"type":"string","pattern":"^ha_[a-z0-9_]+$"}}}}}}}` + +func TestPatternPropertiesAcceptsMatchingKey(t *testing.T) { + data := []byte(`{"services":{"ha_nordpool":{"service_id":"ha_nordpool"}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err != nil { + t.Fatalf("matching key rejected: %v", err) + } +} + +func TestPatternPropertiesRejectsExtraFieldOnMatchingKey(t *testing.T) { + data := []byte(`{"services":{"ha_nordpool":{"service_id":"ha_nordpool","poll_interval_s":60}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err == nil { + t.Fatal("extra field on a matching key was accepted") + } +} + +func TestPatternPropertiesRejectsNonMatchingKey(t *testing.T) { + data := []byte(`{"services":{"foo":{"service_id":"foo"}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err == nil { + t.Fatal("non-matching key was accepted under additionalProperties false") + } +} From e5162ec0b494d39cf939e74c6c8ba65dffd10a74 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:11:06 +0100 Subject: [PATCH 05/16] feat(bundle): add step 87 for Home Assistant ports Step 87 is an optional step, on by default, that sets up the Home Assistant ports. The manifest marks it with ha_ports true, and the bundle stages the port unit template at ha/energy-node-ha@.service, rendered to the target user like the other units. The step script bootstrap/87-*.sh comes in a later change, so until it exists the manifest carries step 87 without a fingerprint. Co-Authored-By: Claude Sonnet 5.5 --- installer/internal/bundle/manifest.go | 4 ++++ installer/internal/bundle/manifest_test.go | 17 +++++++++++++++++ scripts/build/make_bundle.sh | 18 ++++++++++++++++-- scripts/tests/test_build_make_bundle.sh | 17 ++++++++++++++++- 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/installer/internal/bundle/manifest.go b/installer/internal/bundle/manifest.go index 28d262e8..26ba6c31 100644 --- a/installer/internal/bundle/manifest.go +++ b/installer/internal/bundle/manifest.go @@ -34,6 +34,10 @@ type StepEntry struct { // Erstinstallation gilt (89 Beispiel). Gibt es schon einen installierten // Stand, ist er abgewaehlt (plan.sh). FirstInstallOnly bool `json:"first_install_only,omitempty"` + // HAPorts markiert den Schritt, der die Home-Assistant-Ports einrichtet + // (Dienst-Unit energy-node-ha@.service aus ha/). Fehlt das Feld, gilt der + // Schritt als gewoehnlicher optionaler Schritt. + HAPorts bool `json:"ha_ports,omitempty"` // Fingerprint deckt das Skript des Schritts und die Eingaben, die es in // "# step-inputs:" nennt (scripts/build/lib/manifest.sh). Solange er // gleich bleibt, gilt der Stempel auf dem Node auch ueber ein Update diff --git a/installer/internal/bundle/manifest_test.go b/installer/internal/bundle/manifest_test.go index 802a74ee..3a2a56a1 100644 --- a/installer/internal/bundle/manifest_test.go +++ b/installer/internal/bundle/manifest_test.go @@ -201,3 +201,20 @@ func TestStepEntryOmitsEmptyDashboardKey(t *testing.T) { t.Fatalf("dashboard_key sollte bei leerem Wert fehlen: %s", got) } } + +func TestStepEntryParsesHAPortsFlag(t *testing.T) { + var got bundle.StepEntry + if err := json.Unmarshal([]byte(`{"id":"87","optional":true,"default":true,"ha_ports":true}`), &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if !got.HAPorts { + t.Fatal("HAPorts = false, erwartet true") + } + raw, err := json.Marshal(bundle.StepEntry{ID: "10", Optional: false}) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if strings.Contains(string(raw), "ha_ports") { + t.Fatalf("ha_ports sollte bei false fehlen: %s", raw) + } +} diff --git a/scripts/build/make_bundle.sh b/scripts/build/make_bundle.sh index 0a91072b..fb9aab14 100755 --- a/scripts/build/make_bundle.sh +++ b/scripts/build/make_bundle.sh @@ -38,7 +38,7 @@ BINARY_NAME="energy-node-dashboard" # Kern laeuft immer; optional ist waehlbar, Vorgabe an (E7). CORE_STEPS=(10 20 30 50 60 65 67) -OPTIONAL_STEPS=(15 17 35 40 41 70 89) +OPTIONAL_STEPS=(15 17 35 40 41 70 87 89) # 15 (Systempakete aktualisieren) ist optional mit Vorgabe an: abwaehlen # laesst nur die Pruefung uebrig (scripts/bootstrap/15-system-upgrade.sh). # Opt-in: optionale Schritte mit Vorgabe aus. 35 gibt den Port des Shelly- @@ -47,6 +47,10 @@ OPTIONAL_STEPS=(15 17 35 40 41 70 89) # den Arbeitsspeicher: spart Schreibzyklen auf der SD-Karte, kostet aber die # Logs nach einem Neustart (scripts/bootstrap/17-journal-volatile.sh). OPT_IN_STEPS=(17 35) +# ha_ports: optionale Schritte, die die Home-Assistant-Ports einrichten. Sie +# stehen im Manifest mit "ha_ports": true, damit Installer und Oberflaeche sie +# als Port-Schritte erkennen (87 richtet energy-node-ha@.service aus ha/ ein). +HA_PORT_STEPS=(87) # first_install_only: Vorgabe an, aber nur bei der Erstinstallation. Ein Node, # der schon einen installierten Stand hat (installed-manifest.json), waehlt # den Schritt nicht von selbst neu dazu (plan.sh). 89 ist das Beispiel. @@ -230,6 +234,13 @@ for entry in "${SERVICE_TABLE[@]}"; do cp "${src}/manifest.json" "${STAGE}/config/manifests/${service_id}.json" done +# --- ha/ ------------------------------------------------------------------- +# Vorlage der Home-Assistant-Port-Unit; Schritt 87 installiert sie als +# energy-node-ha@.service. Ohne --user bleibt sie unveraendert. +mkdir -p "${STAGE}/ha" +stage_template "${REPO_ROOT}/libs/energy_node_common/systemd/energy-node-ha@.service" \ + "${STAGE}/ha/energy-node-ha@.service" + # --- config/ --------------------------------------------------------------- cp "${REPO_ROOT}/dashboard/internal/appconfig/energy-node.config.json" "${STAGE}/config/config.json" @@ -267,7 +278,7 @@ ARCH="${ARCH}" VERSION="${VERSION}" BOOTSTRAP_VERSION="${BOOTSTRAP_VERSION}" PYT PACKAGES_JSON="${BUILD_DIR}/packages.json" WHEEL_PINS_JSON="${WHEEL_WORK}/pins.json" \ BUNDLE_USER="${BUNDLE_USER}" BUNDLE_BASE="${BUNDLE_BASE}" REPO_ROOT="${REPO_ROOT}" \ UNAME_MACHINES="$(arch_uname_machines "${ARCH}" | paste -sd, -)" \ -CORE_STEPS="${CORE_STEPS[*]}" OPTIONAL_STEPS="${OPTIONAL_STEPS[*]}" OPT_IN_STEPS="${OPT_IN_STEPS[*]}" \ +CORE_STEPS="${CORE_STEPS[*]}" OPTIONAL_STEPS="${OPTIONAL_STEPS[*]}" OPT_IN_STEPS="${OPT_IN_STEPS[*]}" HA_PORT_STEPS="${HA_PORT_STEPS[*]}" \ FIRST_INSTALL_ONLY_STEPS="${FIRST_INSTALL_ONLY_STEPS[*]}" \ SERVICE_ROWS="$(printf '%s\n' "${SERVICE_TABLE[@]}")" \ SERVICE_STEP_ROWS="$(printf '%s\n' "${SERVICE_STEPS[@]}")" \ @@ -293,6 +304,7 @@ steps = [] for step_id in os.environ["CORE_STEPS"].split(): steps.append({"id": step_id, "optional": False}) opt_in = set(os.environ["OPT_IN_STEPS"].split()) +ha_port = set(os.environ["HA_PORT_STEPS"].split()) first_install_only = set(os.environ["FIRST_INSTALL_ONLY_STEPS"].split()) requires = dict(row.split(":", 1) for row in os.environ["STEP_REQUIRES_ROWS"].splitlines() if row.strip()) for step_id in os.environ["OPTIONAL_STEPS"].split(): @@ -301,6 +313,8 @@ for step_id in os.environ["OPTIONAL_STEPS"].split(): entry["requires"] = requires[step_id] if step_id in first_install_only: entry["first_install_only"] = True + if step_id in ha_port: + entry["ha_ports"] = True if step_id in optional_dashboard_keys: entry["dashboard_key"] = optional_dashboard_keys[step_id] steps.append(entry) diff --git a/scripts/tests/test_build_make_bundle.sh b/scripts/tests/test_build_make_bundle.sh index bf39d5e7..b6a0ebec 100755 --- a/scripts/tests/test_build_make_bundle.sh +++ b/scripts/tests/test_build_make_bundle.sh @@ -82,6 +82,12 @@ done || fail "signing public key not staged into the bundle" # --- Units sind gerendert -------------------------------------------------- +[[ -f "$out/ha/energy-node-ha@.service" ]] \ + || fail "ha/energy-node-ha@.service fehlt im Bundle" +grep -q '^User=pruef$' "$out/ha/energy-node-ha@.service" \ + || fail "HA-Port-Unit nicht auf den Benutzer gerendert" "$(cat "$out/ha/energy-node-ha@.service")" +grep -q '\benergynode\b' "$out/ha/energy-node-ha@.service" \ + && fail "Platzhalter in der HA-Port-Unit" "$(cat "$out/ha/energy-node-ha@.service")" grep -q 'energynode' "$out/services/shelly/shelly-rpc.service" \ && fail "Platzhalter in der Dienst-Unit" "$(cat "$out/services/shelly/shelly-rpc.service")" grep -q 'energynode' "$out/dashboard/energy-node-dashboard.service" \ @@ -98,7 +104,7 @@ get() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(eval( [ "$(get 'd["target_user"]')" = pruef ] || fail "target_user falsch" [ "$(get 'd["target_base"]')" = /home/pruef ] || fail "target_base falsch" [ "$(get 'sorted(s["id"] for s in d["steps"])')" \ - = "['10', '15', '17', '20', '30', '35', '40', '41', '50', '60', '65', '67', '70', '81', '82', '83', '84', '85', '88', '89']" ] \ + = "['10', '15', '17', '20', '30', '35', '40', '41', '50', '60', '65', '67', '70', '81', '82', '83', '84', '85', '87', '88', '89']" ] \ || fail "Schrittliste falsch" "$(get 'sorted(s["id"] for s in d["steps"])')" [ "$(get 'next(s["optional"] for s in d["steps"] if s["id"]=="40")')" = True ] \ || fail "40 nicht optional" @@ -110,6 +116,15 @@ get() { python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(eval( || fail "Schritt 83 traegt kein kind=device" [ "$(get 'next(s["kind"] for s in d["steps"] if s["id"]=="88")')" = service ] \ || fail "Schritt 88 traegt kein kind=service" +# Schritt 87 richtet die HA-Ports ein: optional, Vorgabe an, mit ha_ports. +[ "$(get 'next(s["optional"] for s in d["steps"] if s["id"]=="87")')" = True ] \ + || fail "87 nicht optional" +[ "$(get 'next(s["default"] for s in d["steps"] if s["id"]=="87")')" = True ] \ + || fail "87 nicht standardmaessig an" +[ "$(get 'next(s["ha_ports"] for s in d["steps"] if s["id"]=="87")')" = True ] \ + || fail "87 traegt kein ha_ports=true" +[ "$(get 'sorted(s["id"] for s in d["steps"] if s.get("ha_ports"))')" = "['87']" ] \ + || fail "ha_ports steht an anderen Schritten" [ "$(get '"bootstrap" in d["components"]')" = True ] || fail "Bootstrap-Version fehlt" # --- Festlegungen: manifest.packages ist der Eintrag der Architektur ------ From e016b219ee3e1ece389b4fea34186e5ce85e2fce Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:13:06 +0100 Subject: [PATCH 06/16] feat(bootstrap): add the planner for Home Assistant port installs ha_ports.py validates the selected ports against the signed catalog before anything is written: architecture, Python and layer versions, and the SHA-256 of the port wheel and its dependencies. plan writes the manifests and schemas only after all checks pass. config adds the services.ha_ section once, record writes the installed state. Co-Authored-By: Claude Sonnet 5.5 --- scripts/bootstrap/lib/ha_ports.py | 177 +++++++++++++++++++++++++++++ scripts/tests/test_ha_ports.py | 181 ++++++++++++++++++++++++++++++ 2 files changed, 358 insertions(+) create mode 100644 scripts/bootstrap/lib/ha_ports.py create mode 100644 scripts/tests/test_ha_ports.py diff --git a/scripts/bootstrap/lib/ha_ports.py b/scripts/bootstrap/lib/ha_ports.py new file mode 100644 index 00000000..eee6d944 --- /dev/null +++ b/scripts/bootstrap/lib/ha_ports.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Planer und Zustand fuer die Home-Assistant-Ports (Schritt 87). + +Laeuft mit dem System-python3, nur Standardbibliothek plus +pip._vendor.packaging. Unterbefehle: + + plan + Prueft die Auswahl gegen den Katalog und schreibt Manifeste und Schemas + nach . Ausgabe je Zeile: installdomainwheelchanged + oder removedomain. Fehler: eine Zeile FEHLER auf + stderr, Exit 1, und nichts wird nach geschrieben. + + config ... + Ergaenzt services.ha_ = {"service_id": "ha_"}, falls der + Abschnitt fehlt. Alles andere bleibt unveraendert. + + record ... + Schreibt den installierten Stand fuer genau diese Domains. +""" +import hashlib +import importlib.metadata +import json +import sys +from pathlib import Path + +from pip._vendor.packaging.specifiers import SpecifierSet +from pip._vendor.packaging.version import Version + +LAYER_PACKAGE = "energy-node-common" + + +class PlanError(Exception): + def __init__(self, code, detail): + super().__init__(code, detail) + self.code = code + self.detail = detail + + +def installed_layer_version(): + try: + return importlib.metadata.version(LAYER_PACKAGE) + except importlib.metadata.PackageNotFoundError: + return "0" + + +def _load_json(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def _dump_json(data): + return json.dumps(data, indent=2, ensure_ascii=False) + "\n" + + +def _sha256_of(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _check_file(ports_dir, entry): + """Datei muss im Ordner liegen und die SHA-256 aus dem Katalog haben.""" + filename = str(entry.get("filename", "")) + if not filename or Path(filename).name != filename: + raise PlanError("HA_PORT_WHEEL_INVALID", filename) + path = ports_dir / filename + if not path.is_file() or _sha256_of(path) != entry.get("sha256"): + raise PlanError("HA_PORT_WHEEL_INVALID", filename) + + +def _python_version_text(): + info = sys.version_info + return f"{info.major}.{info.minor}.{info.micro}" + + +def _find_port(catalog, domain): + for port in catalog.get("ports") or []: + if port.get("domain") == domain: + return port + return None + + +def _resolve(ports_dir, catalog, arch, domain): + port = _find_port(catalog, domain) + if port is None or arch not in (port.get("arches") or {}): + raise PlanError("HA_PORT_UNKNOWN", domain) + + if Version(_python_version_text()) not in SpecifierSet(port["requires_python"]): + raise PlanError("HA_PORT_PYTHON_TOO_OLD", domain) + + if Version(installed_layer_version()) < Version(port["layer_min"]): + raise PlanError("HA_PORT_LAYER_TOO_OLD", domain) + + _check_file(ports_dir, port["wheel"]) + for dep in port["arches"][arch]: + _check_file(ports_dir, dep) + return port + + +def _plan(ports_dir, bundle_manifest, selection_file, installed_file, out_dir): + catalog = _load_json(ports_dir / "catalog.json") + arch = _load_json(bundle_manifest).get("arch", "") + selection = _load_json(selection_file).get("ha_ports") or [] + selected = sorted(set(selection)) + + installed_ports = {} + if Path(installed_file).is_file(): + installed_ports = _load_json(installed_file).get("ports") or {} + + # Alles pruefen, bevor eine Datei entsteht. + resolved = [(domain, _resolve(ports_dir, catalog, arch, domain)) for domain in selected] + + lines = [] + for domain, port in resolved: + installed_sha = (installed_ports.get(domain) or {}).get("wheel_sha256") + changed = 0 if installed_sha == port["wheel"]["sha256"] else 1 + lines.append(f"install\t{domain}\t{port['wheel']['filename']}\t{changed}") + for domain in sorted(installed_ports): + if domain not in selected: + lines.append(f"remove\t{domain}") + + out_dir = Path(out_dir) + (out_dir / "manifests").mkdir(parents=True, exist_ok=True) + (out_dir / "schemas").mkdir(parents=True, exist_ok=True) + for domain, port in resolved: + (out_dir / "manifests" / f"ha_{domain}.json").write_text( + _dump_json(port["manifest"]), encoding="utf-8") + (out_dir / "schemas" / f"ha_{domain}_devices.schema.json").write_text( + _dump_json(port["schema"]), encoding="utf-8") + return lines + + +def _config(src, dst, domains): + data = _load_json(src) + services = data.setdefault("services", {}) + for domain in domains: + key = f"ha_{domain}" + if key not in services: + services[key] = {"service_id": key} + Path(dst).write_text(_dump_json(data), encoding="utf-8") + return 0 + + +def _record(installed_file, ports_dir, domains): + catalog = _load_json(Path(ports_dir) / "catalog.json") + ports = {} + for domain in sorted(set(domains)): + port = _find_port(catalog, domain) + if port is None: + raise PlanError("HA_PORT_UNKNOWN", domain) + ports[domain] = {"version": port["version"], "wheel_sha256": port["wheel"]["sha256"]} + state = {"catalog_tag": catalog.get("tag", ""), "ports": ports} + Path(installed_file).write_text(_dump_json(state), encoding="utf-8") + return 0 + + +def main(argv): + if not argv: + print("Aufruf: ha_ports.py plan|config|record ...", file=sys.stderr) + return 2 + cmd, args = argv[0], argv[1:] + try: + if cmd == "plan" and len(args) == 5: + ports_dir, bundle, selection, installed, out = args + for line in _plan(Path(ports_dir), bundle, selection, installed, out): + print(line) + return 0 + if cmd == "config" and len(args) >= 2: + return _config(args[0], args[1], args[2:]) + if cmd == "record" and len(args) >= 2: + return _record(args[0], args[1], args[2:]) + except PlanError as err: + print(f"FEHLER {err.code} {err.detail}", file=sys.stderr) + return 1 + print(f"Unbekannter Aufruf: {' '.join(argv)}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/tests/test_ha_ports.py b/scripts/tests/test_ha_ports.py new file mode 100644 index 00000000..e901a54d --- /dev/null +++ b/scripts/tests/test_ha_ports.py @@ -0,0 +1,181 @@ +"""Tests for scripts/bootstrap/lib/ha_ports.py (plan, config, record).""" +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "bootstrap" / "lib" / "ha_ports.py" +spec = importlib.util.spec_from_file_location("ha_ports", SCRIPT) +ha_ports = importlib.util.module_from_spec(spec) +sys.modules["ha_ports"] = ha_ports +spec.loader.exec_module(ha_ports) + +PORT_WHEEL = "energy_node_ha_demo-1.0-py3-none-any.whl" +DEP_WHEEL = "dep_lib-1.0-py3-none-any.whl" +PORT_BYTES = b"port wheel bytes" +DEP_BYTES = b"dependency bytes" + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +@pytest.fixture(autouse=True) +def layer_version(monkeypatch): + # Die installierte energy-node-common-Version ist in Tests fest. + monkeypatch.setattr(ha_ports, "installed_layer_version", lambda: "1.0") + + +def make_catalog(tmp_path, arches=("arm64",), requires_python=">=3.8", layer_min="0.0"): + """Katalog Format 2 mit einem Port demo, Wheels liegen im ha-ports-Ordner.""" + ports_dir = tmp_path / "ha-ports" + ports_dir.mkdir(exist_ok=True) + (ports_dir / PORT_WHEEL).write_bytes(PORT_BYTES) + (ports_dir / DEP_WHEEL).write_bytes(DEP_BYTES) + dep = {"name": "dep-lib", "version": "1.0", "filename": DEP_WHEEL, + "url": "https://example.invalid/" + DEP_WHEEL, "sha256": sha(DEP_BYTES)} + catalog = { + "format": 2, + "tag": "ha-ports-test", + "ha_version": "1.0", + "layer": {"ref": "main", "layer_min": "1.0"}, + "ports": [{ + "domain": "demo", + "package": "energy_node_ha_demo", + "version": "1.0", + "requires_python": requires_python, + "layer_min": layer_min, + "manifest": {"domain": "demo", "name": "Demo"}, + "schema": {"type": "array", "title": "Demo devices"}, + "wheel": {"filename": PORT_WHEEL, "url": "https://example.invalid/" + PORT_WHEEL, + "sha256": sha(PORT_BYTES)}, + "arches": {arch: [dict(dep)] for arch in arches}, + }], + } + (ports_dir / "catalog.json").write_text(json.dumps(catalog), encoding="utf-8") + return ports_dir + + +def write_json(path, data): + path.write_text(json.dumps(data), encoding="utf-8") + return path + + +def run_plan(tmp_path, ports_dir, selection=("demo",), installed=None, arch="arm64", out=None): + bundle = write_json(tmp_path / "bundle.json", {"arch": arch}) + sel_data = {"steps": []} + if selection is not None: + sel_data["ha_ports"] = list(selection) + sel = write_json(tmp_path / "selection.json", sel_data) + inst = write_json(tmp_path / "installed.json", installed or {"catalog_tag": "", "ports": {}}) + out = out or (tmp_path / "out") + return ha_ports.main(["plan", str(ports_dir), str(bundle), str(sel), str(inst), str(out)]), out + + +def test_plan_install_new_port(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + code, out = run_plan(tmp_path, ports_dir) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out.splitlines() == [f"install\tdemo\t{PORT_WHEEL}\t1"] + manifest = json.loads((out / "manifests" / "ha_demo.json").read_text(encoding="utf-8")) + assert manifest == {"domain": "demo", "name": "Demo"} + schema = json.loads((out / "schemas" / "ha_demo_devices.schema.json").read_text(encoding="utf-8")) + assert schema == {"type": "array", "title": "Demo devices"} + + +def test_plan_unchanged_port(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + installed = {"catalog_tag": "ha-ports-test", + "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}} + code, _ = run_plan(tmp_path, ports_dir, installed=installed) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out.splitlines() == [f"install\tdemo\t{PORT_WHEEL}\t0"] + + +def test_plan_remove_deselected(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + installed = {"catalog_tag": "ha-ports-test", + "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}} + code, _ = run_plan(tmp_path, ports_dir, selection=(), installed=installed) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out.splitlines() == ["remove\tdemo"] + + +def test_plan_missing_selection_field_means_none(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + code, _ = run_plan(tmp_path, ports_dir, selection=None) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out == "" + + +def test_plan_wrong_hash(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + (ports_dir / PORT_WHEEL).write_bytes(b"tampered") + code, out = run_plan(tmp_path, ports_dir) + captured = capsys.readouterr() + assert code == 1 + assert f"FEHLER HA_PORT_WHEEL_INVALID {PORT_WHEEL}" in captured.err + assert not out.exists() or list(out.iterdir()) == [] + + +def test_plan_unknown_arch(tmp_path, capsys): + ports_dir = make_catalog(tmp_path, arches=("amd64",)) + code, out = run_plan(tmp_path, ports_dir, arch="arm64") + captured = capsys.readouterr() + assert code == 1 + assert "FEHLER HA_PORT_UNKNOWN demo" in captured.err + assert not out.exists() or list(out.iterdir()) == [] + + +def test_plan_python_too_old(tmp_path, capsys): + ports_dir = make_catalog(tmp_path, requires_python=">=9.0") + code, out = run_plan(tmp_path, ports_dir) + captured = capsys.readouterr() + assert code == 1 + assert "FEHLER HA_PORT_PYTHON_TOO_OLD demo" in captured.err + assert not out.exists() or list(out.iterdir()) == [] + + +def test_plan_layer_too_old(tmp_path, capsys): + ports_dir = make_catalog(tmp_path, layer_min="99.0") + code, out = run_plan(tmp_path, ports_dir) + captured = capsys.readouterr() + assert code == 1 + assert "FEHLER HA_PORT_LAYER_TOO_OLD demo" in captured.err + assert not out.exists() or list(out.iterdir()) == [] + + +def test_config_adds_section_once(tmp_path): + original = { + "services": {"mqtt": {"host": "localhost"}}, + "theme": {"accent": "#0af", "name": "Grün"}, + } + src = write_json(tmp_path / "config.json", original) + dst = tmp_path / "out.json" + assert ha_ports.main(["config", str(src), str(dst), "demo"]) == 0 + assert ha_ports.main(["config", str(dst), str(dst), "demo"]) == 0 + result = json.loads(dst.read_text(encoding="utf-8")) + assert result["services"]["ha_demo"] == {"service_id": "ha_demo"} + assert sum(1 for k in result["services"] if k == "ha_demo") == 1 + assert result["services"]["mqtt"] == original["services"]["mqtt"] + assert result["theme"] == original["theme"] + assert "Grün" in dst.read_text(encoding="utf-8") + + +def test_record_writes_contract_shape(tmp_path): + ports_dir = make_catalog(tmp_path) + installed = tmp_path / "ha-ports-installed.json" + assert ha_ports.main(["record", str(installed), str(ports_dir), "demo"]) == 0 + data = json.loads(installed.read_text(encoding="utf-8")) + assert data == { + "catalog_tag": "ha-ports-test", + "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}, + } From 55fa04e8b90039a4692342384d147e130464c5e8 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:15:27 +0100 Subject: [PATCH 07/16] fix(bootstrap): validate inputs of the port planner Domains from the selection, the catalog and the installed state must match ^[a-z0-9_]{1,40}$. Wheel filenames that are empty, ".", "..", or contain a slash or backslash are rejected explicitly. A malformed catalog reports HA_PORTS_CATALOG_INVALID instead of a traceback. The config step accepts a null services value and rejects any other non-object. A selection that is not a list of strings is rejected. SHA-256 comparisons ignore case. Co-Authored-By: Claude Sonnet 5.5 --- scripts/bootstrap/lib/ha_ports.py | 134 +++++++++++++++++++++++++----- scripts/tests/test_ha_ports.py | 108 ++++++++++++++++++++++++ 2 files changed, 221 insertions(+), 21 deletions(-) diff --git a/scripts/bootstrap/lib/ha_ports.py b/scripts/bootstrap/lib/ha_ports.py index eee6d944..e8d5ba4f 100644 --- a/scripts/bootstrap/lib/ha_ports.py +++ b/scripts/bootstrap/lib/ha_ports.py @@ -20,13 +20,15 @@ import hashlib import importlib.metadata import json +import re import sys from pathlib import Path -from pip._vendor.packaging.specifiers import SpecifierSet -from pip._vendor.packaging.version import Version +from pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet +from pip._vendor.packaging.version import InvalidVersion, Version LAYER_PACKAGE = "energy-node-common" +DOMAIN_RE = re.compile(r"[a-z0-9_]{1,40}") class PlanError(Exception): @@ -55,13 +57,97 @@ def _sha256_of(path): return hashlib.sha256(path.read_bytes()).hexdigest() +def _check_domain(domain): + if not isinstance(domain, str) or not DOMAIN_RE.fullmatch(domain): + raise PlanError("HA_PORT_UNKNOWN", str(domain)) + return domain + + +def _catalog_error(detail): + return PlanError("HA_PORTS_CATALOG_INVALID", detail) + + +def _require(obj, key, kind, where): + if not isinstance(obj, dict) or key not in obj: + raise _catalog_error(f"{where} hat kein Feld {key}") + value = obj[key] + if not isinstance(value, kind): + raise _catalog_error(f"{where}.{key} hat den falschen Typ") + return value + + +def _load_catalog(ports_dir): + try: + catalog = _load_json(Path(ports_dir) / "catalog.json") + except (OSError, ValueError) as err: + raise _catalog_error(f"catalog.json nicht lesbar: {err}") + if not isinstance(catalog, dict) or catalog.get("format") != 2: + raise _catalog_error("catalog hat nicht format 2") + _require(catalog, "tag", str, "catalog") + ports = _require(catalog, "ports", list, "catalog") + for index, port in enumerate(ports): + where = f"ports[{index}]" + if not isinstance(port, dict): + raise _catalog_error(f"{where} ist kein Objekt") + _check_domain(_require(port, "domain", str, where)) + version = _require(port, "version", str, where) + requires_python = _require(port, "requires_python", str, where) + layer_min = _require(port, "layer_min", str, where) + _require(port, "manifest", dict, where) + _require(port, "schema", dict, where) + wheel = _require(port, "wheel", dict, where) + _require(wheel, "filename", str, where + ".wheel") + _require(wheel, "sha256", str, where + ".wheel") + arches = _require(port, "arches", dict, where) + for arch, deps in arches.items(): + if not isinstance(deps, list): + raise _catalog_error(f"{where}.arches.{arch} ist keine Liste") + for dep in deps: + _require(dep, "filename", str, f"{where}.arches.{arch}") + _require(dep, "sha256", str, f"{where}.arches.{arch}") + try: + Version(version) + Version(layer_min) + SpecifierSet(requires_python) + except (InvalidVersion, InvalidSpecifier) as err: + raise _catalog_error(f"{where} hat eine ungueltige Angabe: {err}") + return catalog + + +def _selection(data): + if not isinstance(data, dict): + raise PlanError("HA_PORT_UNKNOWN", "auswahl") + if "ha_ports" not in data: + return [] + value = data["ha_ports"] + if not isinstance(value, list): + raise PlanError("HA_PORT_UNKNOWN", str(value)) + return [_check_domain(domain) for domain in value] + + +def _installed_ports(installed_file): + if not Path(installed_file).is_file(): + return {} + data = _load_json(installed_file) + if not isinstance(data, dict): + raise PlanError("HA_PORT_UNKNOWN", "installed-json") + ports = data.get("ports") or {} + if not isinstance(ports, dict): + raise PlanError("HA_PORT_UNKNOWN", "installed-json") + for domain, entry in ports.items(): + _check_domain(domain) + if not isinstance(entry, dict): + raise PlanError("HA_PORT_UNKNOWN", domain) + return ports + + def _check_file(ports_dir, entry): """Datei muss im Ordner liegen und die SHA-256 aus dem Katalog haben.""" - filename = str(entry.get("filename", "")) - if not filename or Path(filename).name != filename: + filename = entry["filename"] + if filename in ("", ".", "..") or "/" in filename or "\\" in filename: raise PlanError("HA_PORT_WHEEL_INVALID", filename) path = ports_dir / filename - if not path.is_file() or _sha256_of(path) != entry.get("sha256"): + if not path.is_file() or _sha256_of(path) != entry["sha256"].lower(): raise PlanError("HA_PORT_WHEEL_INVALID", filename) @@ -71,15 +157,15 @@ def _python_version_text(): def _find_port(catalog, domain): - for port in catalog.get("ports") or []: - if port.get("domain") == domain: + for port in catalog["ports"]: + if port["domain"] == domain: return port return None def _resolve(ports_dir, catalog, arch, domain): port = _find_port(catalog, domain) - if port is None or arch not in (port.get("arches") or {}): + if port is None or arch not in port["arches"]: raise PlanError("HA_PORT_UNKNOWN", domain) if Version(_python_version_text()) not in SpecifierSet(port["requires_python"]): @@ -95,22 +181,18 @@ def _resolve(ports_dir, catalog, arch, domain): def _plan(ports_dir, bundle_manifest, selection_file, installed_file, out_dir): - catalog = _load_json(ports_dir / "catalog.json") + catalog = _load_catalog(ports_dir) arch = _load_json(bundle_manifest).get("arch", "") - selection = _load_json(selection_file).get("ha_ports") or [] - selected = sorted(set(selection)) - - installed_ports = {} - if Path(installed_file).is_file(): - installed_ports = _load_json(installed_file).get("ports") or {} + selected = sorted(set(_selection(_load_json(selection_file)))) + installed_ports = _installed_ports(installed_file) # Alles pruefen, bevor eine Datei entsteht. resolved = [(domain, _resolve(ports_dir, catalog, arch, domain)) for domain in selected] lines = [] for domain, port in resolved: - installed_sha = (installed_ports.get(domain) or {}).get("wheel_sha256") - changed = 0 if installed_sha == port["wheel"]["sha256"] else 1 + installed_sha = str((installed_ports.get(domain) or {}).get("wheel_sha256") or "") + changed = 0 if installed_sha.lower() == port["wheel"]["sha256"].lower() else 1 lines.append(f"install\t{domain}\t{port['wheel']['filename']}\t{changed}") for domain in sorted(installed_ports): if domain not in selected: @@ -128,8 +210,16 @@ def _plan(ports_dir, bundle_manifest, selection_file, installed_file, out_dir): def _config(src, dst, domains): + for domain in domains: + _check_domain(domain) data = _load_json(src) - services = data.setdefault("services", {}) + if not isinstance(data, dict): + raise PlanError("HA_PORTS_CONFIG_INVALID", "Wurzel ist kein Objekt") + services = data.get("services") + if services is None: + services = data["services"] = {} + if not isinstance(services, dict): + raise PlanError("HA_PORTS_CONFIG_INVALID", "services ist kein Objekt") for domain in domains: key = f"ha_{domain}" if key not in services: @@ -139,14 +229,16 @@ def _config(src, dst, domains): def _record(installed_file, ports_dir, domains): - catalog = _load_json(Path(ports_dir) / "catalog.json") + for domain in domains: + _check_domain(domain) + catalog = _load_catalog(ports_dir) ports = {} for domain in sorted(set(domains)): port = _find_port(catalog, domain) if port is None: raise PlanError("HA_PORT_UNKNOWN", domain) - ports[domain] = {"version": port["version"], "wheel_sha256": port["wheel"]["sha256"]} - state = {"catalog_tag": catalog.get("tag", ""), "ports": ports} + ports[domain] = {"version": port["version"], "wheel_sha256": port["wheel"]["sha256"].lower()} + state = {"catalog_tag": catalog["tag"], "ports": ports} Path(installed_file).write_text(_dump_json(state), encoding="utf-8") return 0 diff --git a/scripts/tests/test_ha_ports.py b/scripts/tests/test_ha_ports.py index e901a54d..732496f2 100644 --- a/scripts/tests/test_ha_ports.py +++ b/scripts/tests/test_ha_ports.py @@ -179,3 +179,111 @@ def test_record_writes_contract_shape(tmp_path): "catalog_tag": "ha-ports-test", "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}, } + + +def edit_catalog(ports_dir, mutate): + path = ports_dir / "catalog.json" + catalog = json.loads(path.read_text(encoding="utf-8")) + mutate(catalog) + path.write_text(json.dumps(catalog), encoding="utf-8") + + +def assert_plan_error(tmp_path, capsys, expected, **kwargs): + ports_dir = kwargs.pop("ports_dir") + code, out = run_plan(tmp_path, ports_dir, **kwargs) + captured = capsys.readouterr() + assert code == 1, captured.err + assert expected in captured.err + assert "Traceback" not in captured.err + assert not out.exists() or list(out.iterdir()) == [] + + +@pytest.mark.parametrize("bad", ["Demo", "de-mo", "", "x" * 41, "a/b"]) +def test_plan_rejects_bad_selected_domain(tmp_path, capsys, bad): + ports_dir = make_catalog(tmp_path) + assert_plan_error(tmp_path, capsys, f"FEHLER HA_PORT_UNKNOWN {bad}", + ports_dir=ports_dir, selection=(bad,)) + + +def test_plan_rejects_bad_installed_domain(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + installed = {"catalog_tag": "", "ports": {"../evil": {"version": "1.0", "wheel_sha256": "x"}}} + assert_plan_error(tmp_path, capsys, "FEHLER HA_PORT_UNKNOWN ../evil", + ports_dir=ports_dir, selection=(), installed=installed) + + +def test_plan_rejects_bad_catalog_domain(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + edit_catalog(ports_dir, lambda c: c["ports"][0].update(domain="Demo")) + assert_plan_error(tmp_path, capsys, "FEHLER HA_PORT_UNKNOWN Demo", ports_dir=ports_dir) + + +@pytest.mark.parametrize("bad", [".", "..", "", "sub/wheel.whl", "sub\\wheel.whl"]) +def test_plan_rejects_bad_wheel_filename(tmp_path, capsys, bad): + ports_dir = make_catalog(tmp_path) + edit_catalog(ports_dir, lambda c: c["ports"][0]["wheel"].update(filename=bad)) + assert_plan_error(tmp_path, capsys, "FEHLER HA_PORT_WHEEL_INVALID", ports_dir=ports_dir) + + +@pytest.mark.parametrize("mutate", [ + lambda p: p.pop("requires_python"), + lambda p: p.update(requires_python=">>=bad"), + lambda p: p.update(layer_min="not a version"), + lambda p: p.pop("wheel"), + lambda p: p.update(arches="arm64"), +]) +def test_plan_reports_malformed_catalog(tmp_path, capsys, mutate): + ports_dir = make_catalog(tmp_path) + edit_catalog(ports_dir, lambda c: mutate(c["ports"][0])) + assert_plan_error(tmp_path, capsys, "FEHLER HA_PORTS_CATALOG_INVALID", ports_dir=ports_dir) + + +@pytest.mark.parametrize("value", ["demo", [1], [None], None]) +def test_plan_selection_must_be_list_of_strings(tmp_path, capsys, value): + ports_dir = make_catalog(tmp_path) + write_json(tmp_path / "selection.json", {"ha_ports": value}) + bundle = write_json(tmp_path / "bundle.json", {"arch": "arm64"}) + inst = write_json(tmp_path / "installed.json", {"catalog_tag": "", "ports": {}}) + out = tmp_path / "out" + code = ha_ports.main(["plan", str(ports_dir), str(bundle), str(tmp_path / "selection.json"), + str(inst), str(out)]) + captured = capsys.readouterr() + assert code == 1 + assert "FEHLER HA_PORT_UNKNOWN" in captured.err + assert not out.exists() + + +def test_plan_compares_sha_case_insensitively(tmp_path, capsys): + ports_dir = make_catalog(tmp_path) + edit_catalog(ports_dir, lambda c: c["ports"][0]["wheel"].update(sha256=sha(PORT_BYTES).upper())) + installed = {"catalog_tag": "ha-ports-test", + "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}} + code, _ = run_plan(tmp_path, ports_dir, installed=installed) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out.splitlines() == [f"install\tdemo\t{PORT_WHEEL}\t0"] + + +def test_config_null_services_becomes_object(tmp_path): + src = write_json(tmp_path / "config.json", {"services": None}) + dst = tmp_path / "out.json" + assert ha_ports.main(["config", str(src), str(dst), "demo"]) == 0 + result = json.loads(dst.read_text(encoding="utf-8")) + assert result["services"] == {"ha_demo": {"service_id": "ha_demo"}} + + +@pytest.mark.parametrize("services", ["text", [1], 3]) +def test_config_rejects_non_object_services(tmp_path, capsys, services): + src = write_json(tmp_path / "config.json", {"services": services}) + dst = tmp_path / "out.json" + assert ha_ports.main(["config", str(src), str(dst), "demo"]) == 1 + assert "FEHLER HA_PORTS_CONFIG_INVALID" in capsys.readouterr().err + assert not dst.exists() + + +def test_config_rejects_bad_domain(tmp_path, capsys): + src = write_json(tmp_path / "config.json", {"services": {}}) + dst = tmp_path / "out.json" + assert ha_ports.main(["config", str(src), str(dst), "Bad-Name"]) == 1 + assert "FEHLER HA_PORT_UNKNOWN Bad-Name" in capsys.readouterr().err + assert not dst.exists() From 4b598c4465d274579e5065ab26b5d5a26980261b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:19:49 +0100 Subject: [PATCH 08/16] feat(bootstrap): install, update and remove Home Assistant ports in step 87 Step 87 reads the port selection, verifies the signed port catalog only when ports are selected, and runs the planner in lib/ha_ports.py. It then installs or removes the ports with pip, renders the port unit, writes manifests, schemas and empty device files, adds the config sections, and enables or restarts the services. The installed state is recorded for the update hint. Without a selection and without installed ports the step is skipped. The service script test skips 87 like 89, since 87 is not a service table entry. Co-Authored-By: Claude Sonnet 5.5 --- scripts/bootstrap/87-ha-ports.sh | 203 ++++++++++++++++++ scripts/tests/test_bootstrap_ha_ports.sh | 200 +++++++++++++++++ .../tests/test_bootstrap_service_scripts.sh | 2 + 3 files changed, 405 insertions(+) create mode 100755 scripts/bootstrap/87-ha-ports.sh create mode 100755 scripts/tests/test_bootstrap_ha_ports.sh diff --git a/scripts/bootstrap/87-ha-ports.sh b/scripts/bootstrap/87-ha-ports.sh new file mode 100755 index 00000000..7c95b76b --- /dev/null +++ b/scripts/bootstrap/87-ha-ports.sh @@ -0,0 +1,203 @@ +#!/usr/bin/env bash +# +# Schritt 87: Home-Assistant-Ports installieren, aktualisieren und entfernen. +# +# Die gewaehlten Ports liegen als Wheels samt signiertem Katalog unter +# ${EN_STATE_DIR}/ha-ports. lib/ha_ports.py prueft die Auswahl gegen den +# Katalog und schreibt Manifeste und Schemas; dieser Schritt setzt das Ergebnis +# um: pip, Unit, Konfiguration, Dienst. Ports sind Opt-in, ohne Auswahl wird +# jeder installierte Port entfernt. +# Eingaben fuer den Fingerabdruck (scripts/build/lib/manifest.sh): solange +# sie gleich bleiben, ueberspringt ein Update diesen Schritt nicht - der Schritt +# laeuft bei jedem Lauf, weil sich die Auswahl ohne neuen Fingerabdruck aendert. +# step-inputs: bootstrap/lib/step.sh bootstrap/lib/render.sh bootstrap/lib/ha_ports.py bootstrap/keys/ ha/ +set -euo pipefail +# shellcheck source=scripts/bootstrap/lib/step.sh +source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/step.sh" +# shellcheck source=scripts/bootstrap/lib/render.sh +source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib/render.sh" + +HA_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/lib" +planner="${HA_LIB_DIR}/ha_ports.py" +ports_dir="${EN_STATE_DIR}/ha-ports" +installed="${EN_STATE_DIR}/ha-ports-installed.json" +cfg="${EN_ROOT}/etc/energy-node/config.json" +unit_template="energy-node-ha@.service" +devices="${EN_ROOT}${EN_TARGET_BASE}/devices" + +# EN_PIP existiert der Testbarkeit wegen, wie in 50-python-deps.sh. +read -r -a PIP <<< "${EN_PIP:-python3 -m pip}" + +step_begin 87 + +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT + +# Eine kaputte selection.json darf nicht als "nichts gewaehlt" durchgehen, +# sonst wuerde jeder installierte Port entfernt (wie 65-dashboard-config.sh). +if [[ -f "${EN_SELECTION}" ]] && ! python3 -c "import json,sys; json.load(open(sys.argv[1], encoding='utf-8'))" "${EN_SELECTION}" 2>/dev/null; then + step_fail SELECTION_UNREADABLE +fi + +arch="$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1], encoding="utf-8")).get("arch", ""))' "${EN_BUNDLE_DIR}/manifest.json" 2>/dev/null || true)" + +# Abgewaehlt oder armv6 heisst: die Auswahl ist leer. Dann entfernt der +# Planer installierte Ports, ohne dass ein Port neu gewaehlt werden kann. +selection="${EN_SELECTION}" +if [[ ! -f "${EN_SELECTION}" ]] || ! step_selected 87 || [[ "${arch}" == armv6 ]]; then + selection="${work}/selection.json" + printf '{"ha_ports": []}\n' > "${selection}" +fi + +# Nur bei gewaehlten Ports muss der Katalog signiert sein. Ohne Auswahl wird +# nichts installiert, also reicht der Planer mit dem bisherigen Stand. +wanted_count="$(python3 - "${selection}" <<'PY' +import json, sys +data = json.load(open(sys.argv[1], encoding="utf-8")) +ports = data.get("ha_ports") if isinstance(data, dict) else None +print(len(ports) if isinstance(ports, list) else 0) +PY +)" +if [[ "${wanted_count}" != 0 ]]; then + if ! openssl pkeyutl -verify -pubin \ + -inkey "${EN_BUNDLE_DIR}/bootstrap/keys/ha_ports_signing_key.pub.pem" \ + -rawin -in "${ports_dir}/catalog.json" \ + -sigfile "${ports_dir}/catalog.json.sig" >/dev/null 2>&1; then + step_fail HA_PORTS_CATALOG_INVALID + fi +fi + +# planner_fail : die FEHLER-Zeile des Planers wird +# zum Schrittfehler. Ohne sie (Absturz) gilt der Ersatzcode. +planner_fail() { + local line code + line="$(head -n 1 "$1")" + if [[ "${line}" == "FEHLER "* ]]; then + sed 's/^/ /' "$1" + read -r _ code _ <<< "${line}" + step_fail "${code}" + fi + sed 's/^/ /' "$1" + step_fail "$2" +} + +out="${work}/out" +mkdir -p "${out}" +plan="${work}/plan.txt" +if ! python3 "${planner}" plan "${ports_dir}" "${EN_BUNDLE_DIR}/manifest.json" \ + "${selection}" "${installed}" "${out}" > "${plan}" 2> "${work}/plan.err"; then + planner_fail "${work}/plan.err" HA_PORTS_PLAN_FAILED +fi + +if [[ ! -s "${plan}" ]]; then + step_skip "keine Ports gewählt" + exit 0 +fi + +installs=() +removes=() +while IFS=$'\t' read -r action domain wheel changed; do + case "${action}" in + install) installs+=("${domain}"$'\t'"${wheel}"$'\t'"${changed}") ;; + remove) removes+=("${domain}") ;; + esac +done < "${plan}" + +# install_port : pip aus dem Ports-Ordner ohne Index, wie 50-python-deps.sh. +# Kein --upgrade und kein --ignore-installed bei Ports. +install_port() { + local log="${work}/pip.log" + if "${SUDO[@]}" "${PIP[@]}" install --no-index --find-links "${ports_dir}" \ + --break-system-packages "${ports_dir}/$1" >"${log}" 2>&1; then + return 0 + fi + if grep -q 'no such option' "${log}"; then + step_log "Legacy-Image ohne Schalter fuer externe Umgebungen. Zweiter Versuch ohne ihn." + if "${SUDO[@]}" "${PIP[@]}" install --no-index --find-links "${ports_dir}" \ + "${ports_dir}/$1" >"${log}" 2>&1; then + return 0 + fi + fi + sed 's/^/ /' "${log}" + return 1 +} + +if [[ "${#installs[@]}" -gt 0 ]]; then + # Unit aus der Bundle-Vorlage fuer den Zielbenutzer rendern (lib/render.sh). + rendered="${work}/unit" + render_unit_as "${EN_BUNDLE_DIR}/ha/${unit_template}" "${rendered}" \ + "${EN_TARGET_USER}" "${EN_TARGET_BASE}" || step_fail TARGET_INVALID + "${SUDO[@]}" mkdir -p "${EN_ROOT}/etc/systemd/system" + "${SUDO[@]}" install -m 0644 "${rendered}" "${EN_ROOT}/etc/systemd/system/${unit_template}" \ + || step_fail SERVICE_UNIT_FAILED + "${SUDO[@]}" systemctl daemon-reload + + "${SUDO[@]}" mkdir -p "${EN_ROOT}/etc/energy-node/manifests" + mkdir -p "${devices}" + + installed_domains=() + config_domains=() + for row in "${installs[@]}"; do + IFS=$'\t' read -r domain wheel changed <<< "${row}" + if [[ "${changed}" == 1 ]] || ! "${PIP[@]}" show "energy-node-ha-${domain}" >/dev/null 2>&1; then + install_port "${wheel}" || step_fail HA_PORT_INSTALL_FAILED + fi + "${SUDO[@]}" install -m 0644 "${out}/manifests/ha_${domain}.json" \ + "${EN_ROOT}/etc/energy-node/manifests/ha_${domain}.json" || step_fail HA_PORT_INSTALL_FAILED + install -m 0644 "${out}/schemas/ha_${domain}_devices.schema.json" "${devices}/" \ + || step_fail HA_PORT_INSTALL_FAILED + # Betreiberdaten: die Geraetedatei entsteht nur, wenn sie fehlt. + if [[ ! -e "${devices}/ha_${domain}_devices.json" ]]; then + printf '[]\n' > "${devices}/ha_${domain}_devices.json" + fi + installed_domains+=("${domain}") + config_domains+=("${domain}") + done + + # Konfiguration wie 65-dashboard-config.sh: neue Datei in der Arbeitsdatei, + # dann per cp -p, tee und mv zurueck, damit Besitzer und Modus bleiben. + [[ -f "${cfg}" ]] || step_fail CONFIG_JSON_MISSING + new_cfg="${work}/config.json" + python3 "${planner}" config "${cfg}" "${new_cfg}" "${config_domains[@]}" \ + 2> "${work}/config.err" || planner_fail "${work}/config.err" HA_PORTS_CONFIG_INVALID + "${SUDO[@]}" cp -p "${cfg}" "${cfg}.tmp" || step_fail CONFIG_WRITE_FAILED + if ! "${SUDO[@]}" tee "${cfg}.tmp" < "${new_cfg}" >/dev/null; then + "${SUDO[@]}" rm -f "${cfg}.tmp" + step_fail CONFIG_WRITE_FAILED + fi + "${SUDO[@]}" mv "${cfg}.tmp" "${cfg}" || step_fail CONFIG_WRITE_FAILED + + for row in "${installs[@]}"; do + IFS=$'\t' read -r domain wheel changed <<< "${row}" + service="energy-node-ha@${domain}.service" + "${SUDO[@]}" systemctl enable "${service}" || step_fail SERVICE_START_FAILED + if [[ "${changed}" == 1 || "${EN_RESTART:-}" == all ]] \ + || ! "${SUDO[@]}" systemctl is-active --quiet "${service}"; then + "${SUDO[@]}" systemctl restart "${service}" || step_fail SERVICE_START_FAILED + step_log "Port ${domain} eingerichtet und neu gestartet." + else + step_log "Port ${domain} eingerichtet, unveraendert, kein Neustart." + fi + done +fi + +for domain in "${removes[@]}"; do + "${SUDO[@]}" systemctl disable --now "energy-node-ha@${domain}.service" \ + || step_log "Port ${domain} konnte nicht gestoppt werden." + "${SUDO[@]}" "${PIP[@]}" uninstall -y --break-system-packages "energy-node-ha-${domain}" \ + >/dev/null 2>&1 || step_log "Port ${domain} konnte nicht entfernt werden." + "${SUDO[@]}" rm -f "${EN_ROOT}/etc/energy-node/manifests/ha_${domain}.json" + rm -f "${devices}/ha_${domain}_devices.schema.json" + step_log "Port ${domain} entfernt. Geraetedatei und Konfiguration bleiben." +done + +# Der installierte Stand gilt fuer genau die Ports, die nach diesem Lauf +# laufen. Entfernte Ports fehlen darin. +recorded=() +if [[ "${#installs[@]}" -gt 0 ]]; then + recorded=("${installed_domains[@]}") +fi +python3 "${planner}" record "${installed}" "${ports_dir}" "${recorded[@]}" \ + 2> "${work}/record.err" || planner_fail "${work}/record.err" HA_PORTS_STATE_FAILED + +step_ok diff --git a/scripts/tests/test_bootstrap_ha_ports.sh b/scripts/tests/test_bootstrap_ha_ports.sh new file mode 100755 index 00000000..29df0c32 --- /dev/null +++ b/scripts/tests/test_bootstrap_ha_ports.sh @@ -0,0 +1,200 @@ +#!/usr/bin/env bash +# Test for scripts/bootstrap/87-ha-ports.sh +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +script="$here/../bootstrap/87-ha-ports.sh" + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +fail() { echo "FAIL: $1"; [ -n "${2:-}" ] && printf '%s\n' "$2"; exit 1; } + +# --- Fakes: pip und systemctl bleiben im Sandkasten ------------------------- +mkdir -p "$tmp/bin" "$tmp/pip-state" +cat > "$tmp/bin/fakepip" <<'SH' +#!/usr/bin/env bash +printf 'pip %s\n' "$*" >> "$PIP_LOG" +name="${@: -1}" +case "$1" in + install) + # Das Wheel ist das letzte Argument, sein Dateiname nennt den Paketnamen. + base="$(basename -- "$name")" + pkg="${base%%-*}" + touch "$PIP_STATE/${pkg//_/-}" + ;; + show) [ -e "$PIP_STATE/$name" ] ;; + uninstall) rm -f "$PIP_STATE/$name" ;; +esac +SH +chmod +x "$tmp/bin/fakepip" +cat > "$tmp/bin/systemctl" <<'SH' +#!/usr/bin/env bash +printf 'systemctl %s\n' "$*" >> "$SYSTEMCTL_LOG" +exit 0 +SH +chmod +x "$tmp/bin/systemctl" +export PATH="$tmp/bin:$PATH" +export PIP_LOG="$tmp/pip.log" PIP_STATE="$tmp/pip-state" SYSTEMCTL_LOG="$tmp/systemctl.log" + +# --- Test-Bundle mit eigenem Schluessel -------------------------------------- +bundle="$tmp/bundle" +mkdir -p "$bundle/bootstrap/keys" "$bundle/ha" +openssl genpkey -algorithm ed25519 -out "$tmp/sign.key" 2>/dev/null +openssl pkey -in "$tmp/sign.key" -pubout \ + -out "$bundle/bootstrap/keys/ha_ports_signing_key.pub.pem" 2>/dev/null +printf '[Service]\nUser=energynode\nWorkingDirectory=/home/energynode/ha\n' \ + > "$bundle/ha/energy-node-ha@.service" +printf '{"version": "v1.0.0", "arch": "arm64", "steps": []}\n' > "$bundle/manifest.json" + +# --- Katalog Format 2 mit einem Port "demo" und einer Abhaengigkeit ---------- +state="$tmp/state" +ports="$state/ha-ports" +mkdir -p "$ports" +printf 'demo wheel\n' > "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" +printf 'dep wheel\n' > "$ports/dep_lib-1.0-py3-none-any.whl" +cat > "$tmp/mkcatalog.py" <<'PY' +import hashlib, json, pathlib, sys +ports = pathlib.Path(sys.argv[1]) +def sha(name): + return hashlib.sha256((ports / name).read_bytes()).hexdigest() +port_wheel = "energy_node_ha_demo-1.0.0-py3-none-any.whl" +dep_wheel = "dep_lib-1.0-py3-none-any.whl" +catalog = { + "format": 2, "tag": "v1.0.0-ha", "ha_version": "1.0.0", + "layer": {"ref": "main", "layer_min": "0.0"}, + "ports": [{ + "domain": "demo", "package": "energy-node-ha-demo", "version": "1.0.0", + "requires_python": ">=3.8", "layer_min": "0.0", + "manifest": {"domain": "demo"}, "schema": {"type": "object"}, + "wheel": {"filename": port_wheel, "url": "", "sha256": sha(port_wheel)}, + "arches": {"arm64": [{"name": "dep-lib", "version": "1.0", "filename": dep_wheel, + "url": "", "sha256": sha(dep_wheel)}]}, + }], +} +(ports / "catalog.json").write_text(json.dumps(catalog, indent=2), encoding="utf-8") +PY +python3 "$tmp/mkcatalog.py" "$ports" +openssl pkeyutl -sign -inkey "$tmp/sign.key" -rawin \ + -in "$ports/catalog.json" -out "$ports/catalog.json.sig" +cp "$ports/catalog.json" "$tmp/catalog.good" +cp "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" "$tmp/wheel.good" + +# --- Zielsystem ------------------------------------------------------------ +root="$tmp/root" +mkdir -p "$root/etc/energy-node" +printf '{"mqtt": {}, "services": {"battery_soc": {"enabled": true}}}\n' \ + > "$root/etc/energy-node/config.json" + +export EN_STATE_DIR="$state" EN_ROOT="$root" EN_BUNDLE_DIR="$bundle" +export EN_BUNDLE_VERSION=v1.0.0 EN_SUDO="" EN_TARGET_BASE=/home/pruef EN_TARGET_USER=pruef +export EN_SELECTION="$state/selection.json" EN_PIP="$tmp/bin/fakepip" + +select_ports() { printf '{"steps": {"87": true}, "ha_ports": %s}\n' "$1" > "$EN_SELECTION"; } +reset_logs() { : > "$PIP_LOG"; : > "$SYSTEMCTL_LOG"; } +run() { rc=0; out="$(bash "$script")" || rc=$?; } + +# --- ohne Auswahl und ohne Ports: Schritt wird uebersprungen --------------- +select_ports '[]' +reset_logs +run +[ "$rc" = 0 ] || fail "leere Auswahl: Exit $rc" "$out" +grep -Fxq '##STEP 87 skip keine Ports gewählt' <<<"$out" \ + || fail "leere Auswahl nicht uebersprungen" "$out" +[ -s "$PIP_LOG" ] && fail "leere Auswahl hat pip aufgerufen" "$(cat "$PIP_LOG")" + +# --- Erstinstallation -------------------------------------------------------- +select_ports '["demo"]' +reset_logs +run +[ "$rc" = 0 ] || fail "Erstinstallation: Exit $rc" "$out" +grep -Fxq '##STEP 87 ok' <<<"$out" || fail "kein ok-Marker" "$out" +grep -q '^pip install .*energy_node_ha_demo' "$PIP_LOG" \ + || fail "Port nicht per pip installiert" "$(cat "$PIP_LOG")" +grep -q -- '--no-index' "$PIP_LOG" || fail "ohne --no-index" "$(cat "$PIP_LOG")" +grep -q -- '--break-system-packages' "$PIP_LOG" \ + || fail "ohne --break-system-packages" "$(cat "$PIP_LOG")" +grep -q -- '--upgrade\|--ignore-installed' "$PIP_LOG" \ + && fail "Port-pip mit --upgrade oder --ignore-installed" "$(cat "$PIP_LOG")" +grep -Fxq 'systemctl daemon-reload' "$SYSTEMCTL_LOG" || fail "kein daemon-reload" "$(cat "$SYSTEMCTL_LOG")" +grep -Fxq 'systemctl enable energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ + || fail "Dienst nicht aktiviert" "$(cat "$SYSTEMCTL_LOG")" +grep -Fxq 'systemctl restart energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ + || fail "Dienst bei Erstinstallation nicht gestartet" "$(cat "$SYSTEMCTL_LOG")" +grep -Fxq 'User=pruef' "$root/etc/systemd/system/energy-node-ha@.service" \ + || fail "Unit nicht fuer den Zielbenutzer gerendert" "$(cat "$root/etc/systemd/system/energy-node-ha@.service")" +[ -f "$root/etc/energy-node/manifests/ha_demo.json" ] || fail "Manifest fehlt" +[ -f "$root/home/pruef/devices/ha_demo_devices.schema.json" ] || fail "Schema fehlt" +[ "$(cat "$root/home/pruef/devices/ha_demo_devices.json")" = "[]" ] || fail "Geraetedatei nicht []" + +python3 - "$root/etc/energy-node/config.json" "$state/ha-ports-installed.json" \ + "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" <<'PY' || fail "Config oder Stand falsch" +import hashlib, json, sys +cfg = json.load(open(sys.argv[1], encoding="utf-8")) +stand = json.load(open(sys.argv[2], encoding="utf-8")) +wheel_sha = hashlib.sha256(open(sys.argv[3], "rb").read()).hexdigest() +if cfg.get("services", {}).get("ha_demo") != {"service_id": "ha_demo"}: + sys.exit("services.ha_demo fehlt: %r" % cfg.get("services")) +if cfg["services"].get("battery_soc") != {"enabled": True} or cfg.get("mqtt") != {}: + sys.exit("andere Config-Abschnitte veraendert") +if stand.get("catalog_tag") != "v1.0.0-ha": + sys.exit("catalog_tag falsch: %r" % stand) +if stand.get("ports") != {"demo": {"version": "1.0.0", "wheel_sha256": wheel_sha}}: + sys.exit("installierter Stand falsch: %r" % stand) +PY + +# --- zweiter Lauf: nichts aendert sich, kein pip, kein Neustart ------------- +reset_logs +run +[ "$rc" = 0 ] || fail "zweiter Lauf: Exit $rc" "$out" +grep -Fxq '##STEP 87 ok' <<<"$out" || fail "zweiter Lauf nicht ok" "$out" +grep -q '^pip install' "$PIP_LOG" && fail "zweiter Lauf hat pip install aufgerufen" "$(cat "$PIP_LOG")" +grep -q '^systemctl restart' "$SYSTEMCTL_LOG" && fail "zweiter Lauf hat neu gestartet" "$(cat "$SYSTEMCTL_LOG")" +grep -Fxq 'systemctl enable energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ + || fail "zweiter Lauf: Dienst nicht aktiviert" "$(cat "$SYSTEMCTL_LOG")" + +# --- Abwahl: Dienst aus, Paket weg, Manifest und Schema weg ----------------- +select_ports '[]' +reset_logs +run +[ "$rc" = 0 ] || fail "Abwahl: Exit $rc" "$out" +grep -Fxq '##STEP 87 ok' <<<"$out" || fail "Abwahl nicht ok" "$out" +grep -Fxq 'systemctl disable --now energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ + || fail "Dienst nicht gestoppt" "$(cat "$SYSTEMCTL_LOG")" +grep -Fxq 'pip uninstall -y --break-system-packages energy-node-ha-demo' "$PIP_LOG" \ + || fail "Paket nicht entfernt" "$(cat "$PIP_LOG")" +[ -e "$root/etc/energy-node/manifests/ha_demo.json" ] && fail "Manifest blieb nach Abwahl" +[ -e "$root/home/pruef/devices/ha_demo_devices.schema.json" ] && fail "Schema blieb nach Abwahl" +[ -f "$root/home/pruef/devices/ha_demo_devices.json" ] || fail "Geraetedatei nach Abwahl weg" +python3 - "$root/etc/energy-node/config.json" "$state/ha-ports-installed.json" <<'PY' \ + || fail "Config oder Stand nach Abwahl falsch" +import json, sys +cfg = json.load(open(sys.argv[1], encoding="utf-8")) +stand = json.load(open(sys.argv[2], encoding="utf-8")) +if cfg["services"].get("ha_demo") != {"service_id": "ha_demo"}: + sys.exit("Config-Abschnitt nach Abwahl entfernt") +if stand.get("ports") != {}: + sys.exit("Stand nach Abwahl nicht leer: %r" % stand) +PY + +# --- Signatur nach Byte-Aenderung ungueltig: kein pip ----------------------- +select_ports '["demo"]' +printf ' ' >> "$ports/catalog.json" +reset_logs +run +[ "$rc" = 1 ] || fail "manipulierter Katalog: Exit $rc statt 1" "$out" +grep -Fxq '##STEP 87 fail HA_PORTS_CATALOG_INVALID' <<<"$out" \ + || fail "kein Fehler HA_PORTS_CATALOG_INVALID" "$out" +[ -s "$PIP_LOG" ] && fail "manipulierter Katalog hat pip aufgerufen" "$(cat "$PIP_LOG")" +cp "$tmp/catalog.good" "$ports/catalog.json" + +# --- falsche Wheel-Pruefsumme: kein pip ------------------------------------ +printf 'kaputt\n' > "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" +reset_logs +run +[ "$rc" = 1 ] || fail "falsche Pruefsumme: Exit $rc statt 1" "$out" +grep -Fxq '##STEP 87 fail HA_PORT_WHEEL_INVALID' <<<"$out" \ + || fail "kein Fehler HA_PORT_WHEEL_INVALID" "$out" +[ -s "$PIP_LOG" ] && fail "falsche Pruefsumme hat pip aufgerufen" "$(cat "$PIP_LOG")" +cp "$tmp/wheel.good" "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" + +echo "OK: $(basename "$0")" diff --git a/scripts/tests/test_bootstrap_service_scripts.sh b/scripts/tests/test_bootstrap_service_scripts.sh index 018418f6..abfcce99 100755 --- a/scripts/tests/test_bootstrap_service_scripts.sh +++ b/scripts/tests/test_bootstrap_service_scripts.sh @@ -71,6 +71,8 @@ for file in "$boot"/8?-*.sh; do name="$(basename "$file")" # 89 ist das Beispiel (kein Dienst, scripts/bootstrap/89-example.sh). [ "$name" = 89-example.sh ] && continue + # 87 richtet die Home-Assistant-Ports ein (scripts/tests/test_bootstrap_ha_ports.sh), kein Dienst dieser Tabelle. + [ "$name" = 87-ha-ports.sh ] && continue printf '%s\n' "${TABLE[@]}" | grep -q "^$name:" \ || fail "unbekanntes Dienst-Skript: $name" done From 7104e9961a8072d5dce16bae718626e99845c47f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:21:30 +0100 Subject: [PATCH 09/16] fix(bootstrap): let step 87 remove ports without a catalog and replace changed wheels Without a selection the planner no longer loads catalog.json and only emits remove lines, so deselecting ports works when ha-ports/ is gone. record with no domains writes an empty state without the catalog. When a changed wheel arrives for a port that is already installed, the step uninstalls the old package before installing the new one. pip would otherwise skip a rebuilt wheel with an unchanged version. Dependencies stay installed. Co-Authored-By: Claude Sonnet 5.5 --- scripts/bootstrap/87-ha-ports.sh | 24 +++++++++++++++++++++-- scripts/bootstrap/lib/ha_ports.py | 14 +++++++++++-- scripts/tests/test_bootstrap_ha_ports.sh | 25 +++++++++++++++++++++++- scripts/tests/test_ha_ports.py | 20 +++++++++++++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) diff --git a/scripts/bootstrap/87-ha-ports.sh b/scripts/bootstrap/87-ha-ports.sh index 7c95b76b..48701465 100755 --- a/scripts/bootstrap/87-ha-ports.sh +++ b/scripts/bootstrap/87-ha-ports.sh @@ -122,6 +122,22 @@ install_port() { return 1 } +# uninstall_port : pip uninstall mit demselben Rueckfall wie install_port. +uninstall_port() { + local log="${work}/pip-uninstall.log" + if "${SUDO[@]}" "${PIP[@]}" uninstall -y --break-system-packages "$1" >"${log}" 2>&1; then + return 0 + fi + if grep -q 'no such option' "${log}"; then + step_log "Legacy-Image ohne Schalter fuer externe Umgebungen. Zweiter Versuch ohne ihn." + if "${SUDO[@]}" "${PIP[@]}" uninstall -y "$1" >"${log}" 2>&1; then + return 0 + fi + fi + sed 's/^/ /' "${log}" + return 1 +} + if [[ "${#installs[@]}" -gt 0 ]]; then # Unit aus der Bundle-Vorlage fuer den Zielbenutzer rendern (lib/render.sh). rendered="${work}/unit" @@ -140,6 +156,11 @@ if [[ "${#installs[@]}" -gt 0 ]]; then for row in "${installs[@]}"; do IFS=$'\t' read -r domain wheel changed <<< "${row}" if [[ "${changed}" == 1 ]] || ! "${PIP[@]}" show "energy-node-ha-${domain}" >/dev/null 2>&1; then + # Ein neu gebautes Wheel mit gleicher Version wuerde von pip uebersprungen. + # Deshalb erst das installierte Paket entfernen; Abhaengigkeiten bleiben. + if "${PIP[@]}" show "energy-node-ha-${domain}" >/dev/null 2>&1; then + uninstall_port "energy-node-ha-${domain}" || step_fail HA_PORT_INSTALL_FAILED + fi install_port "${wheel}" || step_fail HA_PORT_INSTALL_FAILED fi "${SUDO[@]}" install -m 0644 "${out}/manifests/ha_${domain}.json" \ @@ -184,8 +205,7 @@ fi for domain in "${removes[@]}"; do "${SUDO[@]}" systemctl disable --now "energy-node-ha@${domain}.service" \ || step_log "Port ${domain} konnte nicht gestoppt werden." - "${SUDO[@]}" "${PIP[@]}" uninstall -y --break-system-packages "energy-node-ha-${domain}" \ - >/dev/null 2>&1 || step_log "Port ${domain} konnte nicht entfernt werden." + uninstall_port "energy-node-ha-${domain}" || step_log "Port ${domain} konnte nicht entfernt werden." "${SUDO[@]}" rm -f "${EN_ROOT}/etc/energy-node/manifests/ha_${domain}.json" rm -f "${devices}/ha_${domain}_devices.schema.json" step_log "Port ${domain} entfernt. Geraetedatei und Konfiguration bleiben." diff --git a/scripts/bootstrap/lib/ha_ports.py b/scripts/bootstrap/lib/ha_ports.py index e8d5ba4f..e3aaceef 100644 --- a/scripts/bootstrap/lib/ha_ports.py +++ b/scripts/bootstrap/lib/ha_ports.py @@ -181,10 +181,15 @@ def _resolve(ports_dir, catalog, arch, domain): def _plan(ports_dir, bundle_manifest, selection_file, installed_file, out_dir): - catalog = _load_catalog(ports_dir) - arch = _load_json(bundle_manifest).get("arch", "") selected = sorted(set(_selection(_load_json(selection_file)))) installed_ports = _installed_ports(installed_file) + if not selected: + # Ohne Auswahl braucht der Planer keinen Katalog: Abwahl geht auch, + # wenn ha-ports/ fehlt. + return [f"remove\t{domain}" for domain in sorted(installed_ports)] + + catalog = _load_catalog(ports_dir) + arch = _load_json(bundle_manifest).get("arch", "") # Alles pruefen, bevor eine Datei entsteht. resolved = [(domain, _resolve(ports_dir, catalog, arch, domain)) for domain in selected] @@ -231,6 +236,11 @@ def _config(src, dst, domains): def _record(installed_file, ports_dir, domains): for domain in domains: _check_domain(domain) + if not domains: + # Keine Ports mehr: kein Katalog nötig, der Stand ist leer. + state = {"catalog_tag": "", "ports": {}} + Path(installed_file).write_text(_dump_json(state), encoding="utf-8") + return 0 catalog = _load_catalog(ports_dir) ports = {} for domain in sorted(set(domains)): diff --git a/scripts/tests/test_bootstrap_ha_ports.sh b/scripts/tests/test_bootstrap_ha_ports.sh index 29df0c32..23c6c30b 100755 --- a/scripts/tests/test_bootstrap_ha_ports.sh +++ b/scripts/tests/test_bootstrap_ha_ports.sh @@ -77,6 +77,7 @@ python3 "$tmp/mkcatalog.py" "$ports" openssl pkeyutl -sign -inkey "$tmp/sign.key" -rawin \ -in "$ports/catalog.json" -out "$ports/catalog.json.sig" cp "$ports/catalog.json" "$tmp/catalog.good" +cp "$ports/catalog.json.sig" "$tmp/catalog.sig.good" cp "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" "$tmp/wheel.good" # --- Zielsystem ------------------------------------------------------------ @@ -152,10 +153,32 @@ grep -q '^systemctl restart' "$SYSTEMCTL_LOG" && fail "zweiter Lauf hat neu gest grep -Fxq 'systemctl enable energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ || fail "zweiter Lauf: Dienst nicht aktiviert" "$(cat "$SYSTEMCTL_LOG")" -# --- Abwahl: Dienst aus, Paket weg, Manifest und Schema weg ----------------- +# --- neu gebautes Wheel mit gleicher Version: erst deinstallieren, dann installieren +printf 'demo wheel v2\n' > "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" +python3 "$tmp/mkcatalog.py" "$ports" +openssl pkeyutl -sign -inkey "$tmp/sign.key" -rawin \ + -in "$ports/catalog.json" -out "$ports/catalog.json.sig" +select_ports '["demo"]' +reset_logs +run +[ "$rc" = 0 ] || fail "geaendertes Wheel: Exit $rc" "$out" +grep -Fxq '##STEP 87 ok' <<<"$out" || fail "geaendertes Wheel nicht ok" "$out" +u="$(grep -n '^pip uninstall -y --break-system-packages energy-node-ha-demo$' "$PIP_LOG" | cut -d: -f1 || true)" +i="$(grep -n '^pip install .*energy_node_ha_demo' "$PIP_LOG" | cut -d: -f1 || true)" +if [ -z "$u" ] || [ -z "$i" ] || [ "$u" -ge "$i" ]; then + fail "geaendertes Wheel: uninstall fehlt oder steht nach install" "$(cat "$PIP_LOG")" +fi +grep -q 'dep' "$PIP_LOG" && fail "Abhaengigkeit wurde angefasst" "$(cat "$PIP_LOG")" +cp "$tmp/catalog.good" "$ports/catalog.json" +cp "$tmp/catalog.sig.good" "$ports/catalog.json.sig" +cp "$tmp/wheel.good" "$ports/energy_node_ha_demo-1.0.0-py3-none-any.whl" + +# --- Abwahl ohne ha-ports/-Ordner: Dienst aus, Paket weg, Manifest und Schema weg select_ports '[]' +mv "$ports" "$tmp/ports-away" reset_logs run +mv "$tmp/ports-away" "$ports" [ "$rc" = 0 ] || fail "Abwahl: Exit $rc" "$out" grep -Fxq '##STEP 87 ok' <<<"$out" || fail "Abwahl nicht ok" "$out" grep -Fxq 'systemctl disable --now energy-node-ha@demo.service' "$SYSTEMCTL_LOG" \ diff --git a/scripts/tests/test_ha_ports.py b/scripts/tests/test_ha_ports.py index 732496f2..dbc9391a 100644 --- a/scripts/tests/test_ha_ports.py +++ b/scripts/tests/test_ha_ports.py @@ -287,3 +287,23 @@ def test_config_rejects_bad_domain(tmp_path, capsys): assert ha_ports.main(["config", str(src), str(dst), "Bad-Name"]) == 1 assert "FEHLER HA_PORT_UNKNOWN Bad-Name" in capsys.readouterr().err assert not dst.exists() + + +def test_plan_remove_without_catalog(tmp_path, capsys): + # Abwahl ohne ha-ports/-Ordner: nur remove-Zeilen aus dem installierten Stand. + missing = tmp_path / "ha-ports" + installed = {"catalog_tag": "ha-ports-test", + "ports": {"demo": {"version": "1.0", "wheel_sha256": sha(PORT_BYTES)}}} + code, out = run_plan(tmp_path, missing, selection=(), installed=installed) + captured = capsys.readouterr() + assert code == 0, captured.err + assert captured.out.splitlines() == ["remove\tdemo"] + assert not out.exists() + + +def test_record_empty_without_catalog(tmp_path): + # Keine Ports mehr: record schreibt den leeren Stand, auch ohne Katalog. + missing = tmp_path / "ha-ports" + installed = tmp_path / "ha-ports-installed.json" + assert ha_ports.main(["record", str(installed), str(missing)]) == 0 + assert json.loads(installed.read_text(encoding="utf-8")) == {"catalog_tag": "", "ports": {}} From 4ab3000e460422b1a154d431244320fe8b5c57be Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:24:38 +0100 Subject: [PATCH 10/16] feat(dashboard): list Home Assistant port units in diagnostics and service logs Diagnose reports the unit of every ha_*.json manifest next to the step units. The service log accepts ha- keys for manifests with an ha_port entry, through ValidateWith and PortUnits. The display name of ha__devices reads "HA: ". Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/config/config.go | 6 ++ dashboard/internal/config/config_test.go | 7 ++ dashboard/internal/httpapi/servicelogs.go | 15 ++++- .../internal/httpapi/servicelogs_test.go | 48 +++++++++++++ dashboard/internal/servicelogs/servicelogs.go | 67 ++++++++++++++++--- .../internal/servicelogs/servicelogs_test.go | 61 +++++++++++++++++ scripts/bootstrap/diagnose.sh | 16 +++++ scripts/tests/test_bootstrap_diagnose.sh | 12 ++++ 8 files changed, 220 insertions(+), 12 deletions(-) diff --git a/dashboard/internal/config/config.go b/dashboard/internal/config/config.go index 612d11db..5a9baaa3 100644 --- a/dashboard/internal/config/config.go +++ b/dashboard/internal/config/config.go @@ -62,6 +62,12 @@ func displayName(name string) (key, label string) { if info, ok := displayNames[name]; ok { return info.key, info.label } + // Home Assistant port devices: ha__devices. + if rest, ok := strings.CutPrefix(name, "ha_"); ok { + if domain, ok := strings.CutSuffix(rest, "_devices"); ok && domain != "" { + return "", "HA: " + domain + } + } return "", name } diff --git a/dashboard/internal/config/config_test.go b/dashboard/internal/config/config_test.go index d7544b4f..629293d6 100644 --- a/dashboard/internal/config/config_test.go +++ b/dashboard/internal/config/config_test.go @@ -519,3 +519,10 @@ func TestPatternPropertiesRejectsNonMatchingKey(t *testing.T) { t.Fatal("non-matching key was accepted under additionalProperties false") } } + +func TestDisplayNameHAPort(t *testing.T) { + key, label := displayName("ha_nordpool_devices") + if key != "" || label != "HA: nordpool" { + t.Fatalf("displayName(ha_nordpool_devices) = (%q, %q), want (\"\", \"HA: nordpool\")", key, label) + } +} diff --git a/dashboard/internal/httpapi/servicelogs.go b/dashboard/internal/httpapi/servicelogs.go index 51064a48..649c561d 100644 --- a/dashboard/internal/httpapi/servicelogs.go +++ b/dashboard/internal/httpapi/servicelogs.go @@ -4,12 +4,23 @@ import ( "context" "errors" "net/http" + "slices" "strconv" "github.com/Developer-Simon/energy-node-dashboard/internal/auth" "github.com/Developer-Simon/energy-node-dashboard/internal/servicelogs" ) +// portManifestDir is where the installed Home Assistant port manifests live. +// A variable so tests can point it at a temporary directory. +var portManifestDir = servicelogs.DefaultPortManifestDir + +// portLogUnits returns the Home Assistant port units the log screen may show. +// It is kept apart from the fixed units, so this part can be switched off alone. +func portLogUnits() []string { + return servicelogs.PortUnits(portManifestDir) +} + // ServiceLogReader reads the journal entries of one allowlisted service. // *servicelogs.Reader implements it. type ServiceLogReader interface { @@ -60,7 +71,7 @@ func handleServiceLogs(manager *auth.Manager, reader ServiceLogReader) http.Hand } query.Lines = n } - if err := query.Validate(); err != nil { + if err := query.ValidateWith(portLogUnits()); err != nil { writeError(w, http.StatusBadRequest, "log_query_invalid", "Die Log-Abfrage ist ungültig.") return } @@ -102,7 +113,7 @@ func handleServiceLogUnits(manager *auth.Manager) http.HandlerFunc { return } writeJSON(w, map[string]any{ - "units": servicelogs.Units, + "units": slices.Concat(servicelogs.Units, portLogUnits()), "since_minutes": servicelogs.SinceMinutes, "lines": servicelogs.LineLimits, "default_unit": servicelogs.DefaultUnit, diff --git a/dashboard/internal/httpapi/servicelogs_test.go b/dashboard/internal/httpapi/servicelogs_test.go index c1f1757c..cb312d27 100644 --- a/dashboard/internal/httpapi/servicelogs_test.go +++ b/dashboard/internal/httpapi/servicelogs_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "path/filepath" "slices" "strings" @@ -229,3 +230,50 @@ func TestServiceLogsHiddenWithoutReader(t *testing.T) { } } } + +func TestServiceLogUnitsListsPortUnits(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ha_nordpool.json"), []byte(`{"service_id":"ha_nordpool","unit":"energy-node-ha@nordpool.service","ha_port":{}}`), 0o644); err != nil { + t.Fatal(err) + } + previous := portManifestDir + portManifestDir = dir + t.Cleanup(func() { portManifestDir = previous }) + + router := newServiceLogsTestRouter(t, &fakeServiceLogReader{}) + admin, _ := loginAsAdmin(t, router) + recorder := serviceLogsGet(t, router, "/api/v1/system/logs/units", admin) + if recorder.Code != http.StatusOK { + t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String()) + } + var body struct { + Units []string `json:"units"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + want := append(slices.Clone(servicelogs.Units), "ha-nordpool") + if !slices.Equal(body.Units, want) { + t.Fatalf("units = %q, want %q", body.Units, want) + } +} + +func TestServiceLogsAcceptsPortUnitQuery(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ha_nordpool.json"), []byte(`{"service_id":"ha_nordpool","ha_port":{}}`), 0o644); err != nil { + t.Fatal(err) + } + previous := portManifestDir + portManifestDir = dir + t.Cleanup(func() { portManifestDir = previous }) + + reader := &fakeServiceLogReader{} + router := newServiceLogsTestRouter(t, reader) + admin, _ := loginAsAdmin(t, router) + if recorder := serviceLogsGet(t, router, "/api/v1/system/logs?unit=ha-nordpool", admin); recorder.Code != http.StatusOK { + t.Fatalf("port unit status %d: %s", recorder.Code, recorder.Body.String()) + } + if recorder := serviceLogsGet(t, router, "/api/v1/system/logs?unit=ha-unbekannt", admin); recorder.Code != http.StatusBadRequest { + t.Fatalf("unknown port unit status %d, want 400", recorder.Code) + } +} diff --git a/dashboard/internal/servicelogs/servicelogs.go b/dashboard/internal/servicelogs/servicelogs.go index f1f2aa57..6230bd87 100644 --- a/dashboard/internal/servicelogs/servicelogs.go +++ b/dashboard/internal/servicelogs/servicelogs.go @@ -6,9 +6,13 @@ import ( "bufio" "bytes" "context" + "encoding/json" "errors" "fmt" + "os" "os/exec" + "path/filepath" + "regexp" "slices" "strconv" "strings" @@ -18,6 +22,14 @@ import ( var Units = []string{"dashboard", "updater", "automation", "battery-soc", "shelly", "trucki", "tuya", "apsystems", "mosquitto", "caddy", "tailscale"} + +// DefaultPortManifestDir holds the manifests of the installed Home Assistant +// ports. Their ha- units are allowed next to the fixed Units. +const DefaultPortManifestDir = "/etc/energy-node/manifests" + +// portKeyPattern is the shape of a Home Assistant port unit key. +var portKeyPattern = regexp.MustCompile(`^ha-[a-z0-9_]{1,40}$`) + var SinceMinutes = []int{15, 60, 360, 1440, 10080} var LineLimits = []int{100, 200, 500, 1000} @@ -69,11 +81,44 @@ type Runner interface { Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error) } +// PortUnits returns ha- for every ha_.json manifest in +// manifestDir that has an ha_port entry. A missing directory gives no units. +func PortUnits(manifestDir string) []string { + units := []string{} + paths, _ := filepath.Glob(filepath.Join(manifestDir, "ha_*.json")) + for _, path := range paths { + raw, err := os.ReadFile(path) + if err != nil { + continue + } + var manifest map[string]json.RawMessage + if json.Unmarshal(raw, &manifest) != nil { + continue + } + if _, ok := manifest["ha_port"]; !ok { + continue + } + domain := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "ha_"), ".json") + if unit := "ha-" + domain; portKeyPattern.MatchString(unit) { + units = append(units, unit) + } + } + return units +} + // Validate checks every field against the allowlists. The cursor must match // what the helper accepts (prefix "s=", at most 256 characters, only // [A-Za-z0-9=;]), so an invalid cursor is rejected before any sudo call. func (q Query) Validate() error { - if !slices.Contains(Units, q.Unit) { + return q.ValidateWith(nil) +} + +// ValidateWith is Validate with extra allowed unit keys, such as the port +// units from PortUnits. An extra key must also match portKeyPattern. +func (q Query) ValidateWith(extra []string) error { + allowed := slices.Contains(Units, q.Unit) || + (slices.Contains(extra, q.Unit) && portKeyPattern.MatchString(q.Unit)) + if !allowed { return fmt.Errorf("%w: unit %q", ErrInvalidQuery, q.Unit) } if !slices.Contains(SinceMinutes, q.SinceMinutes) { @@ -103,10 +148,11 @@ const maxScanLine = 1 << 20 // Reader runs the system action helper's read-journal action for one query at // a time per slot, and never more than MaxConcurrent at once. type Reader struct { - runner Runner - helper string - timeout time.Duration - sem chan struct{} + runner Runner + helper string + timeout time.Duration + sem chan struct{} + portManifestDir string } // NewReader returns a Reader that calls helper through sudo. A nil runner @@ -116,17 +162,18 @@ func NewReader(runner Runner, helper string) *Reader { runner = execRunner{} } return &Reader{ - runner: runner, - helper: helper, - timeout: QueryTimeout, - sem: make(chan struct{}, MaxConcurrent), + runner: runner, + helper: helper, + timeout: QueryTimeout, + sem: make(chan struct{}, MaxConcurrent), + portManifestDir: DefaultPortManifestDir, } } // Read validates the query, runs the helper and returns the matching entries. // The filter is applied here, the cursor advances past every fetched line. func (r *Reader) Read(ctx context.Context, q Query) (Result, error) { - if err := q.Validate(); err != nil { + if err := q.ValidateWith(PortUnits(r.portManifestDir)); err != nil { return Result{}, err } diff --git a/dashboard/internal/servicelogs/servicelogs_test.go b/dashboard/internal/servicelogs/servicelogs_test.go index 2a679770..6f0bcc66 100644 --- a/dashboard/internal/servicelogs/servicelogs_test.go +++ b/dashboard/internal/servicelogs/servicelogs_test.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + "os" + "path/filepath" "slices" "strings" "sync" @@ -286,3 +288,62 @@ func TestReadRejectsInvalidQueryWithoutRunning(t *testing.T) { t.Errorf("runner called %d times, want 0", n) } } + +func writeManifest(t *testing.T, dir, name, body string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestPortUnitsFromManifests(t *testing.T) { + dir := t.TempDir() + writeManifest(t, dir, "ha_nordpool.json", `{"service_id":"ha_nordpool","unit":"energy-node-ha@nordpool.service","ha_port":{}}`) + writeManifest(t, dir, "ha_plain.json", `{"service_id":"ha_plain","unit":"x.service"}`) + writeManifest(t, dir, "shelly.json", `{"service_id":"shelly","ha_port":{}}`) + got := PortUnits(dir) + if !slices.Equal(got, []string{"ha-nordpool"}) { + t.Fatalf("PortUnits() = %q, want [ha-nordpool]", got) + } + if got := PortUnits(filepath.Join(dir, "fehlt")); len(got) != 0 { + t.Fatalf("PortUnits(missing dir) = %q, want empty", got) + } +} + +func TestValidateWithAcceptsPortKey(t *testing.T) { + q := Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200} + if err := q.ValidateWith([]string{"ha-nordpool"}); err != nil { + t.Fatalf("ValidateWith() = %v, want nil", err) + } +} + +func TestValidateRejectsPortKeyWithoutExtra(t *testing.T) { + q := Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200} + if err := q.Validate(); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("Validate() = %v, want ErrInvalidQuery", err) + } + if err := q.ValidateWith(nil); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("ValidateWith(nil) = %v, want ErrInvalidQuery", err) + } +} + +func TestValidateWithRejectsBadKey(t *testing.T) { + q := Query{Unit: "ha-../x", SinceMinutes: 60, Lines: 200} + if err := q.ValidateWith([]string{"ha-../x"}); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("ValidateWith() = %v, want ErrInvalidQuery", err) + } +} + +func TestReadAcceptsPortUnitFromManifestDir(t *testing.T) { + dir := t.TempDir() + writeManifest(t, dir, "ha_nordpool.json", `{"service_id":"ha_nordpool","ha_port":{}}`) + fake := &fakeRunner{stdout: joinLines(fakeJournalLine(t, "s=1", "ok"))} + r := NewReader(fake, testHelper) + r.portManifestDir = dir + if _, err := r.Read(context.Background(), Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200}); err != nil { + t.Fatalf("Read() of port unit = %v, want nil", err) + } + if _, err := r.Read(context.Background(), Query{Unit: "ha-unbekannt", SinceMinutes: 60, Lines: 200}); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("Read() of unknown port unit = %v, want ErrInvalidQuery", err) + } +} diff --git a/scripts/bootstrap/diagnose.sh b/scripts/bootstrap/diagnose.sh index 2fb81042..3a990070 100755 --- a/scripts/bootstrap/diagnose.sh +++ b/scripts/bootstrap/diagnose.sh @@ -71,6 +71,22 @@ for entry in data.get("steps", []): if entry.get("unit"): print(entry["unit"]) ' "${EN_BUNDLE_DIR}/manifest.json") + fi + # Home-Assistant-Port-Units: je ha_*.json die Unit aus deren Feld "unit". + # Eigener Block, damit er sich allein abschalten laesst. + if [[ -d "${EN_ROOT}/etc/energy-node/manifests" ]]; then + while IFS= read -r unit; do + [[ -n "${unit}" ]] && units+=("${unit}") + done < <(python3 -c ' +import glob, json, os, sys +for path in sorted(glob.glob(os.path.join(sys.argv[1], "ha_*.json"))): + try: + unit = json.load(open(path, encoding="utf-8")).get("unit") + except Exception: + continue + if isinstance(unit, str) and unit: + print(unit) +' "${EN_ROOT}/etc/energy-node/manifests") fi # Units abgewaehlter Schritte (selection.json, gleiche Regel wie # step_selected). Eine Zeile je Unit. diff --git a/scripts/tests/test_bootstrap_diagnose.sh b/scripts/tests/test_bootstrap_diagnose.sh index 6040d8eb..befbf185 100755 --- a/scripts/tests/test_bootstrap_diagnose.sh +++ b/scripts/tests/test_bootstrap_diagnose.sh @@ -346,6 +346,18 @@ while IFS= read -r l; do done < <(EN_APT_GET="$tmp/bin/apt-get-slow" bash "$script" --stream) if [ -z "$first" ] || [ $(( (first - start) / 1000000 )) -ge 1500 ]; then fail "units kommt erst nach apt"; fi +# --- Home-Assistant-Port: Unit aus ha_*.json erscheint --------------------- +rm -f "$EN_STATE_DIR/selection.json" +printf '{"service_id":"ha_nordpool","unit":"energy-node-ha@nordpool.service","ha_port":{}}\n' \ + > "$tmp/root/etc/energy-node/manifests/ha_nordpool.json" +out="$(ACTIVE="" LISTENING="" bash "$script")" +[ "$(get 'd["units"]["energy-node-ha@nordpool.service"]')" = inactive ] \ + || fail "Port-Unit aus ha_nordpool.json fehlt im Bericht" "$out" +out="$(ACTIVE="energy-node-ha@nordpool.service" bash "$script")" +[ "$(get 'd["units"]["energy-node-ha@nordpool.service"]')" = active ] \ + || fail "aktive Port-Unit nicht als active gemeldet" "$out" +rm -f "$tmp/root/etc/energy-node/manifests/ha_nordpool.json" + # --- kaputter Node: trotzdem Exit 0 und vollstaendiges JSON -------------- rm -rf "$tmp/root" "$tmp/state" set +e From 9e8f14cff5ec4d18f19ea58372392a627d3b6e3e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:33:35 +0100 Subject: [PATCH 11/16] feat(dashboard): let the system action helper read and stop Home Assistant port units read-journal accepts the key ha- when the domain matches ^[a-z0-9_]{1,40}$ and the manifest ha_.json exists. The unit is energy-node-ha@.service. service_units also lists every enabled energy-node-ha@*.service whose domain passes the same check, so stop-services and start-services cover port units. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/energy-node-dashboard-system-action | 58 ++++++++++++++++--- .../test_bootstrap_dashboard_read_journal.sh | 37 ++++++++++++ scripts/tests/test_system_action_services.sh | 44 +++++++++++++- 3 files changed, 131 insertions(+), 8 deletions(-) diff --git a/dashboard/energy-node-dashboard-system-action b/dashboard/energy-node-dashboard-system-action index 8266fe2f..00a5fb5c 100644 --- a/dashboard/energy-node-dashboard-system-action +++ b/dashboard/energy-node-dashboard-system-action @@ -23,6 +23,11 @@ APP_CONFIG_OWNER="energynode" # replaces this line with a stub, so keep the assignment on one line. JOURNALCTL="/usr/bin/journalctl" +# Manifest directory of the Home Assistant ports. The test +# scripts/tests/test_bootstrap_dashboard_read_journal.sh replaces this line +# with a temp dir, so keep the assignment on one line. +HA_MANIFEST_DIR="/etc/energy-node/manifests" + # systemctl binary for stop-services and start-services. The test # scripts/tests/test_system_action_services.sh replaces this line with a # stub, so keep the assignment on one line. @@ -178,12 +183,25 @@ apply_app_config() { exit 0 } +# ha_domain_ok succeeds only for a Home Assistant port domain: 1 to 40 +# characters of a-z, 0-9 and underscore. The pattern is a case glob with a +# negated class, so a newline, a slash, a dot, a semicolon or an uppercase +# letter always fails. +ha_domain_ok() { + case "$1" in + ''|*[!a-z0-9_]*) return 1 ;; + esac + [ "${#1}" -le 40 ] +} + # read_journal prints journal entries of one allowlisted unit as JSON lines. -# Arguments: key (dashboard|tailscale), since in minutes (15|60|360|1440|10080), -# lines (100|200|500|1000) and an optional cursor. The key is one of the -# eleven allowlisted service keys in the case below. The cursor must start with -# "s=", be at most 256 characters, and contain only [A-Za-z0-9=;], so it can -# never be read as a journalctl option. Exit codes of journalctl pass through. +# Arguments: key (dashboard|tailscale|ha-), since in minutes +# (15|60|360|1440|10080), lines (100|200|500|1000) and an optional cursor. The +# key is one of the eleven allowlisted service keys in the case below, or +# ha- for a Home Assistant port whose manifest exists. The cursor must +# start with "s=", be at most 256 characters, and contain only [A-Za-z0-9=;], so +# it can never be read as a journalctl option. Exit codes of journalctl pass +# through. read_journal() { key="$1" since="$2" @@ -202,6 +220,12 @@ read_journal() { mosquitto) unit="mosquitto.service" ;; caddy) unit="caddy.service" ;; tailscale) unit="tailscaled.service" ;; + ha-*) + domain="${key#ha-}" + ha_domain_ok "$domain" || exit 65 + [ -f "$HA_MANIFEST_DIR/ha_${domain}.json" ] || exit 65 + unit="energy-node-ha@${domain}.service" + ;; *) exit 65 ;; esac case "$since" in @@ -274,11 +298,31 @@ storage_helper() { esac } -# service_units prints the units that stop-services and start-services act on. -# Keep the names in step with the units of the read_journal case statement. +# service_units prints the units that stop-services and start-services act on: +# the fixed list, then every enabled Home Assistant port unit. Keep the fixed +# names in step with the units of the read_journal case statement. service_units() { printf '%s\n' automation.service battery-soc.service shelly-rpc.service \ trucki-http.service tuya.service apsystems-ez1.service + ha_port_units +} + +# ha_port_units prints every enabled energy-node-ha@.service whose +# domain passes ha_domain_ok. Any other name, including the template unit +# itself, is dropped. +ha_port_units() { + "$SYSTEMCTL" list-unit-files 'energy-node-ha@*.service' --state=enabled --no-legend 2>/dev/null \ + | while read -r unit _; do + case "$unit" in + energy-node-ha@*.service) : ;; + *) continue ;; + esac + domain="${unit#energy-node-ha@}" + domain="${domain%.service}" + if ha_domain_ok "$domain"; then + printf '%s\n' "energy-node-ha@${domain}.service" + fi + done } # service_loop VERB runs "systemctl VERB UNIT" for every enabled unit of diff --git a/scripts/tests/test_bootstrap_dashboard_read_journal.sh b/scripts/tests/test_bootstrap_dashboard_read_journal.sh index 37aa790a..ca0b9ad4 100644 --- a/scripts/tests/test_bootstrap_dashboard_read_journal.sh +++ b/scripts/tests/test_bootstrap_dashboard_read_journal.sh @@ -24,6 +24,15 @@ cp "$helper_src" "$tmp/helper" chmod +x "$tmp/helper" sed -i "s|^JOURNALCTL=\"/usr/bin/journalctl\"|JOURNALCTL=\"$tmp/journalctl\"|" "$tmp/helper" +# Port manifests live in a temp dir. ha_nordpool.json is the only valid port. +mkdir -p "$tmp/manifests" +printf '{}\n' > "$tmp/manifests/ha_nordpool.json" +printf '{}\n' > "$tmp/manifests/ha_$(printf 'a%.0s' $(seq 1 40)).json" +printf '{}\n' > "$tmp/manifests/ha_$(printf 'a%.0s' $(seq 1 41)).json" +printf '{}\n' > "$tmp/manifests/ha_nord"$'\n'"x.json" +sed -i "s|^HA_MANIFEST_DIR=\"/etc/energy-node/manifests\"|HA_MANIFEST_DIR=\"$tmp/manifests\"|" "$tmp/helper" +grep -q "^HA_MANIFEST_DIR=\"$tmp/manifests\"" "$tmp/helper" || fail "test setup: HA_MANIFEST_DIR was not replaced" + helper="$tmp/helper" # run_case LABEL WANT_EXIT STUB_CALLED(yes|no) ARGS... @@ -83,6 +92,34 @@ caddy caddy.service tailscale tailscaled.service EOF +# Home Assistant ports: a valid domain with a manifest reads its port unit +run_case "ha-nordpool 60 200" 0 yes read-journal ha-nordpool 60 200 +cat > "$tmp/want" <<'EOF' +--no-pager +--quiet +--output=json +--output-fields=MESSAGE,PRIORITY,_SYSTEMD_UNIT +--unit=energy-node-ha@nordpool.service +--since=-60min +--lines=200 +EOF +cmp -s "$tmp/args" "$tmp/want" || fail "ha-nordpool 60 200: wrong journalctl arguments" "$(cat "$tmp/args")" + +# The domain may be 40 characters long at most +run_case "ha domain of 40 characters" 0 yes read-journal "ha-$(printf 'a%.0s' $(seq 1 40))" 60 200 + +# A valid domain without a manifest is refused and journalctl is not called +run_case "ha-demo without manifest" 65 no read-journal ha-demo 60 200 + +# Injection and malformed keys are refused even when a file of that name exists +run_case "ha-Nord;rm" 65 no read-journal 'ha-Nord;rm' 60 200 +run_case "ha-../x" 65 no read-journal 'ha-../x' 60 200 +run_case "ha- without domain" 65 no read-journal 'ha-' 60 200 +run_case "ha-Nordpool uppercase" 65 no read-journal 'ha-Nordpool' 60 200 +run_case "ha domain of 41 characters" 65 no read-journal "ha-$(printf 'a%.0s' $(seq 1 41))" 60 200 +run_case "ha domain with newline" 65 no read-journal $'ha-nord\nx' 60 200 +run_case "ha domain with a dot" 65 no read-journal 'ha-nord.x' 60 200 + # Unit, since and lines are checked against fixed lists run_case "unknown unit sshd" 65 no read-journal sshd 60 200 run_case "since 7 not allowed" 65 no read-journal dashboard 7 200 diff --git a/scripts/tests/test_system_action_services.sh b/scripts/tests/test_system_action_services.sh index 7d2125be..d0487a11 100644 --- a/scripts/tests/test_system_action_services.sh +++ b/scripts/tests/test_system_action_services.sh @@ -9,11 +9,18 @@ tmp="$(mktemp -d)" trap 'rm -rf "$tmp"' EXIT fail() { echo "FAIL: $1"; [ -n "${2:-}" ] && printf '%s\n' "$2"; exit 1; } -# Stub systemctl. "is-enabled --quiet UNIT" exits 0 only for units listed in +# Stub systemctl. "list-unit-files" prints LISTED_UNITS as enabled units and is +# not logged. "is-enabled --quiet UNIT" exits 0 only for units listed in # ENABLED_UNITS. "VERB UNIT" is logged to SYSTEMCTL_LOG and exits 1 for units # listed in FAIL_UNITS. cat > "$tmp/systemctl" <<'SH' #!/bin/sh +if [ "$1" = list-unit-files ]; then + for unit in $LISTED_UNITS; do + printf '%s enabled enabled\n' "$unit" + done + exit 0 +fi if [ "$1" = is-enabled ]; then for unit in $ENABLED_UNITS; do [ "$unit" = "$3" ] && exit 0 @@ -39,6 +46,9 @@ grep -q "^SYSTEMCTL=\"$tmp/systemctl\"" "$tmp/helper" || fail "test setup: SYSTE ALL_UNITS="automation.service battery-soc.service shelly-rpc.service trucki-http.service tuya.service apsystems-ez1.service" # run_case LABEL WANT_EXIT ENABLED_UNITS FAIL_UNITS ARGS... +LISTED_UNITS="" +export LISTED_UNITS + run_case() { label="$1"; want="$2"; export ENABLED_UNITS="$3" FAIL_UNITS="$4"; shift 4 rm -f "$SYSTEMCTL_LOG" @@ -84,6 +94,38 @@ want_calls "start with one failing unit" \ "start automation.service" "start battery-soc.service" "start shelly-rpc.service" \ "start trucki-http.service" "start tuya.service" "start apsystems-ez1.service" +# Enabled Home Assistant port units are stopped and started after the fixed units +LISTED_UNITS="energy-node-ha@nordpool.service" +export LISTED_UNITS +run_case "stop enabled port unit" 0 "energy-node-ha@nordpool.service" "" stop-services +want_calls "stop enabled port unit" "stop energy-node-ha@nordpool.service" +run_case "start enabled port unit" 0 "energy-node-ha@nordpool.service" "" start-services +want_calls "start enabled port unit" "start energy-node-ha@nordpool.service" + +LISTED_UNITS="automation.service energy-node-ha@nordpool.service" +export LISTED_UNITS +run_case "stop fixed and port units" 0 "automation.service energy-node-ha@nordpool.service" "" stop-services +want_calls "stop fixed and port units" "stop automation.service" "stop energy-node-ha@nordpool.service" + +# A port unit that fails does not stop the loop, and the verb exits non-zero +run_case "stop with failing port unit" 1 "energy-node-ha@nordpool.service tuya.service" \ + "energy-node-ha@nordpool.service" stop-services +want_calls "stop with failing port unit" "stop tuya.service" "stop energy-node-ha@nordpool.service" + +# Names that do not match the domain pattern are dropped, even when enabled +LISTED_UNITS="energy-node-ha@.service energy-node-ha@Nord.service energy-node-ha@a.b.service energy-node-ha@nord;rm.service energy-node-ha@$(printf 'a%.0s' $(seq 1 41)).service" +export LISTED_UNITS +run_case "stop drops invalid port names" 0 "$LISTED_UNITS" "" stop-services +want_calls "stop drops invalid port names" + +# A disabled port unit is not stopped +LISTED_UNITS="energy-node-ha@nordpool.service" +export LISTED_UNITS +run_case "stop with port disabled" 0 "" "" stop-services +want_calls "stop with port disabled" +LISTED_UNITS="" +export LISTED_UNITS + # Extra arguments and unknown verbs are rejected before systemctl is called run_case "stop with extra argument" 64 "$ALL_UNITS" "" stop-services extra want_calls "stop with extra argument" From d057a72d9994957d3f3e342eeaddff7e7a8a5780 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:35:41 +0100 Subject: [PATCH 12/16] test(bootstrap): leave the ports step out of the service step rule Step 87 installs the Home Assistant ports and has no services/ input, so the service step rule test must skip it like the 89 example. Co-Authored-By: Claude Sonnet 5.5 --- scripts/tests/test_restart_rule.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/tests/test_restart_rule.py b/scripts/tests/test_restart_rule.py index d9d0283f..6f80a8b5 100644 --- a/scripts/tests/test_restart_rule.py +++ b/scripts/tests/test_restart_rule.py @@ -64,6 +64,8 @@ def test_service_steps_rerun_exactly_for_their_libraries(): for script in (REPO / "scripts" / "bootstrap").glob("8*-*.sh"): if script.name == "89-example.sh": continue # das Beispiel ist kein Dienst-Schritt + if script.name == "87-ha-ports.sh": + continue # Port-Schritt, kein Dienst-Schritt text = script.read_text(encoding="utf-8") inputs = " ".join(line.split(":", 1)[1] for line in text.splitlines() if line.startswith("# step-inputs:")).split() directory = next(item.split("/")[1] for item in inputs if item.startswith("services/")) From 855e3d305495a1d78ecb41704b32bc0e516ad550 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 6 Dec 2026 09:39:36 +0000 Subject: [PATCH 13/16] chore(release): bump component versions --- dashboard/VERSION | 2 +- installer/VERSION | 2 +- libs/energy_node_common/VERSION | 2 +- scripts/bootstrap/VERSION | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index 7e511688..b686b712 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.12.1-pre.2 +v0.12.1-pre.3 diff --git a/installer/VERSION b/installer/VERSION index 5aff472d..faa49bf9 100644 --- a/installer/VERSION +++ b/installer/VERSION @@ -1 +1 @@ -v0.4.1 +v0.4.2-pre.1 diff --git a/libs/energy_node_common/VERSION b/libs/energy_node_common/VERSION index 4b328a30..b168654d 100644 --- a/libs/energy_node_common/VERSION +++ b/libs/energy_node_common/VERSION @@ -1 +1 @@ -v0.6.1-pre.1 +v0.6.1-pre.2 diff --git a/scripts/bootstrap/VERSION b/scripts/bootstrap/VERSION index 5aff472d..faa49bf9 100644 --- a/scripts/bootstrap/VERSION +++ b/scripts/bootstrap/VERSION @@ -1 +1 @@ -v0.4.1 +v0.4.2-pre.1 From a8551dff5f2405524dcf010508b179fe068a2662 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 6 Dec 2026 09:40:43 +0000 Subject: [PATCH 14/16] docs(changelog): update changelogs --- changelog/highlights/320.json | 8 ++++++++ dashboard/CHANGELOG.md | 6 +++++- installer/CHANGELOG.md | 7 ++++++- libs/energy_node_common/CHANGELOG.md | 18 ++++++++++++------ scripts/bootstrap/CHANGELOG.md | 15 ++++++++++++++- 5 files changed, 45 insertions(+), 9 deletions(-) create mode 100644 changelog/highlights/320.json diff --git a/changelog/highlights/320.json b/changelog/highlights/320.json new file mode 100644 index 00000000..b5aa416f --- /dev/null +++ b/changelog/highlights/320.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Home Assistant Ports werden auf dem Node installiert und betrieben" + }, + "en": { + "*": "Install and run Home Assistant ports on the node" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 43505c7e..86f0510c 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,11 +1,15 @@ # Changelog -## v0.12.1-pre.2 (2026-12-04) +## v0.12.1-pre.3 (2026-12-06) ### Features - **dashboard:** A compact header whose status chip names the cause of a problem (#316) (6f5aa61) - **overview:** add a device map card to the overview (#318) (1557b48) +- **dashboard:** allow Home Assistant port sections in the config schema (02c1387) +- **dashboard:** list Home Assistant port units in diagnostics and service logs (4ab3000) +- **dashboard:** let the system action helper read and stop Home Assistant port units (9e8f14c) +- **ha:** install and run Home Assistant ports on the node (#320) - **overview:** add the device_map card type to the layout settings (a226f60) - **overview:** add viewport gestures and fit spring for map cards (62c9456) - **overview:** add the device map card component (a99435a) diff --git a/installer/CHANGELOG.md b/installer/CHANGELOG.md index a83b8406..fe5adcb5 100644 --- a/installer/CHANGELOG.md +++ b/installer/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog -## v0.4.1 (2026-12-04) +## v0.4.2-pre.1 (2026-12-06) + +### Features + +- **bundle:** add step 87 for Home Assistant ports (e5162ec) +- **ha:** install and run Home Assistant ports on the node (#320) ### Fixes diff --git a/libs/energy_node_common/CHANGELOG.md b/libs/energy_node_common/CHANGELOG.md index 225c67be..5cfc8ba8 100644 --- a/libs/energy_node_common/CHANGELOG.md +++ b/libs/energy_node_common/CHANGELOG.md @@ -1,23 +1,29 @@ # Changelog -## v0.6.1-pre.1 (2026-12-06) +## v0.6.1-pre.2 (2026-12-06) ### Features +- **common:** add a Home Assistant compat layer for ported integrations (#319) (fb0eb1c) +- **common:** read the devices file of a port as a top-level array (2218c4c) +- **ha:** install and run Home Assistant ports on the node (#320) - **common:** cover the Home Assistant 2026.12 surface of forecast_solar and nordpool (97a3e7a) -- **common:** add a Home Assistant compat layer for ported integrations (#319) -## v0.6.0 (2026-12-06) +### Fixes + +- **common:** use English in the devices loader docstring (ee1f54c) + +## v0.6.0 (2026-11-15) ### Features +- **automation:** react to measurement chains in automations (#226) (0066f15) +- **storage:** Add an additional drive for running data and backups (#233) (015cc2c) +- **performance:** show how much load the node puts on the device (#260) (b93bc98) - **common:** add the base modules of the HA compat layer (c1260f4) - **common:** add entities, coordinator and timers to the HA compat layer (f9b4f7e) - **common:** host HA integrations and map entities to MQTT discovery (c4a7204) - **common:** add the HA port runner and its systemd template (4a9d843) -- **automation:** react to measurement chains in automations (#226) (0066f15) -- **storage:** Add an additional drive for running data and backups (#233) (015cc2c) -- **performance:** show how much load the node puts on the device (#260) (b93bc98) - **common:** report the poll round duration in the service status (5a94108) - **performance:** add the poll floor and the budget setting (7f324af) diff --git a/scripts/bootstrap/CHANGELOG.md b/scripts/bootstrap/CHANGELOG.md index 037cf4ea..f6864452 100644 --- a/scripts/bootstrap/CHANGELOG.md +++ b/scripts/bootstrap/CHANGELOG.md @@ -1,10 +1,23 @@ # Changelog -## v0.4.1 (2026-12-04) +## v0.4.2-pre.1 (2026-12-06) + +### Features + +- **bootstrap:** add the planner for Home Assistant port installs (e016b21) +- **bootstrap:** install, update and remove Home Assistant ports in step 87 (4b598c4) +- **dashboard:** list Home Assistant port units in diagnostics and service logs (4ab3000) +- **ha:** install and run Home Assistant ports on the node (#320) ### Fixes - **installer:** claim a root-owned wheels directory before staging (#317) (5309c47) +- **bootstrap:** validate inputs of the port planner (55fa04e) +- **bootstrap:** let step 87 remove ports without a catalog and replace changed wheels (7104e99) + +### Chores + +- **bootstrap:** add the Home Assistant ports signing key (adb2e5d) ## v0.4.0 (2026-11-20) From 1856b7d3095c0824cc53760e79f2259fb12d6566 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:50:57 +0100 Subject: [PATCH 15/16] fix(dashboard): show port sections in the system settings form The services object of config.schema.json declares ha_ entries via patternProperties. schema-form.js did not know that keyword, so a file with an ha_ port was reported as containing unknown fields and fell back to the raw editor. findUnknownKeys treats a key that fully matches a pattern as known and checks its value against that pattern's schema. renderNode renders such keys as plain children, so readNode writes them back on save. Cache version of schema-form.js bumped to 3. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/cache-bust-history.csv | 1 + .../internal/webui/static/js/schema-form.js | 38 +++++++++--- dashboard/internal/webui/templates/base.html | 4 +- .../internal/webui/templates/settings.html | 2 +- dashboard/internal/webui/webui_test.go | 4 +- dashboard/test/schema-form.test.mjs | 58 +++++++++++++++++++ 6 files changed, 95 insertions(+), 12 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index af731061..01e082f9 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,5 @@ version,date,asset,v,note +v0.12.1-pre.3,2026-12-06,js/schema-form.js,3, v0.12.1-pre.2,2026-12-03,css/base.css,57, v0.12.1-pre.2,2026-12-03,css/manager.css,55, v0.12.1-pre.2,2026-12-03,js/dashboard.js,58, diff --git a/dashboard/internal/webui/static/js/schema-form.js b/dashboard/internal/webui/static/js/schema-form.js index 4adf1dc5..66909696 100644 --- a/dashboard/internal/webui/static/js/schema-form.js +++ b/dashboard/internal/webui/static/js/schema-form.js @@ -223,6 +223,14 @@ return merged; } + // The patternProperties schema for a key, or null. The pattern has to match + // the whole key, so a key like "xha_x" does not count for "^ha_". + function patternSchemaFor(schema, key) { + const patterns = schema.patternProperties || {}; + const match = Object.keys(patterns).find(pattern => new RegExp(`^(?:${pattern})$`).test(key)); + return match === undefined ? null : patterns[match]; + } + // Decides a condition like the server validator for the subset the // schemas use: required, const and enum. An absent value passes a // property rule, as JSON Schema's properties keyword does. @@ -364,6 +372,16 @@ rendered.set(propertyKey, child); if (requiredFields.has(propertyKey)) node.append(child); else optionalFields.append(child); }); + // Keys that only a patternProperties entry declares (e.g. ha_ + // ports) render as plain children, so readNode writes them back. + if (value && typeof value === 'object' && !Array.isArray(value)) { + const declared = allProperties(schema); + Object.keys(value).forEach(childKey => { + if (Object.hasOwn(declared, childKey)) return; + const patternSchema = patternSchemaFor(schema, childKey); + if (patternSchema) node.append(renderNode(ctx, patternSchema, value[childKey], childKey, false, childKey)); + }); + } const branches = conditionalBranches(schema); const conditional = new Map(); const lastBehind = new Map(); @@ -493,17 +511,23 @@ if (!schema || value === null || typeof value !== 'object') return []; const found = []; if (schema.type === 'object' && !Array.isArray(value)) { - const known = new Set(Object.keys(allProperties(schema))); - if (schema.additionalProperties === false || schema.unevaluatedProperties === false) { - Object.keys(value).forEach(childKey => { - if (!known.has(childKey)) found.push(path ? `${path}.${childKey}` : childKey); - }); - } - Object.entries(allProperties(schema)).forEach(([childKey, childSchema]) => { + const declared = allProperties(schema); + const closed = schema.additionalProperties === false || schema.unevaluatedProperties === false; + Object.keys(value).forEach(childKey => { + if (Object.hasOwn(declared, childKey) || patternSchemaFor(schema, childKey)) return; + if (closed) found.push(path ? `${path}.${childKey}` : childKey); + }); + Object.entries(declared).forEach(([childKey, childSchema]) => { if (value[childKey] !== undefined) { found.push(...findUnknownKeys(childSchema, value[childKey], path ? `${path}.${childKey}` : childKey)); } }); + Object.keys(value).forEach(childKey => { + const patternSchema = Object.hasOwn(declared, childKey) ? null : patternSchemaFor(schema, childKey); + if (patternSchema) { + found.push(...findUnknownKeys(patternSchema, value[childKey], path ? `${path}.${childKey}` : childKey)); + } + }); } else if (schema.type === 'array' && Array.isArray(value)) { value.forEach((entry, index) => { found.push(...findUnknownKeys(schema.items || {}, entry, `${path}[${index}]`)); diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 73165beb..a8aba10d 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -241,10 +241,10 @@

{{t "no_access.title"}}

{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} -{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} +{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} diff --git a/dashboard/internal/webui/templates/settings.html b/dashboard/internal/webui/templates/settings.html index d4953f0d..d5dbdfa5 100644 --- a/dashboard/internal/webui/templates/settings.html +++ b/dashboard/internal/webui/templates/settings.html @@ -706,7 +706,7 @@

{{t "settings.history.energy_stats.title"}}

+ data-subpage-script="{{.BasePath}}/static/js/schema-form.js?v=3,{{.BasePath}}/static/js/systemconfig.page.js?v=5" data-subpage-css="">