Merge master into #937 (scenarios: keep A09 + F937)
This commit is contained in:
@@ -112,6 +112,9 @@ used) and seeds a SOURCE `OpcUaClient` driver `opcua` → device `opcplc` with a
|
||||
principal `fixture-cli-nogrant` has no NodeAcl row. `python3 scripts/validation/grpc-data/conditions_scenarios.py --run-id <id>
|
||||
[--only A01,A02,A04,A05,A08]` runs the scenarios (results `evidence/A4S-<id>.json`, `A4S-results.{json,md}`); see
|
||||
`docs/plans/evidence/grpc-data-ext/A4.md` "Live scenarios (part 1)". `conditions_a3_smoke.py` still passes on this profile.
|
||||
`--only A09` (#927) is the driver-failure ack revert: it `docker compose pause`s the run-owned `opcplc` just before a remote ack of
|
||||
`EastTankYellow`, so the OpcUaClient driver's upstream Acknowledge times out and DriverHostActor reverts the condition; it
|
||||
unpauses in its own `finally` (and again in the per-scenario restore). See `docs/plans/evidence/grpc-data-ext/A3-927.md`.
|
||||
|
||||
## H3 projected-history gate (opt-in)
|
||||
|
||||
@@ -139,6 +142,38 @@ primary. The continuation scenarios use the CLI's hand-paged mode (`--page-size`
|
||||
(`originAccounting.historyOpenContinuations`). Every scenario restores the baseline. Results:
|
||||
`evidence/H3-history-<backend>-results.json`.
|
||||
|
||||
## Pinned pre-H2 SOURCE — H05 against a real v1 origin (#921, opt-in)
|
||||
|
||||
`rig.py up --run-id <id> --history --source-revision 0c86edc1` builds the SOURCE pair from a pinned commit; CONTROL and
|
||||
CONSUMER stay on this checkout. The revision must contain X0 (`a15912539`, tolerant readers — a pre-X0 node rejects the whole
|
||||
data-connection snapshot once a newer bit is authored) and must not contain H2 (`ef938b435`); its `data_connection.proto` must
|
||||
have no `HistoryRead` RPC. `0c86edc1` (the #918 merge, between H1 and H2) passes. The rig `git archive`s that commit into the
|
||||
run folder (`pinned-source/`), copies in one rig file — `node-probe/WireTap.cs`, ASP.NET Core only — and builds it with the
|
||||
pinned tree's own Dockerfile (`compose.source-pinned.yml`, image `otopcua-grpc-data-source-pinned:<run-id>`, run-labelled, removed
|
||||
by `down`). The manifest records `source_pinned` (revision, export hash); `verify_candidate` checks the SOURCE stamps against it
|
||||
and the export against its recorded hash, and everything else against this checkout.
|
||||
|
||||
The wire tap (`GRPC_DATA_WIRE_TAP=1`, set only by that overlay) appends to the node's restricted probe directory
|
||||
(`probe/source-N/wire-tap.jsonl`) one line per data-listener request at arrival (gRPC path, `x-otopcua-data-features` value,
|
||||
remote address) and one at completion (gRPC status). No credential or body is recorded.
|
||||
|
||||
```bash
|
||||
python3 scripts/validation/grpc-data/rig.py up --run-id h05v1 --history --source-revision 0c86edc1 --timeout 1500
|
||||
python3 scripts/validation/grpc-data/rig.py seed --run-id h05v1
|
||||
sleep 75
|
||||
python3 scripts/validation/grpc-data/rig.py deploy --run-id h05v1 --timeout 300
|
||||
python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id h05v1 # evidence/H05V1-results.json
|
||||
python3 scripts/validation/grpc-data/rig.py down --run-id h05v1
|
||||
```
|
||||
|
||||
`history_v1_origin_gate.py` asserts the plan §4.3 row "new consumer → v1 origin": projected `counter` (Raw and UNS)
|
||||
`Historizing` False and no HistoryRead `AccessLevel` bit (`Client.CLI read --attribute`), `historyread` ⇒
|
||||
`BadHistoryOperationUnsupported`, the consumer page "Negotiated features none (v1 behaviour) · origin history not advertised",
|
||||
and — from the tap — no consumer call but the capability probe carries the feature header and no HistoryRead/CallConditionMethod
|
||||
reaches the origin. Controls: the origin's own `counter` is historizing and its `historyread` returns rows; the consumer's v1 calls
|
||||
are in the same tap window; the probe's `--scenario history-v1-origin` sends new-shape calls (capabilities with the header are
|
||||
byte-identical to without; HistoryRead ⇒ `PERMISSION_DENIED`: a pre-H2 data listener admits only its six v1 methods) and the tap records them.
|
||||
|
||||
## Scenario authoring and node probes
|
||||
|
||||
The seeder is available through `LocalRig.seed_helper(action, *arguments)`. Its
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# lmxopcua#921 pinned-origin overlay (opt-in: `rig.py up --source-revision <sha>`). The SOURCE pair runs a Host image built
|
||||
# from a pinned post-X0, pre-H2 commit (a "v1 origin": no HistoryRead RPC, no `history` feature), exported by the rig into the
|
||||
# run folder; CONTROL and CONSUMER keep the current checkout's image. The only file the rig adds to the pinned tree is the
|
||||
# self-contained node-probe wire tap (node-probe/WireTap.cs), enabled here with GRPC_DATA_WIRE_TAP: it records, per request
|
||||
# on the data listener, the gRPC path and the x-otopcua-data-features header value into the node's restricted probe
|
||||
# directory (wire-tap.jsonl) — never a credential or a body. Without this file the rig is unchanged.
|
||||
|
||||
x-pinned-env: &pinned-env
|
||||
GRPC_DATA_WIRE_TAP: "1"
|
||||
|
||||
services:
|
||||
source-1:
|
||||
build:
|
||||
context: ${GRPC_DATA_SOURCE_PINNED_CONTEXT:?pinned SOURCE export required}
|
||||
dockerfile: scripts/validation/grpc-data/Dockerfile
|
||||
target: runtime
|
||||
labels:
|
||||
otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID}
|
||||
com.docker.compose.project: ${GRPC_DATA_PROJECT}
|
||||
args: {SOURCE_REVISION: "${GRPC_DATA_SOURCE_PINNED_REVISION:?pinned revision required}", SOURCE_TREE_HASH: "${GRPC_DATA_SOURCE_PINNED_TREE_HASH:?pinned tree hash required}"}
|
||||
image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required}
|
||||
environment: *pinned-env
|
||||
source-2:
|
||||
image: ${GRPC_DATA_SOURCE_IMAGE:?run-scoped pinned SOURCE image required}
|
||||
environment: *pinned-env
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
Part 1 implemented A01, A02, A04, A05 and A08; part 2 adds A03 (origin failover + EventId re-binding), A06 (consumer
|
||||
Primary change, both consumer nodes, two principals) and A07 (consumer node restart, ConditionRefresh vs the first
|
||||
snapshot barrier). Everything else (watchers, browse-resolved ids, per-scenario restore + JSON/markdown result) is shared.
|
||||
snapshot barrier). A09 (lmxopcua#927) is the driver-failure ack revert through DriverHostActor for a remote native ack. 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
|
||||
@@ -30,8 +30,9 @@ from pathlib import Path
|
||||
import rig
|
||||
import scenarios
|
||||
|
||||
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "F937")
|
||||
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "F937": 900}
|
||||
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "F937")
|
||||
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600, "F937": 900}
|
||||
REVERT_LOG = "did not reach the alarm system"
|
||||
REFRESH_REQUIRED = "RefreshRequiredEventType"
|
||||
_LOG_TIME = re.compile(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?)")
|
||||
NO_ACK = int(0b111111111111) & ~(1 << 8) # NodePermissions.Admin (4095) without AlarmAcknowledge (1 << 8)
|
||||
@@ -570,6 +571,88 @@ class ConditionScenarios:
|
||||
self.raise_scripted(0)
|
||||
time.sleep(4)
|
||||
|
||||
# ---- lmxopcua#927 -------------------------------------------------------------------------------------------------
|
||||
def scenario_A09(self):
|
||||
"""A remote (A2b CallConditionMethod) ack of the NATIVE EastTankYellow, under the connection's service principal, that
|
||||
the OpcUaClient driver genuinely fails: the run-owned opc-plc is `docker pause`d just before the ack, so the driver's
|
||||
upstream Acknowledge call gets no reply and times out (no test seam). Asserts: the caller gets Good (plan §5.6 step 5:
|
||||
native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches it as the revert); the origin applies the ack then REVERTS it
|
||||
(DriverHostActor `RevertNativeAlarmAck` ⇒ `EstablishesState: false`, logged "did not reach the alarm system … reverting");
|
||||
the consumer sees the reverted delta; the origin audit records the call on behalf of the end user. The upstream is frozen,
|
||||
so no driver transition can explain the Unacknowledged that follows the ack (control: no upstream event while paused).
|
||||
After unpausing, a second ack of the then-current EventId is not reverted (positive control for the failure)."""
|
||||
source, consumer = self.r.primary("source"), self.r.primary("consumer")
|
||||
name = self.fixture["conditions"]["native"]["condition"]
|
||||
since = self.utc(-2)
|
||||
origin = self.watch(source, "origin")
|
||||
imported = self.watch(consumer, "consumer")
|
||||
unacked = lambda b: b.get("State", "").endswith("Unacknowledged")
|
||||
event = wait_for(lambda: self.latest(imported, name, unacked), 300)
|
||||
origin_event = wait_for(lambda: self.latest(origin, name, unacked), 30)
|
||||
if not self.check("consumer_has_unacknowledged_native_condition", event) or not self.check("origin_has_it_too", origin_event):
|
||||
return
|
||||
condition = event["ConditionNodeId"]
|
||||
self.report["condition_id"] = condition
|
||||
self.report["before"] = {"consumer": event, "origin": origin_event}
|
||||
paused = False
|
||||
try:
|
||||
self.r.rig.compose("pause", "opcplc", timeout=60)
|
||||
paused = True
|
||||
self.report["paused_utc"] = self.utc()
|
||||
origin_mark, consumer_mark = len(origin.blocks(name)), len(imported.blocks(name))
|
||||
result = self.ack(consumer, condition, event["EventId"], "ack-driver-fails")
|
||||
self.report["ack"] = result
|
||||
self.check("caller_gets_good_accepted_unconfirmed", result["good"])
|
||||
|
||||
def reverted(watcher, mark):
|
||||
tail = states(watcher.blocks(name)[mark:])
|
||||
acked = next((i for i, state in enumerate(tail) if state and state.endswith(", Acknowledged")), None)
|
||||
return tail if acked is not None and any(state and state.endswith("Unacknowledged") for state in tail[acked + 1:]) else None
|
||||
|
||||
origin_tail = wait_for(lambda: reverted(origin, origin_mark), 60)
|
||||
consumer_tail = wait_for(lambda: reverted(imported, consumer_mark), 30)
|
||||
self.report["origin_after_ack"] = states(origin.blocks(name)[origin_mark:])
|
||||
self.report["consumer_after_ack"] = states(imported.blocks(name)[consumer_mark:])
|
||||
self.check("origin_applied_then_reverted", origin_tail)
|
||||
self.check("consumer_saw_the_reverted_delta", consumer_tail)
|
||||
latest = self.latest(imported, name)
|
||||
self.check("consumer_reverted_event_is_a_new_event_id", latest and latest.get("EventId") != event["EventId"])
|
||||
self.check("consumer_reverted_condition_id_unchanged", latest and latest.get("ConditionNodeId") == condition)
|
||||
reverts = self.log_lines(source, since, REVERT_LOG)
|
||||
failures = self.log_lines(source, since, "native-alarm acknowledge of")
|
||||
self.report["origin_revert_log"] = reverts[-5:]
|
||||
self.report["origin_driver_failure_log"] = failures[-5:]
|
||||
self.check("origin_logged_the_driver_failure_and_revert",
|
||||
any("reverting the condition to unacknowledged" in line for line in reverts))
|
||||
self.check("driver_instance_logged_the_failed_upstream_ack", any("failed" in line or "refused" in line for line in failures))
|
||||
audit = self.audit(source, since)
|
||||
self.report["origin_audit"] = audit[-10:]
|
||||
self.check("origin_audited_the_remote_ack",
|
||||
any(re.search(r"condition method \W?Acknowledge\b", line) and "AcceptedUnconfirmed" in line and "fixture-cli" in line
|
||||
for line in audit))
|
||||
# Control: the upstream is frozen, so the Unacknowledged after the ack cannot be an upstream transition. Every
|
||||
# origin event after the ack is either the ack itself or the revert (plus comms-loss quality, which has no state).
|
||||
self.report["origin_tail_states"] = sorted(set(filter(None, self.report["origin_after_ack"])))
|
||||
finally:
|
||||
if paused:
|
||||
self.r.rig.compose("unpause", "opcplc", timeout=60)
|
||||
self.report["unpaused_utc"] = self.utc()
|
||||
# Positive control: once opc-plc answers again, an ack of the current EventId is not reverted. (The paused call may
|
||||
# still be applied upstream when the container resumes; then the condition is already acknowledged, also recorded.)
|
||||
time.sleep(30)
|
||||
current = self.latest(imported, name)
|
||||
self.report["after_unpause"] = current
|
||||
if current and current.get("State", "").endswith("Unacknowledged"):
|
||||
mark = len(self.log_lines(source, since, REVERT_LOG))
|
||||
result = self.ack(consumer, condition, current["EventId"], "ack-after-unpause")
|
||||
self.report["control_ack"] = result
|
||||
self.check("control_ack_good", result["good"])
|
||||
time.sleep(15)
|
||||
self.check("control_ack_not_reverted", len(self.log_lines(source, since, REVERT_LOG)) == mark)
|
||||
else:
|
||||
self.report["control_note"] = "the upstream applied the paused acknowledge after unpause (condition already acknowledged)"
|
||||
self.check("control_upstream_acknowledged_after_unpause", current and current.get("State", "").endswith(", Acknowledged"))
|
||||
|
||||
# ---- part 2 scenarios -------------------------------------------------------------------------------------------
|
||||
def scenario_A03(self):
|
||||
"""Origin failover mid-stream with standing active alarms. Phase 1: a consumer stream reset against the SAME origin
|
||||
@@ -860,6 +943,9 @@ class ConditionScenarios:
|
||||
finally:
|
||||
self.stop_watchers()
|
||||
try:
|
||||
# A09 unpauses in its own finally; this covers a failure between its pause and that block.
|
||||
if scenario == "A09" and "paused" in self.r.rig.compose("ps", "--all", "--format", "{{.State}}", "opcplc", timeout=30):
|
||||
self.r.rig.compose("unpause", "opcplc", timeout=60)
|
||||
self.r.device("set", address=20, value=0)
|
||||
if scenario in ("A03", "A08"):
|
||||
self.r.deadline = time.monotonic() + 600
|
||||
|
||||
@@ -24,6 +24,8 @@ NODE_PERMISSIONS_ADMIN = 4095 # NodePermissions.Admin = bits 0..11 (HistoryUpda
|
||||
NODE_PERMISSIONS_HISTORY_READ = 1 << 3
|
||||
NODE_PERMISSIONS_BROWSE = 1 << 0
|
||||
EXPORT_WITHOUT_HISTORY = 31 # Browse | Metadata | Read | Write | Subscribe
|
||||
# #922: longer than the rig mappings' 15 s MetadataLeaseMilliseconds, so a projected node idles past its lease.
|
||||
LEASE_LAPSE_SECONDS = 20
|
||||
|
||||
|
||||
def _iso(moment):
|
||||
@@ -266,9 +268,8 @@ class HistoryGate:
|
||||
with self.runner.stopped(source):
|
||||
observed["new_primary"] = self.runner.wait_primary("source", exclude=source)
|
||||
self.runner.wait_connection_ready(consumer, "raw")
|
||||
# Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. Re-browse first so
|
||||
# the node's projection authority is current (it lapses with the 15 s metadata lease, as for a value Read).
|
||||
self.rebrowse()
|
||||
# Resume INSIDE the stop window: the issuing endpoint is down, the pinned resume cannot move. No re-browse: a
|
||||
# projected node whose 15 s metadata lease lapsed renews on demand within the HistoryRead (#922).
|
||||
self.held_resume_now()
|
||||
self.runner.wait_pair_topology("source")
|
||||
|
||||
@@ -374,10 +375,11 @@ class HistoryGate:
|
||||
self.runner.check(any(l.startswith("Page 2: BadContinuationPointInvalid") for l in lines), "resume after the origin rebuild is invalid")
|
||||
self.runner.check(any(l.startswith("Fresh: Good") for l in lines), "a fresh read after the rebuild succeeds")
|
||||
report["rebuild"] = lines
|
||||
# (c) a consumer session close releases the origin continuation. Each held read starts right after a deploy + re-browse:
|
||||
# an idle projected node's authority lapses with its 15 s metadata lease and a re-browse served from the cached page
|
||||
# does not renew it (a value Read is refused the same way — pre-existing v1 projection behaviour, reported).
|
||||
# (c) a consumer session close releases the origin continuation. The restore's deploy retires cold projected nodes, so it
|
||||
# re-browses; the held read then deliberately starts only after the node's 15 s metadata lease has LAPSED (#922: it
|
||||
# renews on demand within the HistoryRead instead of answering BadUserAccessDenied).
|
||||
self.restore()
|
||||
time.sleep(LEASE_LAPSE_SECONDS)
|
||||
consumer = self.runner.primary("consumer")
|
||||
self.runner.check(self.origin_state() == 0, "no origin continuation open before")
|
||||
counts = {}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
"""lmxopcua#921 live gate: H05 (plan §4.3 mixed versions, row "new consumer → v1 origin") against a PINNED pre-H2 origin.
|
||||
|
||||
python3 scripts/validation/grpc-data/rig.py up --run-id <id> --history --source-revision 0c86edc1 --timeout 1500
|
||||
python3 scripts/validation/grpc-data/rig.py seed --run-id <id>
|
||||
sleep 75 # CONTROL's ClusterNode contact refresh before the first deploy
|
||||
python3 scripts/validation/grpc-data/rig.py deploy --run-id <id> --timeout 300
|
||||
python3 scripts/validation/grpc-data/history_v1_origin_gate.py --run-id <id>
|
||||
python3 scripts/validation/grpc-data/rig.py down --run-id <id>
|
||||
|
||||
The SOURCE pair runs a Host built from the pinned commit (post-X0, pre-H2: no HistoryRead RPC, no `history` feature);
|
||||
CONTROL and CONSUMER run this checkout. SOURCE still has a historian (the `--history` overlay) and historizes `counter`, so
|
||||
the origin's OWN HistoryRead is the positive control for "the origin has history, the wire does not carry it".
|
||||
|
||||
What is asserted (results: the run's restricted `evidence/H05V1-results.json`):
|
||||
1. the running build stamps — SOURCE = the pinned revision, CONTROL/CONSUMER = this checkout;
|
||||
2. projected Raw and UNS `counter` variables: `Historizing` False and no HistoryRead bit in `AccessLevel`, while the
|
||||
origin's own `counter` is `Historizing` True (control); a projected value Read is Good (control: the projection is live);
|
||||
3. a CLI `historyread` on each projected variable ⇒ `BadHistoryOperationUnsupported`; on the origin's own node ⇒ Good rows;
|
||||
4. diagnostics say the origin lacks the feature: the CONSUMER data-connections page shows "Negotiated features none (v1
|
||||
behaviour)" and "origin history not advertised"; the SOURCE page names the HistoryRead bit the older build dropped;
|
||||
5. no new-shape call reaches the v1 origin from the consumer: in the pinned origins' wire tap (node-probe/WireTap.cs) for
|
||||
the consumer's window, no HistoryRead / CallConditionMethod arrival, and no data call (anything but the capability
|
||||
probe) carries `x-otopcua-data-features` — with the consumer's v1 calls (GetCapabilities/Browse/GetMetadata/Read/
|
||||
Subscribe) present in the same window (control). The capability probe itself always carries the client's features
|
||||
(plan §4.1); a v1 origin ignores the header, which (6) shows byte-for-byte;
|
||||
6. tap positive control: the probe's `history-v1-origin` scenario sends new-shape calls to both pinned origins — capabilities
|
||||
with the feature header answer byte-identically to capabilities without it, a HistoryRead with the header is refused
|
||||
PERMISSION_DENIED (a pre-H2 data listener admits only its six v1 methods and refuses any other path before routing — not
|
||||
the UNIMPLEMENTED the plan's table guessed) — and the tap records those arrivals with the header and that status.
|
||||
"""
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import history_gate
|
||||
import rig
|
||||
import scenarios
|
||||
|
||||
ACCESS_LEVEL_HISTORY_READ = 0x04
|
||||
V1_PATHS = ("GetCapabilities", "Browse", "GetMetadata", "Read", "Subscribe", "Write")
|
||||
NEW_SHAPE_PATHS = ("HistoryRead", "CallConditionMethod")
|
||||
|
||||
|
||||
class V1OriginGate(history_gate.HistoryGate):
|
||||
def __init__(self, run_id, *, pinned_build=False):
|
||||
super().__init__(run_id, pinned_build=pinned_build)
|
||||
self.pinned = self.runner.manifest.get("source_pinned")
|
||||
if not self.pinned:
|
||||
raise SystemExit("run was not brought up with --source-revision (no pinned SOURCE)")
|
||||
self.checks = {}
|
||||
self.detail = {}
|
||||
|
||||
def check(self, name, condition):
|
||||
self.checks[name] = bool(condition)
|
||||
return bool(condition)
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------ tools
|
||||
|
||||
def tap(self, node):
|
||||
path = self.runner.rig.folder / "probe" / node / "wire-tap.jsonl"
|
||||
if not path.is_file() or path.is_symlink():
|
||||
return []
|
||||
rows = []
|
||||
for line in path.read_text(errors="replace").splitlines():
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except ValueError:
|
||||
continue
|
||||
return rows
|
||||
|
||||
def taps(self):
|
||||
return {node: self.tap(node) for node in ("source-1", "source-2")}
|
||||
|
||||
@staticmethod
|
||||
def method(row):
|
||||
return (row.get("path") or "").rsplit("/", 1)[-1]
|
||||
|
||||
def stamp(self, node):
|
||||
return json.loads(self.runner.rig.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15))
|
||||
|
||||
def container_addresses(self, node):
|
||||
ids = self.runner.rig.compose("ps", "--quiet", node).split()
|
||||
if len(ids) != 1:
|
||||
return []
|
||||
row = json.loads(rig.run_command([*self.runner.rig.docker, "container", "inspect", ids[0]]))[0]
|
||||
return [network.get("IPAddress") for network in row["NetworkSettings"]["Networks"].values() if network.get("IPAddress")]
|
||||
|
||||
def attribute(self, node, node_id, attribute, name):
|
||||
argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key,
|
||||
"-n", node_id, "-a", attribute]
|
||||
result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60)
|
||||
value = re.search(r"^Value:\s*(.*)$", result.stdout, re.M)
|
||||
status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M)
|
||||
return {"exit": result.returncode, "value": value[1].strip() if value else None, "status": status[1] if status else None}
|
||||
|
||||
def value_read(self, node, node_id, name):
|
||||
argv = ["dotnet", str(self.runner.cli_dll), "read", "-u", self.runner.endpoint(node), "-U", "apikey", "-P", self.runner.key,
|
||||
"-n", node_id, "--max-age", "5000"]
|
||||
# As every mapped positive read on this rig: retry only an explicit BadWaitingForInitialData (README), bounded.
|
||||
end = time.monotonic() + 60
|
||||
while True:
|
||||
result = self.runner.process(argv, self.runner.active + "-" + name + "-" + uuid.uuid4().hex[:6], timeout=60)
|
||||
status = re.search(r"^Status:\s*(\S+)", result.stdout, re.M)
|
||||
observed = status[1] if status else None
|
||||
if observed != "BadWaitingForInitialData" or time.monotonic() >= end:
|
||||
return observed
|
||||
time.sleep(2)
|
||||
|
||||
def history(self, node, node_id, name):
|
||||
result = self.cli(node, ["-n", node_id, *self.window_args(), "--max", "50"], name)
|
||||
returned = re.search(r"^(\d+) values returned\.", result.stdout, re.M)
|
||||
rows = int(returned[1]) if returned else 0
|
||||
return {"exit": result.returncode, "status": "Good" if result.returncode == 0 else self.error_status(result), "rows": rows,
|
||||
"tail": (result.stdout + result.stderr)[-400:]}
|
||||
|
||||
def page(self, cluster):
|
||||
"""The AdminUI data-connections page of `cluster`, served by the CONTROL primary (login disabled on the rig)."""
|
||||
control = self.runner.primary("control")
|
||||
url = self.runner.endpoint(control, "admin") + f"/clusters/{cluster}/data-connections"
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(urllib.request.Request(url), timeout=15) as response:
|
||||
text = response.read(8 * 1024 * 1024).decode("utf-8", errors="replace")
|
||||
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", text)))
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------- run
|
||||
|
||||
def run(self):
|
||||
self.runner.publish()
|
||||
self.runner.active, self.runner.deadline = "H05V1", time.monotonic() + 1500
|
||||
started = time.monotonic()
|
||||
error = None
|
||||
try:
|
||||
self.scenario()
|
||||
except Exception as failure: # recorded with every check made so far
|
||||
error = type(failure).__name__ + ": " + str(failure)[:400]
|
||||
passed = error is None and bool(self.checks) and all(self.checks.values())
|
||||
result = {"id": "H05V1", "pinned": self.pinned, "consumer_revision": self.runner.manifest.get("source_revision"),
|
||||
"passed": passed, "error": error, "failed_checks": [k for k, v in self.checks.items() if not v],
|
||||
"checks": self.checks, "detail": self.detail, "duration_seconds": round(time.monotonic() - started, 1),
|
||||
"window": [history_gate._iso(w) for w in self.window] if self.window else None}
|
||||
self.runner.save("H05V1-results.json", result)
|
||||
print(json.dumps({k: result[k] for k in ("id", "passed", "error", "failed_checks", "duration_seconds")}), flush=True)
|
||||
return result
|
||||
|
||||
def scenario(self):
|
||||
# 1. Which build is actually running where.
|
||||
stamps = {node: self.stamp(node) for node in self.runner.manifest["nodes"]}
|
||||
self.detail["stamps"] = stamps
|
||||
self.check("source_nodes_run_the_pinned_pre_h2_build",
|
||||
all(stamps[n].get("revision") == self.pinned["revision"] and stamps[n].get("tree_hash") == self.pinned["tree_hash"]
|
||||
for n in ("source-1", "source-2")))
|
||||
self.check("control_and_consumer_run_this_checkout",
|
||||
all(stamps[n].get("revision") == self.runner.manifest["source_revision"] for n in stamps if not n.startswith("source-")))
|
||||
|
||||
self.accumulate()
|
||||
tap_start = {node: len(rows) for node, rows in self.taps().items()}
|
||||
consumer = self.resolve_projected()
|
||||
source, origin_counter = self.origin_node("raw", "counter")
|
||||
|
||||
# 2. Historizing / AccessLevel: projected false, origin true (control); projected value Read Good (control).
|
||||
attributes = {}
|
||||
for realm in ("raw", "uns"):
|
||||
node_id = self.projected[(realm, "counter")]
|
||||
attributes[realm] = {"historizing": self.attribute(consumer, node_id, "Historizing", f"{realm}-historizing"),
|
||||
"access_level": self.attribute(consumer, node_id, "AccessLevel", f"{realm}-access"),
|
||||
"value_status": self.value_read(consumer, node_id, f"{realm}-value")}
|
||||
attributes["origin"] = {"node": origin_counter,
|
||||
"historizing": self.attribute(source, origin_counter, "Historizing", "origin-historizing"),
|
||||
"access_level": self.attribute(source, origin_counter, "AccessLevel", "origin-access")}
|
||||
self.detail["attributes"] = attributes
|
||||
|
||||
def access(entry):
|
||||
try:
|
||||
return int(entry["value"])
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
for realm in ("raw", "uns"):
|
||||
row = attributes[realm]
|
||||
self.check(f"projected_{realm}_counter_historizing_false", row["historizing"]["value"] == "False" and row["historizing"]["status"] == "Good")
|
||||
level = access(row["access_level"])
|
||||
self.check(f"projected_{realm}_counter_access_level_has_no_history_read", level is not None and level & ACCESS_LEVEL_HISTORY_READ == 0)
|
||||
self.check(f"projected_{realm}_counter_value_read_good", row["value_status"] == "Good")
|
||||
self.check("origin_counter_historizing_true_control", attributes["origin"]["historizing"]["value"] == "True")
|
||||
origin_level = access(attributes["origin"]["access_level"])
|
||||
self.check("origin_counter_access_level_has_history_read_control",
|
||||
origin_level is not None and origin_level & ACCESS_LEVEL_HISTORY_READ != 0)
|
||||
|
||||
# 3. HistoryRead: projected ⇒ unsupported, origin's own node ⇒ Good rows (control).
|
||||
reads = {realm: self.history(consumer, self.projected[(realm, "counter")], f"{realm}-historyread") for realm in ("raw", "uns")}
|
||||
reads["origin"] = self.history(source, origin_counter, "origin-historyread")
|
||||
self.detail["history_reads"] = reads
|
||||
for realm in ("raw", "uns"):
|
||||
self.check(f"projected_{realm}_historyread_bad_history_operation_unsupported",
|
||||
reads[realm]["status"] == "BadHistoryOperationUnsupported")
|
||||
self.check("origin_own_historyread_good_with_rows_control", reads["origin"]["status"] == "Good" and reads["origin"]["rows"] > 0)
|
||||
|
||||
# 4. Diagnostics: the consumer negotiated nothing and the origin advertised no history; the origin names the drop.
|
||||
consumer_page = self.page("CONSUMER")
|
||||
source_page = self.page("SOURCE")
|
||||
line = re.search(r"Negotiated features .{0,400}?open remote continuations", consumer_page)
|
||||
dropped = re.search(r"Exports with dropped unknown operation bits: .{0,400}?upgraded\.", source_page)
|
||||
self.detail["diagnostics"] = {"consumer_history_line": line[0] if line else None, "source_dropped_line": dropped[0] if dropped else None}
|
||||
self.check("consumer_diagnostics_negotiated_features_none_v1",
|
||||
line is not None and "Negotiated features none (v1 behaviour)" in line[0])
|
||||
self.check("consumer_diagnostics_origin_history_not_advertised", line is not None and "origin history not advertised" in line[0])
|
||||
self.check("source_diagnostics_older_build_dropped_history_read", dropped is not None and "HistoryRead" in dropped[0])
|
||||
|
||||
# 5. The consumer's window on the pinned origins' wire tap.
|
||||
consumer_ips = {address for node in ("consumer-1", "consumer-2") for address in self.container_addresses(node)}
|
||||
window = {node: rows[tap_start[node]:] for node, rows in self.taps().items()}
|
||||
arrivals = [dict(row, origin=node) for node, rows in window.items() for row in rows if row.get("phase") == "arrival"]
|
||||
from_consumer = [row for row in arrivals if row.get("remote") in consumer_ips]
|
||||
methods = sorted({self.method(row) for row in from_consumer})
|
||||
featured = [row for row in from_consumer if row.get("features")]
|
||||
self.detail["tap_window"] = {"consumer_addresses": sorted(consumer_ips), "arrivals": len(arrivals), "from_consumer": len(from_consumer),
|
||||
"methods": methods, "featured_methods": sorted({self.method(row) for row in featured}),
|
||||
"featured_values": sorted({row["features"] for row in featured}),
|
||||
"other_remotes": sorted({row.get("remote") for row in arrivals if row.get("remote") not in consumer_ips})}
|
||||
self.check("tap_saw_consumer_v1_calls_control", len({"Read", "Browse", "GetMetadata"} & set(methods)) >= 2)
|
||||
self.check("tap_no_history_read_or_condition_method_from_consumer", not set(NEW_SHAPE_PATHS) & set(methods))
|
||||
self.check("tap_no_data_call_from_consumer_carries_the_feature_header",
|
||||
all(self.method(row) == "GetCapabilities" for row in featured))
|
||||
self.check("tap_all_consumer_calls_are_v1_methods", set(methods) <= set(V1_PATHS))
|
||||
|
||||
# 6. Positive control for the tap (and the Unimplemented wire path): new-shape calls the probe sends on purpose.
|
||||
before = {node: len(rows) for node, rows in self.taps().items()}
|
||||
output = self.runner.folder / ("H05V1-probe-" + uuid.uuid4().hex[:6] + ".json")
|
||||
argv = ["dotnet", str(self.runner.probe_dll), "--manifest", str(self.runner.manifest_path), "--scenario", "history-v1-origin",
|
||||
"--output", str(output)]
|
||||
self.runner.process(argv, "H05V1-probe", timeout=120)
|
||||
report = scenarios.restricted_json(output) if output.exists() else {"passed": False}
|
||||
self.detail["probe"] = report
|
||||
self.check("probe_v1_origin_capabilities_identical_and_history_read_refused", report.get("passed") is True)
|
||||
time.sleep(1)
|
||||
after = {node: rows[before[node]:] for node, rows in self.taps().items()}
|
||||
control = {}
|
||||
for node, rows in after.items():
|
||||
history_arrivals = [row for row in rows if row.get("phase") == "arrival" and self.method(row) == "HistoryRead"]
|
||||
completions = [row for row in rows if row.get("phase") == "completion" and self.method(row) == "HistoryRead"]
|
||||
control[node] = {"history_read_arrivals": len(history_arrivals),
|
||||
"history_read_features": sorted({row.get("features") or "" for row in history_arrivals}),
|
||||
"history_read_grpc_status": sorted({row.get("grpcStatus") or "" for row in completions}),
|
||||
"featured_capabilities": sum(1 for row in rows if row.get("phase") == "arrival"
|
||||
and self.method(row) == "GetCapabilities" and row.get("features"))}
|
||||
self.check(f"tap_recorded_probe_history_read_with_header_{node}",
|
||||
history_arrivals and all(row.get("features") == "history" for row in history_arrivals))
|
||||
self.check(f"tap_recorded_permission_denied_status_{node}", completions and all(row.get("grpcStatus") == "7" for row in completions))
|
||||
self.detail["tap_control"] = control
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--run-id", required=True)
|
||||
parser.add_argument("--pinned-build", action="store_true", help="keep the recorded checkout hash (harness edits during a run)")
|
||||
arguments = parser.parse_args(argv)
|
||||
result = V1OriginGate(arguments.run_id, pinned_build=arguments.pinned_build).run()
|
||||
return 0 if result["passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,104 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
[assembly: HostingStartup(typeof(GrpcDataNodeProbe.WireTapStartup))]
|
||||
|
||||
namespace GrpcDataNodeProbe;
|
||||
|
||||
/// <summary>
|
||||
/// Rig-only data-listener wire tap (lmxopcua#921). Off unless <c>GRPC_DATA_WIRE_TAP=1</c>; the rig sets it only on a
|
||||
/// pinned-origin SOURCE (<c>rig.py up --source-revision</c>). It writes one JSON line when each request arrives on the
|
||||
/// data listener (port 4057) and one when it completes: the UTC time, the gRPC path, the value of the
|
||||
/// <c>x-otopcua-data-features</c> request header (null when absent), the remote address and, at completion, the
|
||||
/// gRPC status. It records no credential, header other than the feature header, or message body.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Self-contained on purpose: it uses ASP.NET Core only, so the rig copies this one file into a pinned older tree's
|
||||
/// node probe and the same tap runs on a Host built from that revision. The arrival line is written before the gRPC
|
||||
/// pipeline runs, so a call the older Host refuses (an unimplemented method, an unauthenticated caller) is recorded
|
||||
/// too. The file is bounded (<see cref="MaximumLines"/>); past it, a single truncation line is written.
|
||||
/// </remarks>
|
||||
public sealed class WireTapStartup : IHostingStartup
|
||||
{
|
||||
/// <summary>The tap's output file name inside the node's probe directory.</summary>
|
||||
public const string FileName = "wire-tap.jsonl";
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Configure(IWebHostBuilder builder)
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("GRPC_DATA_WIRE_TAP") != "1") return;
|
||||
var directory = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR");
|
||||
if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) return;
|
||||
var tap = new WireTapLog(Path.Combine(directory, FileName));
|
||||
builder.ConfigureServices(services => services.AddSingleton<IStartupFilter>(new WireTapStartupFilter(tap)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The bounded append-only line log behind the tap.</summary>
|
||||
public sealed class WireTapLog(string path)
|
||||
{
|
||||
/// <summary>Lines written before the log stops (a soak would otherwise fill the probe directory).</summary>
|
||||
public const int MaximumLines = 50_000;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private int _lines;
|
||||
|
||||
/// <summary>Appends one record as a JSON line; never throws into the request pipeline.</summary>
|
||||
public void Write(object record)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lines > MaximumLines) return;
|
||||
var line = _lines++ == MaximumLines ? JsonSerializer.Serialize(new { truncated = true }) : JsonSerializer.Serialize(record);
|
||||
File.AppendAllText(path, line + "\n");
|
||||
}
|
||||
}
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Records each data-listener request at arrival (before authentication) and at completion.</summary>
|
||||
public sealed class WireTapStartupFilter(WireTapLog log) : IStartupFilter
|
||||
{
|
||||
private const int DataListenerPort = 4057;
|
||||
private const string FeaturesHeader = "x-otopcua-data-features";
|
||||
private static long _sequence;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
|
||||
{
|
||||
app.Use(nextMiddleware => async context =>
|
||||
{
|
||||
if (context.Connection.LocalPort != DataListenerPort)
|
||||
{
|
||||
await nextMiddleware(context);
|
||||
return;
|
||||
}
|
||||
var sequence = Interlocked.Increment(ref _sequence);
|
||||
var path = context.Request.Path.Value;
|
||||
string? features = context.Request.Headers.TryGetValue(FeaturesHeader, out var value) ? value.ToString() : null;
|
||||
var remote = context.Connection.RemoteIpAddress?.ToString();
|
||||
log.Write(new { phase = "arrival", sequence, utc = DateTime.UtcNow.ToString("O"), path, features, remote, protocol = context.Request.Protocol });
|
||||
try
|
||||
{
|
||||
await nextMiddleware(context);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// A trailers-only answer (e.g. Unimplemented) carries grpc-status in the headers; a normal one in the trailers.
|
||||
var trailers = context.Features.Get<IHttpResponseTrailersFeature>()?.Trailers;
|
||||
string? status = trailers is not null && trailers.TryGetValue("grpc-status", out var t) ? t.ToString()
|
||||
: context.Response.Headers.TryGetValue("grpc-status", out var h) ? h.ToString() : null;
|
||||
log.Write(new { phase = "completion", sequence, utc = DateTime.UtcNow.ToString("O"), path, grpcStatus = status, httpStatus = context.Response.StatusCode });
|
||||
}
|
||||
});
|
||||
next(app);
|
||||
};
|
||||
}
|
||||
@@ -26,7 +26,7 @@ try
|
||||
using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath));
|
||||
var root = manifest.RootElement;
|
||||
var scenario = arguments.GetValueOrDefault("--scenario", "all");
|
||||
if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario.");
|
||||
if (scenario is not ("all" or "D13" or "wire" or "history" or "history-v1-origin" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario.");
|
||||
var nodes = root.GetProperty("nodes");
|
||||
var endpoints = root.GetProperty("endpoints");
|
||||
var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!;
|
||||
@@ -462,7 +462,72 @@ try
|
||||
["expect"] = expect, ["expectedFound"] = expected,
|
||||
}));
|
||||
}
|
||||
if (scenario is not ("D13" or "history" or "conditions" or "condition-records"))
|
||||
if (scenario == "history-v1-origin")
|
||||
{
|
||||
// lmxopcua#921 (H05 against a pinned pre-H2 origin): what a NEW caller sees from a v1 origin when it asks for the
|
||||
// features. Capabilities with the full feature header are byte-identical to those without it (no history, no
|
||||
// conditions, no HistoryRead bit), and a HistoryRead with the header is refused PERMISSION_DENIED: a pre-H2 data
|
||||
// listener admits only its six v1 methods (DataConnectionEndpoints.Methods at that revision) and refuses any other
|
||||
// path before gRPC routing, so the call never reaches a handler (observed live, #921). This deliberately sends new-shape calls, so on a wire-tapped origin it is also the tap's
|
||||
// positive control (the tap must record them).
|
||||
failurePhase = ProbeFailurePhase.WireOperation;
|
||||
var fixture = root.GetProperty("fixture");
|
||||
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
|
||||
var historized = fixture.GetProperty("history").GetProperty("historized").GetProperty("raw").GetString()!;
|
||||
foreach (var node in sourceNodes)
|
||||
{
|
||||
var name = node.Name;
|
||||
failureTarget = name;
|
||||
var nodeId = node.Value.GetProperty("node_id").GetString()!;
|
||||
Metadata With(string? features)
|
||||
{
|
||||
var headers = Headers(key, "Node", nodeId);
|
||||
if (features is not null) headers.Add("x-otopcua-data-features", features);
|
||||
return headers;
|
||||
}
|
||||
using var handler = security.Handler(name);
|
||||
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
||||
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
||||
var deadline = () => DateTime.UtcNow.AddSeconds(20);
|
||||
var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(null), deadline());
|
||||
var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With("history,conditions"), deadline());
|
||||
static byte[] Shape(W.CapabilitiesResponse response)
|
||||
{
|
||||
// The serving identity aside, the two answers must be the same bytes.
|
||||
var copy = response.Clone();
|
||||
copy.Serving = null;
|
||||
return copy.ToByteArray();
|
||||
}
|
||||
var v1Shape = plain.History is null && featured.History is null && plain.Conditions is null && featured.Conditions is null
|
||||
&& (plain.Operations & 32) == 0 && (featured.Operations & 32) == 0;
|
||||
var identical = Shape(plain).AsSpan().SequenceEqual(Shape(featured));
|
||||
string historyRead;
|
||||
try
|
||||
{
|
||||
var request = new W.HistoryReadRequest
|
||||
{
|
||||
Budget = new() { TimeoutTicks = TimeSpan.FromSeconds(10).Ticks, MaxItems = 1, MaxBytes = 1024 * 1024 },
|
||||
Raw = new() { NumValuesPerNode = 5, End = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow) },
|
||||
};
|
||||
request.Items.Add(new W.HistoryReadItem { CorrelationId = "one", View = new() { Address = new() { OriginClusterId = "SOURCE",
|
||||
NamespaceUri = rawUri, IdentifierKind = "string", Identifier = historized }, Realm = (int)DataRealm.Raw, Subject = historized } });
|
||||
await client.HistoryReadAsync(request, With("history"), deadline());
|
||||
historyRead = "OK";
|
||||
}
|
||||
catch (RpcException error) { historyRead = error.StatusCode.ToString(); }
|
||||
results.Add(new("history-v1-origin-" + name, "history-v1-origin", v1Shape && identical && historyRead == "PermissionDenied", 3, new()
|
||||
{
|
||||
["withoutHeader"] = new { operations = plain.Operations, historyPresent = plain.History is not null, conditionsPresent = plain.Conditions is not null,
|
||||
protocolMinor = plain.ProtocolMinor, bytes = plain.CalculateSize() },
|
||||
["withHeader"] = new { operations = featured.Operations, historyPresent = featured.History is not null, conditionsPresent = featured.Conditions is not null,
|
||||
protocolMinor = featured.ProtocolMinor, bytes = featured.CalculateSize() },
|
||||
["byteIdentical"] = identical,
|
||||
["historyReadWithHeader"] = historyRead,
|
||||
["serving"] = featured.Serving.ToString(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
if (scenario is not ("D13" or "history" or "history-v1-origin" or "conditions" or "condition-records"))
|
||||
{
|
||||
var fixture = root.GetProperty("fixture");
|
||||
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
|
||||
|
||||
@@ -517,26 +517,91 @@ def run_command(argv, *, timeout=120, environment=None):
|
||||
return result.stdout
|
||||
|
||||
|
||||
def _image_input(name):
|
||||
"""Whether repository-relative `name` is an image build input (the filter both tree hashes share)."""
|
||||
suffix = Path(name).suffix
|
||||
return not name.startswith(("docs/", "tests/", ".playwright-mcp/")) and (
|
||||
suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"}
|
||||
or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"}
|
||||
or name.startswith("src/") and suffix == ".json")
|
||||
|
||||
|
||||
def _tree_hash(root, names):
|
||||
import hashlib
|
||||
digest = hashlib.sha256()
|
||||
for name in sorted(set(filter(None, names))):
|
||||
path = root / name
|
||||
if not _image_input(name):
|
||||
continue
|
||||
if path.is_file() and not path.is_symlink():
|
||||
digest.update(name.encode() + b"\0")
|
||||
digest.update(hashlib.sha256(path.read_bytes()).digest())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def source_tree_hash():
|
||||
"""Hash image build inputs, including pending/new code, excluding review evidence.
|
||||
|
||||
Harness Python and test sources have their own evidence and do not enter the
|
||||
Host/seeder/probe binaries. Notes can change without invalidating an image.
|
||||
"""
|
||||
import hashlib
|
||||
paths = run_command(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"]).split("\0")
|
||||
digest = hashlib.sha256()
|
||||
for name in sorted(set(filter(None, paths))):
|
||||
path = ROOT / name
|
||||
if (name.startswith(("docs/", "tests/", ".playwright-mcp/")) or
|
||||
not (path.suffix in {".cs", ".csproj", ".props", ".targets", ".slnx", ".resx", ".razor", ".css", ".js", ".proto"}
|
||||
or name in {"global.json", "NuGet.Config", "nuget.config", "Directory.Build.rsp", ".dockerignore", "scripts/validation/grpc-data/Dockerfile"}
|
||||
or name.startswith("src/") and path.suffix == ".json")):
|
||||
continue
|
||||
if path.is_file() and not path.is_symlink():
|
||||
digest.update(name.encode() + b"\0")
|
||||
digest.update(hashlib.sha256(path.read_bytes()).digest())
|
||||
return digest.hexdigest()
|
||||
return _tree_hash(ROOT, paths)
|
||||
|
||||
|
||||
# lmxopcua#921: a pinned pre-H2 SOURCE pair (plan §4.3 mixed versions, row "new consumer → v1 origin"). A pinned revision must
|
||||
# CONTAIN X0 (a pre-X0 node rejects the whole data-connection snapshot once any newer bit is authored, so it is not the v1 origin
|
||||
# the row describes) and must NOT contain H2 (whose merge adds the origin HistoryRead RPC and the `history` feature).
|
||||
X0_MERGE = "a15912539f8a48804c31e74b2558994a50a338e6"
|
||||
H2_MERGE = "ef938b435bbad2862bcd4b8e1f39e0b1ef2089b2"
|
||||
PINNED_DATA_PROTO = "src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto"
|
||||
# The only rig file added to a pinned tree: the self-contained data-listener wire tap (ASP.NET Core only, compiles at any revision).
|
||||
PINNED_OVERLAY_FILES = ("scripts/validation/grpc-data/node-probe/WireTap.cs",)
|
||||
|
||||
|
||||
def resolve_pinned_source_revision(revision, *, git=None):
|
||||
"""The full SHA of `revision` once it is proven a post-X0, pre-H2 commit; RigError otherwise."""
|
||||
git = git or (lambda *arguments: run_command(["git", *arguments]))
|
||||
if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{7,40}", revision):
|
||||
raise RigError("a pinned SOURCE revision must be a hexadecimal commit id")
|
||||
full = git("rev-parse", "--verify", "--quiet", revision + "^{commit}").strip()
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", full):
|
||||
raise RigError("the pinned SOURCE revision does not name a commit")
|
||||
if git("merge-base", X0_MERGE, full).strip() != X0_MERGE:
|
||||
raise RigError("the pinned SOURCE revision predates X0 (tolerant readers); it would reject the whole snapshot")
|
||||
if git("merge-base", H2_MERGE, full).strip() == H2_MERGE:
|
||||
raise RigError("the pinned SOURCE revision contains H2; it is not a v1 (pre-history) origin")
|
||||
if re.search(r"^\s*rpc\s+HistoryRead\b", git("show", f"{full}:{PINNED_DATA_PROTO}"), re.M):
|
||||
raise RigError("the pinned SOURCE revision's data contract already has HistoryRead")
|
||||
return full
|
||||
|
||||
|
||||
def export_pinned_source(revision, directory):
|
||||
"""Extract `revision`'s committed tree into a new restricted `directory` and add the rig's wire tap."""
|
||||
import shutil
|
||||
import subprocess
|
||||
if directory.exists():
|
||||
raise RigError("pinned SOURCE export directory already exists")
|
||||
directory.mkdir(mode=0o700)
|
||||
archive = subprocess.Popen(["git", "archive", "--format=tar", revision], cwd=ROOT, stdout=subprocess.PIPE)
|
||||
try:
|
||||
extract = subprocess.run(["tar", "-x", "-C", str(directory)], stdin=archive.stdout, timeout=600, check=False)
|
||||
finally:
|
||||
archive.stdout.close()
|
||||
if archive.wait(timeout=600) != 0 or extract.returncode != 0:
|
||||
raise RigError("could not export the pinned SOURCE revision")
|
||||
for name in PINNED_OVERLAY_FILES:
|
||||
target = directory / name
|
||||
if target.exists():
|
||||
raise RigError("the pinned SOURCE tree already has a rig overlay file")
|
||||
shutil.copyfile(ROOT / name, target)
|
||||
return pinned_tree_hash(directory)
|
||||
|
||||
|
||||
def pinned_tree_hash(directory):
|
||||
"""The image-input hash of an exported pinned tree (same filter as `source_tree_hash`)."""
|
||||
names = [str(path.relative_to(directory)) for path in directory.rglob("*") if path.is_file() and not path.is_symlink()]
|
||||
return _tree_hash(directory, [name.replace(os.sep, "/") for name in names])
|
||||
|
||||
|
||||
def device_tree_hash():
|
||||
@@ -678,6 +743,8 @@ class LocalRig:
|
||||
files.extend(["--file", str(HERE / "compose.history.questdb.yml")])
|
||||
if self.environment.get("GRPC_DATA_CONDITIONS") == "1":
|
||||
files.extend(["--file", str(HERE / "compose.conditions.yml")])
|
||||
if self.environment.get("GRPC_DATA_SOURCE_PINNED") == "1":
|
||||
files.extend(["--file", str(HERE / "compose.source-pinned.yml")])
|
||||
return files
|
||||
|
||||
def compose(self, *args, timeout=120):
|
||||
@@ -749,10 +816,18 @@ class LocalRig:
|
||||
expected = source_tree_hash()
|
||||
if manifest.get("source_tree_hash") != expected:
|
||||
raise RigError("running manifest does not match current image build inputs")
|
||||
pinned = manifest.get("source_pinned")
|
||||
if pinned is not None:
|
||||
# lmxopcua#921: the SOURCE pair runs the pinned revision; its export must still hash to what was built.
|
||||
if (not isinstance(pinned, dict) or pinned_tree_hash(self.folder / "pinned-source") != pinned.get("tree_hash")
|
||||
or pinned.get("revision") != self.environment.get("GRPC_DATA_SOURCE_PINNED_REVISION")):
|
||||
raise RigError("pinned SOURCE export does not match the recorded pinned build")
|
||||
for node in NODES:
|
||||
raw = self.compose("exec", "--no-TTY", node, "cat", "/app/grpc-data-source.json", timeout=15)
|
||||
stamp = json.loads(raw)
|
||||
if stamp.get("tree_hash") != expected or stamp.get("revision") != manifest.get("source_revision"):
|
||||
want = ((pinned["tree_hash"], pinned["revision"]) if pinned is not None and node.startswith("source-")
|
||||
else (expected, manifest.get("source_revision")))
|
||||
if stamp.get("tree_hash") != want[0] or stamp.get("revision") != want[1]:
|
||||
raise RigError("running Host build stamp does not match the candidate")
|
||||
device_hash = device_tree_hash()
|
||||
if manifest.get("device_source_hash") != device_hash:
|
||||
@@ -848,7 +923,7 @@ class LocalRig:
|
||||
self.save(manifest)
|
||||
return manifest
|
||||
|
||||
def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False):
|
||||
def up(self, timeout=600, history=False, history_backend="sqlserver", conditions=False, source_revision=None):
|
||||
import secrets
|
||||
import credentials
|
||||
if self.folder.exists():
|
||||
@@ -875,6 +950,16 @@ class LocalRig:
|
||||
settings["GRPC_DATA_HISTORY_BACKEND"] = history_backend
|
||||
if conditions:
|
||||
settings["GRPC_DATA_CONDITIONS"] = "1"
|
||||
pinned = None
|
||||
if source_revision is not None:
|
||||
# lmxopcua#921: the SOURCE pair is built from a pinned post-X0, pre-H2 revision (the "v1 origin"); CONTROL and
|
||||
# CONSUMER stay on this checkout. Only the wire tap is added to the pinned tree.
|
||||
full = resolve_pinned_source_revision(source_revision)
|
||||
pinned = {"revision": full, "tree_hash": export_pinned_source(full, self.folder / "pinned-source"),
|
||||
"x0_merge": X0_MERGE, "h2_merge_absent": H2_MERGE, "overlay_files": list(PINNED_OVERLAY_FILES)}
|
||||
settings.update({"GRPC_DATA_SOURCE_PINNED": "1", "GRPC_DATA_SOURCE_PINNED_REVISION": full,
|
||||
"GRPC_DATA_SOURCE_PINNED_TREE_HASH": pinned["tree_hash"], "GRPC_DATA_SOURCE_PINNED_CONTEXT": str(self.folder / "pinned-source"),
|
||||
"GRPC_DATA_SOURCE_IMAGE": f"otopcua-grpc-data-source-pinned:{self.run_id}"})
|
||||
atomic_write_secret(self.folder / "environment.json", json.dumps(settings))
|
||||
self.environment.update(settings)
|
||||
credentials.provision_tls(self.folder / "security", NODES[2:])
|
||||
@@ -891,12 +976,15 @@ class LocalRig:
|
||||
resolved = json.loads(self.compose("config", "--format", "json"))
|
||||
validate_fixture_endpoints(resolved, local_services=SERVICES)
|
||||
try:
|
||||
self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", timeout=1800)
|
||||
self.compose("build", "--pull", "migrator", "device", "control-1", "seeder", *(["source-1"] if pinned else []),
|
||||
timeout=2400 if pinned else 1800) # a pinned run builds a second Host image
|
||||
self.compose("up", "--detach", "sql", "device", "migrator", *NODES, timeout=timeout)
|
||||
manifest = self.allocate_manifest()
|
||||
manifest["source_revision"] = revision
|
||||
manifest["source_tree_hash"] = tree_hash
|
||||
manifest["device_source_hash"] = settings["DEVICE_TREE_HASH"]
|
||||
if pinned is not None:
|
||||
manifest["source_pinned"] = pinned
|
||||
self.capture(manifest)
|
||||
wait_until(lambda: self.health(manifest, require_catalog=False), timeout=timeout, description="six node health and independent pair roles")
|
||||
manifest["state"] = "up"
|
||||
@@ -1347,6 +1435,8 @@ def main(argv=None):
|
||||
parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down"))
|
||||
parser.add_argument("--run-id")
|
||||
parser.add_argument("--timeout", type=float, default=None)
|
||||
parser.add_argument("--source-revision", default=None,
|
||||
help="up only (#921): build the SOURCE pair from this pinned post-X0, pre-H2 commit (a v1 origin), e.g. 0c86edc1")
|
||||
parser.add_argument("--conditions", action="store_true", help="up only: add the A2a conditions overlay (AlarmSubscribe exports + one scripted alarm)")
|
||||
parser.add_argument("--history", action="store_true", help="up only: add the H2 history overlay (SOURCE historian + history seed profile)")
|
||||
parser.add_argument("--history-backend", choices=HISTORY_BACKENDS, default=None,
|
||||
@@ -1381,6 +1471,10 @@ def main(argv=None):
|
||||
if arguments.action != "up":
|
||||
raise RigError("--conditions applies to up only; the run remembers it")
|
||||
options["conditions"] = True
|
||||
if arguments.source_revision is not None:
|
||||
if arguments.action != "up":
|
||||
raise RigError("--source-revision applies to up only; the run remembers it")
|
||||
options["source_revision"] = arguments.source_revision
|
||||
result = action(**options)
|
||||
print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")}))
|
||||
return 0
|
||||
|
||||
@@ -569,3 +569,85 @@ class AkkaSeedEndpointTests(unittest.TestCase):
|
||||
for row in variants:
|
||||
with self.subTest(row=row), self.assertRaises(rig.RigError):
|
||||
rig.validate_fixture_endpoints(row, local_services={"source-1"})
|
||||
|
||||
|
||||
class PinnedSourceRevisionTests(unittest.TestCase):
|
||||
"""lmxopcua#921: a pinned SOURCE must be a post-X0, pre-H2 commit; no Docker or real git."""
|
||||
|
||||
PINNED = "0c86edc194bf50c2a902a081959333097e0b3bb5"
|
||||
PROTO_V1 = "service DataConnectionService {\n rpc Read(ReadRequest) returns (ReadResponse);\n}\n"
|
||||
|
||||
def git(self, *, x0=True, h2=False, proto=None):
|
||||
def run(*arguments):
|
||||
if arguments[0] == "rev-parse":
|
||||
return self.PINNED + "\n"
|
||||
if arguments[0] == "merge-base":
|
||||
if arguments[1] == rig.X0_MERGE:
|
||||
return (rig.X0_MERGE if x0 else "1" * 40) + "\n"
|
||||
return (rig.H2_MERGE if h2 else "2" * 40) + "\n"
|
||||
if arguments[0] == "show":
|
||||
return proto if proto is not None else self.PROTO_V1
|
||||
raise AssertionError(arguments)
|
||||
return run
|
||||
|
||||
def test_a_post_x0_pre_h2_commit_resolves_to_its_full_sha(self):
|
||||
self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1", git=self.git()), self.PINNED)
|
||||
|
||||
def test_pre_x0_h2_or_a_history_rpc_is_refused(self):
|
||||
history = self.PROTO_V1 + " rpc HistoryRead(HistoryReadRequest) returns (HistoryReadResponse);\n"
|
||||
for options in ({"x0": False}, {"h2": True}, {"proto": history}):
|
||||
with self.subTest(options=options), self.assertRaises(rig.RigError):
|
||||
rig.resolve_pinned_source_revision("0c86edc1", git=self.git(**options))
|
||||
|
||||
def test_only_hexadecimal_commit_ids_are_accepted(self):
|
||||
for value in ("HEAD", "master", "0c86edc1;rm", "abc", None, "--all"):
|
||||
with self.subTest(value=value), self.assertRaises(rig.RigError):
|
||||
rig.resolve_pinned_source_revision(value, git=self.git())
|
||||
|
||||
def test_the_real_pin_0c86edc1_is_post_x0_and_pre_h2(self):
|
||||
"""The committed history itself (read-only git): the issue's suggested pin passes the guard."""
|
||||
self.assertEqual(rig.resolve_pinned_source_revision("0c86edc1"), self.PINNED)
|
||||
with self.assertRaises(rig.RigError):
|
||||
rig.resolve_pinned_source_revision(rig.H2_MERGE[:12])
|
||||
|
||||
def test_pinned_tree_hash_uses_the_image_input_filter(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / "src").mkdir()
|
||||
(root / "docs").mkdir()
|
||||
(root / "src" / "A.cs").write_text("class A {}")
|
||||
(root / "docs" / "note.cs").write_text("ignored")
|
||||
first = rig.pinned_tree_hash(root)
|
||||
(root / "docs" / "note.cs").write_text("still ignored")
|
||||
self.assertEqual(rig.pinned_tree_hash(root), first)
|
||||
(root / "src" / "A.cs").write_text("class A { int x; }")
|
||||
self.assertNotEqual(rig.pinned_tree_hash(root), first)
|
||||
|
||||
def test_candidate_expects_the_pinned_stamp_on_source_nodes_only(self):
|
||||
instance = object.__new__(rig.LocalRig)
|
||||
instance.folder = Path("/nonexistent")
|
||||
instance.environment = {"GRPC_DATA_SOURCE_PINNED_REVISION": "pinned-rev"}
|
||||
instance.load = Mock(return_value={"source_tree_hash": "code", "source_revision": "revision", "device_source_hash": "device",
|
||||
"source_pinned": {"revision": "pinned-rev", "tree_hash": "pinned-code"}})
|
||||
|
||||
def stamp(*args, **kwargs):
|
||||
if "device" in args:
|
||||
return "device\n"
|
||||
pinned = args[2].startswith("source-")
|
||||
return json.dumps({"tree_hash": "pinned-code" if pinned else "code", "revision": "pinned-rev" if pinned else "revision"})
|
||||
|
||||
def current_everywhere(*args, **kwargs):
|
||||
return "device\n" if "device" in args else json.dumps({"tree_hash": "code", "revision": "revision"})
|
||||
|
||||
instance.compose = Mock(side_effect=stamp)
|
||||
with patch.object(rig, "source_tree_hash", return_value="code"), patch.object(rig, "device_tree_hash", return_value="device"):
|
||||
with patch.object(rig, "pinned_tree_hash", return_value="pinned-code"):
|
||||
self.assertEqual(instance.verify_candidate(), "code")
|
||||
# A current-checkout stamp on a SOURCE node (the pinned image is not what runs) is refused.
|
||||
instance.compose.side_effect = current_everywhere
|
||||
with self.assertRaises(rig.RigError):
|
||||
instance.verify_candidate()
|
||||
# The export edited after the build is refused before any stamp is read.
|
||||
instance.compose.side_effect = stamp
|
||||
with patch.object(rig, "pinned_tree_hash", return_value="edited-export"), self.assertRaises(rig.RigError):
|
||||
instance.verify_candidate()
|
||||
|
||||
Reference in New Issue
Block a user