304 lines
15 KiB
Python
304 lines
15 KiB
Python
"""Run the isolated production CLI/probe gate and validate actual operation evidence."""
|
|
import argparse
|
|
from datetime import datetime
|
|
import ipaddress
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
from urllib.parse import urlsplit
|
|
|
|
from processes import ProcessResult
|
|
|
|
|
|
class CliGateError(RuntimeError):
|
|
"""Missing or unsuccessful CLI evidence."""
|
|
|
|
|
|
def _process_ok(result):
|
|
if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.returncode != 0 or result.truncated:
|
|
raise CliGateError("CLI failed, was cancelled, timed out, or produced truncated evidence")
|
|
if not isinstance(result.stdout, str) or not result.stdout.strip():
|
|
raise CliGateError("CLI stdout evidence is missing")
|
|
|
|
|
|
def _field(text, name):
|
|
values = re.findall(rf"^{re.escape(name)}:[ \t]*(.*)$", text, re.M)
|
|
if len(values) != 1:
|
|
raise CliGateError(f"CLI evidence needs exactly one {name} field")
|
|
return values[0].strip()
|
|
|
|
|
|
def _timestamp(value):
|
|
try:
|
|
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
except (ValueError, TypeError):
|
|
raise CliGateError("CLI timestamp is missing or invalid") from None
|
|
if parsed.tzinfo is None:
|
|
raise CliGateError("CLI timestamp must carry a timezone")
|
|
return value
|
|
|
|
|
|
def is_good_status(status):
|
|
return re.fullmatch(r"Good(?: \[0x00000000\])?", status) is not None
|
|
|
|
|
|
def parse_notification(line):
|
|
match = re.fullmatch(r"\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)\r?", line)
|
|
if match is None:
|
|
return None
|
|
timestamp, node, value, status = match.groups()
|
|
_timestamp(timestamp)
|
|
return {"timestamp": timestamp, "node": node, "value": value, "status": status}
|
|
|
|
|
|
def validate_read(result, *, expected_node):
|
|
_process_ok(result)
|
|
if _field(result.stdout, "Node") != expected_node:
|
|
raise CliGateError("CLI read returned a different node")
|
|
status = _field(result.stdout, "Status")
|
|
if not is_good_status(status):
|
|
raise CliGateError("CLI read status is not Good")
|
|
value = _field(result.stdout, "Value")
|
|
if not value:
|
|
raise CliGateError("CLI read value is missing")
|
|
return {"node": expected_node, "status": "Good", "value": value,
|
|
"source_time": _timestamp(_field(result.stdout, "Source Time")),
|
|
"server_time": _timestamp(_field(result.stdout, "Server Time"))}
|
|
|
|
|
|
def validate_write(result, *, expected_node):
|
|
_process_ok(result)
|
|
successes = re.findall(r"^Write successful: (.+?) = (.+)$", result.stdout, re.M)
|
|
if "Write failed:" in result.stdout or len(successes) != 1 or successes[0][0] != expected_node:
|
|
raise CliGateError("CLI write lacks an exact successful node confirmation")
|
|
return {"node": expected_node, "accepted_value": successes[0][1].strip()}
|
|
|
|
|
|
def validate_connect(result, *, expected_endpoint):
|
|
_process_ok(result)
|
|
if _field(result.stdout, "Connected to") != expected_endpoint or result.stdout.count("Connection successful.") != 1:
|
|
raise CliGateError("CLI connection did not confirm the selected endpoint")
|
|
return {"endpoint": expected_endpoint, "server": _field(result.stdout, "Server")}
|
|
|
|
|
|
def validate_browse(result, *, expected_nodes):
|
|
_process_ok(result)
|
|
found = re.findall(r"^\s*\[(?:Object|Variable|Method)\] .+? \(NodeId: (.+)\)$", result.stdout, re.M)
|
|
if not expected_nodes or not set(expected_nodes).issubset(found):
|
|
raise CliGateError("CLI browse did not expose every expected child")
|
|
return {"nodes": found, "count": len(found)}
|
|
|
|
|
|
def validate_denial(result, *, command, expected_statuses):
|
|
if not isinstance(result, ProcessResult) or result.cancelled or result.timed_out or result.truncated:
|
|
raise CliGateError("denial evidence was cancelled, timed out, or was truncated")
|
|
combined = result.stdout + "\n" + result.stderr
|
|
if not expected_statuses or not any(status in combined for status in expected_statuses):
|
|
raise CliGateError("CLI did not explicitly report the expected denial")
|
|
if command == "write" and "Write successful:" in combined:
|
|
raise CliGateError("denied CLI write reported success")
|
|
if command == "read" and re.search(r"^Status:[ \t]*Good$", combined, re.M):
|
|
raise CliGateError("denied CLI read reported Good")
|
|
return {"denied": True, "command": command}
|
|
|
|
|
|
def resolve_node_id(namespace_array, namespace_uri, identifier):
|
|
"""Resolve only by an observed NamespaceArray; ambiguous/absent URIs fail."""
|
|
if not isinstance(namespace_array, list) or namespace_array.count(namespace_uri) != 1:
|
|
raise CliGateError("namespace URI is absent or ambiguous")
|
|
index = namespace_array.index(namespace_uri)
|
|
if not 0 < index <= 65535 or not isinstance(identifier, str) or not identifier:
|
|
raise CliGateError("invalid namespace or string identifier")
|
|
return f"ns={index};s={identifier}"
|
|
|
|
|
|
_COUNTERS = {
|
|
"total": "Total subscribed",
|
|
"ever_bad": " Ever went BAD during window",
|
|
"never_bad": " NEVER went bad (suspect)",
|
|
"good": " Last status GOOD",
|
|
"bad": " Last status NOT-GOOD",
|
|
"never": " No update received at all",
|
|
}
|
|
_SUMMARY_HEADING = "==================== SUMMARY ===================="
|
|
|
|
|
|
def _summary(text):
|
|
if not isinstance(text, str) or text.count(_SUMMARY_HEADING) != 1:
|
|
raise CliGateError("CLI summary file/header is missing or ambiguous")
|
|
counters = {}
|
|
for field, label in _COUNTERS.items():
|
|
value = _field(text, label)
|
|
if not re.fullmatch(r"\d+", value):
|
|
raise CliGateError("CLI summary counter is invalid")
|
|
counters[field] = int(value)
|
|
if counters["total"] <= 0 or counters["good"] + counters["bad"] + counters["never"] != counters["total"]:
|
|
raise CliGateError("CLI summary item counts are inconsistent")
|
|
if any(counters[field] > counters["total"] for field in ("ever_bad", "never_bad")):
|
|
raise CliGateError("CLI summary quality counts are inconsistent")
|
|
return counters
|
|
|
|
|
|
def validate_subscription(result, *, summary_text, expected_nodes, require_change=True):
|
|
"""Require all intended items attached, fresh Good updates, and both summaries.
|
|
|
|
The current CLI's Total subscribed counter is the number of *targets*, not
|
|
the number of successful SubscribeAsync calls. The attachment line and every
|
|
per-node notification therefore remain independently mandatory.
|
|
"""
|
|
_process_ok(result)
|
|
if not isinstance(expected_nodes, (set, frozenset, list, tuple)) or not expected_nodes or any(
|
|
not isinstance(node, str) or not node for node in expected_nodes):
|
|
raise CliGateError("explicit expected subscription nodes are required")
|
|
expected = set(expected_nodes)
|
|
if "FAILED to subscribe" in result.stdout or "Failed to write summary file:" in result.stdout:
|
|
raise CliGateError("CLI reported a per-item or summary-write failure")
|
|
attached = re.findall(r"^Subscribed to (\d+)/(\d+) nodes \(interval: (\d+)ms\)\.", result.stdout, re.M)
|
|
if len(attached) != 1 or any(int(value) != len(expected) for value in attached[0][:2]) or int(attached[0][2]) <= 0:
|
|
raise CliGateError("CLI did not attach every intended subscription")
|
|
file_counts = _summary(summary_text)
|
|
stdout_counts = _summary(result.stdout)
|
|
if file_counts != stdout_counts:
|
|
raise CliGateError("CLI file/stdout summaries disagree")
|
|
if file_counts["total"] != len(expected) or file_counts["good"] != len(expected) or any(
|
|
file_counts[field] for field in ("bad", "never", "ever_bad")):
|
|
raise CliGateError("CLI summary contains missing or non-Good updates")
|
|
notifications = {node: [] for node in expected}
|
|
for line in result.stdout.splitlines():
|
|
match = re.fullmatch(r"\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)", line)
|
|
if match is None:
|
|
continue
|
|
timestamp, node, value, status = match.groups()
|
|
if node not in expected:
|
|
raise CliGateError("CLI notification refers to an unexpected node")
|
|
_timestamp(timestamp)
|
|
if not is_good_status(status):
|
|
raise CliGateError("CLI notification status is not Good")
|
|
notifications[node].append(value)
|
|
for values in notifications.values():
|
|
if not values:
|
|
raise CliGateError("CLI subscription has no per-node notifications")
|
|
if require_change and len(set(values)) < 2:
|
|
raise CliGateError("CLI subscription has no changing per-node values")
|
|
return {"notifications": {node: len(values) for node, values in notifications.items()},
|
|
"summary": file_counts}
|
|
|
|
|
|
def validate_recovery_subscription(result, *, summary_text, expected_node, require_gap, require_held_session=False):
|
|
_process_ok(result)
|
|
attached = re.findall(r"^Subscribed to (\d+)/(\d+) nodes \(interval: (\d+)ms\)\.", result.stdout, re.M)
|
|
if len(attached) != 1 or attached[0][:2] != ("1", "1") or int(attached[0][2]) <= 0 or "FAILED to subscribe" in result.stdout:
|
|
raise CliGateError("recovery subscription did not attach its item")
|
|
counts = _summary(summary_text)
|
|
if counts != _summary(result.stdout) or counts["total"] != 1 or counts["good"] != 1 or counts["bad"] or counts["never"]:
|
|
raise CliGateError("CLI subscription did not finish with a recovered Good item")
|
|
if require_gap and counts["ever_bad"] != 1:
|
|
raise CliGateError("CLI subscription did not observe the remote quality gap")
|
|
if require_held_session and re.search(r"Session lost on .+?\. Attempting failover\.\.\.",
|
|
result.stdout.split(_SUMMARY_HEADING, 1)[0]):
|
|
raise CliGateError("CLI started transport failover before the held subscription finished")
|
|
notifications = re.findall(r"^\[([^\]]+)\] (.+?) = (.*) \(([^()]*)\)$", result.stdout, re.M)
|
|
good = []
|
|
for timestamp, node, value, status in notifications:
|
|
if node != expected_node:
|
|
raise CliGateError("recovery notification has unexpected node")
|
|
_timestamp(timestamp)
|
|
if is_good_status(status):
|
|
good.append(value)
|
|
if len(good) < 2 or len(set(good)) < 2:
|
|
raise CliGateError("recovery lacks changing Good values")
|
|
if not notifications or not is_good_status(notifications[-1][3]):
|
|
raise CliGateError("recovery final notification is not Good")
|
|
if require_gap:
|
|
bad_indexes = [index for index, entry in enumerate(notifications) if entry[3].startswith("Bad")]
|
|
if not bad_indexes or not any(is_good_status(entry[3]) for entry in notifications[:bad_indexes[0]]) or not any(
|
|
is_good_status(entry[3]) for entry in notifications[bad_indexes[-1] + 1:]):
|
|
raise CliGateError("recovery must have Good notifications before and after a Bad gap")
|
|
return {"summary": counts, "good_notifications": len(good)}
|
|
|
|
|
|
def _local_endpoint(url):
|
|
try:
|
|
parsed = urlsplit(url)
|
|
host = parsed.hostname
|
|
local = host == "localhost" or ipaddress.ip_address(host).is_loopback
|
|
return (parsed.scheme == "opc.tcp" and local and parsed.port is not None and
|
|
1 <= parsed.port <= 65535 and not parsed.username and not parsed.password and
|
|
not parsed.query and not parsed.fragment)
|
|
except (ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
def build_cli_argv(dll, command, endpoint, credential, *, node=None, value=None,
|
|
summary_file=None, duration=30, interval=200, recursive=False, depth=6,
|
|
partner_endpoint=None, max_age_ms=0):
|
|
"""Build portable argv from a published DLL and current supported CLI flags.
|
|
|
|
Returned argv contains the key solely to pass it to the CLI, which currently
|
|
exposes no credential-file flag. Feed it directly to processes.run_process;
|
|
persist only that wrapper's redacted ProcessResult argv.
|
|
"""
|
|
dll = Path(dll)
|
|
if not dll.is_absolute() or dll.suffix.lower() != ".dll":
|
|
raise CliGateError("a published CLI DLL absolute path is required")
|
|
if command not in {"connect", "browse", "read", "write", "subscribe", "redundancy"}:
|
|
raise CliGateError("unsupported CLI command")
|
|
if not _local_endpoint(endpoint) or (partner_endpoint is not None and not _local_endpoint(partner_endpoint)):
|
|
raise CliGateError("CLI endpoints must use allocated loopback OPC UA ports")
|
|
if not isinstance(credential, str) or not credential:
|
|
raise CliGateError("a presented CLI credential is required")
|
|
argv = ["dotnet", str(dll), command, "-u", endpoint, "-U", "apikey", "-P", credential]
|
|
if partner_endpoint is not None:
|
|
argv.extend(["-F", partner_endpoint])
|
|
if command in {"browse", "read", "write", "subscribe"}:
|
|
if not isinstance(node, str) or not node:
|
|
raise CliGateError("an explicit resolved NodeId is required")
|
|
argv.extend(["-n", node])
|
|
if command == "read":
|
|
if type(max_age_ms) is not int or not 0 <= max_age_ms <= 30000:
|
|
raise CliGateError("read maximum age must be a bounded millisecond value")
|
|
if max_age_ms:
|
|
argv.extend(["--max-age", str(max_age_ms)])
|
|
if command == "write":
|
|
if value is None:
|
|
raise CliGateError("an explicit write value is required")
|
|
# The physical fixture scalars are UInt16; writing must not require read access.
|
|
argv.extend(["-v", str(value), "--type", "UInt16"])
|
|
if command == "browse" and recursive:
|
|
if type(depth) is not int or depth <= 0:
|
|
raise CliGateError("browse depth must be positive")
|
|
argv.extend(["-r", "-d", str(depth)])
|
|
if command == "subscribe":
|
|
if summary_file is None or not Path(summary_file).is_absolute() or type(duration) is not int or duration <= 0 or type(interval) is not int or interval <= 0:
|
|
raise CliGateError("subscriptions require a run-owned absolute summary path and positive duration/interval")
|
|
argv.extend(["-i", str(interval), "--duration", str(duration), "--summary-file", str(summary_file)])
|
|
if recursive:
|
|
if type(depth) is not int or depth <= 0:
|
|
raise CliGateError("subscription depth must be positive")
|
|
argv.extend(["-r", "--max-depth", str(depth)])
|
|
return argv
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--run-id", required=True)
|
|
parser.add_argument("--scenario", required=True)
|
|
parser.add_argument("--manifest", type=Path)
|
|
parser.add_argument("--cli-dll", type=Path)
|
|
parser.add_argument("--probe-dll", type=Path)
|
|
arguments = parser.parse_args(argv)
|
|
try:
|
|
from scenarios import ScenarioRunner
|
|
runner = ScenarioRunner(arguments.run_id, manifest_path=arguments.manifest,
|
|
cli_dll=arguments.cli_dll, probe_dll=arguments.probe_dll)
|
|
report = runner.run(arguments.scenario)
|
|
print(__import__("json").dumps(report, sort_keys=True))
|
|
return 0 if report["passed"] else 1
|
|
except Exception as error:
|
|
print("grpc-data CLI gate: " + type(error).__name__ + "; restricted diagnostics retained", file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|