Merge #921/#927: live gates — H05 against a pinned pre-H2 origin (wire tap proves no new-shape frame) and A09 native-ack driver-failure revert under the service principal; CLI read --attribute
This commit is contained in:
@@ -121,6 +121,8 @@ otopcua-cli read -u opc.tcp://localhost:4840/OtOpcUa -n "ns=3;s=DEV.ScanState" -
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `-n` / `--node` | Node ID to read (required) |
|
||||
| `--max-age` | Maximum cached value age in milliseconds (0–2147483647; default 0). Value attribute only |
|
||||
| `-a` / `--attribute` | Attribute to read instead of the value (case-insensitive): `Value` (default), `Historizing`, `AccessLevel`, `UserAccessLevel`, `DataType`, `ValueRank`, `ArrayDimensions`, `MinimumSamplingInterval`, `NodeClass`, `BrowseName`, `DisplayName`, `EventNotifier`. The output gains an `Attribute:` line. Used by the #921 gate to show a projected variable's `Historizing` is False when its origin lacks the history feature |
|
||||
|
||||
Output:
|
||||
|
||||
|
||||
@@ -200,6 +200,10 @@ the bit (see "Mixed versions" below); the AdminUI editor shows a reminder.
|
||||
**Negotiation.** The capabilities probe always asks for `history`; an origin advertises it only when a historian backend
|
||||
is configured. Other calls carry the header only toward an endpoint that advertised it. An origin without a historian, a
|
||||
pre-H2 origin, or a call without the header answers unsupported — the v1 responses are unchanged.
|
||||
Live-gated against a real pre-H2 origin (#921, `docs/plans/evidence/grpc-data-ext/H05-v1-origin.md`): a pre-H2 origin
|
||||
ignores the probe's header (capabilities byte-identical with and without it), so the consumer's projected variables have
|
||||
`Historizing` False, HistoryRead answers `BadHistoryOperationUnsupported` locally, and no HistoryRead or feature-headed data
|
||||
call is sent. (Sent anyway, a HistoryRead is refused `PERMISSION_DENIED` by the old data listener's v1 method allowlist.)
|
||||
|
||||
**Limits.**
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# #927 — live gate: driver-failure ack revert through DriverHostActor under the connection service principal
|
||||
|
||||
A2b (remote `CallConditionMethod`) had been gated live only for a scripted condition. The path where a remote ack of a
|
||||
**native** condition reaches a driver that fails it, and DriverHostActor reverts the node (`RevertNativeAlarmAck`,
|
||||
`AlarmStateUpdate(EstablishesState: false)`), was unit-tested only (`ConditionMethodNodeManagerTests`, A2.md "Driver failure
|
||||
revert seen in the stream"). This adds scenario **A09** to `scripts/validation/grpc-data/conditions_scenarios.py` and runs it.
|
||||
|
||||
## How the driver is made to fail (a real failure, no seam)
|
||||
|
||||
The conditions profile's SOURCE `OpcUaClient` driver `source-opcua` watches the run-owned `opc-plc:2.14.10 --alm` native alarm
|
||||
`EastTankYellow`. A09 `docker compose pause`s the `opcplc` container immediately before the consumer's ack. The driver is still
|
||||
`Connected` (its keep-alive has not yet noticed), so `OpcUaClientDriver.AcknowledgeAsync` sends the upstream
|
||||
`AcknowledgeableConditionType.Acknowledge` call and gets **no reply**; the SDK call fails with a `ServiceResultException`
|
||||
(request timeout) inside the 5 s ack window, `DriverInstanceActor.HandleAcknowledgeAsync` reports `AlarmAckFailed`, and
|
||||
DriverHostActor reverts. The container is unpaused in the scenario's `finally` (and again by the per-scenario restore if it
|
||||
was left paused). Pausing also freezes opc-plc's own alarm cycling, so no upstream transition can explain the
|
||||
Unacknowledged that follows the ack.
|
||||
|
||||
**Why not an upstream refusal.** The option the issue suggests — an upstream that answers the Acknowledge with a Bad status
|
||||
(stale EventId, already acked) — does **not** revert today: `OpcUaClientDriver.AcknowledgeAsync` only logs a per-ack Bad
|
||||
result (and an ack whose condition id resolves to nothing), by design (`docs/drivers/OpcUaClient.md`: "a reply still returns
|
||||
normally, including per-ack refusals … a refusal is the server answering"), to keep refusals off the AlarmAcknowledge breaker.
|
||||
`DriverOperationRefusedException` now exists for exactly that (breaker-exempt, reverts), so an upstream refusal leaving the
|
||||
node Acknowledged is a gap — reported as a follow-up, not changed here (it reverses a documented driver decision). A
|
||||
no-reply transport failure is the failure class the driver does surface, and it exercises the whole revert path.
|
||||
|
||||
## Result — run `a927-1`, 2026-11-28, HEAD `cdbbe22a9`: A09 **PASS** (12/12)
|
||||
|
||||
`rig.py up --conditions` → `seed` → 85 s → `deploy --timeout 300` → `conditions_scenarios.py --only A09` → `rig.py down`
|
||||
(0 run containers, 0 run volumes).
|
||||
|
||||
| Check | Evidence |
|
||||
|---|---|
|
||||
| native condition present on both sides, Unacknowledged | consumer `EastTankYellow` `Inactive, Unacknowledged` (opaque `ns=6;s=c1.…` id), origin `ns=2;s=opcua/opcplc/EastTankYellow` same record time |
|
||||
| caller gets Good | 15:13:40 `opcplc` paused; consumer CLI `ack` ⇒ `Acknowledge successful` (plan §5.6 step 5: native ⇒ Good, `AcceptedUnconfirmed`; the failure reaches the caller as the revert) |
|
||||
| audit records the remote call | origin `source-1`: `Data-connection condition method Acknowledge by fixture-consumer (key …) on Raw:…:opcua/opcplc/EastTankYellow op a3-…: AcceptedUnconfirmed 0x00000000; on behalf of fixture-cli` — the connection's **service principal** (`fixture-consumer`) on behalf of the end user |
|
||||
| the driver really failed | 15:13:46 `DriverInstance source-opcua: native-alarm acknowledge of opcua/opcplc/EastTankYellow failed` |
|
||||
| DriverHostActor reverted (EstablishesState: false) | 15:13:46 `DriverHost source-1:4053: … did not reach the alarm system (the upstream acknowledge failed (ServiceResultException)); reverting the condition to unacknowledged` — `RevertNativeAlarmAck` is the only producer of that line and of an `EstablishesState: false` update |
|
||||
| origin node applied, then reverted | origin Server-object events after the ack: `Inactive, Acknowledged` → `Inactive, Unacknowledged` (nothing else: upstream frozen) |
|
||||
| consumer saw the reverted delta | consumer events after the ack: `Inactive, Acknowledged` → `Inactive, Unacknowledged`; same ConditionId, a new EventId |
|
||||
| positive control | 15:13:48 unpaused; 30 s later the condition was `Active, Unacknowledged` (opc-plc had re-activated it; whether the paused call was later applied upstream is not observable from this state); a second consumer ack of the current EventId ⇒ Good and **no** new revert line in the next 15 s |
|
||||
|
||||
Evidence files (removed with the run folder; copies taken before `down`): `evidence/A4S-A09.json`, `A4S-results.md`, the CLI
|
||||
`*.process.json` logs.
|
||||
|
||||
## Not covered
|
||||
|
||||
- The upstream-refusal flavour (Bad per-ack status) — it does not revert; follow-up above.
|
||||
- `/alerts` (alarm-history) rows for the ack and its revert were not asserted.
|
||||
@@ -0,0 +1,59 @@
|
||||
# #921 — H05 live gate against a real pre-H2 (v1) origin
|
||||
|
||||
The H3 gate replaced H05 ("v1 origin ⇒ unsupported") with an origin export that drops HistoryRead (H3.md "Not verified /
|
||||
substitutions"). That removes `Historizing` before any wire call, so the plan §4.3 mixed-version row "new consumer → v1 origin"
|
||||
was never exercised live. This gate runs it against a SOURCE pair built from a pinned pre-H2 commit.
|
||||
|
||||
## Rig additions (`scripts/validation/grpc-data/`, README "Pinned pre-H2 SOURCE")
|
||||
|
||||
- `rig.py up --source-revision <sha>`: `resolve_pinned_source_revision` requires X0 `a15912539` to be an ancestor (a pre-X0
|
||||
node rejects the whole snapshot once a newer bit is authored), H2 `ef938b435` **not** to be one, and no `rpc HistoryRead` in
|
||||
that revision's `data_connection.proto`. **`0c86edc19`** (the #918 merge, between H1 and H2 on master's first-parent line)
|
||||
passes; it is post-X0 (tolerant readers, feature header parsed with `SupportedFeatures = None`), its
|
||||
`LocalDataServices.Implemented()` has no HistoryRead and its proto has no HistoryRead RPC — a genuine v1 origin.
|
||||
- The rig `git archive`s it into the run folder, adds one rig file (`node-probe/WireTap.cs`, ASP.NET Core only, compiled
|
||||
unchanged against the pinned tree) and builds the pinned tree's own Dockerfile (`compose.source-pinned.yml`). CONTROL and
|
||||
CONSUMER run this checkout. `verify_candidate` checks SOURCE stamps against the pinned revision and export hash, the other
|
||||
four against this checkout. Unit tests: `PinnedSourceRevisionTests` (6, incl. the real `0c86edc1` / H2 commits).
|
||||
- **Wire tap** (`GRPC_DATA_WIRE_TAP=1`, only on the pinned SOURCE): per data-listener request, one line at arrival (gRPC path,
|
||||
`x-otopcua-data-features` value, remote address — before authentication) and one at completion (gRPC status). No credential
|
||||
or body.
|
||||
- `Client.CLI read --attribute <name>` (new; `Historizing`, `AccessLevel`, …) for a real OPC UA attribute read.
|
||||
- `history_v1_origin_gate.py` (H05V1) and probe `--scenario history-v1-origin`.
|
||||
|
||||
## Result — run `h05v1-1`, 2026-11-28 15:20–15:26 UTC: **PASS, 25/25 checks**
|
||||
|
||||
`rig.py up --history --source-revision 0c86edc1 --timeout 1500` → `seed` → 80 s → `deploy --timeout 300` (all six nodes
|
||||
applied the HEAD-built artifact, including the pinned SOURCE pair) → `history_v1_origin_gate.py` → `down` (0 containers,
|
||||
0 volumes, 0 images left). SOURCE has a SqlServer historian and historizes `counter` (the `--history` overlay).
|
||||
|
||||
| Assertion | Observed |
|
||||
|---|---|
|
||||
| builds | `source-1/2` stamp `0c86edc194bf…` (pinned export hash `1111f654…`); `control-*`, `consumer-*` stamp HEAD `cdbbe22a9` |
|
||||
| projected Raw + UNS `counter` `Historizing` | `False` (Good) on both; `AccessLevel` = 1 (CurrentRead, no HistoryRead bit) |
|
||||
| control: origin's own `counter` | `Historizing` `True`, `AccessLevel` = 13 (HistoryRead bit set); projected value Read Good on both realms |
|
||||
| `historyread` on projected Raw / UNS `counter` | `HistoryRead of ns=4;s=p1.… failed: BadHistoryOperationUnsupported (0x80720000).` (UNS `ns=5` same) |
|
||||
| control: `historyread` on the origin's node | Good, 30–31 rows in the window |
|
||||
| diagnostics (CONSUMER page, prerendered) | `Negotiated features none (v1 behaviour) · origin history not advertised · projected history reads good 0 · uncertain 0 · bad 0` |
|
||||
| diagnostics (SOURCE page) | `Exports with dropped unknown operation bits: export-raw: HistoryRead; export-uns: HistoryRead — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.` |
|
||||
| tap, consumer window (12 arrivals, all from the two consumer containers, no other remote) | methods `GetCapabilities, Browse, GetMetadata, Read` (control: the consumer's v1 traffic is there); **no** `HistoryRead` / `CallConditionMethod`; the only arrivals carrying the feature header are the capability probes (`history,conditions`, plan §4.1: the probe always asks) |
|
||||
| tap positive control (probe `history-v1-origin`, both origins) | capabilities with `history,conditions` byte-identical to capabilities without (operations 31, no `history`, no `conditions`); a HistoryRead with header `history` arrives at the tap with that header and completes **`grpc-status 7` (PERMISSION_DENIED)** |
|
||||
|
||||
**Finding (harness expectation, not a product defect).** The first pass (same run) failed two expectations of mine, both
|
||||
corrected in the harness and re-run green:
|
||||
1. A sent HistoryRead is refused **PERMISSION_DENIED**, not the UNIMPLEMENTED the issue/plan text guessed. At `0c86edc1`,
|
||||
`DataConnectionEndpoints` admits only its six v1 methods (`GetCapabilities, Browse, GetMetadata, Read, Write, Subscribe`) on
|
||||
the data listener and refuses any other path before gRPC routing. A current consumer never sends one (the tap shows it), so
|
||||
this only affects a hand-rolled caller; documented in `DataConnections.md`.
|
||||
2. The first projected value Read answered `BadWaitingForInitialData`; the gate now retries only that status (bounded 60 s),
|
||||
as every mapped positive read on this rig does (README).
|
||||
|
||||
The re-run used `--pinned-build` (harness and probe source edited after `up`; images unchanged, probe republished).
|
||||
|
||||
Evidence (run folder removed by `down`; copies taken before): `evidence/H05V1-results.json`, `probe/source-1/wire-tap.jsonl`.
|
||||
|
||||
## Not covered
|
||||
|
||||
- Subscribe / Write from the consumer to the v1 origin did not occur in the window (the gate reads via the CLI); the H2/A2
|
||||
recorded-v1-client gates cover the header-less shapes of those calls.
|
||||
- Conditions against a v1 origin (`--conditions` with a pinned SOURCE) were not run.
|
||||
@@ -173,7 +173,7 @@ Round 3 was itself an independent (Fable) verification of the round-2 commits
|
||||
|
||||
- **H05**: the rig builds no pinned v1 image, so "v1 origin" is substituted by an origin that does not advertise history for the
|
||||
principal (export without bit 32). The v1 wire shape itself is covered by the H2 recorded-v1-client gates; the live v1-origin
|
||||
path is follow-up **#921**.
|
||||
path is follow-up **#921** — since run live against a pinned pre-H2 origin (`0c86edc1`), PASS 25/25: `H05-v1-origin.md`.
|
||||
- **H01 tie clusters**: not representable live on either backend — SqlServer `hist.Sample` PK `(TagId, SourceTimeUtc)`, QuestDB
|
||||
`DEDUP UPSERT KEYS(ts, tag)` keep one sample per timestamp. Tie paging is proven by the H1 port fuzz (10k seeds).
|
||||
- **ReadyReplica consistency** on projected history and the Gateway backend (H4) were not run.
|
||||
|
||||
@@ -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")
|
||||
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720}
|
||||
SCENARIOS = ("A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09")
|
||||
TIMEOUTS = {"A01": 420, "A02": 360, "A03": 1200, "A04": 480, "A05": 720, "A06": 1200, "A07": 900, "A08": 720, "A09": 600}
|
||||
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)
|
||||
@@ -510,6 +511,88 @@ class ConditionScenarios:
|
||||
return {"code": code, "output": text[-300:], "good": code == 0 and ("successful" in text or "Comment added" in text),
|
||||
"event_id_unknown": "BadEventIdUnknown" in text}
|
||||
|
||||
# ---- 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
|
||||
@@ -800,6 +883,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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -29,11 +29,29 @@ public class ReadCommand : CommandBase
|
||||
[CommandOption("max-age", Description = "Maximum cached value age in milliseconds (0 to 2147483647; default 0)")]
|
||||
public double MaxAgeMilliseconds { get; init; }
|
||||
|
||||
/// <summary>Gets the attribute to read; <c>Value</c> (the default) is the current value.</summary>
|
||||
[CommandOption("attribute", 'a', Description = "Attribute to read: Value (default), Historizing, AccessLevel, UserAccessLevel, DataType, ValueRank, ArrayDimensions, MinimumSamplingInterval, NodeClass, BrowseName, DisplayName, EventNotifier")]
|
||||
public string Attribute { get; init; } = "Value";
|
||||
|
||||
/// <summary>The attributes <c>--attribute</c> accepts (case-insensitive), by name.</summary>
|
||||
internal static readonly IReadOnlyDictionary<string, uint> AttributeIds = new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Value"] = Attributes.Value, ["Historizing"] = Attributes.Historizing, ["AccessLevel"] = Attributes.AccessLevel,
|
||||
["UserAccessLevel"] = Attributes.UserAccessLevel, ["DataType"] = Attributes.DataType, ["ValueRank"] = Attributes.ValueRank,
|
||||
["ArrayDimensions"] = Attributes.ArrayDimensions, ["MinimumSamplingInterval"] = Attributes.MinimumSamplingInterval,
|
||||
["NodeClass"] = Attributes.NodeClass, ["BrowseName"] = Attributes.BrowseName, ["DisplayName"] = Attributes.DisplayName,
|
||||
["EventNotifier"] = Attributes.EventNotifier,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
if (!double.IsFinite(MaxAgeMilliseconds) || MaxAgeMilliseconds < 0 || MaxAgeMilliseconds > int.MaxValue)
|
||||
throw new CommandException("Invalid --max-age value: expected a finite number from 0 to 2147483647 milliseconds.");
|
||||
if (!AttributeIds.TryGetValue(Attribute ?? "", out var attributeId))
|
||||
throw new CommandException($"Invalid --attribute value: expected one of {string.Join(", ", AttributeIds.Keys)}.");
|
||||
if (attributeId != Attributes.Value && MaxAgeMilliseconds != 0)
|
||||
throw new CommandException("--max-age applies to the Value attribute only.");
|
||||
|
||||
ConfigureLogging();
|
||||
|
||||
@@ -56,9 +74,11 @@ public class ReadCommand : CommandBase
|
||||
DataValue value;
|
||||
try
|
||||
{
|
||||
value = MaxAgeMilliseconds == 0
|
||||
? await service.ReadValueAsync(nodeId, ct)
|
||||
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
|
||||
value = attributeId != Attributes.Value
|
||||
? await service.ReadAttributeAsync(nodeId, attributeId, ct)
|
||||
: MaxAgeMilliseconds == 0
|
||||
? await service.ReadValueAsync(nodeId, ct)
|
||||
: await service.ReadValueAsync(nodeId, TimeSpan.FromMilliseconds(MaxAgeMilliseconds), ct);
|
||||
}
|
||||
catch (ServiceResultException ex) when (ex.StatusCode != StatusCodes.BadSessionIdInvalid
|
||||
&& ex.StatusCode != StatusCodes.BadConnectionClosed
|
||||
@@ -68,12 +88,14 @@ public class ReadCommand : CommandBase
|
||||
// BadUserAccessDenied, ...) as an exception. A read command's job is to REPORT that status,
|
||||
// not crash with a stack trace — session-level failures still propagate.
|
||||
await console.Output.WriteLineAsync($"Node: {NodeId}");
|
||||
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
|
||||
await console.Output.WriteLineAsync($"Value: ");
|
||||
await console.Output.WriteLineAsync($"Status: {(StatusCode)ex.StatusCode} ({ex.StatusCode.SymbolicId})");
|
||||
return;
|
||||
}
|
||||
|
||||
await console.Output.WriteLineAsync($"Node: {NodeId}");
|
||||
if (attributeId != Attributes.Value) await console.Output.WriteLineAsync($"Attribute: {Attribute}");
|
||||
await console.Output.WriteLineAsync($"Value: {ValueFormatter.Format(ValueConverter.ToClrObject(value.WrappedValue))}");
|
||||
await console.Output.WriteLineAsync($"Status: {value.StatusCode}");
|
||||
await console.Output.WriteLineAsync($"Source Time: {value.SourceTimestamp.ToString("O")}");
|
||||
|
||||
@@ -76,6 +76,14 @@ internal sealed class DefaultSessionAdapter : ISessionAdapter
|
||||
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct)
|
||||
{
|
||||
ArrayOf<ReadValueId> nodes = [new ReadValueId { NodeId = nodeId, AttributeId = attributeId }];
|
||||
var response = await _session.ReadAsync(null, 0, TimestampsToReturn.Both, nodes, ct);
|
||||
return ValidateReadResult(response.ResponseHeader, response.Results, nodeId);
|
||||
}
|
||||
|
||||
internal static DataValue ValidateReadResult(ResponseHeader? header, ArrayOf<DataValue> results, NodeId nodeId)
|
||||
{
|
||||
var serviceStatus = header?.ServiceResult.Code ?? StatusCodes.BadUnexpectedError;
|
||||
|
||||
@@ -64,6 +64,17 @@ internal interface ISessionAdapter : IDisposable
|
||||
/// <summary>Reads a value using the supplied maximum cache age.</summary>
|
||||
Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>). A Bad result throws
|
||||
/// <see cref="ServiceResultException"/> with its status, like <see cref="ReadValueAsync(NodeId, CancellationToken)"/>.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The node to read.</param>
|
||||
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
|
||||
/// <param name="ct">The cancellation token that aborts the read.</param>
|
||||
/// <returns>The attribute's data value.</returns>
|
||||
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException("This session adapter does not read node attributes.");
|
||||
|
||||
/// <summary>
|
||||
/// Writes a typed value to a node on the connected OPC UA server.
|
||||
/// </summary>
|
||||
|
||||
@@ -56,6 +56,14 @@ public interface IOpcUaClientService : IDisposable
|
||||
return ReadValueAsync(nodeId, ct);
|
||||
}
|
||||
|
||||
/// <summary>Reads one attribute of a node (for example <see cref="Attributes.Historizing"/>).</summary>
|
||||
/// <param name="nodeId">The node to read.</param>
|
||||
/// <param name="attributeId">The attribute id (<see cref="Attributes"/>).</param>
|
||||
/// <param name="ct">The cancellation token that aborts the read.</param>
|
||||
/// <returns>The attribute's data value; a Bad result throws <see cref="ServiceResultException"/>.</returns>
|
||||
Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default) =>
|
||||
throw new NotSupportedException("This client does not read node attributes.");
|
||||
|
||||
/// <summary>
|
||||
/// Writes an operator-supplied value to an OPC UA node after applying client-side type conversion when needed.
|
||||
/// </summary>
|
||||
|
||||
@@ -223,6 +223,14 @@ public sealed class OpcUaClientService : IOpcUaClientService
|
||||
return await _session!.ReadValueAsync(nodeId, maximumAge, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
ThrowIfNotConnected();
|
||||
return await _session!.ReadAttributeAsync(nodeId, attributeId, ct);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<StatusCode> WriteValueAsync(NodeId nodeId, object value, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -199,6 +199,17 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
|
||||
|
||||
public TimeSpan? LastMaximumAge { get; private set; }
|
||||
|
||||
/// <summary>The (node, attribute id) pairs passed to ReadAttributeAsync.</summary>
|
||||
public List<(NodeId NodeId, uint AttributeId)> ReadAttributes { get; } = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<DataValue> ReadAttributeAsync(NodeId nodeId, uint attributeId, CancellationToken ct = default)
|
||||
{
|
||||
ReadAttributes.Add((nodeId, attributeId));
|
||||
if (ReadException != null) throw ReadException;
|
||||
return Task.FromResult(ReadValueResult);
|
||||
}
|
||||
|
||||
public Task<DataValue> ReadValueAsync(NodeId nodeId, TimeSpan maximumAge, CancellationToken ct = default)
|
||||
{
|
||||
LastMaximumAge = maximumAge;
|
||||
|
||||
@@ -42,6 +42,41 @@ public class ReadCommandTests
|
||||
service.ReadNodeIds.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#921: <c>--attribute Historizing</c> reads that attribute (not the value) and labels the output.</summary>
|
||||
[Fact]
|
||||
public async Task Execute_ReadsTheRequestedAttribute()
|
||||
{
|
||||
var service = new FakeOpcUaClientService { ReadValueResult = new DataValue(new Variant(false), StatusCodes.Good) };
|
||||
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = "historizing"
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await command.ExecuteAsync(console);
|
||||
service.ReadAttributes.ShouldBe([(new NodeId("Test", 2), Attributes.Historizing)]);
|
||||
service.ReadNodeIds.ShouldBeEmpty();
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("Attribute: historizing");
|
||||
output.ShouldContain("Value: False");
|
||||
}
|
||||
|
||||
/// <summary>An unknown attribute, or <c>--max-age</c> with a non-Value attribute, is refused before connecting.</summary>
|
||||
[Theory]
|
||||
[InlineData("Bogus", 0)]
|
||||
[InlineData("Historizing", 5000)]
|
||||
public async Task Execute_RejectsAnUnknownAttributeOrMaxAgeOffTheValue(string attribute, double maxAge)
|
||||
{
|
||||
var service = new FakeOpcUaClientService();
|
||||
var command = new ReadCommand(new FakeOpcUaClientServiceFactory(service))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840", NodeId = "ns=2;s=Test", Attribute = attribute, MaxAgeMilliseconds = maxAge
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
await Should.ThrowAsync<CliFx.Exceptions.CommandException>(async () => await command.ExecuteAsync(console));
|
||||
service.ReadAttributes.ShouldBeEmpty();
|
||||
service.ReadNodeIds.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>Verifies that execute prints the read value.</summary>
|
||||
[Fact]
|
||||
public async Task Execute_PrintsReadValue()
|
||||
|
||||
Reference in New Issue
Block a user