"""Standalone local Docker fixture, with pure safety and polling boundaries.""" import argparse import copy from contextlib import contextmanager import ipaddress import json import math import os from pathlib import Path import re import tempfile import time from urllib.parse import urljoin, urlsplit import uuid class RigError(RuntimeError): """The local gate cannot safely proceed.""" def bundle_commit_matches(expected, observed): """Require both production stores to acknowledge the exact published scope/version.""" if not isinstance(expected, dict) or not isinstance(observed, dict): return False if type(expected.get("scopeVersion")) is not int or expected["scopeVersion"] <= 0: return False if not all(type(observed.get(key)) is int and observed[key] == expected["scopeVersion"] for key in ("credentialScopeVersion", "trustScopeVersion")): return False if expected.get("kind") == "scope-only": return all(observed.get(key) is None for key in ("credentialVersion", "trustVersion", "credentialDeleted", "trustRetired")) if expected.get("kind", "entry") != "entry" or any(type(expected.get(key)) is not int or expected[key] <= 0 for key in ("credentialVersion", "trustVersion")): return False pairs = (("credentialScopeVersion", "scopeVersion"), ("trustScopeVersion", "scopeVersion"), ("credentialVersion", "credentialVersion"), ("trustVersion", "trustVersion")) return (all(type(observed.get(actual)) is int and observed[actual] == expected[wanted] for actual, wanted in pairs) and all(type(expected.get(flag, False)) is bool and observed.get(flag) is expected.get(flag, False) for flag in ("credentialDeleted", "trustRetired"))) def deployment_bundle_expectations(scope, published, *, selected=None): """Wait only for enabled scope entries actually published to required consumers.""" required = scope.get("required_node_ids") connections = scope.get("connections") if not isinstance(required, list) or not isinstance(connections, list) or not isinstance(published, list): raise RigError("published deployment bundle inventory is missing") consumers = NODES[2:] if selected is None else selected wanted = {(node, item["connection_id"]) for item in connections for node in consumers if node + ":4053" in required and node + ":4053" in item["consumer_node_ids"]} scope_only_nodes = {node for node in consumers if node + ":4053" in required and not any(pair[0] == node for pair in wanted)} wanted.update((node, "fixture-scope-only") for node in scope_only_nodes) selected = [] seen = set() for entry in published: pair = (entry.get("node"), entry.get("connectionId")) if pair not in wanted: continue if (pair in seen or (entry.get("kind") == "scope-only") != (pair[0] in scope_only_nodes) or entry.get("scopeVersion") != scope.get("scope_version") or not bundle_commit_matches(entry, { "credentialScopeVersion": entry.get("scopeVersion"), "trustScopeVersion": entry.get("scopeVersion"), "credentialVersion": entry.get("credentialVersion"), "trustVersion": entry.get("trustVersion"), "credentialDeleted": entry.get("credentialDeleted", False), "trustRetired": entry.get("trustRetired", False)})): raise RigError("published deployment bundle inventory is invalid") seen.add(pair) selected.append(dict(entry)) if seen != wanted: raise RigError("required deployment bundle entry was not published") return selected RUN_LABEL = "otopcua.grpc-data.run" PROJECT_LABEL = "com.docker.compose.project" _RUN_PATTERN = re.compile(r"[a-z0-9][a-z0-9-]{0,47}\Z") _SERVICE_PATTERN = re.compile(r"[a-z][a-z0-9-]{0,62}\Z") _URL_PATTERN = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*://[^\s;\"'<>]+") _DB_HOST_PATTERN = re.compile(r"(?:^|[;(\s])(?:Server|Host|Data\s+Source|Address|Addr|Network\s+Address)\s*=\s*([^;)\s]+)", re.I) def validate_local_docker(endpoint): """Allow only a local Unix socket or the local Windows Docker named pipe.""" if not isinstance(endpoint, str) or not endpoint or any(character in endpoint for character in "\r\n\0"): raise RigError("Docker requires an explicit local socket endpoint") try: parsed = urlsplit(endpoint) except ValueError: raise RigError("invalid Docker socket endpoint") from None if parsed.query or parsed.fragment: raise RigError("Docker socket endpoint cannot have a query or fragment") if parsed.scheme == "unix" and not parsed.netloc and parsed.path.startswith("/") and parsed.path != "/": if ".." not in Path(parsed.path).parts: return if endpoint.lower().startswith("npipe:////./pipe/") and parsed.path[len("//./pipe/"):] and ".." not in parsed.path.split("/"): return raise RigError("Docker daemon must use a local unix socket or npipe; remote/TCP contexts are forbidden") def validate_docker_context(context, *, environment): """Validate the actual `docker context inspect` row and overriding variables. A context name is not locality evidence. The caller must obtain this row read-only for the selected context before any Docker mutation. """ if not isinstance(context, dict) or not isinstance(environment, dict): raise RigError("Docker context inspection and environment are required") name = context.get("Name") try: endpoint = context["Endpoints"]["docker"]["Host"] except (KeyError, TypeError): raise RigError("Docker context has no inspected daemon endpoint") from None if not isinstance(name, str) or not name: raise RigError("Docker context has no name") validate_local_docker(endpoint) if environment.get("DOCKER_HOST"): validate_local_docker(environment["DOCKER_HOST"]) if environment["DOCKER_HOST"] != endpoint: raise RigError("Docker host override differs from the inspected context") if environment.get("DOCKER_CONTEXT") and environment["DOCKER_CONTEXT"] != name: raise RigError("Docker context override differs from the inspected context") def _loopback(host): if host == "localhost": return True try: address = ipaddress.ip_address(host) return address.is_loopback or bool(getattr(address, "ipv4_mapped", None) and address.ipv4_mapped.is_loopback) except (ValueError, TypeError): return False def _host_allowed(host, services): return isinstance(host, str) and (_loopback(host) or host in services) def _plain_host(value): value = value.strip().strip("\"'") if value.lower().startswith("tcp:"): value = value[4:] if value.startswith("["): end = value.find("]") return value[1:end] if end >= 0 else value if value.count(":") > 1: return value return re.split(r"[,:/\\]", value, maxsplit=1)[0] def validate_fixture_endpoints(document, *, local_services): """Reject endpoint escape in resolved Compose/config/seed data, without DNS. Pass resolved data, never a YAML file with uninterpreted environment expansion. Image registries are build inputs; endpoint URLs, SQL connection hosts, and host/server/address configuration values must name an explicit local service or loopback. No arbitrary private subnet is treated as local. """ services = set(local_services) if not services or any(not isinstance(name, str) or not _SERVICE_PATTERN.fullmatch(name) for name in services): raise RigError("an explicit local service allowlist is required") def check_host(host): if not _host_allowed(host, services): # Do not echo source values: a malformed URL/connection can contain a key. raise RigError("fixture endpoint is outside loopback and run-owned service DNS") def walk(value, key=""): if isinstance(value, dict): for child_key, child in value.items(): walk(child, str(child_key)) elif isinstance(value, (list, tuple)): for child in value: walk(child, key) elif isinstance(value, str): if "${" in value: raise RigError("fixture configuration must be fully resolved") urls = _URL_PATTERN.findall(value) for url in urls: try: parsed = urlsplit(url) host = parsed.hostname except ValueError: raise RigError("fixture endpoint URL is invalid") from None check_host(host) akka_seed = (parsed.scheme == "akka.tcp" and parsed.username == "otopcua" and parsed.password is None and parsed.path == "" and not parsed.query and not parsed.fragment and re.fullmatch(r"(?:Cluster__SeedNodes__|Cluster:SeedNodes:)\d+|SeedNodes", key) is not None) if (parsed.username is not None or parsed.password is not None) and not akka_seed: raise RigError("fixture endpoint URLs cannot contain credentials") db_hosts = _DB_HOST_PATTERN.findall(value) for host in db_hosts: check_host(_plain_host(host)) suffix = re.split(r"__|:", key)[-1].lower() if not urls and not db_hosts and suffix in {"host", "hostname", "publichostname", "server", "address", "endpoint"}: check_host(_plain_host(value)) # An IP endpoint hidden in an unfamiliar option must not pass merely # because its key does not match an expected Host/Server suffix. for match in re.findall(r"(?= deadline: raise RigError("deployment request exceeded polling deadline timeout") return response status, response_headers, body = call("POST", origin + "/api/deployments", None if created_by is None else {"createdBy": created_by}) if status == 409: raise RigError("another deployment is in flight; no new trigger was sent") if not isinstance(body, dict) or (status, body.get("outcome")) not in {(202, "Accepted"), (200, "NoChanges")}: raise RigError("deployment trigger was rejected or returned an unexpected outcome") deployment_id = _deployment_id(body.get("deploymentId")) revision = body.get("revisionHash") if not _required_text(revision): raise RigError("deployment trigger has no expected revision") expected_location = f"/api/deployments/{deployment_id}" if not isinstance(response_headers, dict): raise RigError("deployment response headers are invalid") location = next((value for key, value in response_headers.items() if key.lower() == "location"), None) if status == 202 and not location: raise RigError("accepted deployment has no Location") poll_url = origin + expected_location if location is not None: if not isinstance(location, str) or urljoin(origin + "/", location) != poll_url: raise RigError("deployment Location does not match the same local origin and deployment") if on_accepted is not None: required = on_accepted(deployment_id, revision) if required is not None: if (not isinstance(required, (set, frozenset, list, tuple)) or not required or any(not isinstance(node, str) for node in required) or not set(required) <= expected_nodes): raise RigError("deployment required-node inventory is outside the owned topology") expected_nodes = set(required) while True: status, _, body = call("GET", poll_url) if status != 200: raise RigError("deployment status resource did not return HTTP 200") if _status_complete(body, deployment_id, revision, expected_nodes): return body remaining = deadline - clock() if remaining <= 0: raise RigError("deployment polling deadline timeout") sleep(min(poll_interval, remaining)) _PREREQUISITES = { "preflight": ("docker_context_inspector", "resolved_composition"), "up": ("resolved_composition", "current_source_image_builder", "local_sql_migrator", "pair_starter", "health_role_catalog_observer", "tls_and_scoped_secret_provisioner"), "seed": ("production_validating_seeder", "namespace_identity_resolver", "credential_file_writer"), "deploy": ("deployment_transport", "intended_node_identities", "runtime_revision_observer"), "down": ("restricted_manifest", "resource_label_inspector", "exact_resource_remover"), } def require_production_prerequisites(action, available): """Report incomplete wiring rather than fabricating successful rig actions.""" if action not in _PREREQUISITES: raise RigError("unknown rig action") missing = [name for name in _PREREQUISITES[action] if not available.get(name)] if missing: raise RigError(f"{action} prerequisites not configured: {', '.join(missing)}") # Runtime composition. Every subprocess is argv-only, bounded and captures output; # failed child diagnostics are deliberately withheld because Docker can echo env. ROOT = Path(__file__).resolve().parents[3] HERE = Path(__file__).resolve().parent NODES = tuple(f"{pair}-{n}" for pair in ("control", "source", "consumer") for n in (1, 2)) SERVICES = ("sql", "migrator", "device", "seeder", *NODES) def run_command(argv, *, timeout=120, environment=None): from processes import ProcessError, run_process import threading if not isinstance(argv, list) or not argv or any(not isinstance(arg, str) or "\0" in arg for arg in argv): raise RigError("invalid subprocess argv") progress = None observer = None run_id = (environment or {}).get("GRPC_DATA_RUN_ID") if run_id and _RUN_PATTERN.fullmatch(run_id): log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics" log_dir.mkdir(parents=True, exist_ok=True, mode=0o700) if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked") fd = os.open(log_dir / (uuid.uuid4().hex + ".progress.log"), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) progress = os.fdopen(fd, "w") lock = threading.Lock() def observer(stream, chunk): with lock: progress.write(chunk); progress.flush() try: result = run_process(argv, cwd=ROOT, environment=environment, timeout=timeout, max_output_bytes=16 * 1024 * 1024, observer=observer) except (OSError, ProcessError): raise RigError("local tool failed or exceeded its deadline; credentials withheld") from None finally: if progress is not None: progress.close() if result.returncode or result.cancelled or result.timed_out or result.truncated: run_id = (environment or {}).get("GRPC_DATA_RUN_ID") if run_id and _RUN_PATTERN.fullmatch(run_id): log_dir = ROOT / "artifacts" / "grpc-data" / "runs" / run_id / "diagnostics" log_dir.mkdir(parents=True, exist_ok=True, mode=0o700) if log_dir.is_symlink(): raise RigError("diagnostics directory cannot be linked") name = uuid.uuid4().hex atomic_write_secret(log_dir / (name + ".stdout.log"), result.stdout or "(empty)\n") atomic_write_secret(log_dir / (name + ".stderr.log"), result.stderr or "(empty)\n") raise RigError("local tool returned failure; inspect restricted run diagnostics locally") return result.stdout 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() def device_tree_hash(): """Identify the fixture protocol/ledger implementation independently of Hosts.""" import hashlib digest = hashlib.sha256() for name in ("Dockerfile", "server.py"): path = HERE / "device" / name if path.is_symlink() or not path.is_file(): raise RigError("device fixture input is unavailable") digest.update(name.encode() + b"\0" + path.read_bytes()) return digest.hexdigest() def docker_context(): name = run_command(["docker", "context", "show"]).strip() rows = json.loads(run_command(["docker", "context", "inspect", name])) if not isinstance(rows, list) or len(rows) != 1: raise RigError("Docker context inspection was ambiguous") validate_docker_context(rows[0], environment=dict(os.environ)) return rows[0] def http_request(method, url, *, headers, json_body=None, timeout=10): import urllib.request import urllib.error class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, hdrs, newurl): return None data = None if json_body is None else json.dumps(json_body).encode() request = urllib.request.Request(url, data=data, headers={**headers, **({"Content-Type": "application/json"} if data else {})}, method=method) opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) try: response = opener.open(request, timeout=min(timeout, 15)) except urllib.error.HTTPError as error: response = error with response: raw = response.read(1024 * 1024 + 1) if len(raw) > 1024 * 1024: raise RigError("HTTP response exceeded limit") try: body = json.loads(raw) if raw else None except (ValueError, UnicodeError): body = None return response.status, dict(response.headers), body def wait_until(predicate, *, timeout, description, interval=1): deadline = time.monotonic() + timeout while time.monotonic() < deadline: try: if predicate(): return except (OSError, ValueError, RigError): pass time.sleep(min(interval, max(0, deadline - time.monotonic()))) raise RigError(f"deadline waiting for {description}") def observe_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None): """Observe the whole pair; one failed endpoint cannot hide its partner.""" _duration(timeout, "active endpoint observation timeout") if not isinstance(node_urls, dict) or len(node_urls) != 2: raise RigError("an explicit two-node active endpoint inventory is required") clock = clock or time.monotonic deadline = clock() + timeout active = [] for node, origin in node_urls.items(): remaining = deadline - clock() if remaining <= 0: return None # An incomplete pair observation cannot select a node. try: status, _, _ = request("GET", origin.rstrip("/") + "/health/active", headers={}, timeout=min(5, remaining)) except OSError: continue if status == 200: active.append(node) if len(active) > 1: raise RigError("pair has more than one observed active node") if not active or clock() >= deadline: return None selected = active[0] if require_ready: remaining = deadline - clock() if remaining <= 0: return None try: status, _, _ = request("GET", node_urls[selected].rstrip("/") + "/health/ready", headers={}, timeout=min(5, remaining)) except OSError: return None if status != 200 or clock() >= deadline: return None return selected def wait_active_endpoint(node_urls, *, request, timeout, require_ready=False, clock=None, sleep=None): """Bound startup/election polling without retrying any deployment mutation.""" _duration(timeout, "active endpoint selection timeout") clock, sleep = clock or time.monotonic, sleep or time.sleep deadline = clock() + timeout while True: remaining = deadline - clock() if remaining <= 0: raise RigError("deadline waiting for one ready active endpoint") selected = observe_active_endpoint(node_urls, request=request, timeout=min(15, remaining), require_ready=require_ready, clock=clock) if selected is not None: return selected remaining = deadline - clock() if remaining <= 0: raise RigError("deadline waiting for one ready active endpoint") sleep(min(1, remaining)) class LocalRig: def __init__(self, run_id, *, base=None): if not _RUN_PATTERN.fullmatch(run_id or ""): raise RigError("a safe explicit --run-id is required") self.run_id = run_id self.folder = (Path(base) if base else ROOT / "artifacts" / "grpc-data" / "runs") / run_id self.path = self.folder / "manifest.json" self.project = "grpc-data-" + run_id self.environment = dict(os.environ) self.environment["COMPOSE_PROJECT_NAME"] = self.project self.context = docker_context() self.docker = ["docker", "--context", self.context["Name"]] if self.folder.exists(): if self.folder.is_symlink() or self.folder.stat().st_mode & 0o077: raise RigError("run directory must be restricted and cannot be a symlink") env_path = self.folder / "environment.json" if env_path.exists(): self.environment.update(json.loads(env_path.read_text())) def compose(self, *args, timeout=120): return run_command([*self.docker, "compose", "--project-name", self.project, "--file", str(HERE / "compose.yml"), *args], timeout=timeout, environment=self.environment) @contextmanager def hub_partitions(self, count): """Restart only the owned SOURCE pair with an explicit hub partition count. Port allocation changes when Compose recreates a container, so every transition refreshes the canonical manifest before readiness polling. """ if type(count) is not int or not 1 <= count <= 256: raise RigError("hub partition count must be between 1 and 256") with self._configuration_experiment("hub-partitions", ("source-1", "source-2"), {"DataConnections__Hub__PartitionCount": str(count)}): yield @contextmanager def compact_batches(self, enabled): """Exercise the production caller's negotiated encoding preference.""" if type(enabled) is not bool: raise RigError("compact encoding preference must be boolean") with self._configuration_experiment("compact-batches", ("consumer-1", "consumer-2"), {"DataConnections__UseCompactBatches": str(enabled).lower()}): yield @contextmanager def _configuration_experiment(self, name, nodes, environment, *, before_restore=None): override = self.folder / (name + ".json") if override.exists(): raise RigError("a configuration experiment is already present") def transition(extra): # Inspect exact project resources before changing its owned services. self.inspect_resources() run_command([*self.docker, "compose", "--project-name", self.project, "--file", str(HERE / "compose.yml"), *extra, "up", "--detach", "--no-deps", *nodes], timeout=300, environment=self.environment) manifest = self.refresh_endpoints(nodes) self.capture(manifest) wait_until(lambda: self.health(manifest), timeout=180, description="configuration experiment pair readiness") atomic_write_secret(override, json.dumps({"services": {node: {"environment": environment} for node in nodes}})) try: transition(["--file", str(override)]) yield finally: try: if before_restore is not None: before_restore() transition([]) finally: override.unlink(missing_ok=True) def save(self, manifest): atomic_write_secret(self.path, json.dumps(manifest, indent=2, sort_keys=True) + "\n") def load(self): if not self.path.is_file() or self.path.is_symlink(): raise RigError("restricted run manifest is missing") manifest = json.loads(self.path.read_text()) validate_manifest(manifest, expected_run_id=self.run_id) if manifest.get("docker_context") != self.context["Name"]: raise RigError("selected Docker context differs from the recorded run") return manifest def verify_candidate(self): """Match every running Host binary stamp to the actual compiled inputs.""" manifest = self.load() expected = source_tree_hash() if manifest.get("source_tree_hash") != expected: raise RigError("running manifest does not match current image build inputs") 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"): raise RigError("running Host build stamp does not match the candidate") device_hash = device_tree_hash() if manifest.get("device_source_hash") != device_hash: raise RigError("device manifest does not match current fixture inputs") observed = self.compose("exec", "--no-TTY", "device", "cat", "/fixture/source-hash", timeout=15).strip() if observed != device_hash: raise RigError("running device fixture does not match current protocol/ledger inputs") return expected def inspect_resources(self): resources = [] for kind, listing in (("container", ["container", "ls", "-a", "-q"]), ("network", ["network", "ls", "-q"]), ("volume", ["volume", "ls", "-q"]), ("image", ["image", "ls", "-q"])): ids = run_command([*self.docker, *listing, "--filter", f"label={RUN_LABEL}={self.run_id}", "--filter", f"label={PROJECT_LABEL}={self.project}"]).split() for identity in dict.fromkeys(ids): row = json.loads(run_command([*self.docker, kind, "inspect", identity]))[0] labels = row.get("Config", {}).get("Labels") if kind in {"container", "image"} else row.get("Labels") if not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id or labels.get(PROJECT_LABEL) != self.project: raise RigError("observed Docker object ownership mismatch") resources.append({"kind": kind, "id": row.get("Id", row.get("Name")), "labels": labels}) return resources def capture(self, manifest): manifest["resources"] = self.inspect_resources() self.save(manifest) def allocate_manifest(self): endpoints = {} for node in (*NODES, "sql", "device"): ids = self.compose("ps", "--all", "--quiet", node).split() if len(ids) != 1: raise RigError("fixture must contain exactly one container per service") row = json.loads(run_command([*self.docker, "container", "inspect", ids[0]]))[0] for container_port, bindings in row["NetworkSettings"]["Ports"].items(): if not bindings: continue port = int(container_port.split("/")[0]) if len(bindings) != 1 or bindings[0]["HostIp"] != "127.0.0.1": raise RigError("Docker published a fixture port outside loopback") suffix = {9000: "admin", 4840: "opcua", 4057: "data", 1433: "sql", 5020: "modbus", 8080: "control"}[port] scheme = {4840: "opc.tcp", 4057: "https", 1433: "tcp", 5020: "tcp"}.get(port, "http") host_port = int(bindings[0]["HostPort"]) path = "/OtOpcUa" if port == 4840 else "" endpoints[f"{node}.{suffix}"] = {"scheme": scheme, "host": "127.0.0.1", "host_port": host_port, "container_host": node, "container_port": port, "url": f"{scheme}://127.0.0.1:{host_port}{path}"} return {"schema_version": 1, "run_id": self.run_id, "project": self.project, "labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project}, "services": list(SERVICES), "docker_context": self.context["Name"], "endpoints": endpoints, "resources": [], "nodes": {node: {"cluster_id": node.split("-")[0].upper(), "node_id": node + ":4053", "application_uri": "urn:OtOpcUa:grpc-data:" + node} for node in NODES}, "tls": {"ca_file": str(self.folder / "security" / "ca.pem")}, "state": "started"} def refresh_endpoints(self, nodes): """Refresh only restarted owned services, preserving intentionally stopped peers.""" if (not isinstance(nodes, (tuple, list)) or not nodes or any(not isinstance(node, str) or node not in NODES for node in nodes) or len(nodes) != len(set(nodes))): raise RigError("endpoint refresh requires unique owned node services") manifest = copy.deepcopy(self.load()) for node in nodes: ids = self.compose("ps", "--all", "--quiet", node).split() if len(ids) != 1: raise RigError("endpoint refresh requires exactly one owned service container") try: rows = json.loads(run_command([*self.docker, "container", "inspect", ids[0]])) if not isinstance(rows, list) or len(rows) != 1: raise ValueError() row = rows[0] labels = row.get("Config", {}).get("Labels", {}) if (not isinstance(labels, dict) or labels.get(RUN_LABEL) != self.run_id or labels.get(PROJECT_LABEL) != self.project or labels.get("com.docker.compose.service") != node or row.get("State", {}).get("Running") is not True): raise ValueError() ports = row["NetworkSettings"]["Ports"] expected = {"4840/tcp": ("opcua", "opc.tcp"), "9000/tcp": ("admin", "http")} if not node.startswith("control-"): expected["4057/tcp"] = ("data", "https") if not isinstance(ports, dict) or any(bindings and port not in expected for port, bindings in ports.items()): raise ValueError() for port, (suffix, scheme) in expected.items(): bindings = ports.get(port) if (not isinstance(bindings, list) or len(bindings) != 1 or bindings[0].get("HostIp") != "127.0.0.1"): raise ValueError() allocated = int(bindings[0]["HostPort"]) if not _port(allocated): raise ValueError() container_port = int(port.split("/")[0]) path = "/OtOpcUa" if suffix == "opcua" else "" manifest["endpoints"][node + "." + suffix] = {"scheme": scheme, "host": "127.0.0.1", "host_port": allocated, "container_host": node, "container_port": container_port, "url": f"{scheme}://127.0.0.1:{allocated}{path}"} except (ValueError, TypeError, KeyError, AttributeError): raise RigError("endpoint refresh requires an owned running container with complete loopback bindings") from None validate_manifest(manifest, expected_run_id=self.run_id) self.save(manifest) return manifest def up(self, timeout=600): import secrets import credentials if self.folder.exists(): raise RigError("run already exists; use status or owned down before reusing its id") self.folder.mkdir(parents=True, mode=0o700) os.chmod(self.folder, 0o700) atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project})) revision = run_command(["git", "rev-parse", "HEAD"]).strip() tree_hash = source_tree_hash() settings = {"GRPC_DATA_UID": str(os.getuid()) if hasattr(os, "getuid") else "0", "GRPC_DATA_GID": str(os.getgid()) if hasattr(os, "getgid") else "0", "GRPC_DATA_RUN_ID": self.run_id, "GRPC_DATA_PROJECT": self.project, "SOURCE_REVISION": revision, "SOURCE_TREE_HASH": tree_hash, "DEVICE_TREE_HASH": device_tree_hash(), "GRPC_DATA_IMAGE": f"otopcua-grpc-data:{self.run_id}", "GRPC_DATA_MIGRATOR_IMAGE": f"otopcua-grpc-migrator:{self.run_id}", "GRPC_DATA_DEVICE_IMAGE": f"otopcua-grpc-device:{self.run_id}", "GRPC_DATA_SEED_IMAGE": f"otopcua-grpc-seed:{self.run_id}", "GRPC_DATA_CERT_DIR": str(self.folder / "security" / "tls"), "GRPC_DATA_CREDENTIAL_DIR": str(self.folder / "security" / "credentials"), "GRPC_DATA_OUTPUT_DIR": str(self.folder / "seed"), "GRPC_DATA_PROBE_DIR": str(self.folder / "probe")} for name in ("APIKEY_PEPPER", "JWT_KEY", "DEPLOY_KEY", "CONFIG_KEY", "TELEMETRY_KEY", "MESH_PSK_CONTROL", "MESH_PSK_SOURCE", "MESH_PSK_CONSUMER", "SYNC_KEY_SOURCE", "SYNC_KEY_CONSUMER"): settings["GRPC_DATA_" + name] = secrets.token_hex(32) settings["GRPC_DATA_SQL_PASSWORD"] = "Gd!" + secrets.token_hex(24) import base64 settings["GRPC_DATA_SECRETS_KEK"] = base64.b64encode(secrets.token_bytes(32)).decode() atomic_write_secret(self.folder / "environment.json", json.dumps(settings)) self.environment.update(settings) credentials.provision_tls(self.folder / "security", NODES[2:]) (self.folder / "security" / "credentials").mkdir(mode=0o700) for node in NODES[2:]: (self.folder / "security" / "credentials" / node).mkdir(parents=True, mode=0o700) (self.folder / "seed").mkdir(mode=0o700) (self.folder / "probe").mkdir(mode=0o700) for node in NODES: (self.folder / "probe" / node).mkdir(parents=True, mode=0o700) # Save a restricted setup journal before the first mutation, so interrupted # builds can still be collected by exact observed object IDs on `down`. atomic_write_secret(self.folder / "setup.json", json.dumps({"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project})) 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("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"] 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" self.capture(manifest) return manifest except BaseException: # Capture whatever exists; no broad compose down/prune is permitted. atomic_write_secret(self.folder / "interrupted-resources.json", json.dumps(self.inspect_resources())) raise def health(self, manifest, *, require_catalog=False, timeout=None): deadline = None if timeout is None else time.monotonic() + timeout def request_timeout(): remaining = 5 if deadline is None else deadline - time.monotonic() if remaining <= 0: raise RigError("fixture readiness deadline timeout") return min(5, remaining) active = {} for node in NODES: origin = manifest["endpoints"][node + ".admin"]["url"] status, _, _ = http_request("GET", origin + "/health/ready", headers={}, timeout=request_timeout()) if status != 200: return False status, _, _ = http_request("GET", origin + "/health/active", headers={}, timeout=request_timeout()) active[node] = status == 200 if any(sum(active[node] for node in NODES if node.startswith(pair + "-")) != 1 for pair in ("control", "source", "consumer")): return False if require_catalog: # Namespace resolution reads through real OPC UA sessions on all six # hosts, validates each URI, and requires Good fixture leaf values. remaining = 120 if deadline is None else deadline - time.monotonic() if remaining <= 0: raise RigError("fixture catalog readiness deadline timeout") self.seed_helper("resolve", timeout=min(120, remaining)) if deadline is not None and time.monotonic() >= deadline: raise RigError("fixture readiness exceeded its deadline") return True def seed_helper(self, action, *arguments, timeout=120): self.compose("run", "--rm", "--no-deps", "seeder", action, *arguments, timeout=timeout) def seed(self): manifest = self.load() self.seed_helper("seed") fixture = json.loads((self.folder / "seed" / "fixture.json").read_text()) validate_fixture_endpoints(fixture.get("endpoints", {}), local_services=SERVICES) manifest["fixture"] = fixture manifest["node_probe_dirs"] = {node: str(self.folder / "probe" / node) for node in NODES} manifest["credentials"] = {"cli_key_file": str(self.folder / "seed" / "cli.key"), "data_key_files": {"source": str(self.folder / "seed" / "source.key")}} manifest["state"] = "seeded" self.capture(manifest) return manifest def provision_deployment(self, deployment_id, revision, *, timeout=120): import credentials self.seed_helper("scope", deployment_id, revision, timeout=timeout) scope = json.loads((self.folder / "seed" / "scope.json").read_text()) published = self.publish_scope(scope) scope["bundle_expectations"] = deployment_bundle_expectations(scope, published) return scope def bundle_version(self, node): directory = self.folder / "security" / "credentials" / node bundle = directory / "bundle.json" generation = directory / "generation.txt" return max(json.loads(bundle.read_text())["Version"] if bundle.exists() else 0, int(generation.read_text()) if generation.exists() else 0) + 1 def publish_scope(self, scope, *, selected=None, deleted=False): import base64 import credentials key = (self.folder / "seed" / "source.key").read_text().strip() state_path = self.folder / "trust-state.json" ca_files = json.loads(state_path.read_text())["roots"] if state_path.exists() else [str(self.folder / "security" / "ca.pem")] roots = [base64.b64encode(credentials._openssl("x509", "-in", path, "-outform", "DER")).decode("ascii") for path in ca_files] nodes = {} for node in selected if selected is not None else NODES[2:]: entries = [{"ConnectionId": item["connection_id"], "SecretReference": item["secret_reference"], "Value": None if deleted else key, "Deleted": deleted} for item in scope["connections"] if node + ":4053" in item["consumer_node_ids"]] version = self.bundle_version(node) nodes[node] = {"owner": node.split("-")[0].upper(), "scope_version": scope["scope_version"], "entries": entries, "bundle_version": version, "trust_version": version, "trust_roots": roots} directory = self.folder / "security" / "credentials" / node for name in ("bundle", "trust"): current = directory / (name + ".json") if current.exists(): atomic_write_secret(directory / (name + "-previous.json"), current.read_text()) credentials.write_bundles(self.folder / "security", nodes) for node, spec in nodes.items(): atomic_write_secret(self.folder / "security" / "credentials" / node / "generation.txt", str(spec["bundle_version"])) entries = [{"node": node, "connectionId": entry["ConnectionId"], "scopeVersion": spec["scope_version"], "kind": "entry", "credentialVersion": spec["bundle_version"], "trustVersion": spec["trust_version"], "credentialDeleted": entry["Deleted"], "trustRetired": False} for node, spec in nodes.items() for entry in spec["entries"]] return entries + [{"node": node, "connectionId": "fixture-scope-only", "kind": "scope-only", "scopeVersion": spec["scope_version"], "credentialVersion": None, "trustVersion": None, "credentialDeleted": None, "trustRetired": None} for node, spec in nodes.items() if not spec["entries"]] def wait_bundle_commits(self, expectations, *, timeout): """Observe exact numeric acknowledgements through each caller's production DI stores.""" _duration(timeout, "bundle commit readiness timeout") if not isinstance(expectations, list): raise RigError("published bundle expectations are missing") deadline = time.monotonic() + timeout records = [] safe_fields = ("credentialScopeVersion", "credentialVersion", "trustScopeVersion", "trustVersion", "credentialDeleted", "trustRetired") diagnostics = self.folder / "seed" / "bundle-commit-readiness.json" atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) for expected in expectations: node = expected["node"] folder = self.folder / "probe" / node if node not in NODES[2:] or folder.is_symlink() or not folder.is_dir(): raise RigError("bundle acknowledgement requires an owned data-node probe directory") record = {"node": node, "connectionId": expected["connectionId"], "expected": {key: expected[key] for key in ("scopeVersion", "credentialVersion", "trustVersion", "credentialDeleted", "trustRetired")}, "observed": None, "matched": False} record["expected"]["kind"] = expected.get("kind", "entry") records.append(record) atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) while True: remaining = deadline - time.monotonic() if remaining <= 0: raise RigError("deadline waiting for exact credential and trust bundle acknowledgements") identity = "bundle-" + uuid.uuid4().hex request = folder / (identity + ".request.json") response = folder / (identity + ".result.json") atomic_write_secret(request, json.dumps({"id": identity, "operation": "bundle-commit", "connectionId": expected["connectionId"], "timeoutSeconds": max(1, min(5, int(remaining)))})) try: while not response.exists(): remaining = deadline - time.monotonic() if remaining <= 0: raise RigError("deadline waiting for bundle acknowledgement probe") time.sleep(min(.1, remaining)) if time.monotonic() > deadline: raise RigError("deadline waiting for bundle acknowledgement probe") if response.is_symlink() or not response.is_file() or response.stat().st_size > 16384: raise RigError("bundle acknowledgement probe output is invalid") result = json.loads(response.read_text()) if (result.get("id") != identity or result.get("operation") != "bundle-commit" or result.get("passed") is not True or type(result.get("assertions")) is not int or result["assertions"] <= 0 or not isinstance(result.get("observations"), dict)): raise RigError("bundle acknowledgement probe identity or result is invalid") observed = {key: result["observations"].get(key) for key in safe_fields} if any(value is not None and type(value) is not (bool if key in {"credentialDeleted", "trustRetired"} else int) for key, value in observed.items()): raise RigError("bundle acknowledgement fields must be nullable numeric versions or state flags") record["observed"] = observed record["matched"] = bundle_commit_matches(record["expected"], record["observed"]) atomic_write_secret(diagnostics, json.dumps({"required_entries": len(expectations), "entries": records})) if record["matched"]: break finally: request.unlink(missing_ok=True) time.sleep(min(.1, max(0, deadline - time.monotonic()))) return records def credential_action(self, action, node=None): """Publish through the actual node bundle loader, never fake an auth result.""" if node is not None and node not in NODES[2:]: raise RigError("credential action requires an owned data node") selected = [node] if node is not None else [name for name in NODES if name.startswith("consumer-")] if action == "reload_stale_bundle": for name in selected: directory = self.folder / "security" / "credentials" / name for kind in ("bundle", "trust"): previous = directory / (kind + "-previous.json") if not previous.is_file(): raise RigError("no previous bundle is available for stale replay") atomic_write_secret(directory / (kind + ".json"), previous.read_text()) elif action in {"remove_consumer_secret", "provision_consumer_secret"}: scope = json.loads((self.folder / "seed" / "scope.json").read_text()) published = self.publish_scope(scope, selected=selected, deleted=action == "remove_consumer_secret") self.wait_bundle_commits(deployment_bundle_expectations(scope, published, selected=selected), timeout=120) else: raise RigError("unknown credential fixture action") return {"action": action, "nodes": selected} def trust_action(self, action): """Stage trust, replace owned server certs, then retire the original CA.""" import credentials security = self.folder / "security" next_security = self.folder / "security-next" state_path = self.folder / "trust-state.json" if action == "stage_new": if next_security.exists(): raise RigError("a CA rotation is already staged") credentials.provision_tls(next_security, NODES[2:]) for node in NODES[2:]: for kind in ("pem", "key"): directory = security / "tls" / node atomic_write_secret(directory / ("server-original." + kind), (directory / ("server." + kind)).read_text()) original = security / "ca-original.pem" atomic_write_secret(original, (security / "ca.pem").read_text()) atomic_write_secret(state_path, json.dumps({"phase": "staged", "roots": [str(original), str(next_security / "ca.pem")]})) atomic_write_secret(security / "ca.pem", original.read_text() + (next_security / "ca.pem").read_text()) else: if not state_path.exists(): raise RigError("CA rotation has not been staged") state = json.loads(state_path.read_text()) if action == "rotate_server": if state["phase"] != "staged": raise RigError("server certificates can rotate only after trust staging") for node in NODES[2:]: for name in ("server.pem", "server.key"): atomic_write_secret(security / "tls" / node / name, (next_security / "tls" / node / name).read_text()) self.compose("restart", *NODES[2:], timeout=120) self.refresh_endpoints(NODES[2:]) state["phase"] = "rotated" elif action == "retire_old": if state["phase"] != "rotated": raise RigError("old CA can retire only after server certificate rotation") state = {"phase": "retired", "roots": [str(next_security / "ca.pem")]} atomic_write_secret(security / "ca.pem", (next_security / "ca.pem").read_text()) else: raise RigError("unknown trust fixture action") atomic_write_secret(state_path, json.dumps(state)) scope = json.loads((self.folder / "seed" / "scope.json").read_text()) published = self.publish_scope(scope) self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120) manifest = self.load() manifest["tls"]["rotation"] = json.loads(state_path.read_text())["phase"] manifest["tls"]["ca_file"] = str(security / "ca.pem") self.save(manifest) return {"action": action, "phase": manifest["tls"]["rotation"]} def restore_security(self): """Restore the original local CA/certificates while keeping bundle generations monotonic.""" import shutil security = self.folder / "security" state_path = self.folder / "trust-state.json" if not state_path.exists(): return {"restored": False} original = security / "ca-original.pem" if not original.is_file(): raise RigError("original local CA material is unavailable") for node in NODES[2:]: for kind in ("pem", "key"): directory = security / "tls" / node atomic_write_secret(directory / ("server." + kind), (directory / ("server-original." + kind)).read_text()) atomic_write_secret(security / "ca.pem", original.read_text()) atomic_write_secret(state_path, json.dumps({"phase": "restored", "roots": [str(original)]})) self.compose("restart", *NODES[2:], timeout=120) self.refresh_endpoints(NODES[2:]) scope = json.loads((self.folder / "seed" / "scope.json").read_text()) published = self.publish_scope(scope) self.wait_bundle_commits(deployment_bundle_expectations(scope, published), timeout=120) next_security = self.folder / "security-next" if next_security.is_symlink(): raise RigError("staged security directory cannot be a symlink") if next_security.exists(): shutil.rmtree(next_security) state_path.unlink() manifest = self.load() manifest["tls"]["rotation"] = "restored" manifest["tls"]["ca_file"] = str(security / "ca.pem") self.save(manifest) return {"restored": True} @contextmanager def retired_server_identity(self, node): """Present an old-CA server identity after actual consumers retired it.""" if node not in ("source-1", "source-2"): raise RigError("retired identity experiment requires an owned SOURCE node") state_path = self.folder / "trust-state.json" if not state_path.is_file() or json.loads(state_path.read_text()).get("phase") != "retired": raise RigError("old CA must be retired before the identity experiment") directory = self.folder / "security" / "tls" / node original = {} for kind in ("pem", "key"): old = directory / ("server-original." + kind) if old.is_symlink() or not old.is_file(): raise RigError("restricted server identities are unavailable") original[kind] = old.read_text() with self._server_identity_material(node, original): yield @contextmanager def rejected_server_identity(self, node, reason): """Serve a real invalid identity to the production caller trust policy.""" if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san"): raise RigError("invalid owned TLS rejection experiment") if reason == "wrong-ca": import credentials isolated = self.folder / "security-rejected" if isolated.is_symlink(): raise RigError("rejected identity directory cannot be linked") if not isolated.exists(): credentials.provision_tls(isolated, ("source-1", "source-2")) directory = isolated / "tls" / node else: partner = "source-2" if node == "source-1" else "source-1" directory = self.folder / "security" / "tls" / partner material = {} for kind in ("pem", "key"): path = directory / ("server." + kind) if path.is_symlink() or not path.is_file(): raise RigError("owned TLS test identity is unavailable") material[kind] = path.read_text() if reason == "wrong-san": # The Host correctly checks its own certificate against AllowedHosts # at startup. Admit the partner identity on that server only, while # the actual caller remains pinned to this node's original URI. live = self.folder / "security" / "tls" / node saved = {kind: (live / ("server." + kind)).read_text() for kind in ("pem", "key")} def restore(): for kind, content in saved.items(): atomic_write_secret(live / ("server." + kind), content) try: for kind, content in material.items(): atomic_write_secret(live / ("server." + kind), content) with self._configuration_experiment("wrong-san-" + node, (node,), {"DataConnections__AllowedHosts__0": partner}, before_restore=restore): yield finally: restore() return with self._server_identity_material(node, material): yield def verify_test_tls_listener(self, node, reason): """Validate the presented test certificate independently of consumer trust. This control proves that the same owned TLS listener is reachable while the production consumer must reject its configured identity. It sends no HTTP request and grants no trust material to that consumer. """ import hashlib import socket import ssl if node not in ("source-1", "source-2") or reason not in ("wrong-ca", "wrong-san", "retired-ca"): raise RigError("invalid owned TLS listener control") security = self.folder / "security" ca = (self.folder / "security-rejected" / "ca.pem") if reason == "wrong-ca" else ( security / "ca-original.pem" if reason == "retired-ca" else security / "ca.pem") server_name = ("source-2" if node == "source-1" else "source-1") if reason == "wrong-san" else node endpoint = self.load()["endpoints"][node + ".data"] context = ssl.create_default_context(cafile=str(ca)) context.minimum_version = ssl.TLSVersion.TLSv1_2 with socket.create_connection((endpoint["host"], endpoint["host_port"]), timeout=5) as transport: with context.wrap_socket(transport, server_hostname=server_name) as channel: actual = channel.getpeercert(binary_form=True) expected = ssl.PEM_cert_to_DER_cert((security / "tls" / node / "server.pem").read_text()) if actual != expected: raise RigError("TLS control observed another server identity") return {"server_name": server_name, "certificate_sha256": hashlib.sha256(actual).hexdigest(), "tls_version": channel.version(), "listener_reachable": True} @contextmanager def _server_identity_material(self, node, material): directory = self.folder / "security" / "tls" / node current = {} for kind in ("pem", "key"): path = directory / ("server." + kind) if path.is_symlink() or not path.is_file(): raise RigError("restricted server identity is unavailable") current[kind] = path.read_text() def apply(material): self.inspect_resources() for kind, content in material.items(): atomic_write_secret(directory / ("server." + kind), content) self.compose("restart", node, timeout=90) manifest = self.refresh_endpoints((node,)) wait_until(lambda: self.health(manifest), timeout=180, description="server identity experiment readiness") try: apply(material) yield finally: apply(current) def deploy(self, timeout=180, *, require_catalog=True): _duration(timeout, "deployment operation timeout") deadline = time.monotonic() + timeout def remaining(): value = deadline - time.monotonic() if value <= 0: raise RigError("deployment operation deadline timeout") return value manifest = self.load() if "fixture" not in manifest: raise RigError("seed must complete before deploy") primary = wait_active_endpoint({node: manifest["endpoints"][node + ".admin"]["url"] for node in NODES[:2]}, request=http_request, timeout=remaining(), require_ready=True) scope = {} def accepted(identity, revision): scope.update(self.provision_deployment(identity, revision, timeout=remaining())) # This inventory comes from the sealer's immutable artifact, not the # status rows we are about to validate. Maintenance deliberately # removes a node from expected apply acknowledgements. required = scope.get("required_node_ids") if not isinstance(required, list) or not required: raise RigError("sealed artifact has no required-node inventory") return required outcome = deploy_and_wait(manifest["endpoints"][primary + ".admin"]["url"], self.environment["GRPC_DATA_DEPLOY_KEY"], {node + ":4053" for node in NODES}, request=http_request, timeout=remaining(), on_accepted=accepted) manifest["deployment"] = {"id": outcome["deploymentId"], "revision_hash": outcome["revisionHash"], "scope_version": scope["scope_version"], "nodes": outcome["nodes"], "required_node_ids": scope["required_node_ids"]} manifest["deployment"]["bundle_commits"] = self.wait_bundle_commits(scope["bundle_expectations"], timeout=remaining()) if require_catalog: wait_until(lambda: self.health(manifest, require_catalog=True, timeout=remaining()), timeout=remaining(), description="deployed catalog and OPC UA namespace identity") manifest["resolved_nodes"] = json.loads((self.folder / "seed" / "resolved.json").read_text()) remaining() manifest["state"] = "ready" self.capture(manifest) return manifest def status(self): manifest = self.load() try: manifest["healthy"] = self.health(manifest, require_catalog=manifest.get("state") == "ready") except (OSError, ValueError, RigError): manifest["healthy"] = False self.capture(manifest) return manifest def down(self): if self.path.exists(): manifest = self.load() # Refresh exact-ID inventory of the same run; labels are checked twice. manifest["resources"] = self.inspect_resources() else: setup = json.loads((self.folder / "setup.json").read_text()) if setup != {"run_id": self.run_id, "docker_context": self.context["Name"], "project": self.project}: raise RigError("interrupted setup journal ownership mismatch") # cleanup_owned also validates endpoint/node schema; this placeholder # is safety-only and cannot be reported as running or ready. manifest = {"schema_version": 1, "run_id": self.run_id, "project": self.project, "labels": {RUN_LABEL: self.run_id, PROJECT_LABEL: self.project}, "services": list(SERVICES), "endpoints": {"journal": {"scheme": "tcp", "host": "127.0.0.1", "host_port": 1, "container_host": "sql", "container_port": 1433}}, "nodes": {"source-1": {"cluster_id": "SOURCE", "application_uri": "urn:OtOpcUa:grpc-data:source-1"}}, "resources": self.inspect_resources()} order = {"container": 0, "network": 1, "volume": 2, "image": 3} manifest["resources"].sort(key=lambda row: order[row["kind"]]) def remove(kind, identity): run_command([*self.docker, kind, "rm", *(["--force"] if kind == "container" else []), identity]) cleanup_owned(manifest, self.inspect_resources(), remove=remove) manifest["state"] = "down" manifest["resources"] = [] self.save(manifest) return manifest def main(argv=None): parser = argparse.ArgumentParser(description="Standalone owned local gRPC data integration rig") parser.add_argument("action", choices=("preflight", "up", "seed", "deploy", "status", "down")) parser.add_argument("--run-id") parser.add_argument("--timeout", type=float, default=None) arguments = parser.parse_args(argv) try: if arguments.action == "preflight": context = docker_context() environment = dict(os.environ) for name in re.findall(r"\$\{([A-Z][A-Z0-9_]*)", (HERE / "compose.yml").read_text()): environment[name] = "preflight" environment.update({"GRPC_DATA_PROJECT": "grpc-data-preflight", "GRPC_DATA_RUN_ID": "preflight", "GRPC_DATA_UID": "0", "GRPC_DATA_GID": "0", "GRPC_DATA_CERT_DIR": "/tmp/grpc-data-preflight/tls", "GRPC_DATA_CREDENTIAL_DIR": "/tmp/grpc-data-preflight/credentials", "GRPC_DATA_OUTPUT_DIR": "/tmp/grpc-data-preflight/output", "GRPC_DATA_PROBE_DIR": "/tmp/grpc-data-preflight/probe"}) resolved = json.loads(run_command(["docker", "--context", context["Name"], "compose", "--file", str(HERE / "compose.yml"), "config", "--format", "json"], environment=environment)) validate_fixture_endpoints(resolved, local_services=SERVICES) print(json.dumps({"local_docker": True, "resolved_fixture_local": True, "context": context["Name"]})) return 0 rig = LocalRig(arguments.run_id) action = getattr(rig, arguments.action) result = action(**({"timeout": arguments.timeout} if arguments.timeout is not None and arguments.action in {"up", "deploy"} else {})) print(json.dumps({"run_id": result["run_id"], "state": result.get("state"), "manifest": str(rig.path), "healthy": result.get("healthy")})) return 0 except (RigError, ValueError, OSError, KeyError) as error: # Only our own fixed RigError messages are public. Parser/system errors # can include paths or env supplied secrets, so withhold their contents. message = str(error) if isinstance(error, RigError) else "fixture operation failed; inspect restricted run files" print("grpc-data rig: " + message, file=__import__("sys").stderr) return 2 if __name__ == "__main__": raise SystemExit(main())