test: scaffold isolated grpc data docker fixtures
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
# Standalone P10 host image. The run coordinator supplies SOURCE_REVISION from
|
||||
# the current checkout and uses a run-scoped image name in compose.yml.
|
||||
FROM --platform=linux/amd64 mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN dotnet restore ZB.MOM.WW.OtOpcUa.slnx
|
||||
ARG SOURCE_REVISION
|
||||
RUN test -n "$SOURCE_REVISION" && dotnet publish \
|
||||
src/Server/ZB.MOM.WW.OtOpcUa.Host/ZB.MOM.WW.OtOpcUa.Host.csproj \
|
||||
-c Release -o /app --no-restore -p:SourceRevisionId="$SOURCE_REVISION"
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime
|
||||
WORKDIR /app
|
||||
COPY --from=build /app ./
|
||||
EXPOSE 9000 4053 4055 4056 4057 4840 9001
|
||||
ENTRYPOINT ["dotnet", "OtOpcUa.Host.dll"]
|
||||
|
||||
FROM build AS migrator
|
||||
RUN dotnet tool install --global dotnet-ef --version 10.0.7
|
||||
ENV PATH="${PATH}:/root/.dotnet/tools"
|
||||
WORKDIR /src
|
||||
ENTRYPOINT ["dotnet", "ef", "database", "update", \
|
||||
"--project", "src/Core/ZB.MOM.WW.OtOpcUa.Configuration", \
|
||||
"--startup-project", "src/Core/ZB.MOM.WW.OtOpcUa.Configuration"]
|
||||
@@ -0,0 +1,61 @@
|
||||
# gRPC data local fixture scaffold
|
||||
|
||||
This directory contains the **preparation** for the P10 gate. The standalone
|
||||
Compose file describes six Host processes in three independent two-node pairs:
|
||||
CONTROL (admin and deployment), SOURCE, and CONSUMER. Each process has its own
|
||||
LocalDb/secrets volume. SOURCE and CONSUMER have pair-local LocalDb replication.
|
||||
The SQL Server and Modbus simulator are run-local services; exposed host ports
|
||||
use Docker's dynamic allocation on `127.0.0.1`.
|
||||
|
||||
The fixture is **not ready for integration execution**. P07's dedicated TLS
|
||||
listener, client trust options, target-issued credential provisioner, and
|
||||
production seeding/deployment path are still in progress. The certificate
|
||||
mounts reserve `/run/grpc-data/tls` on the four data nodes, but no guessed P07
|
||||
option names or TLS activation are included. The existing `rig.py` currently
|
||||
provides pure safety/polling boundaries, not `up`, `seed`, or `deploy` behavior.
|
||||
The presence of this Compose file does not establish a healthy cluster, a
|
||||
deployed catalog, or passing D01–D14 scenarios.
|
||||
|
||||
## Run-owned inputs for later rig integration
|
||||
|
||||
The future `rig.py up` must generate a restricted run directory and inject all
|
||||
required Compose variables. `GRPC_DATA_PROJECT`, `GRPC_DATA_RUN_ID`,
|
||||
`GRPC_DATA_IMAGE`, `GRPC_DATA_MIGRATOR_IMAGE`, and `GRPC_DATA_DEVICE_IMAGE` must
|
||||
identify the run uniquely. `SOURCE_REVISION` must be the current source SHA,
|
||||
including a dirty marker when applicable. `GRPC_DATA_CERT_DIR` must contain
|
||||
per-node SAN certificates and private keys under `source-1`, `source-2`,
|
||||
`consumer-1`, and `consumer-2`; their common trust material belongs in the same
|
||||
restricted run directory. The rig must generate `GRPC_DATA_SQL_PASSWORD`,
|
||||
`GRPC_DATA_APIKEY_PEPPER`, `GRPC_DATA_JWT_KEY`, `GRPC_DATA_DEPLOY_KEY`,
|
||||
`GRPC_DATA_SECRETS_KEK`, `GRPC_DATA_CONFIG_KEY`, `GRPC_DATA_TELEMETRY_KEY`,
|
||||
three `GRPC_DATA_MESH_PSK_*` values, and both `GRPC_DATA_SYNC_KEY_*` values.
|
||||
None has a tracked default. The rig should pass them from a `0600` environment
|
||||
file without writing values to logs or a public manifest.
|
||||
|
||||
The current Compose image build follows the repository's Host publish graph and
|
||||
requires a nonempty `SourceRevisionId`. The future coordinator must build the
|
||||
runtime and migrator images for the current checkout before starting nodes,
|
||||
inspect Docker's allocated loopback ports, and record the exact run-owned
|
||||
resource IDs and labels. A separate production-path seeder must create the
|
||||
CONTROL/SOURCE/CONSUMER cluster rows, author source and mapping configuration,
|
||||
provision every eligible consumer, and deploy through `/api/deployments` before
|
||||
any readiness or CLI assertion is meaningful. No node should use a shared-host
|
||||
endpoint or another node's OPC UA endpoint as its source driver.
|
||||
|
||||
## Device fixture
|
||||
|
||||
`device/server.py` uses the Python standard library. Modbus TCP unit 1 listens
|
||||
on container port 5020. Holding register 0 is a counter changed only by the
|
||||
fixture control action `{"action":"advance","steps":N}` (1–1000). Registers
|
||||
10–12 start at `[7, 11, 13]`; registers 20–63 are writable uint16 values.
|
||||
FC03/FC04 reads and FC06/FC16 writes are supported. Read requests and committed
|
||||
writes have separate bounded ledgers with monotonic totals. The HTTP control
|
||||
listener on container port 8080 offers `GET /state` and `POST /control`, with
|
||||
`advance`, bounded `set`, and `drop_next_write_response` actions. The last
|
||||
action closes one Modbus write connection after applying and recording the
|
||||
effect, so D08 can distinguish an ambiguous response from a second effect.
|
||||
The control listener is fixture-only and its allocated host port is loopback
|
||||
bound; it must never be wired into the production Host.
|
||||
|
||||
Unit tests in `tests/test_device.py` and `tests/test_compose_fixture.py` are
|
||||
pure. They do not start a socket, container, migration, or network client.
|
||||
@@ -0,0 +1,279 @@
|
||||
# P10 standalone infrastructure scaffold. Secrets and TLS files are generated in
|
||||
# a run-owned restricted directory. See README.md before using this file.
|
||||
name: ${GRPC_DATA_PROJECT:?run-scoped project required}
|
||||
|
||||
x-labels: &labels
|
||||
otopcua.grpc-data.run: ${GRPC_DATA_RUN_ID:?run id required}
|
||||
otopcua.grpc-data.fixture: "v1"
|
||||
|
||||
x-common-env: &common-env
|
||||
Security__Ldap__Enabled: "false"
|
||||
Security__Auth__DisableLogin: "true"
|
||||
Security__Acl__Enabled: "true"
|
||||
Security__ApiKeys__Pepper: ${GRPC_DATA_APIKEY_PEPPER:?generated pepper required}
|
||||
Security__Jwt__SigningKey: ${GRPC_DATA_JWT_KEY:?generated JWT key required}
|
||||
Security__Jwt__Issuer: grpc-data-local
|
||||
Security__Jwt__Audience: grpc-data-local
|
||||
Security__DeployApiKey: ${GRPC_DATA_DEPLOY_KEY:?generated deploy key required}
|
||||
Secrets__SqlitePath: /data/otopcua-secrets.db
|
||||
Secrets__Replication__Enabled: "true"
|
||||
Secrets__Replication__AnnounceInterval: "00:00:05"
|
||||
ZB_SECRETS_MASTER_KEY: ${GRPC_DATA_SECRETS_KEK:?generated KEK required}
|
||||
Cluster__Port: "4053"
|
||||
ConfigServe__ApiKey: ${GRPC_DATA_CONFIG_KEY:?generated config key required}
|
||||
Telemetry__Mode: Grpc
|
||||
Telemetry__GrpcListenPort: "4056"
|
||||
Telemetry__ApiKey: ${GRPC_DATA_TELEMETRY_KEY:?generated telemetry key required}
|
||||
MeshTransport__Mode: Grpc
|
||||
MeshTransport__CentralGrpcEndpoints__0: http://control-1:4055
|
||||
MeshTransport__CentralGrpcEndpoints__1: http://control-2:4055
|
||||
LocalDb__Path: /app/data/otopcua-localdb.db
|
||||
Serilog__MinimumLevel__Override__Microsoft.EntityFrameworkCore: Warning
|
||||
Serilog__MinimumLevel__Override__Microsoft.AspNetCore: Warning
|
||||
# P07_TLS_BINDING_PENDING: match the actual P07 listener/client option names
|
||||
# before enabling data gRPC. Certificate mounts are already isolated below.
|
||||
|
||||
x-control-env: &control-env
|
||||
<<: *common-env
|
||||
OTOPCUA_ROLES: admin,driver,cluster-CONTROL
|
||||
Cluster__Roles__0: admin
|
||||
Cluster__Roles__1: driver
|
||||
Cluster__Roles__2: cluster-CONTROL
|
||||
ConfigSource__Mode: Direct
|
||||
ConfigServe__GrpcListenPort: "4055"
|
||||
ConnectionStrings__ConfigDb: "Server=sql,1433;Database=OtOpcUa;User Id=sa;Password=${GRPC_DATA_SQL_PASSWORD:?generated SQL password required};TrustServerCertificate=True;"
|
||||
MeshTransport__GrpcPsk: ${GRPC_DATA_MESH_PSK_CONTROL:?generated CONTROL mesh PSK required}
|
||||
MeshTransport__ClusterPsks__CONTROL: ${GRPC_DATA_MESH_PSK_CONTROL:?generated CONTROL mesh PSK required}
|
||||
MeshTransport__ClusterPsks__SOURCE: ${GRPC_DATA_MESH_PSK_SOURCE:?generated SOURCE mesh PSK required}
|
||||
MeshTransport__ClusterPsks__CONSUMER: ${GRPC_DATA_MESH_PSK_CONSUMER:?generated CONSUMER mesh PSK required}
|
||||
TelemetryDial__Mode: Grpc
|
||||
TelemetryDial__ApiKey: ${GRPC_DATA_TELEMETRY_KEY:?generated telemetry key required}
|
||||
|
||||
x-data-env: &data-env
|
||||
<<: *common-env
|
||||
ConfigSource__Mode: FetchAndCache
|
||||
ConfigSource__CentralFetchEndpoints__0: http://control-1:4055
|
||||
ConfigSource__CentralFetchEndpoints__1: http://control-2:4055
|
||||
ConfigSource__ApiKey: ${GRPC_DATA_CONFIG_KEY:?generated config key required}
|
||||
LocalDb__SyncListenPort: "9001"
|
||||
LocalDb__Replication__MaxBatchSize: "16"
|
||||
|
||||
x-host: &host
|
||||
image: ${GRPC_DATA_IMAGE:?run-scoped current-SHA image required}
|
||||
labels: *labels
|
||||
networks: [rig]
|
||||
restart: unless-stopped
|
||||
mem_limit: 2g
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
|
||||
x-founder-health: &founder-health
|
||||
test: ["CMD-SHELL", "bash -c '</dev/tcp/localhost/4053' || exit 1"]
|
||||
interval: 3s
|
||||
timeout: 2s
|
||||
retries: 20
|
||||
start_period: 8s
|
||||
|
||||
x-device-origin: device:5020
|
||||
|
||||
services:
|
||||
sql:
|
||||
image: mcr.microsoft.com/mssql/server:2022-latest
|
||||
platform: linux/amd64
|
||||
labels: *labels
|
||||
networks: [rig]
|
||||
environment:
|
||||
ACCEPT_EULA: "Y"
|
||||
MSSQL_PID: Developer
|
||||
SA_PASSWORD: ${GRPC_DATA_SQL_PASSWORD:?generated SQL password required}
|
||||
ports: ["127.0.0.1::1433"]
|
||||
volumes: [sql-data:/var/opt/mssql]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "/opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P \"$$SA_PASSWORD\" -No -Q 'SELECT 1' >/dev/null"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
migrator:
|
||||
build:
|
||||
context: ../../..
|
||||
dockerfile: scripts/validation/grpc-data/Dockerfile
|
||||
target: migrator
|
||||
args: {SOURCE_REVISION: "${SOURCE_REVISION:?current checkout revision required}"}
|
||||
image: ${GRPC_DATA_MIGRATOR_IMAGE:?run-scoped migrator image required}
|
||||
labels: *labels
|
||||
networks: [rig]
|
||||
depends_on:
|
||||
sql: {condition: service_healthy}
|
||||
environment:
|
||||
OTOPCUA_CONFIG_CONNECTION: "Server=sql,1433;Database=OtOpcUa;User Id=sa;Password=${GRPC_DATA_SQL_PASSWORD:?generated SQL password required};TrustServerCertificate=True;"
|
||||
restart: "no"
|
||||
|
||||
device:
|
||||
build:
|
||||
context: ../../..
|
||||
dockerfile: scripts/validation/grpc-data/device/Dockerfile
|
||||
image: ${GRPC_DATA_DEVICE_IMAGE:?run-scoped device image required}
|
||||
labels: *labels
|
||||
networks: [rig]
|
||||
ports: ["127.0.0.1::5020", "127.0.0.1::8080"]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/state', timeout=2).read()"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
control-1:
|
||||
<<: *host
|
||||
build:
|
||||
context: ../../..
|
||||
dockerfile: scripts/validation/grpc-data/Dockerfile
|
||||
target: runtime
|
||||
args: {SOURCE_REVISION: "${SOURCE_REVISION:?current checkout revision required}"}
|
||||
environment:
|
||||
<<: *control-env
|
||||
Cluster__Hostname: control-1
|
||||
Cluster__PublicHostname: control-1
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@control-1:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@control-2:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:control-1
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:control-2
|
||||
ASPNETCORE_URLS: http://control-1:9000
|
||||
healthcheck: *founder-health
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000"]
|
||||
volumes: [control-1-data:/app/data, control-1-data:/data]
|
||||
|
||||
control-2:
|
||||
<<: *host
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
control-1: {condition: service_healthy}
|
||||
environment:
|
||||
<<: *control-env
|
||||
Cluster__Hostname: control-2
|
||||
Cluster__PublicHostname: control-2
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@control-2:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@control-1:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:control-2
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:control-1
|
||||
ASPNETCORE_URLS: http://control-2:9000
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000"]
|
||||
volumes: [control-2-data:/app/data, control-2-data:/data]
|
||||
|
||||
source-1:
|
||||
<<: *host
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
control-1: {condition: service_healthy}
|
||||
device: {condition: service_healthy}
|
||||
environment:
|
||||
<<: *data-env
|
||||
OTOPCUA_ROLES: driver,cluster-SOURCE
|
||||
Cluster__Roles__0: driver
|
||||
Cluster__Roles__1: cluster-SOURCE
|
||||
Cluster__Hostname: source-1
|
||||
Cluster__PublicHostname: source-1
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@source-1:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@source-2:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:source-1
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:source-2
|
||||
ASPNETCORE_URLS: http://source-1:9000
|
||||
MeshTransport__GrpcPsk: ${GRPC_DATA_MESH_PSK_SOURCE:?generated SOURCE mesh PSK required}
|
||||
LocalDb__Replication__PeerAddress: http://source-2:9001
|
||||
LocalDb__Replication__ApiKey: ${GRPC_DATA_SYNC_KEY_SOURCE:?generated SOURCE sync key required}
|
||||
healthcheck: *founder-health
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000", "127.0.0.1::4057"]
|
||||
volumes:
|
||||
- source-1-data:/app/data
|
||||
- source-1-data:/data
|
||||
- ${GRPC_DATA_CERT_DIR:?restricted generated certificate directory required}/source-1:/run/grpc-data/tls:ro
|
||||
|
||||
source-2:
|
||||
<<: *host
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
source-1: {condition: service_healthy}
|
||||
environment:
|
||||
<<: *data-env
|
||||
OTOPCUA_ROLES: driver,cluster-SOURCE
|
||||
Cluster__Roles__0: driver
|
||||
Cluster__Roles__1: cluster-SOURCE
|
||||
Cluster__Hostname: source-2
|
||||
Cluster__PublicHostname: source-2
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@source-2:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@source-1:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:source-2
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:source-1
|
||||
ASPNETCORE_URLS: http://source-2:9000
|
||||
MeshTransport__GrpcPsk: ${GRPC_DATA_MESH_PSK_SOURCE:?generated SOURCE mesh PSK required}
|
||||
LocalDb__Replication__ApiKey: ${GRPC_DATA_SYNC_KEY_SOURCE:?generated SOURCE sync key required}
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000", "127.0.0.1::4057"]
|
||||
volumes:
|
||||
- source-2-data:/app/data
|
||||
- source-2-data:/data
|
||||
- ${GRPC_DATA_CERT_DIR:?restricted generated certificate directory required}/source-2:/run/grpc-data/tls:ro
|
||||
|
||||
consumer-1:
|
||||
<<: *host
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
control-1: {condition: service_healthy}
|
||||
environment:
|
||||
<<: *data-env
|
||||
OTOPCUA_ROLES: driver,cluster-CONSUMER
|
||||
Cluster__Roles__0: driver
|
||||
Cluster__Roles__1: cluster-CONSUMER
|
||||
Cluster__Hostname: consumer-1
|
||||
Cluster__PublicHostname: consumer-1
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@consumer-1:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@consumer-2:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:consumer-1
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:consumer-2
|
||||
ASPNETCORE_URLS: http://consumer-1:9000
|
||||
MeshTransport__GrpcPsk: ${GRPC_DATA_MESH_PSK_CONSUMER:?generated CONSUMER mesh PSK required}
|
||||
LocalDb__Replication__PeerAddress: http://consumer-2:9001
|
||||
LocalDb__Replication__ApiKey: ${GRPC_DATA_SYNC_KEY_CONSUMER:?generated CONSUMER sync key required}
|
||||
healthcheck: *founder-health
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000", "127.0.0.1::4057"]
|
||||
volumes:
|
||||
- consumer-1-data:/app/data
|
||||
- consumer-1-data:/data
|
||||
- ${GRPC_DATA_CERT_DIR:?restricted generated certificate directory required}/consumer-1:/run/grpc-data/tls:ro
|
||||
|
||||
consumer-2:
|
||||
<<: *host
|
||||
depends_on:
|
||||
migrator: {condition: service_completed_successfully}
|
||||
consumer-1: {condition: service_healthy}
|
||||
environment:
|
||||
<<: *data-env
|
||||
OTOPCUA_ROLES: driver,cluster-CONSUMER
|
||||
Cluster__Roles__0: driver
|
||||
Cluster__Roles__1: cluster-CONSUMER
|
||||
Cluster__Hostname: consumer-2
|
||||
Cluster__PublicHostname: consumer-2
|
||||
Cluster__SeedNodes__0: akka.tcp://otopcua@consumer-2:4053
|
||||
Cluster__SeedNodes__1: akka.tcp://otopcua@consumer-1:4053
|
||||
OpcUa__ApplicationUri: urn:OtOpcUa:grpc-data:consumer-2
|
||||
OpcUa__PeerApplicationUris__0: urn:OtOpcUa:grpc-data:consumer-1
|
||||
ASPNETCORE_URLS: http://consumer-2:9000
|
||||
MeshTransport__GrpcPsk: ${GRPC_DATA_MESH_PSK_CONSUMER:?generated CONSUMER mesh PSK required}
|
||||
LocalDb__Replication__ApiKey: ${GRPC_DATA_SYNC_KEY_CONSUMER:?generated CONSUMER sync key required}
|
||||
ports: ["127.0.0.1::4840", "127.0.0.1::9000", "127.0.0.1::4057"]
|
||||
volumes:
|
||||
- consumer-2-data:/app/data
|
||||
- consumer-2-data:/data
|
||||
- ${GRPC_DATA_CERT_DIR:?restricted generated certificate directory required}/consumer-2:/run/grpc-data/tls:ro
|
||||
|
||||
networks:
|
||||
rig:
|
||||
labels: *labels
|
||||
|
||||
volumes:
|
||||
sql-data: {labels: *labels}
|
||||
control-1-data: {labels: *labels}
|
||||
control-2-data: {labels: *labels}
|
||||
source-1-data: {labels: *labels}
|
||||
source-2-data: {labels: *labels}
|
||||
consumer-1-data: {labels: *labels}
|
||||
consumer-2-data: {labels: *labels}
|
||||
@@ -0,0 +1,6 @@
|
||||
FROM python:3.13-slim
|
||||
WORKDIR /fixture
|
||||
COPY scripts/validation/grpc-data/device/server.py /fixture/server.py
|
||||
EXPOSE 5020 8080
|
||||
USER 65534:65534
|
||||
ENTRYPOINT ["python", "-u", "/fixture/server.py"]
|
||||
@@ -0,0 +1,213 @@
|
||||
"""Deterministic, fixture-only Modbus TCP source and bounded control ledger.
|
||||
|
||||
Register map (unit 1): 0 counter; 10..12 fixed array; 20..63 writable scalar/
|
||||
array window. Control calls advance or set values explicitly; wall time never
|
||||
changes samples. A one-shot fault can discard a write response *after* recording
|
||||
its effect, which gives the integration gate a reproducible ambiguous outcome.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import socketserver
|
||||
import struct
|
||||
import threading
|
||||
|
||||
|
||||
MODBUS_PORT = 5020
|
||||
CONTROL_PORT = 8080
|
||||
MAX_PDU_BYTES = 253
|
||||
MAX_CONTROL_BYTES = 4096
|
||||
MAX_LEDGER_ITEMS = 1024
|
||||
|
||||
|
||||
class DeviceState:
|
||||
def __init__(self):
|
||||
self._lock = threading.RLock()
|
||||
self._registers = {0: 0, 10: 7, 11: 11, 12: 13}
|
||||
self._registers.update({address: 0 for address in range(20, 64)})
|
||||
self._effect_total = 0
|
||||
self._read_total = 0
|
||||
self._effects = deque(maxlen=MAX_LEDGER_ITEMS)
|
||||
self._reads = deque(maxlen=MAX_LEDGER_ITEMS)
|
||||
self._drop_next_write_response = False
|
||||
|
||||
def snapshot(self):
|
||||
with self._lock:
|
||||
return {
|
||||
"counter": self._registers[0],
|
||||
"effect_total": self._effect_total,
|
||||
"read_total": self._read_total,
|
||||
"effects": list(self._effects),
|
||||
"reads": list(self._reads),
|
||||
"writable": {str(address): self._registers[address] for address in range(20, 64)},
|
||||
"drop_next_write_response": self._drop_next_write_response,
|
||||
}
|
||||
|
||||
def read(self, address, quantity):
|
||||
if type(address) is not int or type(quantity) is not int or not 1 <= quantity <= 125:
|
||||
raise ValueError("invalid read span")
|
||||
with self._lock:
|
||||
if any(register not in self._registers for register in range(address, address + quantity)):
|
||||
raise ValueError("unmapped read span")
|
||||
self._read_total += 1
|
||||
self._reads.append({"sequence": self._read_total, "address": address, "quantity": quantity})
|
||||
return [self._registers[register] for register in range(address, address + quantity)]
|
||||
|
||||
def write(self, address, values):
|
||||
if (type(address) is not int or not isinstance(values, list) or not 1 <= len(values) <= 44
|
||||
or address < 20 or address + len(values) > 64
|
||||
or any(type(value) is not int or not 0 <= value <= 65535 for value in values)):
|
||||
raise ValueError("write outside bounded fixture window")
|
||||
with self._lock:
|
||||
for offset, value in enumerate(values):
|
||||
self._registers[address + offset] = value
|
||||
self._effect_total += 1
|
||||
self._effects.append({"sequence": self._effect_total, "address": address, "values": list(values)})
|
||||
drop = self._drop_next_write_response
|
||||
self._drop_next_write_response = False
|
||||
return drop
|
||||
|
||||
|
||||
def apply_control(state, command):
|
||||
if not isinstance(command, dict) or not isinstance(command.get("action"), str):
|
||||
raise ValueError("control action required")
|
||||
action = command["action"]
|
||||
if action == "advance":
|
||||
steps = command.get("steps")
|
||||
if type(steps) is not int or not 1 <= steps <= 1000:
|
||||
raise ValueError("advance steps must be 1..1000")
|
||||
with state._lock:
|
||||
state._registers[0] = (state._registers[0] + steps) & 0xFFFF
|
||||
elif action == "set":
|
||||
address, value = command.get("address"), command.get("value")
|
||||
if type(address) is not int or not 20 <= address <= 63 or type(value) is not int or not 0 <= value <= 65535:
|
||||
raise ValueError("set requires writable address and uint16 value")
|
||||
with state._lock:
|
||||
state._registers[address] = value
|
||||
elif action == "drop_next_write_response":
|
||||
with state._lock:
|
||||
state._drop_next_write_response = True
|
||||
else:
|
||||
raise ValueError("unknown fixture control action")
|
||||
return state.snapshot()
|
||||
|
||||
|
||||
def handle_modbus_pdu(state, unit_id, pdu):
|
||||
"""Return a reply PDU; None means deliberately close after a committed write."""
|
||||
if unit_id != 1 or not isinstance(pdu, bytes) or not 1 <= len(pdu) <= MAX_PDU_BYTES:
|
||||
raise ValueError("invalid Modbus unit or PDU")
|
||||
function = pdu[0]
|
||||
if function in (3, 4):
|
||||
if len(pdu) != 5:
|
||||
raise ValueError("malformed read PDU")
|
||||
address, quantity = struct.unpack(">HH", pdu[1:])
|
||||
values = state.read(address, quantity)
|
||||
return bytes([function, len(values) * 2]) + struct.pack(f">{len(values)}H", *values)
|
||||
if function == 6:
|
||||
if len(pdu) != 5:
|
||||
raise ValueError("malformed single-write PDU")
|
||||
address, value = struct.unpack(">HH", pdu[1:])
|
||||
return None if state.write(address, [value]) else pdu
|
||||
if function == 16:
|
||||
if len(pdu) < 6:
|
||||
raise ValueError("malformed multi-write PDU")
|
||||
address, quantity, byte_count = struct.unpack(">HHB", pdu[1:6])
|
||||
if not 1 <= quantity <= 44 or byte_count != 2 * quantity or len(pdu) != 6 + byte_count:
|
||||
raise ValueError("invalid multi-write count")
|
||||
values = list(struct.unpack(f">{quantity}H", pdu[6:]))
|
||||
return None if state.write(address, values) else bytes([16]) + pdu[1:5]
|
||||
raise ValueError("unsupported Modbus function")
|
||||
|
||||
|
||||
class _ModbusHandler(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
self.request.settimeout(5)
|
||||
while True:
|
||||
try:
|
||||
header = _receive_exactly(self.request, 7)
|
||||
if header is None:
|
||||
return
|
||||
transaction, protocol, length, unit = struct.unpack(">HHHB", header)
|
||||
if protocol != 0 or not 2 <= length <= MAX_PDU_BYTES + 1:
|
||||
return
|
||||
pdu = _receive_exactly(self.request, length - 1)
|
||||
if pdu is None:
|
||||
return
|
||||
try:
|
||||
reply = handle_modbus_pdu(self.server.device_state, unit, pdu)
|
||||
except ValueError:
|
||||
return
|
||||
if reply is None:
|
||||
return
|
||||
self.request.sendall(struct.pack(">HHHB", transaction, 0, len(reply) + 1, unit) + reply)
|
||||
except (OSError, TimeoutError):
|
||||
return
|
||||
|
||||
|
||||
def _receive_exactly(sock, length):
|
||||
chunks = bytearray()
|
||||
while len(chunks) < length:
|
||||
chunk = sock.recv(length - len(chunks))
|
||||
if not chunk:
|
||||
return None
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
|
||||
class _ModbusServer(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, address, state):
|
||||
super().__init__(address, _ModbusHandler)
|
||||
self.device_state = state
|
||||
|
||||
|
||||
class _ControlHandler(BaseHTTPRequestHandler):
|
||||
def log_message(self, _format, *_args):
|
||||
pass
|
||||
|
||||
def _json(self, status, payload):
|
||||
data = json.dumps(payload, sort_keys=True).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path != "/state":
|
||||
self._json(404, {"error": "unknown fixture path"})
|
||||
return
|
||||
self._json(200, self.server.device_state.snapshot())
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/control":
|
||||
self._json(404, {"error": "unknown fixture path"})
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", ""))
|
||||
if not 1 <= length <= MAX_CONTROL_BYTES:
|
||||
raise ValueError("control body exceeds fixture bound")
|
||||
command = json.loads(self.rfile.read(length))
|
||||
result = apply_control(self.server.device_state, command)
|
||||
except (ValueError, UnicodeError, json.JSONDecodeError):
|
||||
self._json(400, {"error": "invalid fixture control"})
|
||||
return
|
||||
self._json(200, result)
|
||||
|
||||
|
||||
def main():
|
||||
state = DeviceState()
|
||||
modbus_port = int(os.environ.get("GRPC_DATA_MODBUS_PORT", MODBUS_PORT))
|
||||
control_port = int(os.environ.get("GRPC_DATA_CONTROL_PORT", CONTROL_PORT))
|
||||
with _ModbusServer(("0.0.0.0", modbus_port), state) as modbus, ThreadingHTTPServer(("0.0.0.0", control_port), _ControlHandler) as control:
|
||||
control.device_state = state
|
||||
threading.Thread(target=modbus.serve_forever, daemon=True).start()
|
||||
control.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Static standalone rig contract checks; no Compose invocation or network I/O."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ROOT / "compose.yml"
|
||||
DOCKERFILE = ROOT / "Dockerfile"
|
||||
|
||||
|
||||
def service_block(document, service):
|
||||
match = re.search(rf"(?ms)^ {re.escape(service)}:\s*\n(.*?)(?=^ [a-z][a-z0-9-]*:|\Z)", document)
|
||||
if match is None:
|
||||
raise AssertionError(f"missing service {service}")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def extension_block(document, name):
|
||||
match = re.search(rf"(?ms)^{re.escape(name)}:\s*&[a-z-]+\s*\n(.*?)(?=^[a-z][a-z0-9-]*:|\Z)", document)
|
||||
if match is None:
|
||||
raise AssertionError(f"missing extension {name}")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
class StandaloneComposeContractTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.compose = COMPOSE.read_text(encoding="utf-8")
|
||||
cls.dockerfile = DOCKERFILE.read_text(encoding="utf-8")
|
||||
|
||||
def test_run_scoped_project_revision_and_no_fixed_container_names_or_shared_hosts(self):
|
||||
self.assertRegex(self.compose, r"(?m)^name:\s*\$\{GRPC_DATA_PROJECT:\?[^}]+\}")
|
||||
self.assertIn("SOURCE_REVISION", self.compose)
|
||||
self.assertNotIn("container_name:", self.compose)
|
||||
self.assertNotIn("10.100.0.35", self.compose)
|
||||
self.assertNotIn("host.docker.internal", self.compose)
|
||||
self.assertNotIn("docker-dev/docker-compose.yml", self.compose)
|
||||
self.assertIn("SourceRevisionId", self.dockerfile)
|
||||
|
||||
def test_three_independent_pairs_with_self_first_seed_nodes(self):
|
||||
common = extension_block(self.compose, "x-common-env")
|
||||
control = extension_block(self.compose, "x-control-env")
|
||||
data = extension_block(self.compose, "x-data-env")
|
||||
self.assertIn("MeshTransport__Mode: Grpc", common)
|
||||
self.assertIn("Telemetry__Mode: Grpc", common)
|
||||
self.assertIn("ConfigSource__Mode: Direct", control)
|
||||
self.assertIn("ConfigSource__Mode: FetchAndCache", data)
|
||||
self.assertIn("cluster-CONTROL", control)
|
||||
for pair in ("control", "source", "consumer"):
|
||||
for suffix, partner in (("1", "2"), ("2", "1")):
|
||||
node = f"{pair}-{suffix}"
|
||||
block = service_block(self.compose, node)
|
||||
self.assertIn("<<: *host", block)
|
||||
expected_env = "control-env" if pair == "control" else "data-env"
|
||||
self.assertIn(f"<<: *{expected_env}", block)
|
||||
if pair != "control":
|
||||
self.assertIn(f"cluster-{pair.upper()}", block)
|
||||
self.assertIn(f"Cluster__SeedNodes__0: akka.tcp://otopcua@{node}:4053", block)
|
||||
self.assertIn(f"Cluster__SeedNodes__1: akka.tcp://otopcua@{pair}-{partner}:4053", block)
|
||||
for other in ({"control", "source", "consumer"} - {pair}):
|
||||
self.assertNotIn(f"akka.tcp://otopcua@{other}-", block)
|
||||
self.assertIn("/app/data", block)
|
||||
|
||||
def test_local_sql_device_and_generated_tls_mounts(self):
|
||||
self.assertIn(" sql:", self.compose)
|
||||
self.assertIn(" device:", self.compose)
|
||||
for node in ("source-1", "source-2", "consumer-1", "consumer-2"):
|
||||
block = service_block(self.compose, node)
|
||||
self.assertIn("GRPC_DATA_CERT_DIR", block)
|
||||
self.assertIn("/run/grpc-data/tls", block)
|
||||
self.assertIn("P07_TLS_BINDING_PENDING", self.compose)
|
||||
self.assertIn("device:5020", self.compose)
|
||||
self.assertRegex(self.compose, r"127\.0\.0\.1::(?:4840|9000)")
|
||||
self.assertNotRegex(self.compose, r"(?m)^\s+- ['\"]?0\.0\.0\.0:")
|
||||
|
||||
def test_no_tracked_secrets_or_private_keys(self):
|
||||
for line in self.compose.splitlines():
|
||||
match = re.match(r"^\s*(?:SA_PASSWORD|ZB_SECRETS_MASTER_KEY|Security__ApiKeys__Pepper):\s*(.*)$", line)
|
||||
if match:
|
||||
self.assertTrue(match.group(1).startswith("${"), line)
|
||||
self.assertNotIn("BEGIN PRIVATE KEY", self.compose + self.dockerfile)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Pure Modbus fixture tests; no sockets, Docker, or production process starts."""
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "device"))
|
||||
from server import DeviceState, apply_control, handle_modbus_pdu
|
||||
|
||||
|
||||
def request(function, address, value):
|
||||
return bytes([function]) + struct.pack(">HH", address, value)
|
||||
|
||||
|
||||
def words(response):
|
||||
return struct.unpack(f">{response[1] // 2}H", response[2:])
|
||||
|
||||
|
||||
class ModbusFixtureTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.state = DeviceState()
|
||||
|
||||
def test_counter_advances_only_by_explicit_bounded_control(self):
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 0, 1))), (0,))
|
||||
apply_control(self.state, {"action": "advance", "steps": 3})
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 0, 1))), (3,))
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 0, 1))), (3,))
|
||||
with self.assertRaises(ValueError):
|
||||
apply_control(self.state, {"action": "advance", "steps": 1001})
|
||||
self.assertEqual(self.state.snapshot()["counter"], 3)
|
||||
|
||||
def test_scalar_and_array_registers_have_deterministic_readback(self):
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 10, 3))), (7, 11, 13))
|
||||
self.assertEqual(handle_modbus_pdu(self.state, 1, request(6, 20, 42)), request(6, 20, 42))
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 20, 1))), (42,))
|
||||
payload = bytes([16]) + struct.pack(">HHBHH", 30, 2, 4, 0x1234, 0x00FF)
|
||||
self.assertEqual(handle_modbus_pdu(self.state, 1, payload), request(16, 30, 2))
|
||||
self.assertEqual(words(handle_modbus_pdu(self.state, 1, request(3, 30, 2))), (0x1234, 0x00FF))
|
||||
|
||||
def test_each_committed_write_has_one_effect_and_repeated_value_is_a_new_request(self):
|
||||
write = request(6, 20, 42)
|
||||
handle_modbus_pdu(self.state, 1, write)
|
||||
handle_modbus_pdu(self.state, 1, write)
|
||||
ledger = self.state.snapshot()["effects"]
|
||||
self.assertEqual([item["sequence"] for item in ledger], [1, 2])
|
||||
self.assertEqual([item["values"] for item in ledger], [[42], [42]])
|
||||
self.assertEqual(self.state.snapshot()["effect_total"], 2)
|
||||
|
||||
def test_response_loss_is_armed_for_one_write_after_effect(self):
|
||||
apply_control(self.state, {"action": "drop_next_write_response"})
|
||||
self.assertIsNone(handle_modbus_pdu(self.state, 1, request(6, 20, 42)))
|
||||
snapshot = self.state.snapshot()
|
||||
self.assertEqual(snapshot["effect_total"], 1)
|
||||
self.assertEqual(snapshot["effects"][0]["values"], [42])
|
||||
self.assertEqual(handle_modbus_pdu(self.state, 1, request(6, 20, 43)), request(6, 20, 43))
|
||||
self.assertEqual(self.state.snapshot()["effect_total"], 2)
|
||||
|
||||
def test_malformed_and_out_of_range_requests_never_mutate(self):
|
||||
invalid = [b"", b"\x06\x00", request(3, 0, 0), request(3, 0, 126),
|
||||
request(6, 999, 1), bytes([16]) + struct.pack(">HHB", 30, 2, 2) + b"\x00\x01"]
|
||||
before = self.state.snapshot()
|
||||
for payload in invalid:
|
||||
with self.subTest(payload=payload), self.assertRaises(ValueError):
|
||||
handle_modbus_pdu(self.state, 1, payload)
|
||||
self.assertEqual(self.state.snapshot(), before)
|
||||
|
||||
def test_control_rejects_unknown_actions_and_unbounded_input(self):
|
||||
for command in ({"action": "set", "address": 20, "value": -1},
|
||||
{"action": "set", "address": 999, "value": 3},
|
||||
{"action": "advance", "steps": True},
|
||||
{"action": "unknown"}):
|
||||
with self.subTest(command=command), self.assertRaises(ValueError):
|
||||
apply_control(self.state, command)
|
||||
self.assertEqual(self.state.snapshot()["effect_total"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user