prole/knoe/tools/cleanup_cnpg_storage.py
chrisfu dba8a2d1dc feat(installer): TDD stabilization for k3d install path; dual-cluster GKE TUI
Junie's session targeted the prompt "stabilize ./install.py -c conf/k3d.cfg
using strict TDD" — broad installer-side work, not the k3d-mirror Phase 3
brief I had filed (which she didn't pick up; phase-3 brief stays open). All
750 installer tests pass post-change.

What Junie produced:

  install.py                          (NEW) Top-level CLI entry point. Was
                                            imagined by the prompt but didn't
                                            exist; this commit makes it real.
  knoe/deployment.py                  (NEW) `KnoeDeployment` orchestrator for
                                            the k3s service-mode deploy pipeline.
                                            Wraps Ansible kubeconfig fetch,
                                            opentofu apply, init_*.sh post-apply
                                            scripts, and (optionally) supabase/
                                            deploy.sh.
  knoe/ui/screens/cluster.py          Dual-cluster GKE kubecontext UI: prod env
  knoe/ui/screens/cfg.py              now shows separate "App Cluster:" and
                                       "DB Cluster:" dropdowns instead of a
                                       single "Kubernetes Context:" combo.
                                       New _app_kubectx_combo + _db_kubectx_combo
                                       widgets; new app/db_cluster_kubecontext
                                       tk.StringVars.
  knoe/core/{actions,env,milestones}.py
  knoe/core/ops/storage.py
  knoe/config.py, knoe/knoe_conf.py   Plumbing changes for the dual-cluster
                                       kubecontext flow + storage-class topology
                                       detection cleanup.
  knoe/tools/cleanup_cnpg_storage.py  (NEW) Stand-alone cleanup utility.
  tools/dashboard.sh                  (NEW) Dashboard helper.
  conf/knoe.cfg                       (NEW) Master cfg generated by knoe_conf.
  conf/dev/                           (NEW) Dev-mode cfg directory.
  conf/port-mapping.cfg               Port mapping tweaks for k3d.
  tests/installer/* (8 files)         New + extended tests for the dual-cluster
  tests/test_database_options.py      TUI, kubecontext save flow, storage ops,
                                       topology detection, deploy helpers,
                                       database-options screen.

Issues found in Junie's working state and fixed here:

  1. install.py was a 11-line import shim with no shebang, no `chmod +x`,
     no `if __name__ == '__main__'` block. `./install.py -c conf/k3d.cfg`
     returned `Permission denied` and `python install.py` did nothing.
     Added `#!/usr/bin/env python3`, `chmod +x`, and a __main__ block
     that delegates to `knoe.ui.screens.main()`. `./install.py --help`
     now prints the canonical argparse help.

  2. knoe/deployment.py had FIVE `subprocess.run()` call sites with no
     `timeout=` argument (`_run_script`, `_run_cmd`, the Ansible playbook
     fetch, `tofu init`, `tofu apply`). A hung child process — typical
     failure mode is a script waiting on stdin or a stalled network
     call — would lock up the installer indefinitely. Added timeouts:
       - Ansible kubeconfig fetch: 120s
       - tofu init: 300s
       - tofu apply, _run_script, _run_cmd: bounded by new module
         constant `_MILESTONE_TIMEOUT` (default 1800s = 30 min, override
         via `KNOE_MILESTONE_TIMEOUT_SECONDS` env var).
     `subprocess.TimeoutExpired` is caught explicitly; on timeout the
     run helpers return exit code 124 (conventional timeout code).

  3. `conf/k3d.cfg` was corrupted with MagicMock string-reprs on disk:
        KNOE_CONF = <MagicMock name='Canvas().tk.call().strip()' id='4743999712'>
        argocd.node_selector = <MagicMock name='mock.StringVar().get().strip()' id='...'>
     Likely path: Junie ran `./install.py -c conf/k3d.cfg` interactively
     in a non-Tk environment (or with a partially-mocked widget set) and
     the installer's "save current state" path wrote the mock-objects'
     `__repr__` strings into the cfg file. This commit reverts the cfg
     to its pre-Junie state. **Followup: harden the cfg save path
     against non-string widget values** — track separately.

  4. The corrupted cfg caused the installer to call `os.makedirs()` on
     the mock-string values, producing 10 directories on disk literally
     named `<MagicMock name='Canvas().tk.call().strip()' id='4733210304'>/`
     etc., with 5–86 files of install artifacts inside each. Removed.

The "final step is timing out" the user reported was almost certainly
issue #2 above: install.py walked the milestone pipeline, hit one of
the unbounded subprocess.run calls, and the wrapped command (probably
supabase/deploy.sh, which Junie was reading for context when her
session timed out) hung. With the timeouts in place that path now
exits cleanly with rc=124 instead of locking up.

Verification:
  - pytest tests/installer/ -q                                   750 passed in ~25s
  - python3 -c "import knoe.deployment"                          imports clean
  - ./install.py --help                                          prints argparse help
  - find . -maxdepth 1 -type d -name '<MagicMock*' | wc -l       0
  - head -7 conf/k3d.cfg                                          clean (no MagicMock)

Out of scope for this commit (followups):
  - The cfg save-path that wrote mock-objects-as-strings (issue #3 root cause).
    Reproducer: launch the installer in an env where Tk widget vars are
    `unittest.mock.MagicMock` instances. The cfg save code should refuse to
    serialize non-str values rather than calling `str()` on a MagicMock.
  - The k3d-mirror Phase 3 brief (`docs/plans/junie/k3d-knoe-auth-pod-deploy.md`)
    is still open — Junie picked a different prompt this round.

Co-authored-by: Junie <junie@jetbrains.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 23:51:14 -07:00

173 lines
6.2 KiB
Python

from __future__ import annotations
import argparse
from dataclasses import dataclass, field
from typing import Any
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_cli_args(argv: list[str] | None = None) -> argparse.Namespace:
# shared args for all subcommands
common = argparse.ArgumentParser(add_help=False)
common.add_argument("--dry-run", action="store_true", default=True)
common.add_argument("--database-namespace", required=True)
common.add_argument("--cluster-name", default=None)
# separate parent without --cluster-name for cleanup-cluster (which makes it required)
common_no_cluster = argparse.ArgumentParser(add_help=False)
common_no_cluster.add_argument("--dry-run", action="store_true", default=True)
common_no_cluster.add_argument("--database-namespace", required=True)
parser = argparse.ArgumentParser(description="CNPG storage cleanup tool")
sub = parser.add_subparsers(dest="command")
sub.add_parser("inspect", parents=[common])
cleanup_cluster = sub.add_parser("cleanup-cluster", parents=[common_no_cluster])
cleanup_cluster.add_argument("--cluster-name", required=True, dest="cluster_name")
ns = parser.parse_args(argv)
if not hasattr(ns, "dry_run") or ns.dry_run is None:
ns.dry_run = True
if not hasattr(ns, "cluster_name"):
ns.cluster_name = None
return ns
# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------
@dataclass
class ResourceItem:
name: str
raw: dict
reasons: list[str] = field(default_factory=list)
@dataclass
class ResourceSnapshot:
clusters: list[dict] = field(default_factory=list)
pvcs: list[dict] = field(default_factory=list)
pvs: list[dict] = field(default_factory=list)
pods: list[dict] = field(default_factory=list)
jobs: list[dict] = field(default_factory=list)
@dataclass
class SelectedResources:
clusters: list[ResourceItem] = field(default_factory=list)
pvcs: list[ResourceItem] = field(default_factory=list)
pvs: list[ResourceItem] = field(default_factory=list)
pods: list[ResourceItem] = field(default_factory=list)
jobs: list[ResourceItem] = field(default_factory=list)
@dataclass
class MatchFilters:
namespace: str
cluster_name: str | None = None
# ---------------------------------------------------------------------------
# Selection logic
# ---------------------------------------------------------------------------
def _meta_name(obj: dict) -> str:
return obj.get("metadata", {}).get("name", "")
def _meta_namespace(obj: dict) -> str:
return obj.get("metadata", {}).get("namespace", "")
def _meta_labels(obj: dict) -> dict:
return obj.get("metadata", {}).get("labels", {})
def select_resources(snapshot: ResourceSnapshot, filters: MatchFilters) -> SelectedResources:
result = SelectedResources()
# clusters
for c in snapshot.clusters:
ns = _meta_namespace(c)
if ns == filters.namespace:
reasons = [f"metadata.namespace={ns}"]
if filters.cluster_name and _meta_name(c) == filters.cluster_name:
reasons.append(f"metadata.name={filters.cluster_name}")
result.clusters.append(ResourceItem(name=_meta_name(c), raw=c, reasons=reasons))
# pvcs
for pvc in snapshot.pvcs:
ns = _meta_namespace(pvc)
labels = _meta_labels(pvc)
reasons: list[str] = []
if ns == filters.namespace:
reasons.append(f"metadata.namespace={ns}")
if filters.cluster_name and labels.get("cnpg.io/cluster") == filters.cluster_name:
reasons.append(f"label cnpg.io/cluster={filters.cluster_name}")
if reasons:
result.pvcs.append(ResourceItem(name=_meta_name(pvc), raw=pvc, reasons=reasons))
# pvs
for pv in snapshot.pvs:
labels = _meta_labels(pv)
spec = pv.get("spec", {})
claim_ref = spec.get("claimRef", {})
reasons: list[str] = []
if filters.namespace and claim_ref.get("namespace") == filters.namespace:
reasons.append(f"spec.claimRef.namespace={filters.namespace}")
if filters.cluster_name and labels.get("knoe.io/cluster") == filters.cluster_name:
reasons.append(f"label knoe.io/cluster={filters.cluster_name}")
if reasons:
result.pvs.append(ResourceItem(name=_meta_name(pv), raw=pv, reasons=reasons))
# pods
for pod in snapshot.pods:
ns = _meta_namespace(pod)
labels = _meta_labels(pod)
reasons: list[str] = []
if ns == filters.namespace:
reasons.append(f"metadata.namespace={ns}")
if filters.cluster_name and labels.get("cnpg.io/cluster") == filters.cluster_name:
reasons.append(f"label cnpg.io/cluster={filters.cluster_name}")
if reasons:
result.pods.append(ResourceItem(name=_meta_name(pod), raw=pod, reasons=reasons))
# jobs
for job in snapshot.jobs:
ns = _meta_namespace(job)
labels = _meta_labels(job)
reasons: list[str] = []
if ns == filters.namespace:
reasons.append(f"metadata.namespace={ns}")
if filters.cluster_name and labels.get("cnpg.io/cluster") == filters.cluster_name:
reasons.append(f"label cnpg.io/cluster={filters.cluster_name}")
if reasons:
result.jobs.append(ResourceItem(name=_meta_name(job), raw=job, reasons=reasons))
return result
# ---------------------------------------------------------------------------
# PV helpers
# ---------------------------------------------------------------------------
def _should_patch_pv_claim_ref(pv: dict, *, delete_pv: bool) -> bool:
if delete_pv:
return False
phase = pv.get("status", {}).get("phase", "")
return phase == "Released" and bool(pv.get("spec", {}).get("claimRef"))
def _should_delete_pv(pv: dict, *, delete_pv: bool, force: bool) -> bool:
if not delete_pv:
return False
phase = pv.get("status", {}).get("phase", "")
if phase != "Released" and not force:
return False
return True