|
| 1 | +"""`otdf-local instance` subcommands: init / ls / rm.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import shutil |
| 6 | +from pathlib import Path |
| 7 | +from typing import Annotated, Optional |
| 8 | + |
| 9 | +import typer |
| 10 | +from otdf_sdk_mgr.schema import Instance, Metadata, PlatformPin, PortsConfig, dump_instance |
| 11 | + |
| 12 | +from otdf_local.config.settings import get_settings |
| 13 | + |
| 14 | +instance_app = typer.Typer(help="Manage named test environment instances.") |
| 15 | + |
| 16 | + |
| 17 | +@instance_app.command("init") |
| 18 | +def init( |
| 19 | + name: Annotated[str, typer.Argument(help="Instance name (used as directory name)")], |
| 20 | + from_scenario: Annotated[ |
| 21 | + Optional[Path], |
| 22 | + typer.Option("--from-scenario", help="Initialize from a scenarios.yaml or instance.yaml"), |
| 23 | + ] = None, |
| 24 | + ports_base: Annotated[ |
| 25 | + int, |
| 26 | + typer.Option("--ports-base", help="Base port (KAS ports computed as base+N*101)"), |
| 27 | + ] = 8080, |
| 28 | + platform_dist: Annotated[ |
| 29 | + Optional[str], |
| 30 | + typer.Option("--platform", help="Platform dist version (e.g., v0.9.0)"), |
| 31 | + ] = None, |
| 32 | +) -> None: |
| 33 | + """Scaffold a new instance directory at tests/instances/<name>/.""" |
| 34 | + settings = get_settings() |
| 35 | + instance_dir = settings.instances_root / name |
| 36 | + |
| 37 | + if from_scenario is not None: |
| 38 | + _init_from_scenario(name, from_scenario, instance_dir) |
| 39 | + else: |
| 40 | + if platform_dist is None: |
| 41 | + typer.echo("Error: --platform <dist> is required when not using --from-scenario", err=True) |
| 42 | + raise typer.Exit(2) |
| 43 | + _init_minimal(name, instance_dir, ports_base, platform_dist) |
| 44 | + |
| 45 | + _validate_port_uniqueness(settings.instances_root, name) |
| 46 | + typer.echo(f" Initialized instance '{name}' at {instance_dir}") |
| 47 | + |
| 48 | + |
| 49 | +def _init_from_scenario(name: str, scenario_path: Path, instance_dir: Path) -> None: |
| 50 | + """Copy the embedded Instance from a Scenario or load a standalone Instance.""" |
| 51 | + from otdf_sdk_mgr.schema import load_instance, load_scenario |
| 52 | + from ruamel.yaml import YAML |
| 53 | + |
| 54 | + y = YAML(typ="safe") |
| 55 | + raw = y.load(scenario_path.read_text()) |
| 56 | + if not isinstance(raw, dict): |
| 57 | + raise typer.BadParameter(f"{scenario_path} top-level YAML must be a mapping") |
| 58 | + kind = raw.get("kind") |
| 59 | + if kind == "Scenario": |
| 60 | + scenario = load_scenario(scenario_path) |
| 61 | + instance = scenario.instance |
| 62 | + elif kind == "Instance": |
| 63 | + instance = load_instance(scenario_path) |
| 64 | + else: |
| 65 | + raise typer.BadParameter(f"{scenario_path} has unknown kind {kind!r}") |
| 66 | + # Ensure the metadata name matches the chosen directory name. |
| 67 | + instance.metadata = Metadata(**{**instance.metadata.model_dump(exclude_none=True), "name": name}) |
| 68 | + instance_dir.mkdir(parents=True, exist_ok=True) |
| 69 | + (instance_dir / "kas").mkdir(parents=True, exist_ok=True) |
| 70 | + (instance_dir / "keys").mkdir(mode=0o700, parents=True, exist_ok=True) |
| 71 | + (instance_dir / "logs").mkdir(parents=True, exist_ok=True) |
| 72 | + dump_instance(instance, instance_dir / "instance.yaml") |
| 73 | + |
| 74 | + |
| 75 | +def _init_minimal(name: str, instance_dir: Path, ports_base: int, platform_dist: str) -> None: |
| 76 | + """Create a barebones instance.yaml with default KAS layout.""" |
| 77 | + instance = Instance( |
| 78 | + metadata=Metadata(name=name), |
| 79 | + platform=PlatformPin(dist=platform_dist), |
| 80 | + ports=PortsConfig(base=ports_base), |
| 81 | + kas={}, |
| 82 | + ) |
| 83 | + instance_dir.mkdir(parents=True, exist_ok=True) |
| 84 | + (instance_dir / "kas").mkdir(parents=True, exist_ok=True) |
| 85 | + (instance_dir / "keys").mkdir(mode=0o700, parents=True, exist_ok=True) |
| 86 | + (instance_dir / "logs").mkdir(parents=True, exist_ok=True) |
| 87 | + dump_instance(instance, instance_dir / "instance.yaml") |
| 88 | + |
| 89 | + |
| 90 | +def _validate_port_uniqueness(instances_root: Path, new_name: str) -> None: |
| 91 | + """Warn if another instance shares the same `ports.base`.""" |
| 92 | + from otdf_sdk_mgr.schema import load_instance |
| 93 | + |
| 94 | + new_yaml = instances_root / new_name / "instance.yaml" |
| 95 | + if not new_yaml.exists(): |
| 96 | + return |
| 97 | + new_inst = load_instance(new_yaml) |
| 98 | + new_base = new_inst.ports.base |
| 99 | + if not instances_root.exists(): |
| 100 | + return |
| 101 | + for child in instances_root.iterdir(): |
| 102 | + if not child.is_dir() or child.name == new_name: |
| 103 | + continue |
| 104 | + other_yaml = child / "instance.yaml" |
| 105 | + if not other_yaml.is_file(): |
| 106 | + continue |
| 107 | + try: |
| 108 | + other = load_instance(other_yaml) |
| 109 | + except Exception: |
| 110 | + continue |
| 111 | + if other.ports.base == new_base: |
| 112 | + typer.echo( |
| 113 | + f" Warning: instance '{child.name}' already uses ports.base={new_base}; " |
| 114 | + f"running both simultaneously will collide. Change one with `otdf-local instance init`.", |
| 115 | + err=True, |
| 116 | + ) |
| 117 | + |
| 118 | + |
| 119 | +@instance_app.command("ls") |
| 120 | +def ls( |
| 121 | + as_json: Annotated[bool, typer.Option("--json", "-j", help="Emit JSON")] = False, |
| 122 | +) -> None: |
| 123 | + """List known instances.""" |
| 124 | + import json as _json |
| 125 | + |
| 126 | + from otdf_sdk_mgr.schema import load_instance |
| 127 | + |
| 128 | + settings = get_settings() |
| 129 | + root = settings.instances_root |
| 130 | + if not root.exists(): |
| 131 | + if as_json: |
| 132 | + typer.echo(_json.dumps([])) |
| 133 | + else: |
| 134 | + typer.echo(" (no instances yet)") |
| 135 | + return |
| 136 | + rows: list[dict[str, object]] = [] |
| 137 | + for child in sorted(root.iterdir()): |
| 138 | + if not child.is_dir(): |
| 139 | + continue |
| 140 | + ymp = child / "instance.yaml" |
| 141 | + if not ymp.is_file(): |
| 142 | + continue |
| 143 | + try: |
| 144 | + inst = load_instance(ymp) |
| 145 | + except Exception as e: |
| 146 | + rows.append({"name": child.name, "error": str(e)}) |
| 147 | + continue |
| 148 | + rows.append( |
| 149 | + { |
| 150 | + "name": child.name, |
| 151 | + "platform": ( |
| 152 | + inst.platform.dist |
| 153 | + or (inst.platform.source.ref if inst.platform.source else inst.platform.image) |
| 154 | + ), |
| 155 | + "ports_base": inst.ports.base, |
| 156 | + "kas": list(inst.kas.keys()), |
| 157 | + } |
| 158 | + ) |
| 159 | + if as_json: |
| 160 | + typer.echo(_json.dumps(rows, indent=2)) |
| 161 | + else: |
| 162 | + for row in rows: |
| 163 | + typer.echo(f" {row}") |
| 164 | + |
| 165 | + |
| 166 | +@instance_app.command("rm") |
| 167 | +def rm( |
| 168 | + name: Annotated[str, typer.Argument(help="Instance to remove")], |
| 169 | + yes: Annotated[bool, typer.Option("--yes", "-y", help="Skip confirmation")] = False, |
| 170 | +) -> None: |
| 171 | + """Remove an instance directory.""" |
| 172 | + settings = get_settings() |
| 173 | + instance_dir = settings.instances_root / name |
| 174 | + if not instance_dir.exists(): |
| 175 | + typer.echo(f"Error: instance '{name}' not found at {instance_dir}", err=True) |
| 176 | + raise typer.Exit(1) |
| 177 | + if not yes: |
| 178 | + confirm = typer.confirm(f"Delete {instance_dir}?", default=False) |
| 179 | + if not confirm: |
| 180 | + typer.echo("aborted") |
| 181 | + raise typer.Exit(1) |
| 182 | + shutil.rmtree(instance_dir) |
| 183 | + typer.echo(f" Removed {instance_dir}") |
0 commit comments