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

159 lines
8.9 KiB
Python

"""H2 remote-history live smoke on a `rig.py up --history` run (plan §9 H2 exit gate).
Drives the deployed rig only through its owned surfaces: the device control API (advances the
historized `counter`), the probe's raw origin RPCs (`--scenario history`), the CONSUMER node probe's
deployed-connection lease (`history` operation = a runtime consumer's IDataHistoryService read) and the
Client CLI's OPC UA `historyread` on the SOURCE node. Evidence lands in the run's restricted
`evidence/` folder; keys are redacted by ScenarioRunner.save.
"""
import argparse
import json
import re
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path
import scenarios
import rig
def _iso(moment):
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _cli_rows(stdout):
"""`historyread` rows (`<source time O> <value> <Good|Bad|Uncertain>`) → [(UTC datetime, value text, quality)]."""
rows = []
for line in stdout.splitlines():
parts = line.split()
if len(parts) == 3 and parts[2] in {"Good", "Bad", "Uncertain"} and re.match(r"^\d{4}-\d{2}-\d{2}T", parts[0]):
rows.append((_parse(parts[0]), parts[1], parts[2]))
return rows
def _parse(text):
"""ISO 8601 with up to 7 fractional digits → aware datetime truncated to microseconds."""
match = re.match(r"^(.*?T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$", text)
fraction = (match[2] or "")[:6].ljust(6, "0")
zone = match[3] or "Z"
return datetime.fromisoformat(match[1] + "." + fraction + ("+00:00" if zone == "Z" else zone))
def _wire_rows(samples):
rows = []
for sample in samples:
value = json.loads(sample["value"])
scalar = next(v for k, v in value.items() if k != "kind")
rows.append((_parse(sample["sourceTimestampUtc"]), str(scalar), "Good" if int(sample["statusCode"], 16) >> 30 == 0 else "Other"))
return rows
def compare(cli_stdout, wire_samples):
cli, wire = _cli_rows(cli_stdout), _wire_rows(wire_samples)
return {"cli_count": len(cli), "wire_count": len(wire), "identical": cli == wire and len(cli) > 0,
"first": [str(x) for x in (cli[:1] + wire[:1])], "last": [str(x) for x in (cli[-1:] + wire[-1:])]}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--accumulate-seconds", type=int, default=40)
parser.add_argument("--denied-expect", choices=("permission-denied", "unsupported"), default="permission-denied",
help="the second principal: export lacks HistoryRead (RPC PermissionDenied) or export granted + ACL denies (per-item 0x80720000)")
parser.add_argument("--label", default="smoke", help="evidence file suffix")
parser.add_argument("--pinned-build", action="store_true",
help="the checkout moved after `up`: verify the running Host stamps against the run's RECORDED build hash "
"instead of the current checkout (recorded in the report; tools publish from the current checkout)")
arguments = parser.parse_args(argv)
current_hash = rig.source_tree_hash()
if arguments.pinned_build:
recorded = scenarios.restricted_json(rig.LocalRig(arguments.run_id).path)["source_tree_hash"]
rig.source_tree_hash = lambda: recorded
runner = scenarios.ScenarioRunner(arguments.run_id)
if runner.manifest["fixture"].get("history") is None:
raise SystemExit("run was not brought up with --history")
runner.active, runner.deadline = "H2", time.monotonic() + 900
runner.publish()
report = {"denied_expect": arguments.denied_expect, "run_id": arguments.run_id, "source_revision": runner.manifest.get("source_revision"),
"source_tree_hash": runner.manifest.get("source_tree_hash"), "checkout_tree_hash_at_smoke": current_hash,
"pinned_build": arguments.pinned_build, "items": {}}
# 1. Accumulate history: one counter step per second.
started = datetime.now(timezone.utc)
for _ in range(arguments.accumulate_seconds):
runner.device("advance", steps=1)
time.sleep(1)
finished = datetime.now(timezone.utc)
time.sleep(4) # let the outbox drain (DrainIntervalSeconds=1)
window_start = (started + timedelta(seconds=5)).replace(microsecond=0)
window_end = (finished - timedelta(seconds=5)).replace(microsecond=0)
report["accumulation"] = {"started": started.isoformat(), "finished": finished.isoformat(),
"window": [_iso(window_start), _iso(window_end)], "device": runner.device()}
# 2. Origin RPCs on both SOURCE data listeners.
output = runner.folder / ("H2-history-wire-" + arguments.label + ".json")
result = runner.process(["dotnet", str(runner.probe_dll), "--manifest", str(runner.manifest_path), "--scenario", "history",
"--history-start", _iso(window_start), "--history-end", _iso(window_end),
"--denied-expect", arguments.denied_expect, "--output", str(output)],
"H2-history-wire-" + arguments.label, timeout=120)
wire = scenarios.restricted_json(output) if output.exists() else {"passed": False, "stderr": result.stderr[-4000:]}
report["items"]["wire"] = wire
# 3. OPC UA historyread on each SOURCE node for the same window.
cli = {}
for node in ("source-1", "source-2"):
resolved = runner.manifest["resolved_nodes"][node]["aliases"]["raw"]
node_id = resolved.rsplit("/", 1)[0] + "/counter"
argv = ["dotnet", str(runner.cli_dll), "historyread", "-u", runner.endpoint(node), "-U", "apikey", "-P", runner.key,
"-n", node_id, "--start", _iso(window_start), "--end", _iso(window_end), "--max", "1000"]
run = runner.process(argv, "H2-cli-historyread-" + node, timeout=60)
cli[node] = {"node_id": node_id, "returncode": run.returncode, "stdout": run.stdout[-8000:], "stderr": run.stderr[-2000:]}
# The non-historized tag over OPC UA, for contrast with the remote refusal.
argv[argv.index("-n") + 1] = resolved
run = runner.process(argv, "H2-cli-historyread-unhistorized-" + node, timeout=60)
cli[node]["unhistorized"] = {"node_id": resolved, "returncode": run.returncode, "stdout": run.stdout[-2000:], "stderr": run.stderr[-2000:]}
report["items"]["cli"] = cli
# 4. Runtime consumer: the deployed connection lease on each CONSUMER node.
consumer = {}
paths = runner.manifest["fixture"]["history"]
for node in ("consumer-1", "consumer-2"):
observed = {}
for name, fields in (
("newest5", {"path": paths["historized"]["raw"], "historyNumValues": 5}),
("window", {"path": paths["historized"]["raw"], "historyNumValues": 0,
"historyStartUtc": window_start.isoformat(), "historyEndUtc": window_end.isoformat()}),
("unhistorized", {"path": paths["unhistorized"]["raw"], "historyNumValues": 5, "expected_state": "Unsupported"}),
("uns-newest5", {"realm": "uns", "path": paths["historized"]["uns"], "historyNumValues": 5})):
realm = fields.pop("realm", "raw")
expected = fields.pop("expected_state", None)
try:
observed[name] = {"passed": True, "observations": runner.probe(node, "history", realm, expected_state=expected, timeout=60, **fields)}
except Exception as error: # record and continue: the smoke reports per item
observed[name] = {"passed": False, "error": type(error).__name__ + ": " + str(error)}
consumer[node] = observed
report["items"]["consumer"] = consumer
# 5. Value parity: OPC UA historyread on the SOURCE node vs the remote origin read vs the runtime consumer, same window.
parity = {}
for result_row in wire.get("results", []):
if result_row["id"].startswith("history-window-"):
node = result_row["id"][len("history-window-"):]
parity["wire-" + node + "-vs-cli-" + node] = compare(cli[node]["stdout"], result_row["observations"]["samples"])
for node, rows in consumer.items():
if rows["window"]["passed"]:
samples = rows["window"]["observations"]["pages"][0]["samples"]
parity["consumer-" + node + "-vs-cli-source-1"] = compare(cli["source-1"]["stdout"], samples)
report["items"]["parity"] = parity
runner.save("H2-history-" + arguments.label + ".json", report)
print(json.dumps({"saved": str(runner.folder / ("H2-history-" + arguments.label + ".json")), "wire_passed": wire.get("passed"),
"consumer": {node: {k: v["passed"] for k, v in rows.items()} for node, rows in consumer.items()},
"cli": {node: row["returncode"] for node, row in cli.items()},
"parity": {k: v["identical"] for k, v in parity.items()}}, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())