Files
lmxopcua/scripts/validation/grpc-data/conditions_scenarios.py
T

503 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""A4 live condition-forwarding scenarios (plan §9 A4, A01–A08) on a `rig.py up --conditions` run.
python3 scripts/validation/grpc-data/conditions_scenarios.py --run-id <id> [--only A01,A02,A04,A05,A08]
Part 1 implements A01, A02, A04, A05 and A08. Part 2 (A03 origin failover, A06 consumer Primary change, A07 consumer
restart) adds `scenario_A03`/`scenario_A06`/`scenario_A07` methods to `ConditionScenarios` and their ids to `SCENARIOS`;
everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared.
Rules every scenario follows:
- ids are RESOLVED, never constructed: projected folders by browsing the consumer's address space, imported ConditionIds
and EventIds from the `alarms` notifications the CLI prints (`ConditionNodeId`, `EventId`);
- every absence assertion has a positive control observed in the same window;
- configuration changes go through the seeder's `mutate` (+ deploy) or a rig configuration experiment, and are undone
before the next scenario (`restore` + deploy, or the experiment's own restart).
Evidence: the run's restricted `evidence/` folder — `A4S-<id>-*.txt` CLI logs, `*.process.json`, `*.probe.json`,
`A4S-<id>.json` per scenario and `A4S-results.json` / `A4S-results.md` for the selection.
"""
import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
import uuid
from pathlib import Path
import rig
import scenarios
SCENARIOS = ("A01", "A02", "A04", "A05", "A08") # part 2 appends A03, A06, A07
TIMEOUTS = {"A01": 420, "A02": 360, "A04": 480, "A05": 720, "A08": 720}
NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8)
ADMIN = 4095
_BROWSE = re.compile(r"^(\s*)\[(\w+)\]\s+(.*?)\s+\(NodeId:\s*(.*)\)\s*$")
class Watch:
"""One CLI `alarms` subscription (Server object by default, or a notifier folder) writing to a restricted log."""
def __init__(self, runner, node, name, *, notifier=None, key=None, refresh=True):
self.log = runner.folder / name
self.started = time.time()
descriptor = os.open(self.log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
argv = ["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(node), "-U", "apikey", "-P", key or runner.key, "-i", "250"]
if notifier:
argv += ["-n", notifier]
if refresh:
argv.append("--refresh")
self.process = subprocess.Popen(argv, stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True, cwd=rig.ROOT)
os.close(descriptor)
def stop(self):
if self.process.poll() is None:
self.process.send_signal(signal.SIGINT)
try:
self.process.wait(timeout=20)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=10)
def text(self):
return self.log.read_text(errors="replace") if self.log.exists() else ""
def blocks(self, condition=None):
found = []
for block in self.text().split("\n\n"):
header = re.search(r"\[(\S+)\] ALARM\s+(.*)$", block, re.M)
if not header:
continue
fields = {"Time": header.group(1), "Source": header.group(2).strip()}
for line in block.splitlines():
match = re.match(r"\s*(Condition|State|Severity|Message|Retain|ConditionNodeId|EventId):\s*(.*)$", line)
if match:
fields[match.group(1)] = match.group(2).strip()
if condition is None or fields.get("Condition") == condition:
found.append(fields)
return found
def wait_for(predicate, timeout, step=1.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
value = predicate()
if value:
return value
time.sleep(step)
return predicate()
def states(blocks):
return [b.get("State") for b in blocks]
class ConditionScenarios:
def __init__(self, run_id):
self.r = scenarios.ScenarioRunner(run_id)
self.fixture = self.r.manifest["fixture"]
if not self.fixture.get("conditions"):
raise scenarios.ScenarioError("the run was not seeded with the conditions profile (rig.py up --conditions)")
files = self.r.manifest["credentials"]["data_key_files"]
self.nogrant_key = Path(files["cli_nogrant"]).read_text().strip()
self.report = None
# ---- primitives -------------------------------------------------------------------------------------------------
def check(self, name, condition):
self.report["checks"][name] = bool(condition)
return bool(condition)
def watch(self, node, tag, **options):
name = f"A4S-{self.r.active}-{tag}.txt"
watcher = Watch(self.r, node, name, **options)
self.watchers.append(watcher)
return watcher
def cli(self, node, command, *args, tag, key=None, timeout=60):
argv = ["dotnet", str(self.r.cli_dll), command, "-u", self.r.endpoint(node), "-U", "apikey", "-P", key or self.r.key, *args]
result = self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=timeout)
return result.returncode, (result.stdout + result.stderr)
def browse(self, node, start="i=85", depth=6):
code, text = self.cli(node, "browse", "-n", start, "-r", "-d", str(depth), tag="browse-" + uuid.uuid4().hex[:6], timeout=120)
rows, stack = [], []
for line in text.splitlines():
match = _BROWSE.match(line)
if not match:
continue
indent = len(match.group(1))
while stack and stack[-1][0] >= indent:
stack.pop()
row = {"class": match.group(2), "name": match.group(3), "node_id": match.group(4),
"parent": stack[-1][1]["node_id"] if stack else start, "path": "/".join([s[1]["name"] for s in stack] + [match.group(3)])}
rows.append(row)
stack.append((indent, row))
return rows
def read(self, node, node_id, tag):
code, text = self.cli(node, "read", "-n", node_id, tag=tag)
value = re.search(r"^Value:\s*(.*)$", text, re.M)
status = re.search(r"^Status:\s*(\S+)", text, re.M)
return {"value": value.group(1).strip() if value else None, "status": status.group(1) if status else None}
def condition_child(self, node, condition_id, child, tag):
"""Browse the condition node for `child` (e.g. ConfirmedState) and read its `Id` — resolved, never constructed."""
rows = self.browse(node, condition_id, depth=2)
state = next((r for r in rows if r["name"] == child and r["parent"] == condition_id), None)
identifier = next((r for r in rows if state and r["name"] == "Id" and r["parent"] == state["node_id"]), None)
return self.read(node, identifier["node_id"], tag) if identifier else {"value": None, "status": "unresolved"}
def projected_folders(self, node):
"""Resolve each condition mapping's projected branch folder (and its child folders) by browsing the consumer."""
rows = self.browse(node)
native = self.fixture["conditions"]["native"]
folders = {}
for alias, branch in [("uns-plc", self.fixture["conditions"]["scripted"]["branch"]), *native["branches"].items()]:
matches = [r for r in rows if r["name"] == branch]
folders[alias] = [{"node_id": r["node_id"], "path": r["path"],
"children": [c for c in rows if c["parent"] == r["node_id"] and c["class"] == "Object"]} for r in matches]
self.report["browse"] = {"folders": folders, "rows": len(rows)}
return folders
def raise_scripted(self, value=150):
self.r.device("set", address=20, value=value)
def stop_watchers(self):
for watcher in self.watchers:
watcher.stop()
self.watchers = []
def audit(self, node, since):
"""The origin's DataConnections audit lines (one per remote condition-method call) logged since `since`."""
output = self.r.rig.compose("logs", "--no-color", "--since", since, node, timeout=60)
return [line for line in output.splitlines() if "Data-connection condition method" in line]
def node_probe_async(self, node, operation, timeout_seconds, **fields):
identity = self.r.active + "-" + uuid.uuid4().hex
folder = self.r.rig.folder / "probe" / node
command = {"id": identity, "connectionId": "consumer-source", "operation": operation, "realm": "raw", "originCluster": "SOURCE",
"namespaceUri": "", "path": "", "timeoutSeconds": timeout_seconds, **fields}
rig.atomic_write_secret(folder / (identity + ".request.json"), json.dumps(command))
def result():
output = folder / (identity + ".result.json")
if not wait_for(output.exists, timeout_seconds + 20, 0.5):
raise scenarios.ScenarioError("node probe result missing")
raw = scenarios.restricted_json(output)
self.r.save(identity + ".probe.json", raw)
return raw
return result
def probe_records(self, tag, **arguments):
output = self.r.folder / f"A4S-{self.r.active}-{tag}.json"
argv = ["dotnet", str(self.r.probe_dll), "--manifest", str(self.r.manifest_path), "--scenario", "condition-records", "--output", str(output)]
for key, value in arguments.items():
argv += ["--" + key.replace("_", "-"), value]
self.r.process(argv, f"A4S-{self.r.active}-{tag}", timeout=120)
return scenarios.restricted_json(output) if output.exists() else {"passed": False}
# ---- scenarios --------------------------------------------------------------------------------------------------
def scenario_A01(self):
"""Scripted raise, ack, confirm via the consumer; origin and consumer both show each transition exactly once."""
source, consumer = self.r.primary("source"), self.r.primary("consumer")
name = self.fixture["conditions"]["scripted"]["condition"]
origin = self.watch(source, "origin")
imported = self.watch(consumer, "consumer")
time.sleep(6)
self.raise_scripted()
active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120)
if not self.check("consumer_imports_active_unacked", active):
return
condition = active["ConditionNodeId"]
self.report["condition_id"] = condition
self.check("imported_condition_id_is_opaque", condition.startswith("ns=") and "c1." in condition and "source-scalar-high" not in condition)
code, text = self.cli(consumer, "ack", "-n", condition, "-e", active["EventId"], "-c", "A01 consumer ack", tag="ack")
self.check("ack_good", code == 0 and "Acknowledge successful" in text)
acked = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Acknowledged"), None), 30)
self.check("consumer_sees_ack", acked)
time.sleep(5)
before = {"origin": len(origin.blocks(name)), "consumer": len(imported.blocks(name))}
self.report["ack_counts"] = {"origin": states(origin.blocks(name)).count("Active, Acknowledged"),
"consumer": states(imported.blocks(name)).count("Active, Acknowledged")}
self.check("origin_exactly_one_ack_event", self.report["ack_counts"]["origin"] == 1)
self.check("consumer_exactly_one_ack_event", self.report["ack_counts"]["consumer"] == 1)
latest = imported.blocks(name)[-1] if acked else active
code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A01 consumer confirm", tag="confirm")
self.report["confirm_output"] = text[-300:]
self.check("confirm_good", code == 0 and "Confirm successful" in text)
time.sleep(8)
after = {"origin": origin.blocks(name)[before["origin"]:], "consumer": imported.blocks(name)[before["consumer"]:]}
self.report["confirm_events"] = {k: [(b.get("State"), b.get("Message")) for b in v] for k, v in after.items()}
self.check("origin_exactly_one_confirm_event", len(after["origin"]) == 1)
self.check("consumer_exactly_one_confirm_event", len(after["consumer"]) == 1)
origin_condition = next((b.get("ConditionNodeId") for b in origin.blocks(name) if b.get("ConditionNodeId")), None)
self.report["origin_condition_id"] = origin_condition
confirmed = {"consumer": self.condition_child(consumer, condition, "ConfirmedState", "read-confirmed-consumer"),
"origin": self.condition_child(source, origin_condition, "ConfirmedState", "read-confirmed-origin") if origin_condition else None}
self.report["confirmed_state"] = confirmed
self.check("consumer_confirmed_state_true", (confirmed["consumer"] or {}).get("value") == "True")
self.check("origin_confirmed_state_true", (confirmed["origin"] or {}).get("value") == "True")
self.raise_scripted(0)
self.check("origin_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in origin.blocks(name)), 30))
self.check("consumer_clears", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 30))
self.report["states"] = {"origin": states(origin.blocks(name)), "consumer": states(imported.blocks(name))}
def scenario_A02(self):
"""Native condition (OpcUaClient → opc-plc --alm): Ack + AddComment forwarded; Confirm refused BadNotSupported, unsent."""
source, consumer = self.r.primary("source"), self.r.primary("consumer")
name = self.fixture["conditions"]["native"]["condition"]
since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - 2))
origin = self.watch(source, "origin")
imported = self.watch(consumer, "consumer")
event = wait_for(lambda: next((b for b in reversed(imported.blocks(name)) if b.get("EventId") and b.get("ConditionNodeId")), None), 150)
self.report["origin_states"] = states(origin.blocks(name))[:20]
if not self.check("consumer_imports_native_condition", event):
return
condition = event["ConditionNodeId"]
self.report["condition_id"] = condition
self.check("origin_shows_native_condition", origin.blocks(name))
self.check("imported_condition_id_is_opaque", "c1." in condition and "opcua/opcplc" not in condition)
code, text = self.cli(consumer, "ack", "-n", condition, "-e", "00" * 16, "-c", "A02 bogus", tag="ack-bogus")
self.check("bogus_eventid_refused", "BadEventIdUnknown" in text and "successful" not in text)
latest = imported.blocks(name)[-1]
code, text = self.cli(consumer, "ack", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer ack", tag="ack")
self.report["ack_output"] = text[-300:]
self.check("ack_good", code == 0 and "Acknowledge successful" in text)
latest = imported.blocks(name)[-1]
code, text = self.cli(consumer, "comment", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer comment", tag="comment")
self.report["comment_output"] = text[-300:]
self.check("comment_good", code == 0 and "successful" in text.lower() and "failed" not in text.lower())
latest = imported.blocks(name)[-1]
code, text = self.cli(consumer, "confirm", "-n", condition, "-e", latest["EventId"], "-c", "A02 consumer confirm", tag="confirm")
self.report["confirm_output"] = text[-300:]
self.check("confirm_refused_bad_not_supported", "BadNotSupported" in text and "Confirm successful" not in text)
time.sleep(6)
audit = self.audit(source, since)
self.report["origin_audit"] = audit[-20:]
joined = "\n".join(audit)
# Positive control: the ack and the comment reached the origin (audited); the confirm never did.
self.check("origin_audited_ack", re.search(r"condition method \W?Acknowledge\b", joined))
self.check("origin_audited_comment", re.search(r"condition method \W?AddComment\b", joined))
self.check("confirm_unsent", not re.search(r"condition method \W?Confirm\b", joined))
self.report["consumer_states"] = states(imported.blocks(name))[-20:]
def scenario_A04(self):
"""One native alarm, three placements (Raw device + two referencing equipment) ⇒ one consumer condition, three
notifiers, one Server-object event per transition; the same ConditionId whichever subscriber came first; a UNS-only
origin principal's records carry no RawPath."""
consumer, source = self.r.primary("consumer"), self.r.primary("source")
native = self.fixture["conditions"]["native"]
name = native["condition"]
folders = self.projected_folders(consumer)
mapping_aliases = ("raw", "pumpa", "pumpb")
if not self.check("three_branch_folders_resolved", all(len(folders.get(a, [])) == 1 for a in mapping_aliases)):
return
rounds = []
for number, order in enumerate((("pumpa", "raw", "pumpb"), ("raw", "pumpb", "pumpa")), start=1):
if number == 2:
# Let the demand linger (30 s) expire so round 2 re-imports from scratch with a different first subscriber.
self.stop_watchers()
time.sleep(45)
folder_watches = {}
for alias in order:
candidates = [folders[alias][0]] + folders[alias][0]["children"][:3]
folder_watches[alias] = [(c["node_id"], self.watch(consumer, f"r{number}-{alias}-{i}", notifier=c["node_id"], refresh=False))
for i, c in enumerate(candidates)]
time.sleep(2)
server = self.watch(consumer, f"r{number}-server")
window_start = time.time() + 8
wait_for(lambda: len([b for b in server.blocks(name) if b.get("EventId")]) >= 4, 120)
time.sleep(6)
server_events = [b for b in server.blocks(name) if b.get("EventId") and not b.get("Message", "").startswith("Condition refresh")]
ids = {b.get("ConditionNodeId") for b in server_events}
event_ids = [b["EventId"] for b in server_events]
per_folder = {}
for alias, candidates in folder_watches.items():
hits = [(node_id, [b["EventId"] for b in w.blocks(name) if b.get("EventId")]) for node_id, w in candidates]
notifier = next(((node_id, events) for node_id, events in hits if events), (None, []))
per_folder[alias] = {"notifier": notifier[0], "events": len(notifier[1]),
"duplicates": len(notifier[1]) - len(set(notifier[1])),
"condition_ids": sorted({b.get("ConditionNodeId") for _, w in candidates for b in w.blocks(name)})}
# Overlap: every Server-object event raised after all subscribers were up reached each notifier exactly once.
late = [b["EventId"] for b in server_events if self._epoch(b.get("Time")) >= window_start]
for alias, candidates in folder_watches.items():
seen = [e for node_id, w in candidates if node_id == per_folder[alias]["notifier"] for e in
[b["EventId"] for b in w.blocks(name) if b.get("EventId")]]
per_folder[alias]["late_server_events_missing"] = len([e for e in late if e not in seen])
rounds.append({"order": order, "condition_ids": sorted(ids), "server_events": len(server_events),
"server_duplicate_event_ids": len(event_ids) - len(set(event_ids)), "late_events": len(late), "folders": per_folder})
self.report["rounds"] = rounds
for index, round_ in enumerate(rounds, start=1):
self.check(f"r{index}_one_consumer_condition", len(round_["condition_ids"]) == 1)
self.check(f"r{index}_server_object_each_event_once", round_["server_events"] >= 1 and round_["server_duplicate_event_ids"] == 0)
self.check(f"r{index}_three_notifiers", all(round_["folders"][a]["notifier"] and round_["folders"][a]["duplicates"] == 0 for a in mapping_aliases))
self.check(f"r{index}_notifiers_same_condition", all(round_["folders"][a]["condition_ids"] == round_["condition_ids"] for a in mapping_aliases))
self.check(f"r{index}_late_events_reach_every_notifier", round_["late_events"] >= 1
and all(round_["folders"][a]["late_server_events_missing"] == 0 for a in mapping_aliases))
self.check("same_condition_id_both_orders", len(rounds) == 2 and rounds[0]["condition_ids"] == rounds[1]["condition_ids"])
# UNS-only principal: no RawPath anywhere in its records; positive control = the Raw item under the full principal names it.
unsonly = self.probe_records("records-unsonly", node=source, key_name="source_unsonly", realm="uns",
identifier=native["equipment"]["pumpa"], subject=native["subjects"]["pumpa"],
forbid=native["raw_root"], expect=name)
control = self.probe_records("records-raw-control", node=source, key_name="source", realm="raw",
identifier=native["raw_root"], subject=native["raw_root"], expect=native["raw_root"])
self.report["records"] = {"unsonly": self._records_summary(unsonly), "raw_control": self._records_summary(control)}
self.check("unsonly_records_carry_no_rawpath", unsonly.get("passed"))
self.check("raw_principal_records_name_rawpath_positive_control", control.get("passed"))
def scenario_A05(self):
"""ACLs off on the consumer: a session WITHOUT the mapping grant at i=2253 receives zero imported events, live or on
refresh, while a granted session sees them in the same window."""
name, native = self.fixture["conditions"]["scripted"]["condition"], self.fixture["conditions"]["native"]["condition"]
with self.r.rig._configuration_experiment("a4s-acl-off", ("consumer-1", "consumer-2"), {"Security__Acl__Enabled": "false"}):
self.r.manifest = self.r.rig.load()
consumer = self.r.wait_primary("consumer")
self.report["acl_disabled_on"] = consumer
denied = self.watch(consumer, "nogrant", key=self.nogrant_key)
granted = self.watch(consumer, "granted")
time.sleep(5)
self.raise_scripted()
wait_for(lambda: granted.blocks(name) and granted.blocks(native), 150)
time.sleep(15)
# Second refresh pass for the denied session: a fresh subscription's ConditionRefresh replay must also be empty.
denied_refresh = self.watch(consumer, "nogrant-refresh", key=self.nogrant_key)
time.sleep(12)
self.raise_scripted(0)
time.sleep(8)
self.stop_watchers()
imported_denied = [b for w in (denied, denied_refresh) for b in w.blocks() if "c1." in (b.get("ConditionNodeId") or "")
or b.get("Condition") in (name, native)]
markers = [b for b in denied.blocks() if b.get("Message", "").startswith("Condition refresh")]
self.report["granted"] = {"scripted": len(granted.blocks(name)), "native": len(granted.blocks(native))}
self.report["denied"] = {"imported_events": len(imported_denied), "refresh_markers": len(markers),
"all_events": len(denied.blocks()) + len(denied_refresh.blocks())}
self.check("granted_session_sees_scripted_positive_control", granted.blocks(name))
self.check("granted_session_sees_native_positive_control", granted.blocks(native))
self.check("denied_session_alive_refresh_markers", markers)
self.check("denied_session_zero_imported_events", not imported_denied)
self.r.manifest = self.r.rig.load()
self.report["restored"] = "consumer pair restarted with Security__Acl__Enabled from compose.yml"
def scenario_A08(self):
"""Origin ACL loses AlarmAcknowledge ⇒ a consumer ack is denied while state keeps streaming; the consumer publishes
no /alerts (alarm-history) transition for imported conditions while the origin does (positive control)."""
name = self.fixture["conditions"]["scripted"]["condition"]
self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": NO_ACK})
self.r.manifest = self.r.rig.load()
source, consumer = self.r.primary("source"), self.r.primary("consumer")
origin_alerts = self.node_probe_async(source, "alert-transitions", 110)
consumer_alerts = self.node_probe_async(consumer, "alert-transitions", 110)
origin = self.watch(source, "origin")
imported = self.watch(consumer, "consumer")
time.sleep(6)
self.raise_scripted()
active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120)
if self.check("state_streams_after_revocation", active):
code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 denied ack", tag="ack-denied")
self.report["denied_ack_output"] = text[-300:]
self.check("ack_denied", "Acknowledge successful" not in text and re.search(r"Bad\w*(Denied|Access|Permission)", text))
time.sleep(5)
self.check("origin_not_acknowledged", "Active, Acknowledged" not in states(origin.blocks(name)))
self.raise_scripted(0)
self.check("consumer_still_streams_clear", wait_for(lambda: any(b.get("State", "").startswith("Inactive") for b in imported.blocks(name)), 40))
origin_result, consumer_result = origin_alerts(), consumer_alerts()
origin_rows = origin_result.get("observations", {}).get("alarmTransitions", [])
consumer_rows = consumer_result.get("observations", {}).get("alarmTransitions", [])
self.report["alerts"] = {"origin": origin_rows, "consumer": consumer_rows,
"origin_probe_passed": origin_result.get("passed"), "consumer_probe_passed": consumer_result.get("passed")}
self.check("origin_alerts_positive_control", origin_result.get("passed") and any(r.get("alarmName") == name for r in origin_rows))
self.check("consumer_alerts_stream_open", consumer_result.get("passed"))
self.check("consumer_no_alerts_for_imported", not consumer_rows)
# Positive control for the denial: grant restored ⇒ the same consumer ack is applied.
self.stop_watchers()
self.r.mutate(acl_permissions={"node_acl_id": "source-peer", "permission_flags": ADMIN})
self.r.manifest = self.r.rig.load()
consumer = self.r.primary("consumer")
imported = self.watch(consumer, "consumer-restored")
time.sleep(6)
self.raise_scripted()
active = wait_for(lambda: next((b for b in imported.blocks(name) if b.get("State") == "Active, Unacknowledged" and b.get("EventId")), None), 120)
if self.check("restored_raise_imported", active):
code, text = self.cli(consumer, "ack", "-n", active["ConditionNodeId"], "-e", active["EventId"], "-c", "A08 restored ack", tag="ack-restored")
self.check("restored_ack_good_positive_control", code == 0 and "Acknowledge successful" in text)
self.raise_scripted(0)
time.sleep(4)
# ---- helpers ----------------------------------------------------------------------------------------------------
@staticmethod
def _epoch(stamp):
try:
from datetime import datetime
return datetime.fromisoformat((stamp or "")[:26].rstrip("Z") + "+00:00").timestamp()
except ValueError:
return 0
@staticmethod
def _records_summary(result):
rows = result.get("results") if isinstance(result, dict) else None
row = rows[0] if isinstance(rows, list) and rows else result
observations = row.get("observations", row) if isinstance(row, dict) else {}
return {"passed": result.get("passed") if isinstance(result, dict) else None,
"forbiddenFound": observations.get("forbiddenFound"), "expectedFound": observations.get("expectedFound"),
"records": [{"name": (r.get("info") or {}).get("ConditionName"), "placements": (r.get("info") or {}).get("placements")}
for r in observations.get("records", [])]}
# ---- driver -----------------------------------------------------------------------------------------------------
def run(self, selection):
self.r.publish()
self.r.rig.seed_helper("snapshot")
rows = []
for scenario in selection:
self.r.active, self.r.count = "A4S-" + scenario, 0
self.r.deadline = time.monotonic() + TIMEOUTS.get(scenario, 600)
self.report = {"id": scenario, "checks": {}, "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
self.watchers = []
error = None
try:
getattr(self, "scenario_" + scenario)()
except Exception as failure: # recorded, never hides restoration
error = type(failure).__name__ + ": " + str(failure)[:400]
finally:
self.stop_watchers()
try:
self.r.device("set", address=20, value=0)
if scenario in ("A08",):
self.r.deadline = time.monotonic() + 600
self.r.baseline()
self.report["restored"] = self.report.get("restored", True)
except Exception as failure:
self.report["restored"] = False
error = (error + "; " if error else "") + "restoration " + type(failure).__name__ + ": " + str(failure)[:200]
self.report["error"] = error
self.report["passed"] = error is None and bool(self.report["checks"]) and all(self.report["checks"].values())
self.r.save(f"A4S-{scenario}.json", self.report)
rows.append({"id": scenario, "passed": self.report["passed"], "error": error,
"failed_checks": [k for k, v in self.report["checks"].items() if not v], "restored": self.report["restored"]})
print(json.dumps(rows[-1]), flush=True)
summary = {"run_id": self.r.manifest["run_id"], "source_revision": self.r.manifest.get("source_revision"), "rows": rows,
"passed": all(row["passed"] for row in rows)}
self.r.save("A4S-results.json", summary)
lines = ["| Scenario | Result | Failed checks | Restored |", "|---|---|---|---|"]
lines += [f"| {row['id']} | {'PASS' if row['passed'] else 'FAIL'} | {', '.join(row['failed_checks']) or (row['error'] or '—')} | {row['restored']} |" for row in rows]
rig.atomic_write_secret(self.r.folder / "A4S-results.md", "\n".join(lines) + "\n")
return summary
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--run-id", required=True)
parser.add_argument("--only", default=",".join(SCENARIOS), help="comma-separated scenario ids (default: all implemented)")
arguments = parser.parse_args(argv)
selection = [item.strip() for item in arguments.only.split(",") if item.strip()]
unknown = [item for item in selection if item not in SCENARIOS]
if unknown:
parser.error("unknown scenario(s): " + ", ".join(unknown))
summary = ConditionScenarios(arguments.run_id).run(selection)
print(json.dumps(summary, indent=2))
return 0 if summary["passed"] else 1
if __name__ == "__main__":
sys.exit(main())