Files
lmxopcua/scripts/validation/grpc-data/local_fixtures.py
T
2026-11-23 09:55:04 -05:00

772 lines
46 KiB
Python

#!/usr/bin/env python3
"""Run-owned, loopback-only software prerequisites for the final local gate.
No existing Compose stack is started. Fixture sources supply only image build
contexts, commands and read-only seed/config files. Resource creation is journaled
before start; cleanup requires exact recorded identity AND both owner labels.
All subprocess output goes to bounded private logs; no credentials reach stdout.
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import signal
import socket
import stat
import subprocess
import sys
import threading
import time
from rig import RigError, validate_docker_context
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
OWNER_LABEL = "com.zb.otopcua.final-fixtures.owner"
PROJECT_LABEL = "com.docker.compose.project"
INSTANCE_LABEL = "com.zb.otopcua.final-fixtures.instance"
SUFFIX = re.compile(r"[a-z0-9][a-z0-9-]{0,47}\Z")
RESOURCE_ID = re.compile(r"[a-f0-9]{64}\Z")
LIMIT = 2 * 1024 * 1024
DRIVERS = ROOT / "tests/Drivers"
class FixtureError(RuntimeError):
"""A redacted fixture orchestration failure."""
def driver(name):
return DRIVERS / f"ZB.MOM.WW.OtOpcUa.Driver.{name}.IntegrationTests/Docker"
def private_json(path, value, *, exclusive=False):
"""Never follow an existing symlink; replace atomically with mode 0600."""
path = Path(path)
if path.is_symlink() or (path.exists() and not path.is_file()):
raise FixtureError("unsafe structured output path")
if exclusive and path.exists():
raise FixtureError("structured output already exists; use a new run suffix/path")
temporary = path.with_name(path.name + "." + secrets.token_hex(8) + ".tmp")
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w") as stream:
json.dump(value, stream, indent=2, sort_keys=True)
stream.write("\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def read_private(path):
path = Path(path)
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
with os.fdopen(fd) as stream:
info = os.fstat(stream.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
raise FixtureError("structured fixture file must be an owned regular 0600 file")
if info.st_size > LIMIT:
raise FixtureError("structured fixture file exceeds size bound")
return json.loads(stream.read(LIMIT + 1))
class PrivateProcess:
"""Bound duration and output without ever copying tool output to a terminal."""
def __init__(self, directory, environment):
self.directory = Path(directory)
self.environment = environment
self.number = 0
self.invocation = secrets.token_hex(8)
def __call__(self, argv, *, timeout=120, input_bytes=None, check=True):
self.number += 1
log = self.directory / f"command-{self.invocation}-{self.number:05d}.log"
fd = os.open(log, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
chunks = []
state = {"size": 0, "overflow": False, "kill_failed": False}
with os.fdopen(fd, "wb") as output:
process = subprocess.Popen(argv, env=self.environment, stdin=subprocess.PIPE if input_bytes is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
def stop_owned_child():
if process.poll() is not None:
return
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
except PermissionError:
# Some macOS execution hosts deny killpg even for a child
# started in a new session. Fall back to this Popen child's
# handle; never discover/kill an unrelated PID or group.
try:
process.kill()
except ProcessLookupError:
pass
except PermissionError:
state["kill_failed"] = True
def drain():
while True:
block = process.stdout.read(65536)
if not block:
return
available = max(0, LIMIT - state["size"])
if available:
output.write(block[:available])
chunks.append(block[:available])
state["size"] += len(block)
if state["size"] > LIMIT:
state["overflow"] = True
stop_owned_child()
reader = threading.Thread(target=drain, daemon=True)
reader.start()
def write_input():
try:
process.stdin.write(input_bytes)
except BrokenPipeError:
pass
finally:
process.stdin.close()
writer = None
try:
if input_bytes is not None:
writer = threading.Thread(target=write_input, daemon=True)
writer.start()
process.wait(timeout=timeout)
except (subprocess.TimeoutExpired, BrokenPipeError):
stop_owned_child()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
raise FixtureError("owned fixture subprocess could not be stopped; inspect private logs") from None
raise FixtureError("fixture subprocess timed out or rejected input; inspect private logs") from None
except BaseException:
stop_owned_child()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
raise FixtureError("owned fixture subprocess could not be stopped; inspect private logs") from None
raise
finally:
reader.join(timeout=5)
if writer:
writer.join(timeout=5)
process.stdout.close()
if state["overflow"]:
raise FixtureError("fixture subprocess exceeded private output bound")
if state["kill_failed"]:
raise FixtureError("owned fixture subprocess termination failed")
result = b"".join(chunks)
if check and process.returncode:
raise FixtureError("fixture subprocess failed; inspect private logs")
return process.returncode, result
def compose_command(directory, service):
"""Read committed JSON-array commands, never execute its Compose lifecycle."""
source = (directory / "docker-compose.yml").read_text()
block = re.search(r"^ " + re.escape(service) + r":\s*\n(.*?)(?=^ [a-zA-Z][\w-]*:|\Z)", source, re.M | re.S)
if not block:
raise FixtureError("fixture source service is missing")
match = re.search(r"^ command:\s*(\[.*)", block[1], re.M | re.S)
if not match:
raise FixtureError("fixture source command is missing")
command, _ = json.JSONDecoder().raw_decode(match[1])
if not isinstance(command, list) or any(not isinstance(item, str) for item in command):
raise FixtureError("fixture command must be a JSON string array")
return command
def definitions():
"""All software fixtures use published dynamic loopback ports and no restart."""
sql = {"image": "mcr.microsoft.com/mssql/server:2022-latest", "ports": [1433],
"environment": {"ACCEPT_EULA": "Y", "MSSQL_PID": "Developer", "MSSQL_SA_PASSWORD": "@SQL_PASSWORD@"},
"platform": "linux/amd64"}
result = {
"sql": sql,
"sql-blackhole": dict(sql),
"postgres": {"image": "postgres:17-alpine", "ports": [5432], "environment": {"POSTGRES_PASSWORD": "@PG_PASSWORD@", "POSTGRES_DB": "sqlpollfixture"}},
"mysql": {"image": "mysql:8.4", "ports": [3306], "environment": {"MYSQL_ROOT_PASSWORD": "@MYSQL_PASSWORD@"}, "command": ["--log-bin-trust-function-creators=1"]},
"oracle": {"image": "gvenzl/oracle-free:23-slim", "platform": "linux/amd64", "ports": [1521], "environment": {"ORACLE_PASSWORD": "@ORACLE_PASSWORD@", "APP_USER": "otopcua", "APP_USER_PASSWORD": "@ORACLE_PASSWORD@"}},
"questdb": {"image": re.search(r"image:\s*(questdb/questdb:[\w.-]+)", (driver("Historian.QuestDb") / "docker-compose.yml").read_text())[1], "ports": [8812, 9000]},
"opc": {"image": "mcr.microsoft.com/iotedge/opc-plc:2.14.10", "ports": [50000], "same_port": True, "command": ["--pn=@OPC_PORT@", "--ut", "--aa", "--alm"]},
"opc-nat": {"image": "mcr.microsoft.com/iotedge/opc-plc:2.14.10", "ports": [50000], "command": ["--pn=50000", "--ph=owned-opc-private.invalid", "--ut", "--aa"]},
"ldap": {"image": "glauth/glauth:latest", "ports": [3893], "mounts": [(ROOT / "tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/glauth/config.toml", "/app/config/config.cfg")]},
"s7": {"build": driver("S7"), "ports": [1102], "stable_ports": True, "command": compose_command(driver("S7"), "s7_1500")},
"focas": {"build": driver("FOCAS") / "focas-mock", "ports": [8193], "command": ["--profile", "FWLIB64"]},
"mtconnect-adapter": {"image": "python:3.13-alpine", "ports": [], "alias": "adapter", "mounts": [(driver("MTConnect") / "adapter.py", "/fixtures/adapter.py")], "command": ["python", "-u", "/fixtures/adapter.py", "--host", "0.0.0.0", "--port", "7878"]},
"mtconnect": {"image": "mtconnect/agent:2.7.0.12", "ports": [5000], "mounts": [(driver("MTConnect") / "agent.cfg", "/mtconnect/config/agent.cfg"), (driver("MTConnect") / "Devices.xml", "/mtconnect/config/Devices.xml")]},
"mqtt": {"image": "eclipse-mosquitto:2.0.22", "ports": [1883, 8883], "alias": "mosquitto", "user": "0:0", "mounts": [("@MQTT_CONFIG@", "/mosquitto/config/mosquitto.conf"), ("@MQTT_DIR@", "/mosquitto/secrets")]},
"mqtt-publisher": {"image": "eclipse-mosquitto:2.0.22", "ports": [], "environment": {"BROKER_HOST": "mosquitto", "BROKER_PORT": "1883", "TOPIC_PREFIX": "@MQTT_PREFIX@", "MQTT_FIXTURE_USERNAME": "otopcua", "MQTT_FIXTURE_PASSWORD": "@MQTT_PASSWORD@"}, "mounts": [(driver("Mqtt") / "publisher/publish.sh", "/publish.sh")], "entrypoint": "/bin/sh", "command": ["/publish.sh"]},
}
for profile in ("standard", "dl205", "mitsubishi", "s7_1500", "rtu_over_tcp", "exception_injection"):
result["modbus-" + profile.replace("_", "-")] = {"build": driver("Modbus"), "ports": [5021 if profile == "rtu_over_tcp" else 5020], "command": compose_command(driver("Modbus"), profile)}
for profile in ("controllogix", "compactlogix", "micro800", "guardlogix"):
result["ab-" + profile] = {"build": driver("AbCip"), "ports": [44818], "command": compose_command(driver("AbCip"), profile)}
for profile in ("slc500", "micrologix", "plc5"):
result["legacy-" + profile] = {"build": driver("AbCip"), "ports": [44818], "command": compose_command(driver("AbLegacy"), profile)}
return result
class OwnedFixtures:
def __init__(self, environment=None, *, process=None):
self.input = dict(os.environ if environment is None else environment)
self.owner = self.input.get("CI_FIXTURE_SUFFIX", "")
if not SUFFIX.fullmatch(self.owner):
raise FixtureError("local fixtures require a nonempty safe unique CI_FIXTURE_SUFFIX")
if self.input.get("CI_FIXTURE_LOCAL_OWNED") != "1" or self.input.get("FIXTURE_HOST") != "127.0.0.1":
raise FixtureError("local fixtures require explicit local-owned mode and FIXTURE_HOST=127.0.0.1")
raw = self.input.get("CI_FIXTURE_ENV_JSON", "")
if not raw or not Path(raw).is_absolute():
raise FixtureError("CI_FIXTURE_ENV_JSON must be an absolute per-run output path")
self.output = Path(raw)
self.manifest_path = Path(raw + ".manifest.json")
if not self.manifest_path.is_absolute() or self.output == self.manifest_path:
raise FixtureError("fixture manifest requires a separate absolute path")
self.directory = Path(raw + ".d")
self.project = "grpc-final-" + self.owner
self.labels = {OWNER_LABEL: self.owner, PROJECT_LABEL: self.project}
self.odbc_driver = self.input.get("CI_FIXTURE_ODBC_DRIVER", "")
if self.odbc_driver:
if (not Path(self.odbc_driver).is_absolute() or not Path(self.odbc_driver).is_file()
or any(character in self.odbc_driver for character in ";{}\r\n\0")):
raise FixtureError("CI_FIXTURE_ODBC_DRIVER requires an existing absolute local driver library path")
# Never inherit fixture credentials, endpoint URLs, proxies, SSH commands,
# daemon overrides unrelated to the inspected local context, or GITHUB_ENV.
allowed = {"PATH", "HOME", "USER", "TMPDIR", "SystemRoot", "DOCKER_CONTEXT", "DOCKER_HOST", "DOCKER_CONFIG", "DOCKER_API_VERSION"}
self.environment = {k: v for k, v in self.input.items() if k in allowed}
self.process = process
self.manifest = None
self.docker_prefix = ["docker"]
self.ports = {}
self.containers = {}
self.images = {}
def prepare(self, *, creating):
self.output.parent.mkdir(parents=True, exist_ok=True)
if creating:
if self.directory.exists() or self.output.exists() or self.manifest_path.exists():
raise FixtureError("fixture output already exists; use a new unique run path")
self.directory.mkdir(mode=0o700)
else:
info = self.directory.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077 or info.st_uid != os.getuid():
raise FixtureError("fixture directory must be an owned private directory")
if self.process is None:
logs = self.directory / "logs"
logs.mkdir(mode=0o700, exist_ok=True)
self.process = PrivateProcess(logs, self.environment)
# Read-only context validation precedes every mutation, including teardown.
selected = self.environment.get("DOCKER_CONTEXT")
argv = ["docker", "context", "inspect"] + ([selected] if selected else [])
_, raw = self.process(argv)
try:
contexts = json.loads(raw)
if len(contexts) != 1:
raise ValueError()
context = contexts[0]
validate_docker_context(context, environment=self.environment)
except (ValueError, TypeError, KeyError, RigError):
raise FixtureError("Docker local context validation failed") from None
self.docker_prefix = ["docker", "--context", context["Name"]]
if creating:
self.instance = secrets.token_hex(16)
self.labels[INSTANCE_LABEL] = self.instance
self.manifest = {"schema_version": 1, "owner": self.owner, "project": self.project, "labels": self.labels,
"instance": self.instance,
"environment_json": str(self.output), "directory": str(self.directory), "context": context,
"resources": [], "pending": [], "status": "creating", "services": {}}
self.save()
else:
self.manifest = read_private(self.manifest_path)
instance = self.manifest.get("instance", "") if isinstance(self.manifest, dict) else ""
if not isinstance(instance, str) or not re.fullmatch(r"[a-f0-9]{32}", instance):
raise FixtureError("fixture manifest requires a unique creation instance")
self.labels[INSTANCE_LABEL] = instance
self.validate_manifest()
if self.manifest["context"] != context:
raise FixtureError("fixture daemon context changed since creation")
def validate_manifest(self):
m = self.manifest
if not isinstance(m, dict) or m.get("schema_version") != 1 or m.get("owner") != self.owner or m.get("project") != self.project or m.get("labels") != self.labels:
raise FixtureError("fixture manifest owner/project mismatch")
if m.get("environment_json") != str(self.output) or m.get("directory") != str(self.directory):
raise FixtureError("fixture manifest paths mismatch")
if not isinstance(m.get("resources"), list) or not isinstance(m.get("pending"), list):
raise FixtureError("fixture manifest inventory is invalid")
seen = set()
for row in m["resources"]:
identity = (row.get("kind"), row.get("id"))
valid_id = bool(RESOURCE_ID.fullmatch(row.get("id", ""))) if row.get("kind") != "volume" else row.get("id", "").startswith(self.project + "-")
if row.get("kind") not in {"container", "network", "volume", "image"} or not valid_id or row.get("labels") != self.labels or identity in seen:
raise FixtureError("fixture manifest resource identity/labels invalid")
seen.add(identity)
for row in m["pending"]:
if row.get("kind") not in {"container", "network", "volume", "image"} or not row.get("name", "").startswith(self.project + "-"):
raise FixtureError("fixture manifest pending identity invalid")
def save(self):
private_json(self.manifest_path, self.manifest)
def docker(self, *argv, **kwargs):
return self.process(self.docker_prefix + list(argv), **kwargs)
def inspect(self, kind, identity, *, missing=False):
rc, raw = self.docker(kind, "inspect", identity, check=False)
if rc:
# A daemon/permission/transport failure is not proof of absence.
absent = re.search(rb"no such (?:object|container|image|network|volume)\b|(?:network|volume) [^\r\n]+ not found\b", raw, re.I)
if missing and absent:
return None
raise FixtureError("owned fixture resource inspection failed")
try:
rows = json.loads(raw)
if not isinstance(rows, list) or len(rows) != 1:
raise ValueError()
return rows[0]
except (ValueError, TypeError):
raise FixtureError("invalid Docker inspection response") from None
def observed_labels(self, kind, row):
return (row.get("Config", {}).get("Labels") if kind in {"container", "image"} else row.get("Labels")) or {}
def verified(self, kind, identity, *, missing=False):
row = self.inspect(kind, identity, missing=missing)
if row is None:
return None
if any(self.observed_labels(kind, row).get(k) != v for k, v in self.labels.items()):
raise FixtureError("refusing foreign resource; exact owner/project labels are required")
actual = row.get("Name") if kind == "volume" else row.get("Id", "").removeprefix("sha256:")
if actual != identity:
raise FixtureError("resource identity changed; refusing cleanup")
return row
def guard_name(self, kind, name):
# A unique suffix may never adopt even an existing same-owner name on up.
if self.inspect(kind, name, missing=True) is not None:
raise FixtureError("fixture resource name exists; refusing replacement/adoption")
def create(self, kind, name, args, *, result_id=True):
self.guard_name(kind, name)
pending = {"kind": kind, "name": name}
self.manifest["pending"].append(pending)
self.save() # durable intent precedes mutation; interrupted creation is recoverable
_, raw = self.docker(*args)
identity = raw.decode().strip().removeprefix("sha256:") if result_id else name
if kind != "volume" and not RESOURCE_ID.fullmatch(identity):
raise FixtureError("Docker returned an invalid resource identity")
self.verified(kind, identity)
self.manifest["resources"].append({"kind": kind, "id": identity, "labels": self.labels, "name": name})
self.manifest["pending"].remove(pending)
self.save()
return identity
def label_args(self):
return [item for key, value in self.labels.items() for item in ("--label", key + "=" + value)]
def image(self, spec):
if "build" not in spec:
image = spec["image"]
if image not in self.images:
self.docker("pull", *( ["--platform", spec["platform"]] if spec.get("platform") else []), image, timeout=900)
self.images[image] = image
return image
context = str(spec["build"])
if context not in self.images:
name = self.project + "-image-" + str(len(self.images))
self.guard_name("image", name)
pending = {"kind": "image", "name": name}
self.manifest["pending"].append(pending)
self.save()
iid = self.directory / (name + ".iid")
self.docker("build", "--iidfile", str(iid), "--tag", name, *self.label_args(), context, timeout=1200)
identity = iid.read_text().strip().removeprefix("sha256:")
self.verified("image", identity)
self.manifest["resources"].append({"kind": "image", "id": identity, "labels": self.labels, "name": name})
self.manifest["pending"].remove(pending)
self.save()
self.images[context] = identity
return self.images[context]
def substitute(self, value):
for key, replacement in self.tokens.items():
value = value.replace("@" + key + "@", str(replacement))
if re.search(r"@[A-Z_]+@", value):
raise FixtureError("unresolved fixture configuration token")
return value
def start(self, service, spec):
name = self.project + "-" + service
# Guard before pulling/building too; an occupied name is never removed.
self.guard_name("container", name)
image = self.image(spec)
_, image_raw = self.docker("image", "inspect", image)
image_data = json.loads(image_raw)[0]
args = ["container", "create", "--name", name, *self.label_args(), "--network", self.network,
"--network-alias", spec.get("alias", service), "--restart=no", "--log-opt", "max-size=5m", "--log-opt", "max-file=2"]
if spec.get("platform"):
args += ["--platform", spec["platform"]]
if spec.get("user"):
args += ["--user", spec["user"]]
if spec.get("entrypoint"):
args += ["--entrypoint", spec["entrypoint"]]
mounts = []
for entry in spec.get("mounts", []):
source, target = Path(self.substitute(str(entry[0]))), entry[1]
writable = len(entry) == 3 and entry[2] == "writable"
if writable and (service != "mqtt-material" or source != self.directory / "mqtt" or target != "/out"):
raise FixtureError("only run-owned MQTT material output may be mounted writable")
mounts.append((source, target, writable))
# Replace every image-declared volume by an explicitly labelled owned
# volume, including volumes partially covered by a read-only file bind.
for index, target in enumerate((image_data.get("Config", {}).get("Volumes") or {})):
if any(destination == target for _, destination, _ in mounts):
continue
volume_name = name + "-v" + str(index)
volume = self.create("volume", volume_name, ["volume", "create", *self.label_args(), volume_name], result_id=False)
args += ["--mount", f"type=volume,source={volume},target={target}"]
for source, target, writable in mounts:
if not source.exists() or "," in str(source):
raise FixtureError("required fixture mount is missing or unsafe")
args += ["--mount", f"type=bind,source={source},target={target}" + ("" if writable else ",readonly")]
for key, value in spec.get("environment", {}).items():
args += ["--env", key + "=" + self.substitute(value)]
internal_ports = list(spec.get("ports", []))
reserved_ports = {}
if spec.get("same_port"):
# Docker handles the race between releasing this candidate and bind.
# A failed start retains its recorded ID for ownership-safe cleanup.
with socket.socket() as reserve:
reserve.bind(("127.0.0.1", 0))
candidate = reserve.getsockname()[1]
self.tokens["OPC_PORT"] = candidate
internal_ports = [candidate]
args += ["--publish", f"127.0.0.1:{candidate}:{candidate}"]
elif spec.get("stable_ports"):
# Restart tests retain their original .NET endpoint. Choose an owned
# free host port once and bind it explicitly for the container's life.
# A race after release fails start and leaves the exact ID journaled.
for port in internal_ports:
with socket.socket() as reserve:
reserve.bind(("127.0.0.1", 0))
candidate = reserve.getsockname()[1]
reserved_ports[port] = candidate
args += ["--publish", f"127.0.0.1:{candidate}:{port}"]
else:
for port in internal_ports:
args += ["--publish", f"127.0.0.1::{port}"]
command = [self.substitute(item) for item in spec.get("command", [])]
identity = self.create("container", name, args + [image] + command)
self.containers[service] = identity
self.manifest["services"][service] = {"container_id": identity, "ports": {}}
if spec.get("stable_ports"):
self.manifest["services"][service]["stable_ports"] = True
self.save()
self.docker("container", "start", identity)
observed = self.verified("container", identity)
ports = observed.get("NetworkSettings", {}).get("Ports", {})
self.ports[service] = {}
for port in internal_ports:
bindings = ports.get(f"{port}/tcp")
if not bindings or len(bindings) != 1 or bindings[0].get("HostIp") != "127.0.0.1":
raise FixtureError("Docker did not publish exactly one loopback port")
allocated = int(bindings[0]["HostPort"])
if not 1 <= allocated <= 65535:
raise FixtureError("Docker returned an invalid allocated port")
if port in reserved_ports and allocated != reserved_ports[port]:
raise FixtureError("Docker changed the reserved stable fixture publication")
self.ports[service][port] = allocated
self.manifest["services"][service]["ports"] = self.ports[service]
self.save()
self.ready(service)
return identity
def wait(self, probe, timeout=120):
deadline = time.monotonic() + timeout
while True:
try:
if probe():
return
except (OSError, FixtureError):
pass
if time.monotonic() >= deadline:
raise FixtureError("fixture readiness deadline exceeded; inspect private logs")
time.sleep(2)
def execute(self, service, argv, **kwargs):
identity = self.containers[service]
self.verified("container", identity)
return self.docker("container", "exec", *( ["-i"] if kwargs.get("input_bytes") is not None else []), identity, *argv, **kwargs)
def ready(self, service):
if service in {"sql", "sql-blackhole"}:
self.wait(lambda: self.execute(service, ["/opt/mssql-tools18/bin/sqlcmd", "-C", "-S", "localhost", "-U", "sa", "-P", self.tokens["SQL_PASSWORD"], "-Q", "SELECT 1"], check=False, timeout=20)[0] == 0, 360)
elif service == "postgres":
self.wait(lambda: self.execute(service, ["pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "sqlpollfixture"], check=False)[0] == 0)
# pg_isready can observe the temporary init server; TCP psql must work.
command = ["env", "PGPASSWORD=" + self.tokens["PG_PASSWORD"], "psql", "-h", "127.0.0.1", "-U", "postgres", "-d", "sqlpollfixture", "-v", "ON_ERROR_STOP=1", "-v", "app_password=" + self.tokens["PG_PASSWORD"]]
self.wait(lambda: self.execute(service, command + ["-c", "select 1"], check=False)[0] == 0)
self.execute(service, command, input_bytes=(driver("Sql") / "postgres/seed-pg.sql").read_bytes())
elif service == "mysql":
self.wait(lambda: self.execute(service, ["env", "MYSQL_PWD=" + self.tokens["MYSQL_PASSWORD"], "mysqladmin", "ping", "-h", "127.0.0.1", "-uroot", "--silent"], check=False)[0] == 0, 240)
seed = (driver("Sql") / "mysql/seed-mysql.sql").read_text().replace("__APP_PASSWORD__", self.tokens["MYSQL_PASSWORD"])
self.execute(service, ["env", "MYSQL_PWD=" + self.tokens["MYSQL_PASSWORD"], "mysql", "-h", "127.0.0.1", "-uroot"], input_bytes=seed.encode())
elif service == "oracle":
self.wait(lambda: self.execute(service, ["healthcheck.sh"], check=False, timeout=20)[0] == 0, 900)
self.execute(service, ["sqlplus", "-S", "-L", "otopcua/" + self.tokens["ORACLE_PASSWORD"] + "@//127.0.0.1:1521/FREEPDB1"], input_bytes=(driver("Sql") / "oracle/seed-oracle.sql").read_bytes(), timeout=180)
elif service == "mqtt":
self.wait(lambda: self.execute(service, ["mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/ready", "-m", "ready", "-q", "1"], check=False, timeout=10)[0] == 0)
self.execute(service, ["mosquitto_pub", "-h", "127.0.0.1", "-p", "8883", "--cafile", "/mosquitto/secrets/ca.crt", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/ready", "-m", "ready", "-q", "1"])
elif service == "mqtt-publisher":
self.wait(lambda: self.execute("mqtt", ["mosquitto_sub", "-h", "127.0.0.1", "-p", "1883", "-u", "otopcua", "-P", self.tokens["MQTT_PASSWORD"], "-t", self.tokens["MQTT_PREFIX"] + "/retained/seed", "-C", "1", "-W", "5"], check=False, timeout=10)[0] == 0)
elif service.startswith("modbus-"):
port = next(iter(self.ports[service]))
args = ["python", "/fixtures/fc3_probe.py", "--port", str(port), "--deadline", "3"]
if service == "modbus-rtu-over-tcp":
args += ["--framer", "rtu"]
self.wait(lambda: self.execute(service, args, check=False, timeout=10)[0] == 0)
elif service == "mtconnect":
self.wait(lambda: self.execute(service, ["wget", "-q", "-O", "/dev/null", "http://127.0.0.1:5000/probe"], check=False)[0] == 0)
else:
for allocated in self.ports[service].values():
def tcp():
with socket.create_connection(("127.0.0.1", allocated), timeout=2):
return True
self.wait(tcp)
if service == "opc-nat":
cert = self.directory / "opc-nat-server.der"
def copy_certificate():
rc, raw = self.execute(service, ["bash", "-c", "cat /app/pki/own/certs/*.der"], check=False)
if rc or not raw:
return False
cert.write_bytes(raw)
cert.chmod(0o600)
return True
self.wait(copy_certificate, 90)
self.manifest["services"][service]["ready"] = True
self.save()
def mqtt_material(self):
directory = self.directory / "mqtt"
directory.mkdir(mode=0o700)
self.tokens["MQTT_DIR"] = directory
configuration = self.directory / "mosquitto.conf"
# Mosquitto otherwise drops root to uid1883 internally. Keep this
# loopback-only disposable broker as root so host-owned keys/password
# files can remain 0600 rather than opening secret material globally.
configuration.write_text("user root\n" + (driver("Mqtt") / "mosquitto.conf").read_text())
configuration.chmod(0o600)
self.tokens["MQTT_CONFIG"] = configuration
# Broker runs as container root, allowing restricted bind-mounted keys.
self.process(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(directory / "ca.key"), "-out", str(directory / "ca.crt"), "-days", "2", "-subj", "/CN=Owned final fixture CA", "-addext", "basicConstraints=critical,CA:TRUE"])
self.process(["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", str(directory / "server.key"), "-out", str(directory / "server.csr"), "-subj", "/CN=127.0.0.1"])
extensions = directory / "extensions.cnf"
extensions.write_text("subjectAltName=IP:127.0.0.1,DNS:localhost,DNS:mosquitto\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n")
self.process(["openssl", "x509", "-req", "-in", str(directory / "server.csr"), "-CA", str(directory / "ca.crt"), "-CAkey", str(directory / "ca.key"), "-CAcreateserial", "-out", str(directory / "server.crt"), "-days", "2", "-sha256", "-extfile", str(extensions)])
spec = {"image": "eclipse-mosquitto:2.0.22", "ports": [], "user": f"{os.getuid()}:{os.getgid()}", "mounts": [(directory, "/out", "writable")], "entrypoint": "mosquitto_passwd", "command": ["-b", "-c", "/out/passwd", "otopcua", self.tokens["MQTT_PASSWORD"]]}
self.start("mqtt-material", spec)
_, raw = self.docker("container", "wait", self.containers["mqtt-material"], timeout=60)
if raw.strip() != b"0" or not (directory / "passwd").is_file():
raise FixtureError("MQTT password material generation failed")
for path in directory.iterdir():
if path.is_file():
path.chmod(0o600)
def endpoint(self, service, port=None, scheme=""):
values = self.ports[service]
chosen = values[port] if port is not None else next(iter(values.values()))
return scheme + "127.0.0.1:" + str(chosen)
def environment_document(self):
env = {"OTOPCUA_LOCAL_FIXTURE_MODE": "1"}
if "sql" in self.ports:
endpoint = self.endpoint("sql").replace(":", ",")
env.update(OTOPCUA_CONFIG_TEST_SERVER=endpoint, OTOPCUA_CONFIG_TEST_SA_PASSWORD=self.tokens["SQL_PASSWORD"], SQL_TEST_ENDPOINT=endpoint, SQL_TEST_USER="sa", SQL_TEST_PASSWORD=self.tokens["SQL_PASSWORD"],
HISTORIAN_SQL_TEST_CONNECTION=f"Server={endpoint};User Id=sa;Password={self.tokens['SQL_PASSWORD']};TrustServerCertificate=True;Encrypt=False",
OTOPCUA_HARNESS_USE_SQL="1", OTOPCUA_HARNESS_SQL_HOST=endpoint, OTOPCUA_HARNESS_SQL_PASSWORD=self.tokens["SQL_PASSWORD"])
if "sql-blackhole" in self.ports:
env.update(SQL_BLACKHOLE_ENDPOINT=self.endpoint("sql-blackhole").replace(":", ","), SQL_BLACKHOLE_USER="sa", SQL_BLACKHOLE_PASSWORD=self.tokens["SQL_PASSWORD"],
SQL_BLACKHOLE_CONTAINER_ID=self.containers["sql-blackhole"], SQL_BLACKHOLE_FIXTURE_OWNER=self.owner,
SQL_BLACKHOLE_ENV_JSON=str(self.output), SQL_BLACKHOLE_CONTROL_SCRIPT=str(Path(__file__).resolve()))
for service, prefix, token in (("postgres", "SQL_PG", "PG_PASSWORD"), ("mysql", "SQL_MYSQL", "MYSQL_PASSWORD"), ("oracle", "SQL_ORACLE", "ORACLE_PASSWORD")):
if service in self.ports:
env.update({prefix + "_ENDPOINT": self.endpoint(service), prefix + "_USER": "otopcua", prefix + "_PASSWORD": self.tokens[token]})
if self.odbc_driver and "postgres" in self.ports:
env["SQL_ODBC_CONNECTION_STRING"] = (f"Driver={{{self.odbc_driver}}};Server=127.0.0.1;Port={self.ports['postgres'][5432]};"
f"Database=sqlpollfixture;Uid=otopcua;Pwd={self.tokens['PG_PASSWORD']};")
if "oracle" in self.ports:
env["SQL_ORACLE_SERVICE"] = "FREEPDB1"
if "questdb" in self.ports:
env["HISTORIAN_QUESTDB_TEST_CONNECTION"] = f"Host=127.0.0.1;Port={self.ports['questdb'][8812]};Username=admin;Password=quest;Database=qdb;ServerCompatibilityMode=NoTypeLoading"
if "opc" in self.ports:
env["OPCUA_SIM_ENDPOINT"] = self.endpoint("opc", scheme="opc.tcp://")
if "opc-nat" in self.ports:
env.update(OPCUA_NAT_ENDPOINT=self.endpoint("opc-nat", scheme="opc.tcp://"), OPCUA_NAT_SERVER_CERT=str(self.directory / "opc-nat-server.der"))
if "modbus-standard" in self.ports:
env.update(MODBUS_SIM_ENDPOINT=self.endpoint("modbus-standard"), MODBUS_SIM_PROFILE="standard")
if "modbus-rtu-over-tcp" in self.ports:
env["MODBUS_RTU_SIM_ENDPOINT"] = self.endpoint("modbus-rtu-over-tcp")
if "s7" in self.ports:
env.update(S7_SIM_ENDPOINT=self.endpoint("s7"), S7_SIM_ALLOW_WRITES="1")
command = [sys.executable, str(Path(__file__).resolve()), "control", "--environment-json", str(self.output), "--owner", self.owner, "--service", "s7", "--container-id", self.containers["s7"], "--verb"]
env.update(S7_RECONNECT_BOUNCE_CMD=shlex.join(command + ["restart"]), S7_TIMEOUT_OUTAGE_START_CMD=shlex.join(command + ["pause"]), S7_TIMEOUT_OUTAGE_STOP_CMD=shlex.join(command + ["unpause"]))
if "ab-controllogix" in self.ports:
endpoint = self.endpoint("ab-controllogix")
env.update(AB_SERVER_ENDPOINT=endpoint, AB_SERVER_CONTROLLOGIX_ENDPOINT=endpoint,
AB_SERVER_PROFILE="abserver", AB_SERVER_COMPOSE_PROFILE="controllogix", AB_SERVER_ALLOW_WRITES="1")
if "legacy-slc500" in self.ports:
env.update(AB_LEGACY_ENDPOINT=self.endpoint("legacy-slc500"), AB_LEGACY_CIP_PATH="1,0", AB_SERVER_ALLOW_WRITES="1")
for profile in ("slc500", "micrologix", "plc5"):
if "legacy-" + profile in self.ports:
env["AB_LEGACY_" + profile.upper() + "_ENDPOINT"] = self.endpoint("legacy-" + profile)
if "focas" in self.ports:
env.update(OTOPCUA_FOCAS_SIM_ENDPOINT=self.endpoint("focas"), OTOPCUA_FOCAS_SIM_PROFILE="FWLIB64")
if "mtconnect" in self.ports:
env.update(MTCONNECT_AGENT_ENDPOINT=self.endpoint("mtconnect", scheme="http://"), MTCONNECT_WRITE_TARGET="fixture_writeback")
if "mqtt" in self.ports:
env.update(MQTT_FIXTURE_ENDPOINT=self.endpoint("mqtt", 8883), MQTT_FIXTURE_PLAIN_ENDPOINT=self.endpoint("mqtt", 1883), MQTT_FIXTURE_USERNAME="otopcua", MQTT_FIXTURE_PASSWORD=self.tokens["MQTT_PASSWORD"], MQTT_FIXTURE_CA_CERT=str(self.directory / "mqtt/ca.crt"), MQTT_FIXTURE_TOPIC_PREFIX=self.tokens["MQTT_PREFIX"])
if "ldap" in self.ports:
env.update(OTOPCUA_HARNESS_USE_LDAP="1", OTOPCUA_HARNESS_LDAP_HOST="127.0.0.1", OTOPCUA_HARNESS_LDAP_PORT=str(self.ports["ldap"][3893]))
return env
def profile_documents(self, base):
profiles = {}
for profile in ("dl205", "mitsubishi", "s7_1500", "exception_injection"):
service = "modbus-" + profile.replace("_", "-")
if service in self.ports:
profiles["modbus-" + profile] = {**base, "MODBUS_SIM_ENDPOINT": self.endpoint(service), "MODBUS_SIM_PROFILE": profile}
for profile in ("compactlogix", "micro800", "guardlogix"):
if "ab-" + profile in self.ports:
profiles["ab-" + profile] = {**base, "AB_SERVER_ENDPOINT": self.endpoint("ab-" + profile), "AB_SERVER_COMPOSE_PROFILE": profile}
return profiles
def up(self):
self.prepare(creating=True)
self.tokens = {key: "Final1_" + secrets.token_hex(16) for key in ("SQL_PASSWORD", "PG_PASSWORD", "MYSQL_PASSWORD", "ORACLE_PASSWORD", "MQTT_PASSWORD")}
self.tokens["MQTT_PREFIX"] = "otopcua/final/" + self.owner
specs = definitions()
selected = self.input.get("CI_FIXTURE_SERVICES", "").split(",") if self.input.get("CI_FIXTURE_SERVICES") else list(specs)
if not selected or any(service not in specs for service in selected) or len(set(selected)) != len(selected):
raise FixtureError("unknown or duplicate selected fixture service")
if self.odbc_driver and "postgres" not in selected:
raise FixtureError("the local ODBC gate requires the owned seeded PostgreSQL fixture")
for service, prerequisite in (("mqtt-publisher", "mqtt"), ("mtconnect", "mtconnect-adapter")):
if service in selected and prerequisite not in selected:
raise FixtureError("selected fixture service requires its local prerequisite")
network_name = self.project + "-network"
# Docker may omit host publications on an internal-only network.
# The run owns this bridge and publishes each service on loopback.
self.network = self.create("network", network_name,
["network", "create", "--driver", "bridge", *self.label_args(), network_name])
if "mqtt" in selected:
self.mqtt_material()
for service in selected:
self.start(service, specs[service])
env = self.environment_document()
private_json(self.output, env, exclusive=True)
private_json(self.directory / "profile-environments.json", self.profile_documents(env), exclusive=True)
self.manifest["status"] = "ready"
self.save()
def recover_pending(self):
# A process may die after Docker creates a resource but before its ID is
# journaled. A pending exact name is only a lookup key: labels and immutable
# ID must still be validated before it enters the cleanup inventory.
for pending in self.manifest["pending"]:
row = self.inspect(pending["kind"], pending["name"], missing=True)
if row is None:
continue
if any(self.observed_labels(pending["kind"], row).get(k) != v for k, v in self.labels.items()):
raise FixtureError("pending name belongs to a foreign resource; refusing cleanup")
identity = row["Name"] if pending["kind"] == "volume" else row["Id"].removeprefix("sha256:")
self.manifest["resources"].append({**pending, "id": identity, "labels": self.labels})
self.manifest["pending"] = []
self.save()
def down(self):
self.prepare(creating=False)
self.recover_pending()
self.validate_manifest()
# Validate the entire inventory before removing anything. Then recheck
# each ID immediately before mutation, preventing name substitution.
for row in self.manifest["resources"]:
self.verified(row["kind"], row["id"], missing=True)
order = {"container": 0, "network": 1, "volume": 2, "image": 3}
for row in sorted(self.manifest["resources"], key=lambda item: order[item["kind"]]):
if self.verified(row["kind"], row["id"], missing=True) is None:
continue
argv = [row["kind"], "rm"] + (["--force"] if row["kind"] == "container" else []) + [row["id"]]
self.docker(*argv)
self.manifest["status"] = "removed"
self.save()
def logs(self):
self.prepare(creating=False)
for row in self.manifest["resources"]:
if row["kind"] == "container" and self.verified("container", row["id"], missing=True):
self.docker("container", "logs", "--tail", "200", row["id"], check=False)
def control(self, service, identity, verb, endpoint=None):
if service not in {"s7", "sql-blackhole"} or verb not in {"pause", "unpause", "restart", "verify"}:
raise FixtureError("unsupported local fixture control action")
self.prepare(creating=False)
if self.manifest.get("status") != "ready" or self.manifest.get("services", {}).get(service, {}).get("container_id") != identity:
raise FixtureError("control requires a ready fixture and its exact recorded service ID")
observed = self.verified("container", identity)
def verify_s7_publication(row):
recorded = self.manifest["services"]["s7"]
published = recorded.get("ports", {}).get("1102")
bindings = row.get("NetworkSettings", {}).get("Ports", {}).get("1102/tcp")
if (recorded.get("stable_ports") is not True or type(published) is not int or not 1 <= published <= 65535
or bindings != [{"HostIp": "127.0.0.1", "HostPort": str(published)}]):
raise FixtureError("S7 endpoint does not match its owned stable publication")
if service == "s7":
verify_s7_publication(observed)
if service == "sql-blackhole":
published = self.manifest["services"][service].get("ports", {}).get("1433")
bindings = observed.get("NetworkSettings", {}).get("Ports", {}).get("1433/tcp")
if endpoint != f"127.0.0.1,{published}" or bindings != [{"HostIp": "127.0.0.1", "HostPort": str(published)}]:
raise FixtureError("blackhole endpoint does not match its owned container publication")
if verb != "verify":
self.docker("container", verb, identity, timeout=60)
if service == "s7" and verb == "restart":
verify_s7_publication(self.verified("container", identity))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("up", "down", "logs", "control"))
parser.add_argument("--environment-json")
parser.add_argument("--owner")
parser.add_argument("--service")
parser.add_argument("--container-id")
parser.add_argument("--verb")
parser.add_argument("--endpoint")
args = parser.parse_args(argv)
try:
if args.action == "control":
environment = {**os.environ, "CI_FIXTURE_LOCAL_OWNED": "1", "FIXTURE_HOST": "127.0.0.1", "CI_FIXTURE_ENV_JSON": args.environment_json or "", "CI_FIXTURE_SUFFIX": args.owner or ""}
fixtures = OwnedFixtures(environment)
fixtures.control(args.service, args.container_id, args.verb, args.endpoint)
else:
fixtures = OwnedFixtures()
getattr(fixtures, args.action)()
print(json.dumps({"status": args.action + " complete", "environment_json": str(fixtures.output)}))
return 0
except (FixtureError, RigError, OSError, ValueError, KeyError, KeyboardInterrupt):
# Keep journal and logs for an explicit same-owner down after any failure.
print("local owned fixtures failed; inspect the private run directory and use same-owner down", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())