From 8e926f0fc60434c666b01310f0a13934669b0e74 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 15:46:30 -0500 Subject: [PATCH 01/17] "rolled" means the deployment's new pods are ready, not the old one still terminating MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit kobo's upgrade on prod (2026-11-30, run 2): the setup PR's CI applied the deployment, whose template now named the new digest, and under Recreate the old pod began terminating. Its containers still reported ready, so wait_rolled read "template on the digest, 1/1 pods ready" and said rolled at 20:41:55Z. The new pod was created at 20:42:15Z, ready at 20:43:32Z, and the deploy run was still in flight. The receipt was the old pod. pods_ready(ns, image="") now parses each pod's deletionTimestamp, image and container ready flags; pods_summary (pure, shared with the fake) drops any pod being deleted, and with the deployment's image given counts only pods of that repo, ready only when on that exact image. wait_rolled passes the image. The install's namespace-wide "N/N pods ready" keeps its meaning but no longer counts a terminating pod. Tests drive the real upgrade path with a per-poll pods script: old pod ready on the old image, old pod terminating, new pod not ready, new pod ready — done at the fourth poll only. Two mutations fail it: wait_rolled counting the namespace again, and the helper counting deleting pods. Signed-off-by: Shaz Chaudhri Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 6 ++++++ stack/clients.py | 38 +++++++++++++++++++++++++++++++++----- stack/steps.py | 5 ++++- tests/fakes.py | 14 ++++++++++++-- tests/test_upgrade.py | 39 ++++++++++++++++++++++++++++++++++++++- 5 files changed, 93 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f637e75..1355ab3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,12 @@ releases yet; everything is under Unreleased. ### Fixed +- **"rolled" meant the old pod.** A roll's done check read the deployment's image (already the + new digest once CI applied it) and counted every ready pod in the namespace; under Recreate + the old pod reports ready while it terminates, so kobo's upgrade on prod (2026-11-30) said + "rolled, 1/1 pods" while the new pod was Pending and the deploy run still in flight. Done is + now the deployment's own live pods, each ready on the new image; a pod being deleted is not + counted anywhere, including the install's "N/N pods ready". - **The current kube context was offered as `*`.** `list_contexts` read the first column of kubectl's table, where the current context is marked with a star; it reads `-o name` now. Both picks (the env form's CLUSTER and the new add-profile form) carried it. diff --git a/stack/clients.py b/stack/clients.py index 6c875d6..6cb33a9 100644 --- a/stack/clients.py +++ b/stack/clients.py @@ -198,7 +198,7 @@ def configmap_exists(self, ns: str, name: str) -> bool: ... def configmap_value(self, ns: str, name: str, key: str) -> str: ... def apply_configmap(self, ns: str, name: str, data: dict[str, str]) -> None: ... def apply_file(self, path: str) -> str: ... - def pods_ready(self, ns: str) -> tuple[int, int]: ... + def pods_ready(self, ns: str, image: str = "") -> tuple[int, int]: ... def logs_grep(self, ns: str, deploy: str, pattern: str, since: str = "10m") -> str | None: ... def deployed_image(self, ns: str, deploy: str) -> str: ... def restart(self, ns: str, deploy: str) -> None: ... @@ -212,6 +212,28 @@ def account(self) -> str: ... def accounts(self) -> list[str]: ... +def pods_summary(rows: list[tuple[bool, str, list[bool]]], image: str = "") -> tuple[int, int]: + """(ready, total) over pods as (deleting, pod image, container ready flags). + A pod being deleted is not counted at all: it is on its way out, and its + containers report ready until they stop. With `image` given (the deployment's + `repo:tag@digest`), only pods of that repo count, and one is ready only when + it runs that exact image: a roll's receipt is the NEW pods, not the old one + still terminating under a template that already names the new digest + (kobo on prod, 2026-11-30: "rolled, 1/1 pods" while the new pod was Pending). + Without `image`, the whole namespace, as the install's "N/N pods ready".""" + repo = image.split("@", 1)[0].rsplit(":", 1)[0] if image else "" + total = ready = 0 + for deleting, pod_image, readys in rows: + if deleting: + continue + if image and not pod_image.startswith(repo): + continue + total += 1 + if readys and all(readys) and (not image or pod_image == image): + ready += 1 + return ready, total + + class KubectlCLI: def __init__(self, context: str = "", env: dict[str, str] | None = None): self._ctx = ["--context", context] if context else [] @@ -293,12 +315,18 @@ def apply_configmap(self, ns, name, data) -> None: def apply_file(self, path) -> str: return self._k("apply", "-f", path).strip() - def pods_ready(self, ns) -> tuple[int, int]: + def pods_ready(self, ns, image: str = "") -> tuple[int, int]: out = self._k("-n", ns, "get", "pods", "-o", - "jsonpath={range .items[*]}{.status.containerStatuses[*].ready}{\"\\n\"}{end}", + "jsonpath={range .items[*]}{.metadata.deletionTimestamp}|{.spec.containers[0].image}|" + "{.status.containerStatuses[*].ready}{\"\\n\"}{end}", check=False) - lines = [ln for ln in out.splitlines() if ln.strip()] - return sum(1 for ln in lines if "false" not in ln), len(lines) + rows = [] + for ln in out.splitlines(): + if not ln.strip(): + continue + deleting, pod_image, readys = (ln.split("|", 2) + ["", ""])[:3] + rows.append((bool(deleting.strip()), pod_image.strip(), [r == "true" for r in readys.split()])) + return pods_summary(rows, image) def logs_grep(self, ns, deploy, pattern, since: str = "10m") -> str | None: out = self._k("-n", ns, "logs", f"deploy/{deploy}", f"--since={since}", check=False) diff --git a/stack/steps.py b/stack/steps.py index 227e155..67b9d54 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -740,7 +740,10 @@ def wait_rolled(self, app: App, digest: str) -> None: saw_running = False while True: image = self.c.kubectl.deployed_image(app.namespace, app.name) - ready, total = self.c.kubectl.pods_ready(app.namespace) + # the pods ON the new image, not whatever is ready in the namespace: + # the old pod stays ready while it terminates, under a template that + # already names the new digest + ready, total = self.c.kubectl.pods_ready(app.namespace, image) if digest in image and total and ready == total: self.report.note(f"{app.name}: rolled, {ready}/{total} pods on {digest[:19]}…", self.o.say) return diff --git a/tests/fakes.py b/tests/fakes.py index e742fd8..148e8cf 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -2,7 +2,7 @@ from __future__ import annotations -from stack.clients import AppRow, ToolError +from stack.clients import AppRow, ToolError, pods_summary class FakeGojira: @@ -74,6 +74,8 @@ def __init__(self, ready: dict[str, tuple[int, int]] | None = None, log_code: st self.image_polls: dict[str, int] = {} # ns -> how many polls have read it self.image_script: dict[str, list[str]] = {} # ns -> the deployed image, per poll self.image_hooks: dict[str, list] = {} # ns -> fns called after each image read + self.pods_script: dict[str, list[list[tuple[bool, str, list[bool]]]]] = {} # ns -> pods per poll + self.pods_polls: dict[str, int] = {} self.log_code = log_code self.code_after_restart = "FRESH1" self.calls: list[str] = [] @@ -117,7 +119,15 @@ def apply_file(self, path): self.applied.append(path) return "clusterrole.rbac.authorization.k8s.io/x created" - def pods_ready(self, ns): + def pods_ready(self, ns, image=""): + """`pods_script[ns]`: per poll, the namespace's pods as (deleting, image, + [ready flags]) rows, counted by the real `pods_summary` so a test sees + what the installer would; else the flat `ready` tuple.""" + if ns in self.pods_script: + i = self.pods_polls.get(ns, 0) + self.pods_polls[ns] = i + 1 + seq = self.pods_script[ns] + return pods_summary(seq[min(i, len(seq) - 1)], image) return self.ready.get(ns, (1, 1)) def deployed_image(self, ns, deploy): diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py index 0fd842a..13d90c1 100644 --- a/tests/test_upgrade.py +++ b/tests/test_upgrade.py @@ -5,7 +5,7 @@ import pytest -from stack.clients import AppRow, ToolError +from stack.clients import AppRow, ToolError, pods_summary from stack.model import Stack from stack.steps import Clients, Installer, Options from tests.fakes import FakeCrane, FakeGitHub, FakeGojira, FakeKubectl @@ -252,3 +252,40 @@ def _poll(ns, name): rollout_seconds=3.0) # the stop arrives in a couple of polls, well under the 3 s rollout window assert time.monotonic() - t0 < 1.0 + + +def test_rolled_means_the_new_pods_are_ready_not_the_old_one_still_terminating(tmp_path): + """kobo on prod (2026-11-30): the setup PR's CI applied the deployment (its + template named the new digest) and, under Recreate, the old pod began + terminating; its containers still said ready, so "1/1 pods on " + was reported while the new pod was Pending and the deploy run still in + flight. Done is the NEW pods ready on the new image: the old pod, being + deleted, is not counted, and a pod on the old image is not "ready".""" + stack = _stack(tmp_path, [{"name": "kobo", "repo": "up/kobo", "deploy_repo": "org/kobo-deploy", + "image": "reg.example/apps/kobo:v2"}]) + github = FakeGitHub(repos={"org/kobo-deploy": {"gojira.yaml": GOJIRA_YAML}}) + gojira = FakeGojira(apps=[AppRow(id=1, name="kobo", status="active")]) + crane = FakeCrane(digests={"reg.example/apps/kobo:v2": NEW_DIGEST}) + new = f"reg.example/apps/kobo:v2@{NEW_DIGEST}" + old = f"reg.example/apps/kobo@{OLD_DIGEST}" + kubectl = FakeKubectl(images={"kobo": new}) # the template already names the new digest + kubectl.pods_script["kobo"] = [ + [(False, old, [True])], # poll 0: the old pod, ready, on the OLD image + [(True, old, [True])], # poll 1: the old pod terminating, still "ready" + [(False, new, [False])], # poll 2: the new pod, not ready yet + [(False, new, [True])], # poll 3: the new pod ready on the new image + ] + _, report, lines = _upgrade(tmp_path, stack, gojira=gojira, github=github, kubectl=kubectl, crane=crane, + rollout_seconds=5.0) + assert kubectl.pods_polls["kobo"] == 4 # not done at polls 0, 1 or 2 + assert any("rolled, 1/1 pods" in ln for ln in lines) + + +def test_pods_summary_counts_the_deployments_live_pods_on_its_image(): + new, old = "reg/apps/kobo:v2@sha256:bbbb", "reg/apps/kobo@sha256:aaaa" + rows = [(True, old, [True]), # terminating: not counted + (False, new, [True]), # the new pod, ready + (False, new, [True, False]), # a second new pod with a sidecar not ready + (False, "reg/apps/openfga:v1", [True])] # another deployment in the namespace + assert pods_summary(rows, new) == (1, 2) + assert pods_summary(rows) == (2, 3) # namespace-wide, as the install's "N/N pods ready" From fc42eb1f53242d7996a101f4bc6f4a34aee07e31 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 16:11:10 -0500 Subject: [PATCH 02/17] cabal is spoken to over HTTP; the stranger no longer builds a cbl The form's one box a stranger had to type was the path to `cbl`, cabal's command-line client, built from a cabal checkout. The installer called it twice: `cbl login` to trade the bootstrap code for an operator token, and `cbl token mint-service` to mint the tokens liminal and kobo hold. Both are HTTP calls (POST /auth/bootstrap, POST /admin/token/mint-service with the bearer) to the cabal Service, through the port-forward the installer already opens for them. HttpCabal makes the two calls itself, keeps the operator token for the run and writes it nowhere; the tunnel logic is unchanged. The --cbl flag, $STACK_CBL, the profile's cbl box and the preflight row are gone; the Profile keeps a cbl field so older profiles files still load. Tests: the two calls against a small HTTP stand-in (paths, bodies, the bearer, a refused code, a mint before login); the tunnel test moves to HttpCabal. Signed-off-by: Shaz Chaudhri Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 9 ++++ README.md | 10 ++--- docs/install.md | 8 ++-- stack/cli.py | 5 +-- stack/clients.py | 60 ++++++++++++++++----------- stack/preflight.py | 8 ---- stack/profiles.py | 5 +-- stack/runs.py | 12 ++---- stack/steps.py | 2 +- stack/templates/_profile_form.html | 3 -- stack/templates/profile.html | 2 +- stack/ui.py | 4 +- tests/fakes.py | 2 +- tests/test_cabal_http.py | 66 ++++++++++++++++++++++++++++++ tests/test_cli.py | 6 +-- tests/test_preflight.py | 6 +-- tests/test_profile_form.py | 3 +- tests/test_profiles.py | 3 +- tests/test_ui.py | 4 +- 19 files changed, 139 insertions(+), 79 deletions(-) create mode 100644 tests/test_cabal_http.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 1355ab3..75e1bc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -111,3 +111,12 @@ releases yet; everything is under Unreleased. kubectl's table, where the current context is marked with a star; it reads `-o name` now. Both picks (the env form's CLUSTER and the new add-profile form) carried it. +### Removed + +- **`cbl`.** The installer made two calls through cabal's command-line client: trade the + bootstrap code for an operator token, and mint the service tokens liminal and kobo hold. + Both are HTTP calls to cabal through the port-forward the installer already opens, so it + makes them itself (`HttpCabal`). The `--cbl` flag, `$STACK_CBL`, the profile's cbl box and + the preflight row are gone; a stranger no longer builds a cabal venv for a binary called + twice. The token lives in the run and is written nowhere. + diff --git a/README.md b/README.md index bd7d15a..9430d4d 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,7 @@ each step needs from you and what it leaves behind. Read it before you press. Before you start you need: a throwaway GCP project with billing and Owner on it; a GitHub organization you administer; `gcloud`, `kubectl`, `gh`, `terraform`, -`uv` and `crane` (no Docker), with `gcloud` and `gh` logged in; cabal's `cbl` -from a checkout of tenishai/cabal; about an hour. The guide's +`uv` and `crane` (no Docker), with `gcloud` and `gh` logged in; about an hour. The guide's [table](docs/install.md#before-you-start) has the notes on each. Nothing in `examples/stack.yaml` is edited: it carries `{org}`, `{project}`, @@ -35,7 +34,7 @@ every step reads before it writes. The same from a terminal: ```bash .venv/bin/stack env examples/stack.yaml --env-file gojira.env --gojira-repo ../gojira \ --set org= --set project= --set region=us-central1 --set cluster=gojira-sandbox -.venv/bin/stack install examples/stack.yaml --merge-setup-prs --cbl \ +.venv/bin/stack install examples/stack.yaml --merge-setup-prs \ --env-file gojira.env --set org=… --set project=… --set region=… --set cluster=… ``` @@ -200,8 +199,7 @@ is [docs/install.md](docs/install.md). ## What it needs `kubectl` on the install's context, `gh` logged in with access to the repos, -`gcloud` on the project, `terraform` for Install Gojira, for a stack with -cabal a `cbl` binary (`--cbl`, from cabal's own venv), and for `upgrade`, +`gcloud` on the project, `terraform` for Install Gojira, and for `upgrade`, `crane` (its registry auth comes from your docker credential helpers: `gcloud auth configure-docker ` covers Artifact Registry). Gojira is reached through a port-forward of its Service unless `gojira.url` is set. @@ -240,7 +238,7 @@ uv venv .venv && uv sync --locked # the lock is the pin; --locked refuses a st ``` The tests run the installer against fakes of the four hands (Gojira's API, -kubectl, gh, cbl), including the checked-in example end to end. +kubectl, gh, cabal), including the checked-in example end to end. ## Community diff --git a/docs/install.md b/docs/install.md index 52c8876..32a49a6 100644 --- a/docs/install.md +++ b/docs/install.md @@ -29,7 +29,6 @@ registry and applies the manifests. Nothing is built. | A GitHub organization you administer | The deploy repos, kobo's config repo and every agent repo are created there. | | `gcloud`, `kubectl`, `gh`, `terraform`, `uv`, `crane` | `gcloud components install gke-gcloud-auth-plugin` too. `crane` copies images (`brew install crane`). No Docker. | | `gcloud` and `gh` logged in | `gcloud auth login` as the project's owner; `gh auth login` as an account that can create repos in the org. | -| cabal's `cbl` | The switchboard's CLI, from a checkout of tenishai/cabal: `uv venv .venv && uv sync` there, then `.venv/bin/cbl`. The installer logs in to cabal with it once and mints the tokens the other apps hold. | | About an hour | Gojira's install is sixteen minutes of it; the rest is reading. | > More than one Google account on this machine? `kubectl` caches its token per @@ -52,8 +51,7 @@ is (nothing in it is edited); a kubeconfig of this install's own (`~/.kube-/config`, written when the cluster exists); your Google account (the one gcloud is logged in as; a pick when there are several); an env file for Gojira's values (`~/.config/stack//gojira.env`, need not -exist); the Gojira checkout `../gojira`; and cabal's `cbl`, the one box to -type. Picking an existing GKE cluster instead fills its project, region and +exist); and the Gojira checkout `../gojira`. Picking an existing GKE cluster instead fills its project, region and name on the next page. ## 2. Four things @@ -108,7 +106,7 @@ Press **Install all 4**. One run, the apps in the file's order; the page shows its lines as they happen. From a terminal it is: ```bash -.venv/bin/stack install examples/stack.yaml --merge-setup-prs --cbl \ +.venv/bin/stack install examples/stack.yaml --merge-setup-prs \ --env-file --set org=… --set project=… --set region=… --set cluster=… ``` @@ -120,7 +118,7 @@ What you will see, in order: the review: the repo exists for exactly this content). Its CI copies the image and applies; pods come up. 3. **cabal**: the same, then the installer catches cabal's one-time bootstrap - code from its log, logs in with `cbl`, and mints the tokens liminal and kobo + code from its log, logs in with it, and mints the tokens liminal and kobo will hold. 4. **liminal**: the same, holding its token. 5. **kobo**: the same, with the ClusterRole applied first and three Secrets; its diff --git a/stack/cli.py b/stack/cli.py index af08124..f6651a9 100644 --- a/stack/cli.py +++ b/stack/cli.py @@ -12,7 +12,7 @@ (examples/stack.yaml does): --set fills them, or the profile does in the UI. Needs on PATH: kubectl (on the install's context), gh (logged in), and for a -stack with `bootstrap: cabal`, a `cbl` (--cbl, or $STACK_CBL). Repos named +Repos named in `cluster_objects` are expected under --repos (default: the stack file's directory), cloned by you. """ @@ -58,7 +58,6 @@ def main(argv: list[str] | None = None) -> int: s.add_argument("--merge-setup-prs", action="store_true", help="merge every setup PR yourself (a first install of repos you own)") s.add_argument("--repos", default="", help="directory holding clones of the apps' repos") - s.add_argument("--cbl", default=os.environ.get("STACK_CBL", ""), help="path to a cbl binary") s.add_argument("--cabal-port", type=int, default=17497) s.add_argument("-v", "--verbose", action="store_true") s = sub.choices["upgrade"] @@ -106,7 +105,7 @@ def main(argv: list[str] | None = None) -> int: env_file = Path(a.env_file).expanduser() if getattr(a, "env_file", "") else None target = Target(stack_file=path, repos=Path(a.repos).expanduser() if getattr(a, "repos", "") else None, - cbl=getattr(a, "cbl", ""), cabal_port=getattr(a, "cabal_port", 17497), + cabal_port=getattr(a, "cabal_port", 17497), values=values, env_file=env_file) try: report = perform(target, a.cmd, a.apps, merge_setup_prs=a.merge_setup_prs, diff --git a/stack/clients.py b/stack/clients.py index 6cb33a9..104a696 100644 --- a/stack/clients.py +++ b/stack/clients.py @@ -711,7 +711,7 @@ def tags(self, repo) -> list[str]: return _run(["crane", "ls", repo], env=self._env).split() -# --- cabal (through its CLI, against a port-forward) ------------------------ +# --- cabal (over HTTP, against a port-forward) ------------------------------ class CabalClient(Protocol): @@ -719,26 +719,22 @@ def login(self, code: str) -> None: ... def mint(self, sub: str, scope: str, ttl_days: int) -> str: ... -class CblCLI: - """`cbl` from a venv, pointed at a port-forward of the cabal Service. - - CABAL_HOME is a directory the installer owns (the login token lands - there); the operator's own ~/.cabal is never touched. +class HttpCabal: + """cabal's two install-time calls, made directly: trade the bootstrap code + for an operator token (`POST /auth/bootstrap`, what `cbl login` does) and + mint a service token with it (`POST /admin/token/mint-service`, what + `cbl token mint-service` does). The token lives in this object for the + run and is written nowhere. No `cbl` on the machine, no CABAL_HOME. """ - def __init__(self, cbl: str, url: str, home: str, forward: Callable[[], subprocess.Popen] | None = None, - env: dict[str, str] | None = None): + def __init__(self, url: str, forward: Callable[[], subprocess.Popen] | None = None): # The port-forward is opened on demand, right before each call, and # reopened if it is gone: it cannot be opened at startup (the Service # does not exist yet on a fresh install) and it dies when the pod it # reached restarts (which the fresh-code step does on purpose). - self._cbl, self._url, self._home, self._forward = cbl, url, home, forward - self._extra = dict(env or {}) + self._url, self._forward = url.rstrip("/"), forward self._pf: subprocess.Popen | None = None - os.makedirs(home, mode=0o700, exist_ok=True) - - def _env(self) -> dict[str, str]: - return tool_env({**self._extra, "CABAL_HOME": self._home, "CABAL_URL": self._url}) + self._token = "" def _port_open(self) -> bool: u = urlparse(self._url) @@ -767,21 +763,35 @@ def close(self) -> None: if self._pf is not None: self._pf.terminate() + def _post(self, path: str, body: dict, what: str, token: str = "") -> dict: + headers = {"Authorization": f"Bearer {token}"} if token else {} + try: + r = httpx.post(self._url + path, json=body, headers=headers, timeout=30.0) + except httpx.HTTPError as exc: + raise ToolError(f"{what}: could not reach cabal at {self._url}: {exc}") from None + if r.status_code >= 400: + try: + detail = r.json().get("detail", r.text) + except ValueError: + detail = r.text + raise ToolError(f"{what} failed: {str(detail).strip()[-200:]}") + return r.json() + def login(self, code) -> None: self.ensure_tunnel() - proc = subprocess.run([self._cbl, "login"], input=code + "\n", capture_output=True, text=True, - env=self._env()) - if proc.returncode != 0 or "Logged in" not in proc.stdout + proc.stderr: - raise ToolError(f"cbl login failed: {(proc.stdout + proc.stderr).strip()[-200:]}") + body = self._post("/auth/bootstrap", {"code": code.strip().upper()}, "cabal login") + self._token = str(body.get("access_token", "")) + if not self._token: + raise ToolError("cabal login did not return a token") def mint(self, sub, scope, ttl_days) -> str: self.ensure_tunnel() - proc = subprocess.run([self._cbl, "token", "mint-service", "--sub", sub, "--scope", scope, - "--aud", "cabal-core", "--ttl-days", str(ttl_days)], - capture_output=True, text=True, env=self._env()) - if proc.returncode != 0: - raise ToolError(f"cbl token mint-service failed: {proc.stderr.strip()[-200:]}") - token = proc.stdout.strip().splitlines()[-1].strip() + if not self._token: + raise ToolError("cabal mint: not logged in (the bootstrap code was never traded)") + body = self._post("/admin/token/mint-service", + {"sub": sub, "scope": [scope], "aud": "cabal-core", "ttl_days": ttl_days}, + "cabal mint", token=self._token) + token = str(body.get("access_token", "")).strip() if token.count(".") != 2: - raise ToolError("cbl token mint-service did not print a JWT") + raise ToolError("cabal mint did not return a JWT") return token diff --git a/stack/preflight.py b/stack/preflight.py index 93c8c62..ec4e863 100644 --- a/stack/preflight.py +++ b/stack/preflight.py @@ -76,14 +76,6 @@ def check_tools(stack: Stack, target: Target, which: Callable[[str], str | None] out.append(Check(tool, "ok", path or "") if path else Check(tool, "fail", f"{tool} is not on PATH" + (" (brew install crane); upgrades copy images with it" if tool == "crane" else ""))) - if any(a.bootstrap == "cabal" for a in stack.apps): - if not target.cbl: - out.append(Check("cbl", "fail", "this stack bootstraps cabal: the profile needs the path to a cbl " - "(cabal's own venv, .venv/bin/cbl)")) - elif not Path(target.cbl).exists(): - out.append(Check("cbl", "fail", f"no such file: {target.cbl}")) - else: - out.append(Check("cbl", "ok", target.cbl)) return out diff --git a/stack/profiles.py b/stack/profiles.py index 8325b7f..ff99f0c 100644 --- a/stack/profiles.py +++ b/stack/profiles.py @@ -3,7 +3,7 @@ A profile is a name and pointers. The stack file stays the truth about the install; the profile adds what the shell used to carry and strangers got wrong — which kubeconfig, which cloud account, where the repo clones and the -`cbl` binary are — so every tool call is made with those pinned and nothing +clones are — so every tool call is made with those pinned and nothing depends on an export. The list lives in one small YAML file of the operator's own (`~/.config/stack/profiles.yaml`, or $STACK_PROFILES). Nothing in it is secret: paths, never contents. @@ -32,7 +32,7 @@ class Profile(BaseModel): kubeconfig: str = "" # KUBECONFIG for every kubectl call; empty = the operator's default cloud_account: str = "" # CLOUDSDK_CORE_ACCOUNT for gcloud-backed calls (kubectl's auth plugin) repos: str = "" # clones of the apps' upstream repos (--repos); empty = the stack file's dir - cbl: str = "" # the cabal CLI, for a stack that bootstraps cabal (--cbl) + cbl: str = "" # no longer used (cabal is spoken to over HTTP); kept so older profiles files still load env_file: str = "" # the install's gojira.env; recorded now, used by the install flow (#12 increment 2) gojira_repo: str = "" # the profile's Gojira checkout (Install Gojira runs its scripts/install.sh); empty = the repos dir's gojira clone # The four things the install is told (stack.site): they fill the stack @@ -69,7 +69,6 @@ def target(self) -> Target: return Target( stack_file=Path(self.stack_file).expanduser(), repos=Path(self.repos).expanduser() if self.repos else None, - cbl=str(Path(self.cbl).expanduser()) if self.cbl else "", env=self.env(), values=self.values(), env_file=Path(self.env_file).expanduser() if self.env_file else None, diff --git a/stack/runs.py b/stack/runs.py index 7f5a872..c20766c 100644 --- a/stack/runs.py +++ b/stack/runs.py @@ -2,12 +2,12 @@ `perform` is what `stack install` and `stack upgrade` do once the arguments are parsed: open the hands on the install (kubectl on the pinned context, -Gojira through its port-forward, gh, crane, cbl), run the steps, report +Gojira through its port-forward, gh, crane, cabal over HTTP), run the steps, report through `say`. The CLI prints each line; the UI keeps them in a `Run` and shows them while they happen. A `Target` is what a command line and a profile both reduce to: the stack -file, where the repo clones and `cbl` are, and the environment every tool +file, where the repo clones are, and the environment every tool call is pinned to (KUBECONFIG, CLOUDSDK_CORE_ACCOUNT). Runs happen one at a time — one operator, one machine — and live in memory: `stack ui` restarted forgets them, the cluster and the repos remember. @@ -24,7 +24,7 @@ from dataclasses import dataclass, field from pathlib import Path -from stack.clients import CblCLI, CraneCLI, CraneClient, GhCLI, HttpGojira, KubectlCLI, ToolError +from stack.clients import CraneCLI, CraneClient, GhCLI, HttpCabal, HttpGojira, KubectlCLI, ToolError from stack.model import App, Stack, reason from stack.steps import Clients, Installer, Options, Report, ref_parts @@ -36,7 +36,6 @@ class Target: stack_file: Path repos: Path | None = None # default: the stack file's directory - cbl: str = "" cabal_port: int = 17497 env: dict[str, str] = field(default_factory=dict) values: dict[str, str] = field(default_factory=dict) # org/project/region/cluster: fill the stack file's tokens @@ -100,11 +99,8 @@ def _no_pause(path: Path, why: str) -> threading.Event | None: and not any(x.needs_cabal() for x in stack.apps if x.name in apps): cabal_app = None # the named apps neither are cabal nor mint on it if cabal_app is not None: - if not target.cbl: - raise ToolError("this stack bootstraps cabal: pass --cbl (or STACK_CBL)") ns, svc, port = cabal_app.namespace, f"svc/{cabal_app.name}", target.cabal_port - cabal = CblCLI(target.cbl, f"http://127.0.0.1:{port}", str(target.stack_file.parent / ".cabal-home"), - forward=lambda: kubectl.port_forward(ns, svc, port, 80), env=env) + cabal = HttpCabal(f"http://127.0.0.1:{port}", forward=lambda: kubectl.port_forward(ns, svc, port, 80)) clients = Clients(gojira=gojira, kubectl=kubectl, github=GhCLI(env), cabal=cabal) opts = Options(stack_dir=target.stack_file.parent, repo_root=target.repo_root, merge_setup_prs=merge_setup_prs, say=say, on_pause=pause_cb, on_resume=resume_cb, diff --git a/stack/steps.py b/stack/steps.py index 67b9d54..10162bc 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -563,7 +563,7 @@ def bootstrap_cabal(self, app: App) -> None: what the log shows from the last few minutes, and on a miss or a refusal the deployment is restarted once for a fresh one.""" if self.c.cabal is None: - raise ToolError("no cabal client configured (cbl)") + raise ToolError("no cabal client configured") code = self.c.kubectl.logs_grep(app.namespace, app.name, BOOTSTRAP_CODE, since="4m") if code: try: diff --git a/stack/templates/_profile_form.html b/stack/templates/_profile_form.html index f9c4f09..b40248d 100644 --- a/stack/templates/_profile_form.html +++ b/stack/templates/_profile_form.html @@ -38,9 +38,6 @@

Where the page writes Gojira's settings (project, cluster, the App's id and key). It need not exist.

-
-

cabal's command-line client; the install logs in to cabal with it once. From a checkout of tenishai/cabal: - uv venv .venv && uv sync, then .venv/bin/cbl.

{% if p %}
diff --git a/stack/templates/profile.html b/stack/templates/profile.html index 25c57fc..27a1a0c 100644 --- a/stack/templates/profile.html +++ b/stack/templates/profile.html @@ -163,7 +163,7 @@

Apps {{ stack.apps | length } {% for a in stack.apps %} - {{ a.name }}{% if a.bootstrap %} bootstrap{% endif %} + {{ a.name }}{% if a.bootstrap %} bootstrap{% endif %} {% if a.door %}
{% endif %} {{ a.connected_repo }}{% if a.deploy_repo %}from {{ a.repo }}{% endif %} {% if a.image %}{% set tag, digest = a.image | image_parts %} diff --git a/stack/ui.py b/stack/ui.py index 8bab19c..76bf72d 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -262,7 +262,7 @@ def index(request: Request): @app.post("/profiles") def save_profile(request: Request, name: str = Form(), stack_file: str = Form(), kubeconfig: str = Form(""), cloud_account: str = Form(""), repos: str = Form(""), - cbl: str = Form(""), env_file: str = Form(""), gojira_repo: str = Form(""), + env_file: str = Form(""), gojira_repo: str = Form(""), org: str = Form(""), gcp_project: str = Form(""), region: str = Form(""), cluster: str = Form(""), context: str = Form("")): # A GKE context picked on the add form names three of the four things @@ -272,7 +272,7 @@ def save_profile(request: Request, name: str = Form(), stack_file: str = Form(), gcp_project, region, cluster = gcp_project or m[1], region or m[2], cluster or m[3] try: profile = Profile(name=name.strip(), stack_file=stack_file.strip(), kubeconfig=kubeconfig.strip(), - cloud_account=cloud_account.strip(), repos=repos.strip(), cbl=cbl.strip(), + cloud_account=cloud_account.strip(), repos=repos.strip(), env_file=env_file.strip(), gojira_repo=gojira_repo.strip(), org=org.strip(), gcp_project=gcp_project.strip(), region=region.strip(), cluster=cluster.strip()) diff --git a/tests/fakes.py b/tests/fakes.py index 148e8cf..2d7545d 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -318,7 +318,7 @@ def login(self, code): if len(code) != 6: raise ToolError("bad code") if code in self.expired: - raise ToolError("cbl login failed: code expired") + raise ToolError("cabal login failed: code expired") self.logged_in = code def mint(self, sub, scope, ttl_days): diff --git a/tests/test_cabal_http.py b/tests/test_cabal_http.py new file mode 100644 index 0000000..eb7585b --- /dev/null +++ b/tests/test_cabal_http.py @@ -0,0 +1,66 @@ +"""cabal over HTTP: the two calls `cbl` made for the installer, made by the +installer itself. A stranger no longer builds a cabal venv to get a binary +that was called twice (the stranger run, 2026-11-30).""" + +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest + +from stack.clients import HttpCabal, ToolError + + +class _Cabal(BaseHTTPRequestHandler): + seen: list[tuple[str, dict, str]] = [] + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0")) or "{}")) + self.seen.append((self.path, body, self.headers.get("Authorization", ""))) + if self.path == "/auth/bootstrap": + if body.get("code") != "ABC123": + return self._send(401, {"detail": "unknown or expired bootstrap code"}) + return self._send(200, {"access_token": "op.tok.en", "persona": None}) + if self.path == "/admin/token/mint-service": + if self.headers.get("Authorization") != "Bearer op.tok.en": + return self._send(401, {"detail": "not an operator"}) + return self._send(200, {"access_token": "h.svc.s", "sub": body["sub"], "scope": body["scope"], + "aud": body["aud"], "expires_at": "later"}) + return self._send(404, {"detail": "no"}) + + def _send(self, code, obj): + data = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *a): # quiet + pass + + +@pytest.fixture +def cabal(): + _Cabal.seen = [] + srv = HTTPServer(("127.0.0.1", 0), _Cabal) + t = threading.Thread(target=srv.serve_forever, daemon=True) + t.start() + yield HttpCabal(f"http://127.0.0.1:{srv.server_port}") + srv.shutdown() + + +def test_login_trades_the_code_and_mint_uses_the_token(cabal): + cabal.login(" abc123 ") # as cbl does: stripped, upper-cased + assert cabal.mint("service:liminal", "secrets-fetch", 90) == "h.svc.s" + assert _Cabal.seen[0] == ("/auth/bootstrap", {"code": "ABC123"}, "") + path, body, auth = _Cabal.seen[1] + assert path == "/admin/token/mint-service" and auth == "Bearer op.tok.en" + assert body == {"sub": "service:liminal", "scope": ["secrets-fetch"], "aud": "cabal-core", "ttl_days": 90} + + +def test_a_refused_code_and_a_mint_without_login_are_sentences(cabal): + with pytest.raises(ToolError, match="cabal login failed: unknown or expired bootstrap code"): + cabal.login("NOPE00") + with pytest.raises(ToolError, match="not logged in"): + cabal.mint("service:kobo", "operator", 90) diff --git a/tests/test_cli.py b/tests/test_cli.py index 5e0a134..6ee40c5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -22,14 +22,14 @@ def test_check_runs_with_a_hostile_pythonpath(tmp_path): assert "4 apps, in order: litellm, cabal, liminal, kobo" in done.stdout -def test_cbl_opens_its_tunnel_on_demand_and_reopens_a_dead_one(tmp_path): +def test_cabal_opens_its_tunnel_on_demand_and_reopens_a_dead_one(tmp_path): """The forward cannot exist at startup (no Service yet) and dies when the pod restarts; each call checks the port and (re)opens the forward.""" import socket import subprocess import sys - from stack.clients import CblCLI + from stack.clients import HttpCabal srv = socket.socket() srv.bind(("127.0.0.1", 0)) @@ -43,7 +43,7 @@ def forward(): return subprocess.Popen([sys.executable, "-c", f"import socket,time; s=socket.socket(); s.bind(('127.0.0.1',{port})); s.listen(); time.sleep(60)"]) - cbl = CblCLI("/bin/true", f"http://127.0.0.1:{port}", str(tmp_path / "home"), forward=forward) + cbl = HttpCabal(f"http://127.0.0.1:{port}", forward=forward) cbl.ensure_tunnel(timeout=10) assert opened == [1] cbl.ensure_tunnel(timeout=10) # still up: no second forward diff --git a/tests/test_preflight.py b/tests/test_preflight.py index 5d30f3f..c750e32 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -59,11 +59,7 @@ def test_tools_are_asked_for_only_when_the_stack_needs_them(tmp_path): """) checks = check_tools(stack, target, which=lambda t: f"/usr/bin/{t}" if t != "crane" else None) assert _by(checks, "crane").status == "fail" and "brew install crane" in _by(checks, "crane").detail - assert "cbl" in _by(checks, "cbl").detail and _by(checks, "cbl").status == "fail" - target.cbl = str(tmp_path / "cbl") - assert _by(check_tools(stack, target, which=lambda t: t), "cbl").detail.startswith("no such file") - (tmp_path / "cbl").write_text("") - assert _by(check_tools(stack, target, which=lambda t: t), "cbl").status == "ok" + assert not [c for c in checks if c.what == "cbl"] # cabal is spoken to over HTTP: no binary to ask for def test_github_names_the_sso_gap_and_the_repos_it_cannot_see(tmp_path): diff --git a/tests/test_profile_form.py b/tests/test_profile_form.py index 2caedcf..76ae7af 100644 --- a/tests/test_profile_form.py +++ b/tests/test_profile_form.py @@ -39,8 +39,9 @@ def test_the_add_form_offers_the_clusters_kubectl_knows_and_prefills_the_rest(tm assert 'value="me@example.com"' in page # the one account gcloud knows assert "Building the apps from source" in page # --repos is folded away assert 'name="org"' not in page # the four are asked on the profile page's card - for line in ("A short word for this install", "need not exist", "cabal's command-line client"): + for line in ("A short word for this install", "need not exist", "The account gcloud is logged in as"): assert line in page + assert 'name="cbl"' not in page # cabal is spoken to over HTTP; no binary to name def test_picking_a_gke_cluster_fills_the_three_it_names(tmp_path): diff --git a/tests/test_profiles.py b/tests/test_profiles.py index e86b1b0..be6e3ea 100644 --- a/tests/test_profiles.py +++ b/tests/test_profiles.py @@ -10,12 +10,11 @@ def test_a_profile_pins_the_environment_and_expands_its_paths(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) p = Profile(name="prod", stack_file="~/stack/prod.yaml", kubeconfig="~/.kube-prod/config", - cloud_account="me@example.com", repos="~/src", cbl="~/cabal/.venv/bin/cbl") + cloud_account="me@example.com", repos="~/src") assert p.env() == {"KUBECONFIG": str(tmp_path / ".kube-prod/config"), "CLOUDSDK_CORE_ACCOUNT": "me@example.com"} t = p.target() assert t.stack_file == tmp_path / "stack/prod.yaml" assert t.repos == tmp_path / "src" - assert t.cbl == str(tmp_path / "cabal/.venv/bin/cbl") assert t.env == p.env() # nothing pinned when nothing is set: the operator's defaults apply assert Profile(name="dev", stack_file="x.yaml").env() == {} diff --git a/tests/test_ui.py b/tests/test_ui.py index 2f1b870..49e3927 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -49,7 +49,7 @@ def preflight(stack, target): def _add(site, **fields): form = {"name": "dogfood", "stack_file": str(DOGFOOD), "kubeconfig": "~/.kube-dogfood/config", - "cloud_account": "me@example.com", "cbl": "~/cabal/.venv/bin/cbl", **fields} + "cloud_account": "me@example.com", **fields} return site.post("/profiles", data=form, follow_redirects=False) @@ -82,7 +82,7 @@ def test_a_run_gets_the_profiles_target_and_shows_its_lines_and_its_stop(site): target, action, apps, merge, yes, pins = site.calls[0] assert action == "install" and apps == ["litellm", "boom"] and yes is False assert merge is True and pins is True # the press is the review - assert target.stack_file == DOGFOOD and target.cbl.endswith("cabal/.venv/bin/cbl") + assert target.stack_file == DOGFOOD assert target.env["CLOUDSDK_CORE_ACCOUNT"] == "me@example.com" assert target.env["KUBECONFIG"].endswith(".kube-dogfood/config") and "~" not in target.env["KUBECONFIG"] page = site.get("/runs/1").text From 7fef2fb22299c97a00570cd0d57c7b7bc9e37593 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 16:15:23 -0500 Subject: [PATCH 03/17] The Gojira checkout is fetched at the stack file's version, not asked for The add form's other box a stranger could not place was "Gojira checkout": the README told them to clone tenishai/gojira beside the installer, and the form asked where they had put it. Install Gojira needs the checkout (its install script, terraform, manifests), the App card reads its docs/github-app-setup.md and the env form its gojira.env.example; none of that needs the person to choose a directory. The stack file names the release: gojira.version, a tag of tenishai/gojira (the stranger file says v1.3.1, the latest release). Adding a profile fetches it once, a shallow clone into ~/.cache/stack/gojira/ ($STACK_CACHE overrides), and the three readers take it from there; a page render never clones, and a press whose fetch failed says why. A developer's own checkout is still gojira_repo on the settings form, and the repos dir's gojira clone still wins, so the dogfood keeps installing from main. The quickstart loses its git clone line. Tests: adding fetches once and renders never refetch; a stack file without a version is refused with the key's name; a failed fetch does not break the add and is a sentence on the press. Signed-off-by: Shaz Chaudhri Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 7 ++ README.md | 11 ++-- docs/install.md | 7 +- examples/stack.yaml | 3 + stack/model.py | 5 ++ stack/templates/_profile_form.html | 12 ++-- stack/templates/profile.html | 2 +- stack/ui.py | 100 ++++++++++++++++++++++++----- tests/test_gojira_checkout.py | 77 ++++++++++++++++++++++ tests/test_model.py | 1 + 10 files changed, 194 insertions(+), 31 deletions(-) create mode 100644 tests/test_gojira_checkout.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 75e1bc5..3a1f424 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,13 @@ releases yet; everything is under Unreleased. ### Changed +- **The Gojira checkout is fetched, not asked for.** The stack file names the release + (`gojira.version`, a tag of tenishai/gojira); adding a profile fetches it once into + `~/.cache/stack/gojira/`, and Install Gojira, the App card and the env form read + from there. The "Gojira checkout" box leaves the add form (a developer's own checkout is + still `gojira_repo` in the settings form, and the repos dir's clone still wins); the + quickstart loses its `git clone … ../gojira` line. A render never clones; a press that + needs a fetch that failed says so. - **The README reads first.** It opened with "onto a running Gojira" and `make install` in gojira as step one, the order before the page existed. It now opens with the quickstart as the guide has it (clone, sync, Gojira beside it, `stack ui`), the profile diff --git a/README.md b/README.md index 9430d4d..d72e206 100644 --- a/README.md +++ b/README.md @@ -9,12 +9,11 @@ page, one file, and the merges stay with a person. ```bash git clone https://github.com/tenishai/stack && cd stack uv venv .venv && uv sync --locked --extra ui -git clone https://github.com/tenishai/gojira ../gojira # Gojira's own install scripts .venv/bin/stack ui # localhost:8097 ``` -The page asks for a profile (a name; a cluster to install onto, or a new one; -the rest is prefilled and explained), then four things: your GitHub +The page asks for a profile (a name, and a cluster to install onto or a new +one; the rest is prefilled), then four things: your GitHub organization, your GCP project, a region, a cluster name. From there it is buttons, in order: the GitHub App (the one pause only you can take), **Install Gojira** (terraform makes the cluster, about sixteen minutes), **Install** for the apps, **Open** for the @@ -167,8 +166,8 @@ contents. A profile's page shows what its stack file says, and its buttons: - **Install Gojira** — when the profile's context has no Gojira, or no cluster yet and the env file says terraform owns it, the page runs Gojira's own - `install.sh` from the checkout the profile names, with the env file the four - things wrote. Its lines stream like any run's. On an installed Gojira the same + `install.sh` from the release the stack file names (`gojira.version`, fetched + once into `~/.cache/stack/gojira/`), with the env file the four things wrote. Its lines stream like any run's. On an installed Gojira the same button reads "Run install.sh again": the upgrade path, idempotent. - **Check** — preflight. Tools on PATH, every file the stack file names, whether gh is logged in and its token sees the repos' orgs (a token with @@ -199,7 +198,7 @@ is [docs/install.md](docs/install.md). ## What it needs `kubectl` on the install's context, `gh` logged in with access to the repos, -`gcloud` on the project, `terraform` for Install Gojira, and for `upgrade`, +`gcloud` on the project, `git` and `terraform` for Install Gojira, and for `upgrade`, `crane` (its registry auth comes from your docker credential helpers: `gcloud auth configure-docker ` covers Artifact Registry). Gojira is reached through a port-forward of its Service unless `gojira.url` is set. diff --git a/docs/install.md b/docs/install.md index 32a49a6..8d03b71 100644 --- a/docs/install.md +++ b/docs/install.md @@ -27,7 +27,7 @@ registry and applies the manifests. Nothing is built. |---|---| | A GCP project with billing, and Owner on it | A throwaway. Gojira's identity gets broad IAM in it, and so does the room's. Fine for a sandbox and nowhere else. | | A GitHub organization you administer | The deploy repos, kobo's config repo and every agent repo are created there. | -| `gcloud`, `kubectl`, `gh`, `terraform`, `uv`, `crane` | `gcloud components install gke-gcloud-auth-plugin` too. `crane` copies images (`brew install crane`). No Docker. | +| `git`, `gcloud`, `kubectl`, `gh`, `terraform`, `uv`, `crane` | `gcloud components install gke-gcloud-auth-plugin` too. `crane` copies images (`brew install crane`). No Docker. | | `gcloud` and `gh` logged in | `gcloud auth login` as the project's owner; `gh auth login` as an account that can create repos in the org. | | About an hour | Gojira's install is sixteen minutes of it; the rest is reading. | @@ -40,7 +40,6 @@ registry and applies the manifests. Nothing is built. ```bash git clone https://github.com/tenishai/stack && cd stack uv venv .venv && uv sync --locked --extra ui -git clone https://github.com/tenishai/gojira ../gojira # Gojira's own install scripts .venv/bin/stack ui ``` @@ -51,7 +50,9 @@ is (nothing in it is edited); a kubeconfig of this install's own (`~/.kube-/config`, written when the cluster exists); your Google account (the one gcloud is logged in as; a pick when there are several); an env file for Gojira's values (`~/.config/stack//gojira.env`, need not -exist); and the Gojira checkout `../gojira`. Picking an existing GKE cluster instead fills its project, region and +exist). Adding the profile fetches the Gojira release the stack file names +(`gojira.version`) into `~/.cache/stack/gojira/`: that is where +Install Gojira runs from, and nothing is cloned by hand. Picking an existing GKE cluster instead fills its project, region and name on the next page. ## 2. Four things diff --git a/examples/stack.yaml b/examples/stack.yaml index 30b7029..8d9bfc9 100644 --- a/examples/stack.yaml +++ b/examples/stack.yaml @@ -16,6 +16,9 @@ gojira: namespace: gojira + # The Gojira release Install Gojira installs (a tag of tenishai/gojira). The page + # fetches it once into ~/.cache/stack/gojira/; nothing to clone by hand. + version: v1.3.1 # Pin the context: your current kubectl context can be any cluster. This is the # name `gcloud container clusters get-credentials` writes for the cluster below. kube_context: gke_{project}_{region}_{cluster} diff --git a/stack/model.py b/stack/model.py index 6dbb116..d1fbf24 100644 --- a/stack/model.py +++ b/stack/model.py @@ -222,6 +222,11 @@ class Gojira(BaseModel): # Service in `namespace` on the current kubectl context. url: str = "" kube_context: str = "" + # The Gojira release Install Gojira installs: a tag of tenishai/gojira, + # fetched once into ~/.cache/stack/gojira/ on the machine that + # presses. Empty = the profile's own checkout (gojira_repo) or the gojira + # clone under its repos dir, as before. + version: str = "" def reason(exc: BaseException) -> str: diff --git a/stack/templates/_profile_form.html b/stack/templates/_profile_form.html index b40248d..7e270d4 100644 --- a/stack/templates/_profile_form.html +++ b/stack/templates/_profile_form.html @@ -31,15 +31,17 @@

The list of apps to install and where their images come from. The one that ships with the installer is right as it is.

-
-

The tenishai/gojira clone from the quickstart (git clone https://github.com/tenishai/gojira ../gojira). - Install Gojira runs its install script.

-
-

Where the page writes Gojira's settings (project, cluster, the App's id and key). It need not exist.

{% if p %} +
+
+

A developer's own tenishai/gojira checkout. Empty = the release the stack file names + (gojira.version), fetched into ~/.cache/stack/gojira/<version>.

+
+ {% endif %} + {% if p %}
diff --git a/stack/templates/profile.html b/stack/templates/profile.html index 27a1a0c..7ce3083 100644 --- a/stack/templates/profile.html +++ b/stack/templates/profile.html @@ -72,7 +72,7 @@

Check

The full walkthrough — permissions, why each, the webhook secret, verification — is in {{ app_setup.doc }}.

{% else %} -

No docs/github-app-setup.md in the profile's Gojira checkout (set gojira_repo in Profile settings); the App's settings live there.

+

No docs/github-app-setup.md to read: name the Gojira release as gojira.version in the stack file (fetched when the profile is added), or set gojira_repo in Profile settings; the App's settings live there.

{% endif %}
diff --git a/stack/ui.py b/stack/ui.py index 76bf72d..90233af 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -12,13 +12,16 @@ import os import re +import shutil import socket +import subprocess import threading import time from collections.abc import Callable from pathlib import Path from typing import Any +import yaml from fastapi import FastAPI, Form, Request from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates @@ -52,13 +55,46 @@ def image_parts(image: str) -> tuple[str, str]: TEMPLATES.env.filters["image_parts"] = image_parts -def _example_path(profile) -> Path | None: +GOJIRA_REPO = "https://github.com/tenishai/gojira" + + +def gojira_cache(version: str) -> Path: + """Where a fetched Gojira release lives on this machine.""" + return Path(os.environ.get("STACK_CACHE", "~/.cache/stack")).expanduser() / "gojira" / version + + +def fetch_gojira(version: str, dest: Path) -> None: + """A shallow clone of tenishai/gojira at the tag `version` into `dest`: the + install scripts, terraform, manifests, gojira.env.example and the App doc the + page reads. Nothing of the person's; a failed fetch leaves no half directory.""" + dest.parent.mkdir(parents=True, exist_ok=True) + r = subprocess.run(["git", "clone", "--quiet", "--depth", "1", "--branch", version, GOJIRA_REPO, str(dest)], + capture_output=True, text=True, env=tool_env(), timeout=300) + if r.returncode != 0: + shutil.rmtree(dest, ignore_errors=True) + raise ToolError(f"could not fetch Gojira {version} from {GOJIRA_REPO}: {r.stderr.strip()[-200:]}") + + +def _stack_gojira_version(stack_file: str) -> str: + """`gojira.version` read from the stack file as written: the four tokens need + not be filled for this one line, and a file that does not read is no version.""" + try: + data = yaml.safe_load(Path(stack_file).expanduser().read_text()) + except Exception: + return "" + gojira = data.get("gojira") if isinstance(data, dict) else None + return str((gojira or {}).get("version") or "").strip() if isinstance(gojira, dict) else "" + + +def _example_path(profile, checkout: Path | None = None) -> Path | None: """The gojira.env.example the profile's Gojira checkout ships, when one is under its repos dir: the gojira repo the stack references (else the first clone under the repos dir). The repos dir is the source; a checkout the operator has elsewhere is not guessed at.""" base = Path(profile.repos).expanduser() if profile.repos else None guesses = [] + if checkout is not None: + guesses.append(checkout / "gojira.env.example") if getattr(profile, "gojira_repo", ""): guesses.append(Path(profile.gojira_repo).expanduser() / "gojira.env.example") if base is not None: @@ -169,7 +205,7 @@ def _app_usable(app_id: str, app_pem: str) -> bool: return True -def _app_setup_doc(profile: Profile) -> dict: +def _app_setup_doc(profile: Profile, checkout: Path | None = None) -> dict: """The GitHub App settings, read from the checkout's docs/github-app-setup.md at render time (criterion 3: the table has changed twice this month, so the card renders the doc's current table, never a copy in our tree). Returns the @@ -178,6 +214,8 @@ def _app_setup_doc(profile: Profile) -> dict: The checkout is profile.gojira_repo, else the gojira clone under the repos dir.""" import re candidates = [] + if checkout is not None: + candidates.append(checkout / "docs" / "github-app-setup.md") if profile.gojira_repo: candidates.append(Path(profile.gojira_repo).expanduser() / "docs" / "github-app-setup.md") if profile.repos: @@ -201,7 +239,8 @@ def _app_setup_doc(profile: Profile) -> dict: def make_app(profiles_path: Path, runner: _runs.Runner | None = None, perform: Callable = _runs.perform, preflight: Callable = _preflight.preflight, crane: Callable = CraneCLI, github: Callable = GhCLI, - kubectl: Callable = KubectlCLI, gcloud: Callable = GcloudCLI) -> FastAPI: + kubectl: Callable = KubectlCLI, gcloud: Callable = GcloudCLI, + fetch: Callable[[str, Path], None] = fetch_gojira) -> FastAPI: app = FastAPI(title="stack") runner = runner or _runs.Runner(profiles_path.parent / "runs") # runs outlive the process (criterion 7) @@ -211,6 +250,27 @@ def page(name: str, request: Request, status_code: int = 200, **ctx) -> HTMLResp def load_profile(name: str) -> Profile | None: return Profiles.load(profiles_path).get(name) + def gojira_checkout(profile: Profile, fetching: bool = True) -> Path | None: + """The Gojira this profile installs from, in order: the profile's own + checkout (gojira_repo, a developer's); the gojira clone under its repos + dir; else the release the stack file names (gojira.version), fetched once + into ~/.cache/stack/gojira/. `fetching=False` only looks (a page + render never clones); a press fetches, and a failed fetch is a ToolError + the press turns into a sentence.""" + if profile.gojira_repo: + return Path(profile.gojira_repo).expanduser() + if profile.repos and (Path(profile.repos).expanduser() / "gojira" / "scripts" / "install.sh").exists(): + return Path(profile.repos).expanduser() / "gojira" + version = _stack_gojira_version(profile.stack_file) + if not version: + return None + dest = gojira_cache(version) + if not (dest / "scripts" / "install.sh").exists(): + if not fetching: + return None + fetch(version, dest) + return dest + def notice(request: Request, status_code: int, text: str, *, title: str = "Not done", level: str = "fail", link: str = "", link_text: str = "") -> HTMLResponse: """A refusal as a page of its own, not bare text: the words a test @@ -226,14 +286,12 @@ def stack_or_error(profile: Profile) -> tuple[Stack | None, str]: def form_defaults() -> dict[str, Any]: """What the add-profile form can know without asking: the stack file - that ships with the installer, the Gojira clone the quickstart puts - beside it, the kubeconfig kubectl uses by default, the clusters that + that ships with the installer, the kubeconfig kubectl uses by default, the clusters that kubeconfig knows, and the accounts gcloud is logged in as. Each is a prefill or a pick, never a requirement; a missing tool is an empty list, not a page that breaks.""" root = Path(__file__).resolve().parent.parent shipped = root / "examples" / "stack.yaml" - gojira = root.parent / "gojira" kc = os.environ.get("KUBECONFIG", "").split(os.pathsep)[0] or "~/.kube/config" try: contexts = kubectl(env={}).list_contexts() @@ -244,7 +302,6 @@ def form_defaults() -> dict[str, Any]: except Exception: accounts = [] return {"stack_file": str(shipped) if shipped.exists() else "", - "gojira_repo": str(gojira) if (gojira / "scripts" / "install.sh").exists() else "", "default_kubeconfig": kc, "contexts": contexts, "accounts": accounts} def index_rows(): @@ -282,6 +339,13 @@ def save_profile(request: Request, name: str = Form(), stack_file: str = Form(), book = Profiles.load(profiles_path) book.put(profile) book.save(profiles_path) + # the Gojira release the stack file names is fetched now, once, so the + # pages that read it (the App card, the env form) never clone at render; + # a fetch that fails says so on the press that needs it + try: + gojira_checkout(profile) + except ToolError: + pass return RedirectResponse(f"/p/{profile.name}", status_code=303) @app.post("/profiles/{name}/delete") @@ -358,7 +422,7 @@ def profile_page(name: str, request: Request): # before the first /), when they agree; else the first one. orgs = {a.repo.split("/")[0] for a in stack.apps} if stack is not None else set() stack_org = next(iter(orgs)) if len(orgs) == 1 else (next(iter(orgs)) if orgs else "") - app_setup = _app_setup_doc(profile) + app_setup = _app_setup_doc(profile, gojira_checkout(profile, fetching=False)) # The four things (stack.site): shown as a card until Gojira is installed — # the env file Gojira installs from is written from them, so they come # first. The card reads back what the env file holds (never what a form @@ -400,7 +464,7 @@ async def save_values(name: str, request: Request): if stack is None: return notice(request, 422, f"saved on the profile, but the stack file does not read with them: {error}", level="warn", link=f"/p/{name}", link_text=f"Back to {name}") - example = _example_path(profile) + example = _example_path(profile, gojira_checkout(profile, fetching=False)) env_path = Path(profile.env_file).expanduser() if not env_path.exists() and example is None: return notice(request, 422, f"{env_path} does not exist yet and no gojira.env.example was found to start " @@ -532,7 +596,7 @@ def env_page(name: str, request: Request): raw = env_path.read_text() # docs: the example's one-liner where it has one, else the page's own - example = _example_path(profile) + example = _example_path(profile, gojira_checkout(profile, fetching=False)) example_docs = _envfile.example_docs(example.read_text()) if example and example.exists() else {} docs = {k: (example_docs.get(k) or fallback) for k, fallback in _envfile.KNOWN_KNOBS} values = _envfile.get_all(raw) if raw else {k: "" for k, _ in _envfile.KNOWN_KNOBS} @@ -656,7 +720,6 @@ def install_gojira(name: str, request: Request): if profile is None: return notice(request, 404, f"no profile {name!r}", title="No such profile", link="/", link_text="Profiles") env_path = Path(profile.env_file).expanduser() if profile.env_file else None - repo = Path(profile.gojira_repo).expanduser() if profile.gojira_repo else None # Refused before anything runs: name the thing that is missing, and only it. if env_path is None: return notice(request, 422, "Install Gojira needs the profile's env file (Gojira env file) set first", @@ -664,12 +727,17 @@ def install_gojira(name: str, request: Request): if not env_path.exists(): return notice(request, 422, f"no such env file: {env_path}", level="warn", link=f"/p/{name}/env", link_text="Go to the env form") - # the checkout: gojira_repo if set, else the repos dir's gojira clone - if repo is None and profile.repos: - repo = Path(profile.repos).expanduser() / "gojira" + # the checkout: the profile's own, the repos dir's clone, or the release the + # stack file names, fetched now if it is not on this machine yet + try: + repo = gojira_checkout(profile) + except ToolError as exc: + return notice(request, 422, f"Install Gojira could not fetch Gojira: {exc}", + level="warn", link=f"/p/{name}", link_text=f"Back to {name}") if repo is None or not (repo / "scripts" / "install.sh").exists(): - return notice(request, 422, "Install Gojira needs the profile's Gojira checkout (gojira_repo) with a " - "scripts/install.sh; set it in Profile settings", + return notice(request, 422, "Install Gojira needs a Gojira checkout: name the release as gojira.version " + "in the stack file (fetched into ~/.cache/stack/gojira/), or set " + "gojira_repo in Profile settings", level="warn", link=f"/p/{name}", link_text=f"Back to {name}") stack, _ = stack_or_error(profile) target = profile.target() diff --git a/tests/test_gojira_checkout.py b/tests/test_gojira_checkout.py new file mode 100644 index 0000000..6b84555 --- /dev/null +++ b/tests/test_gojira_checkout.py @@ -0,0 +1,77 @@ +"""The Gojira the page installs is the release the stack file names, fetched +once into a cache; the stranger clones nothing by hand (the stranger run, +2026-11-30: a "Gojira checkout" box nobody could explain).""" + +from pathlib import Path + +from fastapi.testclient import TestClient + +from stack.clients import ToolError +from stack.runs import Runner +from stack.ui import make_app +from tests.fakes import FakeGcloud, FakeKubectl + +STACK = """gojira: + namespace: gojira + version: v1.3.1 +cluster: {name: sandbox, gcp_project: proj, location: us-central1} +apps: [] +""" + + +def _site(tmp_path, monkeypatch, fetch, stack_text=STACK): + monkeypatch.setenv("STACK_CACHE", str(tmp_path / "cache")) + (tmp_path / "stack.yaml").write_text(stack_text) + app = make_app(tmp_path / "p.yaml", Runner(), perform=lambda *a, **k: None, preflight=lambda s, t: [], + kubectl=lambda *, env: FakeKubectl(), gcloud=lambda *, env: FakeGcloud(), fetch=fetch) + site = TestClient(app) + site.stack_file = tmp_path / "stack.yaml" + return site + + +def _fake_fetch(calls): + def fetch(version, dest: Path): + calls.append((version, dest)) + (dest / "scripts").mkdir(parents=True) + (dest / "scripts" / "install.sh").write_text("#!/bin/bash\nexit 0\n") + (dest / "docs").mkdir() + (dest / "docs" / "github-app-setup.md").write_text("| Field | Level |\n|---|---|\n| Zebra permissions | Read & write |\n") + (dest / "gojira.env.example").write_text("# GOJIRA_PROJECT\nGOJIRA_PROJECT=\n") + return fetch + + +def test_adding_a_profile_fetches_the_release_the_stack_file_names_once(tmp_path, monkeypatch): + calls = [] + site = _site(tmp_path, monkeypatch, _fake_fetch(calls)) + page = site.get("/").text + assert 'name="gojira_repo"' not in page # nothing to type on the add form + r = site.post("/profiles", data={"name": "sandbox", "stack_file": str(site.stack_file)}, follow_redirects=False) + assert r.status_code == 303 + assert calls == [("v1.3.1", tmp_path / "cache" / "gojira" / "v1.3.1")] + site.get("/p/sandbox") + site.get("/p/sandbox/env") + assert len(calls) == 1 # a render never clones + assert 'name="gojira_repo"' in site.get("/p/sandbox").text # a developer's override lives in the settings form + + +def test_install_gojira_names_what_is_missing_when_the_stack_file_has_no_version(tmp_path, monkeypatch): + calls = [] + site = _site(tmp_path, monkeypatch, _fake_fetch(calls), stack_text=STACK.replace(" version: v1.3.1\n", "")) + env = tmp_path / "gojira.env" + env.write_text("GOJIRA_PROJECT=proj\n") + site.post("/profiles", data={"name": "sandbox", "stack_file": str(site.stack_file), "env_file": str(env)}) + r = site.post("/p/sandbox/install-gojira", follow_redirects=False) + assert r.status_code == 422 and "gojira.version" in r.text and calls == [] + + +def test_a_fetch_that_fails_is_a_sentence_on_the_press_not_a_broken_add(tmp_path, monkeypatch): + def fetch(version, dest): + raise ToolError(f"could not fetch Gojira {version}: no such tag") + site = _site(tmp_path, monkeypatch, fetch) + env = tmp_path / "gojira.env" + env.write_text("GOJIRA_PROJECT=proj\n") + r = site.post("/profiles", data={"name": "sandbox", "stack_file": str(site.stack_file), "env_file": str(env)}, + follow_redirects=False) + assert r.status_code == 303 # the profile is saved regardless + r = site.post("/p/sandbox/install-gojira", follow_redirects=False) + assert r.status_code == 422 and "no such tag" in r.text diff --git a/tests/test_model.py b/tests/test_model.py index a234aa9..eab4fca 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -80,6 +80,7 @@ def test_the_stranger_example_is_the_whole_stack_from_released_images(): four = {"org": "myorg", "project": "my-proj", "region": "us-central1", "cluster": "gojira-sandbox"} s = Stack.load(ROOT / "examples" / "stack.yaml", four) assert [a.name for a in s.apps] == ["litellm", "cabal", "liminal", "kobo"] + assert s.gojira.version.startswith("v1."), "the stranger file names the Gojira release the page installs" for app in s.apps: # a release, pinned: a tag moves, a digest does not assert app.image.startswith("ghcr.io/tenishai/"), app.name From 992b8f18cf0a44b3a2c6297201981836932c07ca Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 17:10:58 -0500 Subject: [PATCH 04/17] The add form stops asking for the stack file and the env file The stranger, on the add-profile form: the stack file box says the shipped one is right as it is, so why look at a list I cannot edit? And does it matter where the Gojira env file goes? No to both. A new profile reads the stack file that ships with the installer and writes Gojira's values to ~/.config/stack//gojira.env; neither is asked. Profile settings keep both boxes for someone with their own copy, and a typed path still wins. The add form is now Name, Cluster, Kubeconfig, Google account, with Repo clones folded away. The env-page test that wanted a profile without an env file makes one through the profiles file, as an older file would. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 6 +++++- README.md | 8 ++++--- docs/install.md | 22 ++++++++++--------- stack/templates/_profile_form.html | 34 +++++++++++++++++------------- stack/ui.py | 28 ++++++++++++++++++------ tests/test_env_page.py | 8 ++++++- tests/test_profile_form.py | 19 ++++++++++++++++- 7 files changed, 88 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a1f424..1f7fd93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,11 @@ releases yet; everything is under Unreleased. Gojira clone beside it, the kubeconfig and env file paths (from the name) and the one gcloud account are prefilled; every box has one line saying what it is and whether it must exist; `--repos` is folded under "Building the apps from source"; the four things leave the - add form (the profile page's card asks them) and stay on the settings form. + add form (the profile page's card asks them) and stay on the settings form. The stack file + and the env file are not asked at all (the stranger: why look at a list I cannot edit, and + does it matter where the env file goes? It does not): a new profile reads the shipped + `examples/stack.yaml` and writes `~/.config/stack//gojira.env`; Profile settings + still name other files. - **The page before a cluster exists.** A kubeconfig with nothing to read used to be "unknown": no App card, no Install Gojira, though terraform would make the cluster. When the env file says `GOJIRA_TERRAFORM=1` and names a `CLUSTER`, the page now says "no cluster diff --git a/README.md b/README.md index d72e206..fb5ae23 100644 --- a/README.md +++ b/README.md @@ -158,9 +158,11 @@ carries the old contract sha); the provision that follows regenerates it. ``` The same files behind buttons (stack#12). A **profile** is one install: a -name and paths — the stack file, and the kubeconfig and cloud account every -call is pinned to, so nothing depends on a shell export (the wrong-context -class of accident lives entirely in the shell). The list is +name and paths — the stack file (the one that ships with the installer unless +its settings say otherwise), the env file Gojira's values go to +(`~/.config/stack//gojira.env`), and the kubeconfig and cloud account +every call is pinned to, so nothing depends on a shell export (the +wrong-context class of accident lives entirely in the shell). The list is `~/.config/stack/profiles.yaml`, or `$STACK_PROFILES`; it holds paths, never contents. A profile's page shows what its stack file says, and its buttons: diff --git a/docs/install.md b/docs/install.md index 8d03b71..11340fb 100644 --- a/docs/install.md +++ b/docs/install.md @@ -44,16 +44,18 @@ uv venv .venv && uv sync --locked --extra ui ``` `localhost:8097`. Add a profile: a name, and leave the cluster on "a new -cluster: this install makes it". The rest is prefilled from what the machine -knows and each box says what it is: the stack file `examples/stack.yaml` as it -is (nothing in it is edited); a kubeconfig of this install's own -(`~/.kube-/config`, written when the cluster exists); your Google -account (the one gcloud is logged in as; a pick when there are several); an -env file for Gojira's values (`~/.config/stack//gojira.env`, need not -exist). Adding the profile fetches the Gojira release the stack file names -(`gojira.version`) into `~/.cache/stack/gojira/`: that is where -Install Gojira runs from, and nothing is cloned by hand. Picking an existing GKE cluster instead fills its project, region and -name on the next page. +cluster: this install makes it". The two other boxes are prefilled and say +what they are: a kubeconfig of this install's own (`~/.kube-/config`, +written when the cluster exists) and your Google account (the one gcloud is +logged in as; a pick when there are several). Nothing else is asked. The +profile reads the stack file that ships with the installer +(`examples/stack.yaml`, the list of apps and their images; nothing in it is +edited) and writes Gojira's values to `~/.config/stack//gojira.env`; +Profile settings can name other files later. Adding the profile fetches the +Gojira release the stack file names (`gojira.version`) into +`~/.cache/stack/gojira/`: that is where Install Gojira runs from, and +nothing is cloned by hand. Picking an existing GKE cluster instead fills its +project, region and name on the next page. ## 2. Four things diff --git a/stack/templates/_profile_form.html b/stack/templates/_profile_form.html index 7e270d4..8bfc1af 100644 --- a/stack/templates/_profile_form.html +++ b/stack/templates/_profile_form.html @@ -1,11 +1,14 @@ {% set p = profile if profile is defined else none %} {% set d = defaults if defaults is defined else {} %} {# One install's profile. Adding one asks a name and offers a cluster; the rest - is prefilled from what the machine already knows (the shipped stack file, the - Gojira clone beside the installer, the kubeconfig, the gcloud accounts) and - every box says in one line what it is and whether it must exist. The four - things are asked on the profile page's own card, not here; the settings form - (an existing profile) still edits them. #} + is prefilled from what the machine already knows (the kubeconfig, the gcloud + accounts) and every box says in one line what it is and whether it must + exist. The stack file and the env file are not asked at all: the one that + ships with the installer, and ~/.config/stack//gojira.env (the stranger + asked why he had to look at a list he could not edit, and whether the env + file's place mattered: it does not). The four things are asked on the profile + page's own card, not here. The settings form (an existing profile) edits + all of them. #}
@@ -28,13 +31,15 @@ {% for a in d.accounts or [] %}

The account gcloud is logged in as (gcloud auth login). It only matters when this machine has more than one.

+ {% if p %}
-
-

The list of apps to install and where their images come from. The one that ships with the installer is right as it is.

-
-

Where the page writes Gojira's settings (project, cluster, the App's id and key). It need not exist.

+
+

The list of apps to install and where their images come from. A new profile reads the one that + ships with the installer; name your own copy here to install something else.

+
+

Where the page writes Gojira's settings (project, cluster, the App's id and key). A new profile + gets ~/.config/stack/<name>/gojira.env; move it here if you must.

- {% if p %}

A developer's own tenishai/gojira checkout. Empty = the release the stack file names @@ -64,14 +69,13 @@ (function () { var f = document.getElementById('profile-form'); var name = f.querySelector('[name=name]'), ctx = f.querySelector('[name=context]'); - var kube = f.querySelector('[name=kubeconfig]'), env = f.querySelector('[name=env_file]'); + var kube = f.querySelector('[name=kubeconfig]'); var dflt = {{ (d.default_kubeconfig or '~/.kube/config') | tojson }}; - var touched = {}; - [kube, env].forEach(function (i) { i.addEventListener('input', function () { touched[i.name] = true; }); }); + var touched = false; + kube.addEventListener('input', function () { touched = true; }); function fill() { var n = name.value.trim() || ''; - if (!touched.kubeconfig) { kube.value = ctx.value ? dflt : '~/.kube-' + n + '/config'; } - if (!touched.env_file) { env.value = '~/.config/stack/' + n + '/gojira.env'; } + if (!touched) { kube.value = ctx.value ? dflt : '~/.kube-' + n + '/config'; } } name.addEventListener('input', fill); ctx.addEventListener('change', fill); fill(); })(); diff --git a/stack/ui.py b/stack/ui.py index 90233af..e3dc271 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -58,6 +58,18 @@ def image_parts(image: str) -> tuple[str, str]: GOJIRA_REPO = "https://github.com/tenishai/gojira" +def shipped_stack_file() -> str: + """The stack file that ships with the installer: what a profile reads unless + its settings name another. Empty when the checkout has none.""" + shipped = Path(__file__).resolve().parent.parent / "examples" / "stack.yaml" + return str(shipped) if shipped.exists() else "" + + +def default_env_file(name: str) -> str: + """Where a profile's gojira.env goes unless its settings say otherwise.""" + return f"~/.config/stack/{name}/gojira.env" + + def gojira_cache(version: str) -> Path: """Where a fetched Gojira release lives on this machine.""" return Path(os.environ.get("STACK_CACHE", "~/.cache/stack")).expanduser() / "gojira" / version @@ -290,8 +302,6 @@ def form_defaults() -> dict[str, Any]: kubeconfig knows, and the accounts gcloud is logged in as. Each is a prefill or a pick, never a requirement; a missing tool is an empty list, not a page that breaks.""" - root = Path(__file__).resolve().parent.parent - shipped = root / "examples" / "stack.yaml" kc = os.environ.get("KUBECONFIG", "").split(os.pathsep)[0] or "~/.kube/config" try: contexts = kubectl(env={}).list_contexts() @@ -301,7 +311,7 @@ def form_defaults() -> dict[str, Any]: accounts = gcloud(env={}).accounts() except Exception: accounts = [] - return {"stack_file": str(shipped) if shipped.exists() else "", + return {"stack_file": shipped_stack_file(), "default_kubeconfig": kc, "contexts": contexts, "accounts": accounts} def index_rows(): @@ -317,7 +327,7 @@ def index(request: Request): return page("index.html", request, rows=index_rows(), error="", defaults=form_defaults()) @app.post("/profiles") - def save_profile(request: Request, name: str = Form(), stack_file: str = Form(), + def save_profile(request: Request, name: str = Form(), stack_file: str = Form(""), kubeconfig: str = Form(""), cloud_account: str = Form(""), repos: str = Form(""), env_file: str = Form(""), gojira_repo: str = Form(""), org: str = Form(""), gcp_project: str = Form(""), region: str = Form(""), cluster: str = Form(""), @@ -327,10 +337,16 @@ def save_profile(request: Request, name: str = Form(), stack_file: str = Form(), m = re.fullmatch(r"gke_([^_]+)_([^_]+)_(.+)", context.strip()) if m: gcp_project, region, cluster = gcp_project or m[1], region or m[2], cluster or m[3] + # The add form asks neither path: the stack file is the one that ships + # with the installer and the env file lives under the profile's name. + # Profile settings may name others; a typed value wins. + name = name.strip() + stack_file = stack_file.strip() or shipped_stack_file() + env_file = env_file.strip() or default_env_file(name) try: - profile = Profile(name=name.strip(), stack_file=stack_file.strip(), kubeconfig=kubeconfig.strip(), + profile = Profile(name=name, stack_file=stack_file, kubeconfig=kubeconfig.strip(), cloud_account=cloud_account.strip(), repos=repos.strip(), - env_file=env_file.strip(), gojira_repo=gojira_repo.strip(), + env_file=env_file, gojira_repo=gojira_repo.strip(), org=org.strip(), gcp_project=gcp_project.strip(), region=region.strip(), cluster=cluster.strip()) except ValueError as exc: diff --git a/tests/test_env_page.py b/tests/test_env_page.py index 43aa359..d6d9144 100644 --- a/tests/test_env_page.py +++ b/tests/test_env_page.py @@ -8,6 +8,7 @@ import pytest from fastapi.testclient import TestClient +from stack.profiles import Profiles from stack.runs import Runner from stack.ui import make_app from tests.fakes import FakeGcloud, FakeKubectl @@ -53,6 +54,7 @@ def site(tmp_path): kubectl=lambda *, env: kubectl, gcloud=lambda *, env: gcloud) client = TestClient(app) client.gcloud, client.kubectl, client.env = gcloud, kubectl, env + client.profiles_path = tmp_path / "p.yaml" # register the profile pointing at our env file client.post("/profiles", data={"name": "prod", "stack_file": str(stack_file), "kubeconfig": str(kubeconfig), "env_file": str(env)}) @@ -119,8 +121,12 @@ def test_saving_a_trailing_comment_is_refused_and_leaves_file_untouched(site): def test_env_page_without_an_env_file_says_so(site): - # a profile with no env file: the page points to Profile settings + # a profile with no env file (an older profiles file; the add form gives + # every new profile one): the page points to Profile settings site.post("/profiles", data={"name": "bare", "stack_file": "/no/such/stack.yaml"}) + book = Profiles.load(site.profiles_path) + book.put(book.get("bare").model_copy(update={"env_file": ""})) + book.save(site.profiles_path) page = site.get("/p/bare/env").text assert "no env file" in page or "Gojira env file" in page assert "Profile settings" in page diff --git a/tests/test_profile_form.py b/tests/test_profile_form.py index 76ae7af..0ddeadd 100644 --- a/tests/test_profile_form.py +++ b/tests/test_profile_form.py @@ -35,7 +35,8 @@ def test_the_add_form_offers_the_clusters_kubectl_knows_and_prefills_the_rest(tm page = _site(tmp_path).get("/").text assert "a new cluster: this install makes it" in page assert f'

@@ -24,14 +24,17 @@ {% endif %}
-
-

The file kubectl keeps the cluster's address in. For a new cluster it need not exist: the install - writes it. A file of its own keeps this cluster out of your other kubectl work.

{% for a in d.accounts or [] %}

The account gcloud is logged in as (gcloud auth login). It only matters when this machine has more than one.

{% if p %} +
+
+

The file kubectl keeps the cluster's address in. A new profile gets the machine's own kubeconfig for a + cluster it already knows, or ~/.kube-<name>/config for one the install makes + (written when the cluster exists; a file of its own keeps it out of your other kubectl work).

+

The list of apps to install and where their images come from. A new profile reads the one that @@ -64,20 +67,3 @@

-{% if not p %} - -{% endif %} diff --git a/stack/templates/index.html b/stack/templates/index.html index f00a4c4..9e9abb0 100644 --- a/stack/templates/index.html +++ b/stack/templates/index.html @@ -34,7 +34,7 @@

Installs {{ rows | length }}< {% else %}

Installs none yet

-

No profiles yet. Add the first one below: a name is enough for a first install; the rest is prefilled.

+

No profiles yet. Add the first one below: a name is enough for a first install.

{% endif %} @@ -42,7 +42,7 @@

Installs {{ rows | length }}<

Add a profile

-

A name is enough for a first install; every other box is prefilled and says what it is. Saved to the profiles file on this machine, paths only.

+

A name is enough for a first install: the cluster is a pick and the account is prefilled. Saved to the profiles file on this machine, paths only.

diff --git a/stack/ui.py b/stack/ui.py index e3dc271..74eefb9 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -70,6 +70,18 @@ def default_env_file(name: str) -> str: return f"~/.config/stack/{name}/gojira.env" +def default_kubeconfig() -> str: + """The kubeconfig kubectl reads on this machine: $KUBECONFIG's first entry + or ~/.kube/config. A profile on a cluster that file already knows uses it.""" + return os.environ.get("KUBECONFIG", "").split(os.pathsep)[0] or "~/.kube/config" + + +def new_cluster_kubeconfig(name: str) -> str: + """A kubeconfig of the install's own for a cluster it makes, so the new + cluster stays out of the person's other kubectl work.""" + return f"~/.kube-{name}/config" + + def gojira_cache(version: str) -> Path: """Where a fetched Gojira release lives on this machine.""" return Path(os.environ.get("STACK_CACHE", "~/.cache/stack")).expanduser() / "gojira" / version @@ -302,7 +314,7 @@ def form_defaults() -> dict[str, Any]: kubeconfig knows, and the accounts gcloud is logged in as. Each is a prefill or a pick, never a requirement; a missing tool is an empty list, not a page that breaks.""" - kc = os.environ.get("KUBECONFIG", "").split(os.pathsep)[0] or "~/.kube/config" + kc = default_kubeconfig() try: contexts = kubectl(env={}).list_contexts() except Exception: @@ -337,14 +349,17 @@ def save_profile(request: Request, name: str = Form(), stack_file: str = Form("" m = re.fullmatch(r"gke_([^_]+)_([^_]+)_(.+)", context.strip()) if m: gcp_project, region, cluster = gcp_project or m[1], region or m[2], cluster or m[3] - # The add form asks neither path: the stack file is the one that ships - # with the installer and the env file lives under the profile's name. - # Profile settings may name others; a typed value wins. + # The add form asks for no path: the stack file is the one that ships + # with the installer, the env file lives under the profile's name, and + # the kubeconfig is the machine's own for a cluster it already knows or + # a file of the install's own for a cluster it makes. Profile settings + # may name others; a typed value wins. name = name.strip() stack_file = stack_file.strip() or shipped_stack_file() env_file = env_file.strip() or default_env_file(name) + kubeconfig = kubeconfig.strip() or (default_kubeconfig() if context.strip() else new_cluster_kubeconfig(name)) try: - profile = Profile(name=name, stack_file=stack_file, kubeconfig=kubeconfig.strip(), + profile = Profile(name=name, stack_file=stack_file, kubeconfig=kubeconfig, cloud_account=cloud_account.strip(), repos=repos.strip(), env_file=env_file, gojira_repo=gojira_repo.strip(), org=org.strip(), gcp_project=gcp_project.strip(), region=region.strip(), diff --git a/tests/test_env_page.py b/tests/test_env_page.py index d6d9144..89d65e3 100644 --- a/tests/test_env_page.py +++ b/tests/test_env_page.py @@ -133,9 +133,13 @@ def test_env_page_without_an_env_file_says_so(site): def test_env_page_without_kubeconfig_says_so(site, tmp_path): - # no kubeconfig pinned: the CLUSTER pick is a note, not a silent empty + # no kubeconfig pinned (an older profiles file; the add form gives every new + # profile one): the CLUSTER pick is a note, not a silent empty site.post("/profiles", data={"name": "naked", "stack_file": str(tmp_path / "x.yaml"), "env_file": str(site.env)}) + book = Profiles.load(site.profiles_path) + book.put(book.get("naked").model_copy(update={"kubeconfig": ""})) + book.save(site.profiles_path) page = site.get("/p/naked/env").text assert "no kubeconfig" in page diff --git a/tests/test_profile_form.py b/tests/test_profile_form.py index 0ddeadd..25a6996 100644 --- a/tests/test_profile_form.py +++ b/tests/test_profile_form.py @@ -37,10 +37,11 @@ def test_the_add_form_offers_the_clusters_kubectl_knows_and_prefills_the_rest(tm assert f'
- - {% if profile.env_file %}writes {{ profile.env_file }}{% else %}set the profile's env file (Profile settings) first{% endif %} + + {% if not profile.env_file %}set the env file in Profile settings first{% endif %}
- - - - {% for k, v in env_has.items() %} - - {% endfor %} - -
In the env file nowValue
{{ k }}{% if v %}{{ v }}{% else %}not written yet{% endif %}
+ {% set written = env_has.values() | select | list %} + {% if written %} +
+ What was written for Gojira ({{ profile.env_file }}) + + + + {% for k, v in env_has.items() %} + + {% endfor %} + +
SettingValue
{{ k }}{% if v %}{{ v }}{% else %}not written{% endif %}
+
+ {% endif %}

diff --git a/stack/templates/profile.html b/stack/templates/profile.html index 7ce3083..2979377 100644 --- a/stack/templates/profile.html +++ b/stack/templates/profile.html @@ -4,17 +4,19 @@

{{ profile.name }}{% if env %} {{ env }} cluster{% endif %}

{% if error %} -
Stack file{{ profile.stack_file }}
+ {# The file's tokens have no values yet (needs_four): the card asks for them and + nothing is red. Any other reason the file does not read is shown with its path. #} + {% if not needs_four %}
Stack file{{ profile.stack_file }}
{% endif %}
-

{{ error }}

+{% if not needs_four %}

{{ error }}

{% endif %} {% if show_values %}{% include "_values_card.html" %}{% endif %} {% else %} {# The strip reads the stack file, so it lives behind the parse guard. #}
-
Stack file{{ profile.stack_file }}
+
Apps{{ stack.apps | map(attribute='name') | join(' · ') }}
Cluster{{ stack.cluster.name }} · {{ stack.cluster.gcp_project }} · {{ stack.cluster.location }}
Gojira context{{ stack.gojira.kube_context or '(current context)' }}
-
Env file{{ profile.env_file or 'not set' }} ▸ the install's gojira.env, edited as a form
+
Gojira settings{{ profile.env_file or 'not set' }} ▸ every value Gojira installs with, edited as a form
diff --git a/stack/ui.py b/stack/ui.py index 579b475..b140447 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -461,12 +461,30 @@ def profile_page(name: str, request: Request): # remembered): a missing file or knob shows as missing. show_values = gojira_state != "installed" env_has = _derived_in_env(profile) + # The card's picks: the orgs gh belongs to and the projects gcloud sees, + # read only while the card is shown; a tool that is not there is an + # empty pick (a box to type into), never a page that breaks. + gh_orgs: list[str] = [] + projects: list[dict[str, str]] = [] + if show_values: + try: + gh_orgs = github(env=profile.target().env).orgs() + except Exception: + gh_orgs = [] + try: + projects = gcloud(env=profile.target().env).projects() + except Exception: + projects = [] + # The stack file's tokens have no values yet and the card below asks for + # them: that is the page's first step, not an error to show in red. + needs_four = show_values and "needs values for" in error return page("profile.html", request, profile=profile, stack=stack, error=error, env=environment(stack), runs=list(reversed(runs)), last_check=last_check, check_level=level_of(last_check), busy=runner.active(), gojira_state=gojira_state, gojira_version=gojira_version, gojira_note=gojira_note, show_card=show_card, app_id=app_id, app_pem=app_pem, stack_org=stack_org, app_setup=app_setup, show_values=show_values, values=profile.values(), values_complete=profile.values_complete(), env_has=env_has, + orgs=gh_orgs, projects=projects, needs_four=needs_four, tokens=_site.TOKENS, defaults=form_defaults()) @app.post("/p/{name}/values") diff --git a/tests/fakes.py b/tests/fakes.py index 2d7545d..eaa8199 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -170,6 +170,7 @@ def __init__(self, states: dict[str, str] | None = None, runs: dict[str, tuple[s self.open_pr_state = "merged" self.pr_files: dict[str, dict[str, str]] = {} self.user = "tester" # "" = not logged in + self.user_orgs: list[str] = [] # what orgs() offers the four-things pick self.org_denied: dict[str, str] = {} # org -> why gh cannot see it self.refuse_merges = 0 # merge_pr: rule refusals before one succeeds self.merge_error: ToolError | None = None @@ -183,6 +184,9 @@ def login(self): def org_access(self, org): return self.org_denied.get(org, "") + def orgs(self): + return list(self.user_orgs) + def repo_exists(self, repo): return repo in self.repos diff --git a/tests/test_env_page.py b/tests/test_env_page.py index 89d65e3..acf8c13 100644 --- a/tests/test_env_page.py +++ b/tests/test_env_page.py @@ -11,7 +11,7 @@ from stack.profiles import Profiles from stack.runs import Runner from stack.ui import make_app -from tests.fakes import FakeGcloud, FakeKubectl +from tests.fakes import FakeGcloud, FakeGitHub, FakeKubectl ROOT = Path(__file__).parent.parent GOJIRA = ROOT.parent / "gojira" @@ -51,7 +51,7 @@ def site(tmp_path): # instead of surfacing as an empty pick on a real machine (Ember 06, item 1) app = make_app(tmp_path / "p.yaml", runner, perform=lambda *a, **k: _noop(), preflight=lambda s, t: [], - kubectl=lambda *, env: kubectl, gcloud=lambda *, env: gcloud) + kubectl=lambda *, env: kubectl, gcloud=lambda *, env: gcloud, github=lambda **kw: FakeGitHub()) client = TestClient(app) client.gcloud, client.kubectl, client.env = gcloud, kubectl, env client.profiles_path = tmp_path / "p.yaml" diff --git a/tests/test_gojira_checkout.py b/tests/test_gojira_checkout.py index 6b84555..0ae0294 100644 --- a/tests/test_gojira_checkout.py +++ b/tests/test_gojira_checkout.py @@ -9,7 +9,7 @@ from stack.clients import ToolError from stack.runs import Runner from stack.ui import make_app -from tests.fakes import FakeGcloud, FakeKubectl +from tests.fakes import FakeGcloud, FakeGitHub, FakeKubectl STACK = """gojira: namespace: gojira @@ -23,7 +23,7 @@ def _site(tmp_path, monkeypatch, fetch, stack_text=STACK): monkeypatch.setenv("STACK_CACHE", str(tmp_path / "cache")) (tmp_path / "stack.yaml").write_text(stack_text) app = make_app(tmp_path / "p.yaml", Runner(), perform=lambda *a, **k: None, preflight=lambda s, t: [], - kubectl=lambda *, env: FakeKubectl(), gcloud=lambda *, env: FakeGcloud(), fetch=fetch) + kubectl=lambda *, env: FakeKubectl(), gcloud=lambda *, env: FakeGcloud(), fetch=fetch, github=lambda **kw: FakeGitHub()) site = TestClient(app) site.stack_file = tmp_path / "stack.yaml" return site diff --git a/tests/test_install_gojira.py b/tests/test_install_gojira.py index 46cfb7e..d04d5e4 100644 --- a/tests/test_install_gojira.py +++ b/tests/test_install_gojira.py @@ -13,6 +13,7 @@ from stack.profiles import Profiles from stack.runs import Runner from stack.ui import make_app +from tests.fakes import FakeGitHub SECRET = "SECRETVALUE123" NS = "gojira" # the Gojira namespace the fake cluster does or does not have @@ -135,7 +136,7 @@ def check_pf(stackf, target): app = make_app(profiles_path, runner, perform=lambda *a, **k: (_ for _ in ()).throw(AssertionError("not the stack engine")), preflight=check_pf, - kubectl=lambda *, env: kubectl, gcloud=lambda *, env: _NoProj()) + kubectl=lambda *, env: kubectl, gcloud=lambda *, env: _NoProj(), github=lambda **kw: FakeGitHub()) client = TestClient(app) client.runner, client.env, client.profiles_path = runner, env, profiles_path client.post("/profiles", data={"name": "prod", "stack_file": str(stack), @@ -256,7 +257,7 @@ def test_profile_form_has_a_gojira_repo_field(tmp_path): site = TestClient(make_app(tmp_path / "p.yaml", Runner(), perform=lambda *a, **k: (_ for _ in ()).throw(AssertionError()), preflight=lambda s, t: [], kubectl=lambda *, env: _k8s(), - gcloud=lambda *, env: _NoProj())) + gcloud=lambda *, env: _NoProj(), github=lambda **kw: FakeGitHub())) site.profiles_path = tmp_path / "p.yaml" site.post("/profiles", data={"name": "prod", "stack_file": str(stack)}) page = site.get("/p/prod").text diff --git a/tests/test_profile_form.py b/tests/test_profile_form.py index ac30be0..5def95c 100644 --- a/tests/test_profile_form.py +++ b/tests/test_profile_form.py @@ -12,7 +12,7 @@ from stack.clients import KubectlCLI from stack.runs import Runner from stack.ui import make_app -from tests.fakes import FakeGcloud, FakeKubectl +from tests.fakes import FakeGcloud, FakeGitHub, FakeKubectl ROOT = Path(__file__).parent.parent SHIPPED = ROOT / "examples" / "stack.yaml" @@ -25,7 +25,7 @@ def _site(tmp_path, contexts=(GKE, "kind-kind"), accounts=("me@example.com",), a app = make_app(tmp_path / "p.yaml", Runner(), perform=lambda *a, **kw: (_ for _ in ()).throw(AssertionError("no run here")), preflight=lambda s, t: [], kubectl=lambda *, env: k, - gcloud=lambda *, env: FakeGcloud(account=account, accounts=list(accounts))) + gcloud=lambda *, env: FakeGcloud(account=account, accounts=list(accounts)), github=lambda **kw: FakeGitHub()) site = TestClient(app) site.profiles_path = tmp_path / "p.yaml" return site @@ -112,7 +112,7 @@ def test_a_machine_without_kubectl_or_gcloud_still_renders_the_form(tmp_path): def missing(*, env): raise RuntimeError("not on PATH") app = make_app(tmp_path / "p.yaml", Runner(), perform=lambda *a, **kw: None, preflight=lambda s, t: [], - kubectl=missing, gcloud=missing) + kubectl=missing, gcloud=missing, github=lambda **kw: FakeGitHub()) page = TestClient(app).get("/").text assert "a new cluster: this install makes it" in page assert 'Save" in r.text + assert "What was written" not in r.text and "not written" not in r.text # nothing written yet: no receipt + assert '' in r.text and '' in r.text + assert '
-
-
+ +

Shown as "App ID" on the App's own settings page.

+
+ +

Where you kept the downloaded key. Only the path is stored; the key is read to check it and never shown.

- checks the key signs a token that answers for that id, and that the App is installed on the stack's repos; stores only the id and the path in the env file + checks that the key and the id answer for each other and that the App is installed on your organization

@@ -93,49 +97,43 @@

Check is on this cluster

- re-runs the checkout's scripts/install.sh under the env file — how Gojira itself is upgraded + runs the install again, idempotent: how Gojira itself is upgraded
{% elif gojira_state == "namespace-only" %}

{{ gojira_note }}

- {% if profile.env_file and profile.gojira_repo %} + {% if profile.env_file %}
- runs the checkout's scripts/install.sh under the env file, as a run + installs Gojira onto the cluster, as a run you can watch
- {% elif not profile.env_file %} -

Set the profile's env file (Gojira env form) to install.

{% else %} -

Set the profile's Gojira checkout (Profile settings) to install.

+

Set the profile's env file (Gojira env form) to install.

{% endif %}
{% elif gojira_state == "empty" %}

no Gojira on this cluster yet

- {% if profile.env_file and profile.gojira_repo %} + {% if profile.env_file %}
- runs the checkout's scripts/install.sh under the env file, as a run + installs Gojira onto the cluster, as a run you can watch
- {% elif not profile.env_file %} -

Set the profile's env file (Gojira env form) to install.

{% else %} -

Set the profile's Gojira checkout (Profile settings) to install.

+

Set the profile's env file (Gojira env form) to install.

{% endif %}
{% elif gojira_state == "no-cluster" %}

no cluster yet

{{ gojira_note }}.

- {% if profile.env_file and profile.gojira_repo %} + {% if profile.env_file %}
- runs the checkout's scripts/install.sh under the env file, as a run: terraform first (about ten minutes), then Gojira + makes the cluster first (terraform, about ten minutes), then installs Gojira; a run you can watch
- {% elif not profile.env_file %} -

Set the profile's env file (Gojira env form) to install.

{% else %} -

Set the profile's Gojira checkout (Profile settings) to install.

+

Set the profile's env file (Gojira env form) to install.

{% endif %}
{% elif gojira_state == "unknown" %} @@ -161,7 +159,7 @@

Apps {{ stack.apps | length }
- + {% for a in stack.apps %} diff --git a/stack/ui.py b/stack/ui.py index b140447..4ac5c3d 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -156,6 +156,15 @@ def level_of(run) -> str: return {"ok": "ok", "warn": "warn", "fail": "fail"}.get(run.lines[-1].level, "idle") +def _app_identity_in(path: Path) -> tuple[str, str]: + """The App id + pem path an env-shaped file carries, ("", "") when unreadable.""" + try: + vals = _envfile.get_all(path.read_text()) + except Exception: + return ("", "") + return (vals.get("GOJIRA_GITHUB_APP_ID", "").strip(), vals.get("GOJIRA_GITHUB_APP_PEM", "").strip()) + + def _app_identity_of(profile: Profile) -> tuple[str, str]: """The GitHub App id + pem path the install's env file carries, or ("", "") when the file is absent, has neither, or is unreadable. Reading the env file @@ -443,6 +452,12 @@ def profile_page(name: str, request: Request): # the card is gone (the gate is passed); an unreadable cluster (unknown) # offers nothing, card or button. app_id, app_pem = _app_identity_of(profile) + checkout = gojira_checkout(profile, fetching=False) + # An env file seeded from gojira.env.example carries the example's own + # placeholder pair; that is no App, and the card must not show it as one + example = _example_path(profile, checkout) + if example is not None and (app_id, app_pem) == _app_identity_in(example): + app_id, app_pem = "", "" # The gate passes only once the App is verified (id + pem present, the # path exists, the key parses) AND Gojira is installed. An installed # cluster shows no card (the gate is passed; see note 13: qa renders the @@ -450,11 +465,16 @@ def profile_page(name: str, request: Request): # whenever the App is not usable; an unreadable cluster (unknown) offers # nothing, card or button. show_card = gojira_state != "installed" and gojira_state != "unknown" and not _app_usable(app_id, app_pem) - # the org the card links to: the org every app's repo lives in (the part - # before the first /), when they agree; else the first one. + # the org the card links to: the one the four things named (the App is + # made there, where the install makes its repos); before that, the org + # every app's repo lives in (the part before the first /) when they agree orgs = {a.repo.split("/")[0] for a in stack.apps} if stack is not None else set() - stack_org = next(iter(orgs)) if len(orgs) == 1 else (next(iter(orgs)) if orgs else "") - app_setup = _app_setup_doc(profile, gojira_checkout(profile, fetching=False)) + stack_org = profile.org or (next(iter(orgs)) if orgs else "") + app_setup = _app_setup_doc(profile, checkout) + # the walkthrough as a web page at the release the stack file names; + # a developer's own checkout keeps the local path + version = _stack_gojira_version(str(profile.target().stack_file)) if not profile.gojira_repo else "" + app_doc_url = f"{GOJIRA_REPO}/blob/{version}/docs/github-app-setup.md" if version else app_setup["doc"] # The four things (stack.site): shown as a card until Gojira is installed — # the env file Gojira installs from is written from them, so they come # first. The card reads back what the env file holds (never what a form @@ -484,7 +504,7 @@ def profile_page(name: str, request: Request): gojira_note=gojira_note, show_card=show_card, app_id=app_id, app_pem=app_pem, stack_org=stack_org, app_setup=app_setup, show_values=show_values, values=profile.values(), values_complete=profile.values_complete(), env_has=env_has, - orgs=gh_orgs, projects=projects, needs_four=needs_four, + orgs=gh_orgs, projects=projects, needs_four=needs_four, app_doc_url=app_doc_url, tokens=_site.TOKENS, defaults=form_defaults()) @app.post("/p/{name}/values") diff --git a/tests/test_no_cluster_yet.py b/tests/test_no_cluster_yet.py index 6029e24..ea4179a 100644 --- a/tests/test_no_cluster_yet.py +++ b/tests/test_no_cluster_yet.py @@ -4,6 +4,7 @@ names a CLUSTER, the page says "no cluster yet", names what the install makes, and offers the card or the button. Every test here fails at 0ff7f32.""" +from stack.profiles import Profiles from tests.test_install_gojira import _fake_install, _k8s, _site, _wait @@ -24,6 +25,20 @@ def test_an_unreadable_cluster_with_terraform_in_the_env_file_is_no_cluster_yet( assert "The install is not offered" not in page +def test_install_gojira_is_offered_without_a_checkout_on_the_profile(tmp_path): + """The release is fetched at gojira.version since 7fef2fb, so a stranger's + profile has no gojira_repo; the page still gated the button on it and said + "Set the profile's Gojira checkout" (found on the stranger run).""" + site = _site(tmp_path, install=_fake_install(tmp_path), kubectl=_k8s(dead=True)) + _say_terraform(site) + book = Profiles.load(site.profiles_path) + book.put(book.get("prod").model_copy(update={"gojira_repo": ""})) + book.save(site.profiles_path) + page = site.get("/p/prod").text + assert 'action="/p/prod/install-gojira"' in page and "Install Gojira" in page + assert "Gojira checkout" not in page.split("Profile settings")[0] + + def test_without_terraform_in_the_env_file_it_stays_unknown(tmp_path): site = _site(tmp_path, install=_fake_install(tmp_path), kubectl=_k8s(dead=True)) _say_terraform(site, terraform="") diff --git a/tests/test_site.py b/tests/test_site.py index 1698a48..d6afb7f 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -116,7 +116,9 @@ def test_write_env_starts_from_the_example_and_keeps_what_the_card_wrote(tmp_pat assert text.startswith("# header\nPROJECT=my-proj\n") and "# the cluster\nCLUSTER=gojira-sandbox\n" in text assert "GOJIRA_TERRAFORM=1\n" in text and "GOJIRA_GRANTABLE_ROLES=roles/aiplatform.user\n" in text assert "GOJIRA_CI_RUNNER=\n" in text # an unrelated knob keeps the example's value - assert "GOJIRA_GITHUB_APP_ID=1234567" in text # the example's sample id until the card writes the real one + # the example's sample id and pem path are placeholders, not an App: a fresh + # file starts with both blank so the card asks (the stranger saw 1234567 as if set) + assert "GOJIRA_GITHUB_APP_ID=\nGOJIRA_GITHUB_APP_PEM=\n" in text # the card writes the App; a rewrite of the derived knobs keeps it from stack.envfile import save_env_file save_env_file(p, {"GOJIRA_GITHUB_APP_ID": "5141957", "GOJIRA_GITHUB_APP_PEM": "/keys/app.pem"}) diff --git a/tests/test_values_card.py b/tests/test_values_card.py index 3dee63a..95d93c2 100644 --- a/tests/test_values_card.py +++ b/tests/test_values_card.py @@ -17,6 +17,7 @@ NS = "gojira" STACK = '''gojira: kube_context: gke_{project}_{region}_{cluster} + version: v1.3.1 cluster: name: "{cluster}" gcp_project: "{project}" @@ -119,6 +120,7 @@ def test_one_press_saves_the_four_and_writes_the_env_file_from_the_example(tmp_p assert "GOJIRA_GRANTABLE_ROLES=roles/aiplatform.user,roles/storage.admin\n" in text assert "GOJIRA_GRANTABLE_CLUSTER_ROLES=kobo-room\n" in text assert "GOJIRA_CI_RUNNER=\n" in text # the example's other knobs ride along, docs and all + assert "GOJIRA_GITHUB_APP_ID=\n" in text and "GOJIRA_GITHUB_APP_PEM=\n" in text # the example's placeholders are no App # the contracts were read from GitHub (no clone anywhere) assert "tenishai/litellm-deploy" in github.repos and "tenishai/kobo" in github.repos # the page now reads the stack file with the four and shows the env file's truth @@ -156,6 +158,25 @@ def test_a_missing_value_or_env_file_is_a_sentence_not_a_write(tmp_path): assert Profiles.load(profiles).get("qa").org == "myorg" +def test_the_app_card_after_the_four_speaks_to_the_stranger(tmp_path): + """The stranger at the App card met red text, "save the .pem next to your Gojira + checkout" (he has none), a path into ~/.cache for the walkthrough, the example's + placeholders 1234567 / ./github-app.pem shown as if set, and a link to make the + App in the apps' upstream org rather than his own.""" + client, profiles, env_file, _ = _site(tmp_path) + assert client.post("/p/qa/values", data=FOUR, follow_redirects=False).status_code == 303 + page = client.get("/p/qa").text + assert 'action="/p/qa/app-card"' in page + assert 'name="app_id" value=""' in page and 'name="app_pem" value=""' in page + assert "github.com/organizations/myorg/settings/apps/new" in page # his org, not tenishai + assert "next to your Gojira checkout" not in page and "~/.config/stack/qa/" in page + # an older file still holding the example's pair reads as no App either + env_file.write_text(env_file.read_text().replace("GOJIRA_GITHUB_APP_ID=\n", "GOJIRA_GITHUB_APP_ID=1234567\n") + .replace("GOJIRA_GITHUB_APP_PEM=\n", "GOJIRA_GITHUB_APP_PEM=./github-app.pem\n")) + page = client.get("/p/qa").text + assert 'name="app_id" value=""' in page and "1234567" not in page + + def test_the_card_is_gone_once_gojira_is_installed(tmp_path): client, profiles, env_file, _ = _site(tmp_path, with_values=True, env_exists=True) k = FakeKubectl(ready={NS: (1, 1)}) From f40db3ed17569d609aedb3fb8ca775dea75bb5b2 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 19:06:14 -0500 Subject: [PATCH 11/17] No cluster yet reads as no cluster yet; the App's key is wherever the card put it Shaz, after Done on the App card, saw "no Gojira on this cluster yet" and an Install Gojira that promised to install onto the cluster. There was no cluster. His profile pins ~/.kube-/config, which terraform has not written yet; kubectl with that file talks to nothing, and its "no" to a namespace probe looks exactly like an empty cluster's. The page now lists the namespaces first and a cluster that cannot be listed is unreadable, which with GOJIRA_TERRAFORM=1 and a CLUSTER in the env file is "no cluster yet": the button says it makes the cluster first. Check says the same in plain words, "no cluster yet: Install Gojira makes in ()", where it used to fail with "Is KUBECONFIG the install's". The same Check warned that ~/.config/stack/github-app.pem was not there: the stack file named a place for the App's key while the card had stored its real path. A file: path may now say {app_pem}, the key wherever the App card put it (GOJIRA_GITHUB_APP_PEM in the env file), read by the run and by Check; Stack.load lets that one late token stand in a stack file. The shipped stack file says file:{app_pem}. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 13 ++++++++++ examples/stack.yaml | 2 +- stack/model.py | 4 ++- stack/preflight.py | 42 +++++++++++++++++++++++++++++++ stack/site.py | 2 +- stack/steps.py | 26 ++++++++++++++++--- stack/ui.py | 6 +++++ tests/test_no_cluster_yet.py | 21 ++++++++++++++++ tests/test_preflight.py | 49 ++++++++++++++++++++++++++++++++++++ tests/test_site.py | 1 + tests/test_steps.py | 17 +++++++++++++ 11 files changed, 176 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1e27ee..c02b07b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -136,6 +136,19 @@ releases yet; everything is under Unreleased. - **Install Gojira was gated on a checkout the stranger no longer has.** Since the release is fetched at `gojira.version`, a new profile has no `gojira_repo`; the page still required one for the button and said "Set the profile's Gojira checkout". The env file is the only gate. +- **A kubeconfig with nothing to read passed as an empty cluster.** The page probed one + namespace and took kubectl's "no" (really "connection refused": the stranger's + `~/.kube-/config` is not there until terraform writes it) for a readable cluster + with no Gojira, and offered to install onto a cluster that did not exist. The page lists + the namespaces first; a cluster that cannot be listed is "no cluster yet" when the env + file says terraform makes it. Check says the same in plain words ("no cluster yet: + Install Gojira makes in ()") instead of failing with a + KUBECONFIG riddle. +- **The stack file named a place for the App's key.** `file:~/.config/stack/github-app.pem` + while the App card had stored the key's real path; Install would have paused asking for a + copy. A `file:` path may say `{app_pem}`: the key wherever the App card put it + (`GOJIRA_GITHUB_APP_PEM` in the env file), read when the run and the Check need it. The + shipped stack file says so. - **"rolled" meant the old pod.** A roll's done check read the deployment's image (already the new digest once CI applied it) and counted every ready pod in the namespace; under Recreate diff --git a/examples/stack.yaml b/examples/stack.yaml index 8d9bfc9..710c4a0 100644 --- a/examples/stack.yaml +++ b/examples/stack.yaml @@ -88,7 +88,7 @@ apps: - roles/storage.admin secrets: kobo-github: - private-key.pem: file:~/.config/stack/github-app.pem # the one file you bring (install.md step 2) + private-key.pem: file:{app_pem} # the App's key, wherever the App card stored it (GOJIRA_GITHUB_APP_PEM) kobo-config: config.yaml: template:stack/kobo-config.template.yaml kobo-cabal: diff --git a/stack/model.py b/stack/model.py index d1fbf24..2bef0a0 100644 --- a/stack/model.py +++ b/stack/model.py @@ -279,5 +279,7 @@ def load(cls, path: str | Path, values: dict[str, str] | None = None) -> Stack: from stack.site import fill - text = fill(Path(path).read_text(), values or {}, allow=()) + # {app_pem} alone may stay in a stack file: it is the App's key wherever the + # App card stored it, filled at read time from the install's env file + text = fill(Path(path).read_text(), values or {}, allow=("app_pem",)) return cls.model_validate(yaml.safe_load(text) or {}) diff --git a/stack/preflight.py b/stack/preflight.py index ec4e863..18d19d6 100644 --- a/stack/preflight.py +++ b/stack/preflight.py @@ -15,6 +15,7 @@ from dataclasses import dataclass from pathlib import Path +from stack import envfile from stack.clients import ( AppRow, GhCLI, @@ -45,6 +46,17 @@ def check_files(stack: Stack, target: Target) -> list[Check]: for obj in (*app.configmaps.values(), *app.secrets.values()): for src in obj.values(): if src.kind in ("file", "template"): + if "{app_pem}" in src.arg: + # the App's key, wherever the App card stored it (GOJIRA_GITHUB_APP_PEM) + pem = _app_pem_in(target.env_file) + if not pem: + out.append(Check(f"{app.name}: {src.kind}:{src.arg}", "warn", + "the App's key: the App card stores its path (GOJIRA_GITHUB_APP_PEM in the " + "env file); not set yet")) + continue + p = Path(src.arg.replace("{app_pem}", pem)).expanduser() + named.append((f"{src.kind}:{src.arg}", p if p.is_absolute() else base / p)) + continue named.append((f"{src.kind}:{src.arg}", src.path if src.path.is_absolute() else base / src.path)) named += [(f, base / f) for f in app.base_files] for label, path in named: @@ -188,6 +200,30 @@ def close(self): pass +def _terraform_cluster(env_file: Path | None) -> dict[str, str] | None: + """What the env file says terraform makes (PROJECT/REGION/CLUSTER) when it + says GOJIRA_TERRAFORM=1 and names a CLUSTER; else None. The page's + no-cluster-yet reading, for the Check row.""" + if env_file is None or not env_file.exists(): + return None + try: + text = env_file.read_text() + except (OSError, ValueError): + return None + vals = {k: envfile.plain(envfile.get(text, k)) for k in ("PROJECT", "REGION", "CLUSTER", "GOJIRA_TERRAFORM")} + return vals if vals["GOJIRA_TERRAFORM"] == "1" and vals["CLUSTER"] else None + + +def _app_pem_in(env_file: Path | None) -> str: + """The App's key path the env file holds (GOJIRA_GITHUB_APP_PEM), "" when none.""" + if env_file is None or not env_file.exists(): + return "" + try: + return envfile.plain(envfile.get(env_file.read_text(), "GOJIRA_GITHUB_APP_PEM")) + except (OSError, ValueError): + return "" + + def preflight(stack: Stack, target: Target, which: Callable[[str], str | None] = shutil.which) -> list[Check]: out = check_tools(stack, target, which) + check_files(stack, target) try: @@ -205,6 +241,12 @@ def preflight(stack: Stack, target: Target, which: Callable[[str], str | None] = listed = kubectl.namespaces() except ToolError: listed = None + if listed is None and (made := _terraform_cluster(target.env_file)) is not None: + # no cluster yet: Install Gojira makes it; the rows say so in plain words + out.append(Check("Gojira", "warn", f"no cluster yet: Install Gojira makes {made['CLUSTER']} in " + f"{made['PROJECT'] or ''} ({made['REGION'] or ''})")) + out += [Check(f"{app.name}: Gojira", "warn", "not installed yet — Install Gojira first") for app in stack.apps] + return out if listed is not None and stack.gojira.namespace not in listed: out.append(Check("Gojira", "warn", "no Gojira on this cluster yet")) # empty cluster: what is missing is Gojira itself, so the app rows say so diff --git a/stack/site.py b/stack/site.py index 0cbf815..4a3da46 100644 --- a/stack/site.py +++ b/stack/site.py @@ -24,7 +24,7 @@ # Tokens a `template:` file may also carry; the installer fills them when it # writes the Secret (the App's id and installation id come from the env file # and GitHub, the token from Gojira). A stack file never carries them. -LATE_TOKENS = ("gojira_token", "app_id", "installation_id") +LATE_TOKENS = ("gojira_token", "app_id", "installation_id", "app_pem") _TOKEN = re.compile(r"\{(" + "|".join(TOKENS + LATE_TOKENS) + r")\}") diff --git a/stack/steps.py b/stack/steps.py index 10162bc..311ab93 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -818,20 +818,38 @@ def _app_values(self, app: App, label: str, with_installation: bool) -> dict[str out["installation_id"] = self._installation_id return out - def _path(self, s: Source) -> Path: - """A relative `file:`/`template:` path is relative to the stack file.""" + def _path(self, s: Source, label: str = "") -> Path: + """A relative `file:`/`template:` path is relative to the stack file. + `{app_pem}` in the path is the App's key wherever the App card stored it + (GOJIRA_GITHUB_APP_PEM in the run's env file): the stranger keeps the key + where he likes and the stack file does not name a place.""" + if "{app_pem}" in s.arg: + p = Path(s.arg.replace("{app_pem}", self._app_pem(label))).expanduser() + return p if p.is_absolute() else self.o.stack_dir / p return s.path if s.path.is_absolute() else self.o.stack_dir / s.path + def _app_pem(self, label: str) -> str: + from stack import envfile + + if self.o.env_file is None or not self.o.env_file.exists(): + raise ToolError(f"{label} names the App's key ({{app_pem}}) but this run has no env file to read " + "GOJIRA_GITHUB_APP_PEM from (the profile's env file; --env-file on the command line)") + pem = envfile.plain(envfile.get(self.o.env_file.read_text(), "GOJIRA_GITHUB_APP_PEM")) + if not pem: + raise ToolError(f"{label} names the App's key but {self.o.env_file} has no GOJIRA_GITHUB_APP_PEM yet " + "(the App card stores it)") + return pem + def _present(self, app: App, s: Source, label: str) -> Path: """The source's file, once it is there. A missing file is a pause, not a stop (criterion 5): the run says which file and what it is for, tells on_pause, and looks again every poll (or at once when the pause's event is set) until it appears or file_wait_seconds pass. The file's contents are read by the caller, after this, and go nowhere but the cluster.""" - path = self._path(s) + why = f"{app.name}: {label or s.kind + ':' + s.arg}" + path = self._path(s, why) if path.exists(): return path - why = f"{app.name}: {label or s.kind + ':' + s.arg}" self.o.say(f" {why} needs {path}, which is not there; put it there and the run continues") event = self.o.on_pause(path, why) deadline = time.monotonic() + self.o.file_wait_seconds diff --git a/stack/ui.py b/stack/ui.py index 4ac5c3d..3f52716 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -420,6 +420,12 @@ def profile_page(name: str, request: Request): if stack is not None: try: kc = kubectl(env=profile.target().env) + # list first: a kubeconfig with nothing to read (the file is not + # there yet, a dead server) answers "no" to a namespace probe just + # as an empty cluster does, and the stranger saw "no Gojira on this + # cluster yet" for a cluster that did not exist + if kc.namespaces() is None: + raise ToolError("the cluster cannot be read") if kc.namespace_exists(ns): ready, total = kc.pods_ready(ns) if total and ready == total: diff --git a/tests/test_no_cluster_yet.py b/tests/test_no_cluster_yet.py index ea4179a..1141ad1 100644 --- a/tests/test_no_cluster_yet.py +++ b/tests/test_no_cluster_yet.py @@ -25,6 +25,27 @@ def test_an_unreadable_cluster_with_terraform_in_the_env_file_is_no_cluster_yet( assert "The install is not offered" not in page +def test_a_kubeconfig_that_reads_nothing_is_no_cluster_yet_not_an_empty_cluster(tmp_path): + """The stranger's profile pins ~/.kube-/config, not there until terraform + writes it; kubectl then talks to nothing and says "no" to a namespace probe + exactly as an empty cluster does. The page said "no Gojira on this cluster + yet" and offered to install onto a cluster that did not exist.""" + from tests.fakes import FakeKubectl + + class Nothing(FakeKubectl): + def namespaces(self): + return None # the real client: unreadable = None + + def namespace_exists(self, ns): + return False # the real client: a non-zero exit, same as "not found" + + site = _site(tmp_path, install=_fake_install(tmp_path), kubectl=Nothing()) + _say_terraform(site) + page = site.get("/p/prod").text + assert "no cluster yet" in page and "no Gojira on this cluster yet" not in page + assert "makes the cluster first" in page + + def test_install_gojira_is_offered_without_a_checkout_on_the_profile(tmp_path): """The release is fetched at gojira.version since 7fef2fb, so a stranger's profile has no gojira_repo; the page still gated the button on it and said diff --git a/tests/test_preflight.py b/tests/test_preflight.py index c750e32..2d5b821 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -136,6 +136,55 @@ def test_the_whole_preflight_turns_a_strangers_shell_into_rows_not_tracebacks(tm assert not any(c.what.startswith("kobo: Gojira") for c in checks) +def test_no_cluster_yet_is_a_warn_naming_what_install_gojira_makes(tmp_path, monkeypatch): + """The stranger's Check before the cluster exists said FAIL "has no namespace + 'gojira'. Is KUBECONFIG the install's…": a riddle for a cluster terraform has + not made yet. With the env file saying terraform makes it, the row is a warn + in plain words and the app rows say "Install Gojira first".""" + bindir = tmp_path / "bin" + bindir.mkdir() + f = bindir / "kubectl" + f.write_text("#!/usr/bin/env bash\nexit 1\n") + f.chmod(f.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("PATH", f"{bindir}:{os.path.dirname(sys.executable)}") + stack, target = _stack(tmp_path, """ +apps: + - {name: kobo, repo: o/kobo, image: r/kobo:v1, deploy_repo: o/kobo-deploy} +""") + env = tmp_path / "gojira.env" + env.write_text("PROJECT=my-proj\nREGION=us-central1\nCLUSTER=gojira-sandbox\nGOJIRA_TERRAFORM=1\n") + target.env_file = env + checks = preflight(stack, target) + gojira = _by(checks, "Gojira") + assert gojira.status == "warn" and gojira.detail == "no cluster yet: Install Gojira makes gojira-sandbox in my-proj (us-central1)" + assert _by(checks, "kobo: Gojira").status == "warn" and "Install Gojira first" in _by(checks, "kobo: Gojira").detail + assert "KUBECONFIG" not in gojira.detail + + +def test_the_apps_key_is_read_where_the_app_card_stored_it(tmp_path): + """file:{app_pem}: the stack file names no place for the App's key; the path + comes from the env file the App card wrote. The stranger kept his key at + ~/tenish-room.pem and the file said ~/.config/stack/github-app.pem.""" + from stack.preflight import check_files + key = tmp_path / "keys" / "app.pem" + key.parent.mkdir() + key.write_text("-----BEGIN RSA PRIVATE KEY-----\nx\n") + stack, target = _stack(tmp_path, """ +apps: + - {name: kobo, repo: o/kobo, image: r/kobo:v1, deploy_repo: o/kobo-deploy, + secrets: {kobo-github: {private-key.pem: "file:{app_pem}"}}} +""") + row = _by(check_files(stack, target), "kobo: file:{app_pem}") + assert row.status == "warn" and "App card" in row.detail # no env file: not set yet + env = tmp_path / "gojira.env" + env.write_text(f"GOJIRA_GITHUB_APP_PEM={key}\n") + target.env_file = env + assert _by(check_files(stack, target), "kobo: file:{app_pem}").status == "ok" + key.unlink() + row = _by(check_files(stack, target), "kobo: file:{app_pem}") + assert row.status == "warn" and str(key) in row.detail # named, but not there + + def test_an_empty_cluster_is_a_plain_word_and_every_row_runs(tmp_path, monkeypatch): """Criterion 2 (Ember 09): a reachable cluster with no gojira namespace is a plain warn ("no Gojira on this cluster yet"), not the refusal, and every other diff --git a/tests/test_site.py b/tests/test_site.py index d6afb7f..b8ec83a 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -46,6 +46,7 @@ def test_the_stranger_file_loads_only_with_the_four_and_then_holds_no_token(): assert app.deploy_repo == f"myorg/infra-{app.name}-deploy" assert s.apps[0].contract["env"]["VERTEX_PROJECT"] == "my-proj" assert "acme" not in path.read_text(), "the example carries tokens, not a sample org to edit" + assert "file:{app_pem}" in path.read_text(), "the App's key is wherever the App card stored it" # the kobo template carries the same four plus the App's two, nothing to edit by hand tmpl = (ROOT / "examples" / "stack" / "kobo-config.template.yaml").read_text() for token in ("{org}", "{project}", "{app_id}", "{installation_id}", "{gojira_token}"): diff --git a/tests/test_steps.py b/tests/test_steps.py index 838e81e..0f64486 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -615,6 +615,23 @@ def test_a_template_takes_the_four_and_the_app_from_the_env_file(home): assert "installation_id:5141957:myorg" in github.calls +def test_a_file_source_at_app_pem_reads_the_key_the_app_card_stored(home): + """`file:{app_pem}` is the App's key at the path the env file holds, wherever + the App card put it; the stack file names no place of its own.""" + key = home / "keys" / "app.pem" + key.parent.mkdir() + key.write_text("KEY-BYTES-7f2a\n") + env_file = home / "gojira.env" + env_file.write_text(f"GOJIRA_GITHUB_APP_ID=5141957\nGOJIRA_GITHUB_APP_PEM={key}\n") + stack = _stack(home, [{"name": "kobo", "repo": "o/kobo", + "secrets": {"kobo-github": {"private-key.pem": "file:{app_pem}"}}}]) + kubectl = FakeKubectl() + _run(home, stack, kubectl=kubectl, merge_setup_prs=True, env_file=env_file) + assert kubectl.secrets[("kobo", "kobo-github")]["private-key.pem"] == "KEY-BYTES-7f2a" + with pytest.raises(ToolError, match="no env file"): + _run(home, stack, merge_setup_prs=True) + + def test_a_template_naming_the_app_without_an_env_file_stops_with_the_reason(home): (home / "kobo.tmpl").write_text('github_app_id: "{app_id}"\n') stack = _stack(home, [{"name": "kobo", "repo": "o/kobo", From 2fb57a2bd535630f775c563cad1bbd14ef3e1e78 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 19:45:03 -0500 Subject: [PATCH 12/17] The App card stores the key's full path; Install Gojira repairs a ~ path it finds Shaz pressed Install Gojira. Terraform made the cluster, then install.sh stopped: "pem not found at ~/tenish-room.pem". The card had stored the path as he typed it; Done passed because Python expands ~, and Gojira's preflight tests the same string in the shell, where ~ is a character. The card stores the expanded path. Install Gojira reads the env file before running and, when GOJIRA_GITHUB_APP_PEM starts with ~, writes the full path into the file (losslessly) and says so on a run line, so a file an older card wrote works on the next press without a hand edit. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 4 ++++ stack/ui.py | 13 +++++++++++-- tests/test_app_card.py | 14 ++++++++++++++ tests/test_install_gojira.py | 16 ++++++++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c02b07b..9da85c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -144,6 +144,10 @@ releases yet; everything is under Unreleased. file says terraform makes it. Check says the same in plain words ("no cluster yet: Install Gojira makes in ()") instead of failing with a KUBECONFIG riddle. +- **The App card stored the key's path as typed.** `~/tenish-room.pem` passed Done (Python + expands `~`) and stopped install.sh with "pem not found at ~/tenish-room.pem" (a shell + string). The card stores the full path, and Install Gojira rewrites a `~` path it finds + in the file before running, saying so on a run line. - **The stack file named a place for the App's key.** `file:~/.config/stack/github-app.pem` while the App card had stored the key's real path; Install would have paused asking for a copy. A `file:` path may say `{app_pem}`: the key wherever the App card put it diff --git a/stack/ui.py b/stack/ui.py index 3f52716..82b2a32 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -823,6 +823,12 @@ def install_gojira(name: str, request: Request): def work(run: _runs.Run): run.add("head", "install.gojira") + # a pem path written as ~/… (an older card stored it as typed) is one + # install.sh cannot find: expand it in the file first, and say so + pem = _envfile.plain(_envfile.get(env_path.read_text(), "GOJIRA_GITHUB_APP_PEM")) + if pem.startswith("~"): + _envfile.save_env_file(env_path, {"GOJIRA_GITHUB_APP_PEM": str(Path(pem).expanduser())}) + run.add("info", f"GOJIRA_GITHUB_APP_PEM was {pem}; written as its full path, which install.sh can read") run.add("info", f"running {repo / 'scripts' / 'install.sh'} under the env file {env_path}") rc = _run_install(repo, target_env, run) if rc != 0: @@ -905,10 +911,13 @@ async def app_card_done(name: str, request: Request): except ToolError as exc: return notice(request, 422, f"the App check failed: {exc}", level="warn", link=f"/p/{name}", link_text=f"Back to {name}") - # pass: store only the id and the path, lossless for the rest of the file + # pass: store only the id and the path, lossless for the rest of the file. + # The path is stored expanded: Gojira's scripts test it as a shell string, + # where `~` is a character (the stranger typed ~/x.pem; Done passed, since + # Python expands it; install.sh stopped with "pem not found at ~/x.pem"). try: _envfile.save_env_file(Path(profile.env_file).expanduser(), - {"GOJIRA_GITHUB_APP_ID": app_id, "GOJIRA_GITHUB_APP_PEM": pem}) + {"GOJIRA_GITHUB_APP_ID": app_id, "GOJIRA_GITHUB_APP_PEM": str(Path(pem).expanduser())}) except ToolError as exc: return notice(request, 422, f"checked, but could not write the env file: {exc}", level="warn", link=f"/p/{name}", link_text=f"Back to {name}") diff --git a/tests/test_app_card.py b/tests/test_app_card.py index e0ee4e1..b39d3ac 100644 --- a/tests/test_app_card.py +++ b/tests/test_app_card.py @@ -236,6 +236,20 @@ def test_done_writes_id_and_path_and_card_goes_away(tmp_path): assert gh.calls == [f"app_identity:{APP_ID}", "covers:tenishai/gojira,tenishai/kobo-deploy"] +def test_done_stores_the_keys_full_path_not_a_tilde(tmp_path, monkeypatch): + """The stranger typed ~/tenish-room.pem; Done passed (Python expands ~) and + install.sh stopped with "pem not found at ~/tenish-room.pem": Gojira's scripts + test the path as a shell string. The card stores the full path.""" + monkeypatch.setenv("HOME", str(tmp_path)) + site = _site(tmp_path, kubectl=_k8s(ns_exists=False), github=FakeGitHub(), ns_exists=False, app_lines=False) + pem = _rsa_pem(tmp_path) + typed = "~/" + str(Path(pem).relative_to(tmp_path)) + r = site.post("/p/qa/app-card", data={"app_id": APP_ID, "app_pem": typed}, follow_redirects=False) + assert r.status_code == 303 + vals = {ln.split("=", 1)[0]: ln.split("=", 1)[1] for ln in site.env.read_text().splitlines() if "=" in ln} + assert vals["GOJIRA_GITHUB_APP_PEM"] == pem and "~" not in vals["GOJIRA_GITHUB_APP_PEM"] + + # --- the pem's bytes never appear in a page or run line --- def test_pem_body_never_on_the_page(tmp_path): diff --git a/tests/test_install_gojira.py b/tests/test_install_gojira.py index d04d5e4..c559963 100644 --- a/tests/test_install_gojira.py +++ b/tests/test_install_gojira.py @@ -227,6 +227,22 @@ def test_install_gojira_runs_install_sh_as_a_subprocess(tmp_path): assert site.env.name in page and "PROJECT=vidios-qa" in page +def test_install_gojira_expands_a_tilde_pem_path_before_running(tmp_path, monkeypatch): + """A file an older card wrote holds GOJIRA_GITHUB_APP_PEM=~/…; install.sh cannot + find that. The press writes the full path into the file first and says so.""" + monkeypatch.setenv("HOME", str(tmp_path)) + site = _site(tmp_path, install=_fake_install(tmp_path), kubectl=_k8s(ns_exists=False)) + lines = [ln for ln in site.env.read_text().splitlines() if not ln.startswith("GOJIRA_GITHUB_APP_PEM=")] + site.env.write_text("\n".join(lines) + "\nGOJIRA_GITHUB_APP_PEM=~/keys/app.pem\n") + r = site.post("/p/prod/install-gojira", follow_redirects=False) + assert r.status_code == 303 + run = site.runner.runs[max(site.runner.runs)] + _wait(run) + assert f"GOJIRA_GITHUB_APP_PEM={tmp_path}/keys/app.pem" in site.env.read_text() + assert any("written as its full path" in ln.text for ln in run.lines) + assert not any("~/keys" in ln.text and "running" in ln.text for ln in run.lines) + + def test_env_values_never_appear_in_the_run_lines(tmp_path): site = _site(tmp_path, install=_fake_install(tmp_path), kubectl=_k8s(ns_exists=False)) # the env file carries a secret value From 6b4a1c5d6a3b3c6ee4e9f5cc798d43dfcd690c1f Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 20:31:26 -0500 Subject: [PATCH 13/17] The run page says what it is waiting on, and for how long The stranger, watching Install all 4: "nothing changes, I don't really know what's happening and wonder if it's actually doing anything or stuck". The run had ten lines and was quietly polling a deploy run on GitHub for minutes; a quiet page and a stuck page look the same. Every wait in the engine (Gojira provisioning, a setup or pin PR, the deploy run on GitHub, pods, a fresh bootstrap code, the setup command in the pod) now tells the run what it waits on, with the link where there is one and for how long, through Options.now; the wait clears it when it ends. The run keeps it as Run.now, never written to the run's file, and the lines block shows it as a "now" line under the lines while the run runs. The CLI ignores it. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 4 +++ stack/runs.py | 14 ++++++++--- stack/steps.py | 49 +++++++++++++++++++++++++++++++------ stack/templates/_lines.html | 4 +++ stack/ui.py | 4 +-- tests/test_steps.py | 27 +++++++++++++++++++- tests/test_ui.py | 29 ++++++++++++++++++++++ 7 files changed, 118 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9da85c5..3d5d475 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,10 @@ releases yet; everything is under Unreleased. longer listed is still offered); each box has one line saying what it is; the button says Save; what was written for Gojira is a folded receipt once something is. The strip names the apps, not the stack file's path. +- **The run page says what it is waiting on.** Between lines a run can be quiet for minutes + (a deploy run on GitHub, a PR, pods, a bootstrap code) and the stranger could not tell a + quiet run from a stuck one. Every wait now reports what it waits on, with the link and + for how long, on a "now" line under the lines; it goes when the wait ends. - **The GitHub App card speaks to a stranger.** Not red; the App is made in the organization the four things named, not the apps' upstream org; the key is kept "somewhere on this machine", not "next to your Gojira checkout"; the walkthrough is a link to the doc at the diff --git a/stack/runs.py b/stack/runs.py index c20766c..066140d 100644 --- a/stack/runs.py +++ b/stack/runs.py @@ -64,7 +64,8 @@ def open_gojira(stack: Stack, target: Target, say: Callable[[str], None] = print def perform(target: Target, action: str, apps: list[str], *, merge_setup_prs: bool = False, yes: bool = False, merge_pins: bool = False, say: Callable[[str], None] = print, on_pause: Callable[[Path, str], threading.Event | None] | None = None, - on_resume: Callable[[], None] | None = None) -> Report: + on_resume: Callable[[], None] | None = None, + now: Callable[[str], None] | None = None) -> Report: """`stack install` or `stack upgrade` on `target`. Raises ToolError with the sentence to show; never prints a traceback. `on_pause(path, why)` is told when the run waits for a file a person must put there (criterion 5) @@ -75,6 +76,7 @@ def _no_pause(path: Path, why: str) -> threading.Event | None: pause_cb: Callable[[Path, str], threading.Event | None] = on_pause or _no_pause resume_cb: Callable[[], None] = on_resume or (lambda: None) + now_cb: Callable[[str], None] = now or (lambda text: None) try: stack = Stack.load(target.stack_file, target.values) except ValueError as exc: @@ -89,7 +91,7 @@ def _no_pause(path: Path, why: str) -> threading.Event | None: if action == "upgrade": clients = Clients(gojira=gojira, kubectl=kubectl, github=GhCLI(env), crane=CraneCLI(env)) opts = Options(stack_dir=target.stack_file.parent, repo_root=target.stack_file.parent, - merge_setup_prs=merge_setup_prs, yes=yes, merge_pins=merge_pins, say=say, on_pause=pause_cb, on_resume=resume_cb, + merge_setup_prs=merge_setup_prs, yes=yes, merge_pins=merge_pins, say=say, now=now_cb, on_pause=pause_cb, on_resume=resume_cb, values=target.values, env_file=target.env_file) return Installer(stack, clients, opts).upgrade(apps) if action != "install": @@ -103,7 +105,7 @@ def _no_pause(path: Path, why: str) -> threading.Event | None: cabal = HttpCabal(f"http://127.0.0.1:{port}", forward=lambda: kubectl.port_forward(ns, svc, port, 80)) clients = Clients(gojira=gojira, kubectl=kubectl, github=GhCLI(env), cabal=cabal) opts = Options(stack_dir=target.stack_file.parent, repo_root=target.repo_root, - merge_setup_prs=merge_setup_prs, say=say, on_pause=pause_cb, on_resume=resume_cb, + merge_setup_prs=merge_setup_prs, say=say, now=now_cb, on_pause=pause_cb, on_resume=resume_cb, values=target.values, env_file=target.env_file) return Installer(stack, clients, opts).install(apps) finally: @@ -196,6 +198,9 @@ class Run: ok: bool | None = None lines: list[Line] = field(default_factory=list) paused: Pause | None = None + # What the run is waiting on right now (Options.now): shown under the lines + # while it runs, never kept; a restarted `stack ui` has nothing to show here. + now: str = "" # What a finished install offers to open (Report.doors); the page shows a button per door. doors: list = field(default_factory=list) # Slice 6 (criterion 7): every line also goes to the run's file, so a restarted @@ -214,6 +219,9 @@ def add(self, level: str, text: str) -> None: if self.sink is not None: self.sink({"level": level, "text": text}) + def set_now(self, text: str) -> None: + self.now = text + def say(self, text: str) -> None: """The engine's `say`: `== app` headings, everything else a step.""" text = text.rstrip() diff --git a/stack/steps.py b/stack/steps.py index 311ab93..1eab3c1 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -109,6 +109,11 @@ class Options: yes: bool = False # upgrade: the data_mount backup gate was answered merge_pins: bool = False # upgrade: merge the pin PR this run opens (the UI: the press is the review) say: Callable[[str], None] = print + # What the run is waiting on right now, with how long: set on every poll of + # every wait, cleared when the wait ends. The page shows it under the lines, + # so a quiet run is never mistaken for a stuck one (the stranger: "nothing + # changes, I don't know if it's doing anything"). The CLI ignores it. + now: Callable[[str], None] = lambda text: None # Criterion 5: a `file:`/`template:` source whose file is absent pauses the run # until a person puts it there. on_pause may answer an Event that cuts the poll # short (the page's Done button); the CLI leaves both alone and polls. @@ -260,12 +265,14 @@ def run_setup(self, app: App, *, fresh: bool) -> None: return args = shlex.split(app.setup.run) self.o.say(f" {app.name}: running `{app.setup.run}` in the pod") + self.o.now(f"{app.name}: its setup command is running in the pod (`{app.setup.run}`)") try: out = self.c.kubectl.exec(app.namespace, app.name, args) except ToolError as exc: raise ToolError(f"{app.name}: `{app.setup.run}` failed: {exc}") from None for ln in [x for x in out.splitlines() if x.strip()][-8:]: self.o.say(f" {ln.strip()}") + self.o.now("") self.report.note(f"{app.name}: setup ran (`{app.setup.run}`)", self.o.say) if app.setup.restart: self.c.kubectl.restart(app.namespace, app.name) @@ -419,13 +426,21 @@ def connect(self, app: App, contract_changed: bool = False, asked: bool = False) self.report.note(f"{app.name}: connected (app {row.id}, new)", self.o.say) return row + def _waiting(self, text: str, since: float) -> None: + """Tell the run what it waits on and for how long (Options.now).""" + s = int(time.monotonic() - since) + self.o.now(f"{text} (for {s // 60} min {s % 60} s)" if s >= 60 else f"{text} (for {s} s)") + def wait_provisioned(self, row: AppRow) -> AppRow: - deadline = time.monotonic() + self.o.rollout_seconds + since = time.monotonic() + deadline = since + self.o.rollout_seconds while row.status not in (ACTIVE, AWAITING_PR, FAILED): + self._waiting(f"{row.name}: Gojira is provisioning it (status {row.status})", since) if time.monotonic() > deadline: raise ToolError(f"{row.name}: still {row.status} after {self.o.rollout_seconds:.0f}s") time.sleep(self.o.poll_seconds) row = self.c.gojira.app(row.id) + self.o.now("") return row def apply_configmaps(self, app: App) -> None: @@ -485,14 +500,17 @@ def settle_setup_pr(self, app: App, row: AppRow) -> AppRow: if not auto: self.o.say(f" {app.name}: waiting for someone to merge {url}") self.report.waited_on.append(url) - deadline = time.monotonic() + self.o.pr_wait_seconds + since = time.monotonic() + deadline = since + self.o.pr_wait_seconds while state == "open": + self._waiting(f"{app.name}: waiting for {url} to merge", since) if time.monotonic() > deadline: raise ToolError(f"{app.name}: {url} still open after {self.o.pr_wait_seconds:.0f}s") time.sleep(self.o.poll_seconds) state = self.c.github.pr_state(url) if state == "open" and auto and self.try_merge(app, url): state = "merged" + self.o.now("") if state == "merged": row = self.c.gojira.sync(row.id) self.report.note(f"{app.name}: setup PR merged, synced ({row.status})", self.o.say) @@ -532,24 +550,31 @@ def ensure_deployed(self, app: App, row: AppRow) -> None: def wait_run(self, app: App) -> str: """The conclusion of the latest workflow run once it completes.""" - deadline = time.monotonic() + self.o.rollout_seconds + since = time.monotonic() + deadline = since + self.o.rollout_seconds time.sleep(min(self.o.poll_seconds, 5)) # the dispatch takes a moment to appear while True: status, conclusion = self.c.github.last_run(app.connected_repo, WORKFLOW) if status == "completed": + self.o.now("") return conclusion + self._waiting(f"{app.name}: the deploy run on GitHub is {status}: " + f"https://github.com/{app.connected_repo}/actions", since) if time.monotonic() > deadline: raise ToolError(f"{app.name}: the deploy is still {status} after " f"{self.o.rollout_seconds:.0f}s") time.sleep(self.o.poll_seconds) def wait_ready(self, app: App) -> None: - deadline = time.monotonic() + self.o.rollout_seconds + since = time.monotonic() + deadline = since + self.o.rollout_seconds while True: ready, total = self.c.kubectl.pods_ready(app.namespace) if total and ready == total: + self.o.now("") self.report.note(f"{app.name}: {ready}/{total} pods ready", self.o.say) return + self._waiting(f"{app.name}: {ready}/{total} pods ready", since) if time.monotonic() > deadline: raise ToolError(f"{app.name}: {ready}/{total} pods ready after {self.o.rollout_seconds:.0f}s") time.sleep(self.o.poll_seconds) @@ -575,11 +600,14 @@ def bootstrap_cabal(self, app: App) -> None: else: self.o.say(f" {app.name}: no fresh bootstrap code in the log; restarting for one") self.c.kubectl.restart(app.namespace, app.name) - deadline = time.monotonic() + self.o.bootstrap_seconds + since = time.monotonic() + deadline = since + self.o.bootstrap_seconds while True: code = self.c.kubectl.logs_grep(app.namespace, app.name, BOOTSTRAP_CODE, since="4m") if code: + self.o.now("") break + self._waiting(f"{app.name}: waiting for a fresh bootstrap code in its log after the restart", since) if time.monotonic() > deadline: raise ToolError(f"{app.name}: no bootstrap code in its log after a restart; " "is `cabal.bootstrap_code` set to `log`?") @@ -699,13 +727,16 @@ def land_pin(self, app: App, text: str, current: str, desired: str) -> None: return self.o.say(f" {app.name}: waiting for someone to merge {url}") self.report.waited_on.append(url) - deadline = time.monotonic() + self.o.pr_wait_seconds + since = time.monotonic() + deadline = since + self.o.pr_wait_seconds state = self.c.github.pr_state(url) while state == "open": + self._waiting(f"{app.name}: waiting for the pin PR {url} to merge", since) if time.monotonic() > deadline: raise ToolError(f"{app.name}: {url} still open after {self.o.pr_wait_seconds:.0f}s") time.sleep(self.o.poll_seconds) state = self.c.github.pr_state(url) + self.o.now("") if state != "merged": raise ToolError(f"{app.name}: the pin PR {url} is {state}") self.report.note(f"{app.name}: pin merged ({url})", self.o.say) @@ -736,7 +767,8 @@ def wait_rolled(self, app: App, digest: str) -> None: if not digest: return marked = self.c.github.last_run(app.connected_repo, WORKFLOW) - deadline = time.monotonic() + self.o.rollout_seconds + since = time.monotonic() + deadline = since + self.o.rollout_seconds saw_running = False while True: image = self.c.kubectl.deployed_image(app.namespace, app.name) @@ -745,9 +777,12 @@ def wait_rolled(self, app: App, digest: str) -> None: # already names the new digest ready, total = self.c.kubectl.pods_ready(app.namespace, image) if digest in image and total and ready == total: + self.o.now("") self.report.note(f"{app.name}: rolled, {ready}/{total} pods on {digest[:19]}…", self.o.say) return status, conclusion = self.c.github.last_run(app.connected_repo, WORKFLOW) + self._waiting(f"{app.name}: deploy run {status}, {ready}/{total} pods on the new image: " + f"https://github.com/{app.connected_repo}/actions", since) if status in ("queued", "in_progress"): saw_running = True if status == "completed" and conclusion != "success" \ diff --git a/stack/templates/_lines.html b/stack/templates/_lines.html index 73f1568..7b4085a 100644 --- a/stack/templates/_lines.html +++ b/stack/templates/_lines.html @@ -27,5 +27,9 @@

Lines {{ run.stat {% else %}

opening the hands on the install…

{% endfor %} + {# What the run waits on right now, with how long: a quiet run is not a stuck one. #} + {% if run.finished is none and run.now %} +
now{{ run.now }}
+ {% endif %} diff --git a/stack/ui.py b/stack/ui.py index 82b2a32..35f5c0f 100644 --- a/stack/ui.py +++ b/stack/ui.py @@ -600,7 +600,7 @@ def on_resume() -> None: run.paused = None # The press is the review: PRs this run opens on the install's own repos are merged by it. - report = perform(target, "install", apps, merge_setup_prs=True, merge_pins=True, say=run.say, + report = perform(target, "install", apps, merge_setup_prs=True, merge_pins=True, say=run.say, now=run.set_now, on_pause=on_pause, on_resume=on_resume) run.doors = list(report.doors) # what to open now: a button per door on the run page run.add("ok", f"done: {len(report.done)} steps") @@ -767,7 +767,7 @@ def work(run: _runs.Run): old, new = _runs.set_image(target, app_name, tag, crane(target.env)) # refuses before writing run.add("info", f"{app_name}: stack file now pins {new} (was {old})") report = perform(target, "upgrade", [app_name], merge_setup_prs=True, merge_pins=True, yes=yes, - say=run.say) + say=run.say, now=run.set_now) run.add("ok", f"done: {len(report.done)} steps") return _started(request, runner.start(name, "upgrade", f"{app_name} to {tag}", work)) diff --git a/tests/test_steps.py b/tests/test_steps.py index 0f64486..12991a4 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -9,7 +9,7 @@ from stack.clients import AppRow, ToolError from stack.model import Stack from stack.steps import Clients, Installer, Options -from tests.fakes import FakeCabal, FakeGitHub, FakeGojira, FakeKubectl +from tests.fakes import FakeCabal, FakeCrane, FakeGitHub, FakeGojira, FakeKubectl ROOT = Path(__file__).parent.parent @@ -615,6 +615,31 @@ def test_a_template_takes_the_four_and_the_app_from_the_env_file(home): assert "installation_id:5141957:myorg" in github.calls +def test_every_wait_tells_the_run_what_it_waits_on_and_for_how_long(home): + """Options.now is set on each poll of a wait with the thing and the elapsed + time, and cleared when the wait ends (the stranger's quiet-page finding).""" + import threading + seen: list[str] = [] + stack = _stack(home, [{"name": "litellm", "repo": "o/litellm", "deploy_repo": "o/infra-litellm-deploy", + "image": "r/litellm:v1@sha256:aaaa"}]) + kubectl, github = FakeKubectl(), FakeGitHub() + kubectl.pods_script["litellm"] = [[(False, "r/litellm:v1", [False])], [(False, "r/litellm:v1", [True])]] + clients = Clients(gojira=FakeGojira(), kubectl=kubectl, github=github, crane=FakeCrane(), cabal=None) + inst = Installer(stack, clients, Options(stack_dir=home, repo_root=home, poll_seconds=0.01, now=seen.append)) + inst.wait_ready(stack.apps[0]) + assert seen[0].startswith("litellm: 0/1 pods ready (for ") and seen[-1] == "" + github.runs["o/infra-litellm-deploy"] = ("queued", "") + seen.clear() + + def flip(): + time.sleep(0.05) + github.runs["o/infra-litellm-deploy"] = ("completed", "success") + threading.Thread(target=flip).start() + assert inst.wait_run(stack.apps[0]) == "success" + assert any(s.startswith("litellm: the deploy run on GitHub is queued: https://github.com/o/infra-litellm-deploy/actions (for ") for s in seen) + assert seen[-1] == "" + + def test_a_file_source_at_app_pem_reads_the_key_the_app_card_stored(home): """`file:{app_pem}` is the App's key at the path the env file holds, wherever the App card put it; the stack file names no place of its own.""" diff --git a/tests/test_ui.py b/tests/test_ui.py index e661106..ae1ebe5 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -78,6 +78,35 @@ def test_a_profile_shows_its_stack_file_and_stores_only_paths(site): assert "nope.yaml" in site.get("/p/broken").text +def test_the_run_page_says_what_the_run_is_waiting_on_while_it_waits(tmp_path): + """The stranger watched ten lines for minutes: "nothing changes, I don't know + if it's doing anything or stuck". A run tells the page what it waits on + (perform's `now`); the lines block shows it while it runs, never after.""" + gate = threading.Event() + + def perform(target, action, apps, *, say=print, now=lambda t: None, **_): + say("== litellm") + now("litellm: the deploy run on GitHub is queued: https://github.com/o/r/actions (for 3 min 2 s)") + gate.wait(5) + now("") + return Report(done=["litellm: deployed"]) + + runner = Runner() + site = TestClient(make_app(tmp_path / "p.yaml", runner, perform=perform, preflight=lambda s, t: [], + github=lambda **kw: FakeGitHub(), gcloud=lambda **kw: FakeGcloud())) + site.post("/profiles", data={"name": "dogfood", "stack_file": str(DOGFOOD), "kubeconfig": KUBE}) + site.post("/p/dogfood/install", data={"apps": ["litellm"]}, follow_redirects=False) + deadline = time.monotonic() + 5 + while runner.runs[1].now == "" and time.monotonic() < deadline: + time.sleep(0.02) + page = site.get("/runs/1/lines").text + assert "the deploy run on GitHub is queued" in page and "for 3 min 2 s" in page and 'class="line now"' in page + gate.set() + _wait(runner.runs[1]) + page = site.get("/runs/1/lines").text + assert 'class="line now"' not in page and "deploy run on GitHub" not in page + + def test_a_run_gets_the_profiles_target_and_shows_its_lines_and_its_stop(site): _add(site) r = site.post("/p/dogfood/install", data={"apps": ["litellm", "boom"]}, follow_redirects=False) From f2bab3cc661f2bb891b7b67f80ad74a34bf535c3 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 21:03:45 -0500 Subject: [PATCH 14/17] kobo gets the operator token the run logged in with; a changed configmap is updated Run 10 of the stranger's install stopped at its last wiring step: "cabal mint failed: mint-service doesn't mint operator tokens; use bootstrap or POST /auth/renew". cabal 0.5.2 (its #403) refuses to mint a long-lived operator token over HTTP, and kobo's CABAL_OPERATOR_TOKEN is exactly that: kobo reads it once at boot and never renews it. The old cbl path had hidden the refusal behind the same words. Scope `operator` in a cabal-token source is now the operator token this run traded the bootstrap code for, which is what cabal's message says to do; the stranger's cabal identity sets operator_token_ttl_seconds to 90 days so that login lasts as long as the service tokens the run mints. kobo should renew its token itself one day; until then this is honest about what it holds. cabal on the stranger's cluster was already up with the one-hour identity, and "configmap exists" would have left it there. A configmap whose file now says something else is updated and its app restarted to read it, before the bootstrap login that follows. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 7 +++++++ README.md | 2 +- examples/stack/cabal-identity.toml | 5 +++++ stack/clients.py | 10 ++++++++++ stack/steps.py | 26 ++++++++++++++++++++++--- tests/fakes.py | 7 +++++++ tests/test_site.py | 2 ++ tests/test_steps.py | 31 +++++++++++++++++++++++++++++- 8 files changed, 85 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d5d475..e2b1762 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -148,6 +148,13 @@ releases yet; everything is under Unreleased. file says terraform makes it. Check says the same in plain words ("no cluster yet: Install Gojira makes in ()") instead of failing with a KUBECONFIG riddle. +- **kobo's cabal token stopped the install on cabal 0.5.2.** `cabal-token:service:kobo:operator` + asked cabal to mint a long-lived operator token, which cabal 0.5.2 refuses (its #403: "use + bootstrap or POST /auth/renew"); the old `cbl` path had hidden it. Scope `operator` is now + the operator token the run logged in with at bootstrap; the stranger's cabal identity sets + `operator_token_ttl_seconds` to 90 days, since kobo holds that token and does not renew it. + A configmap whose file changed (cabal's identity here) is updated and its app restarted to + read it, where "exists" used to leave the old one in place. - **The App card stored the key's path as typed.** `~/tenish-room.pem` passed Done (Python expands `~`) and stopped install.sh with "pem not found at ~/tenish-room.pem" (a shell string). The card stores the full path, and Install Gojira rewrites a `~` path it finds diff --git a/README.md b/README.md index 69ce2f7..c02b81e 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ dependency order. Every Secret and ConfigMap value is a *source*, never a value: | `generate:[:]` | n random bytes, base64, made once and kept in `.generated/` (mode 600) beside the file; a named value is one value for every source in the stack that names it | | `gojira-token` | the install's own API token, read from Gojira's Secret | | `template:` | a file with `{gojira_token}` filled in; relative like `file:` | -| `cabal-token::` | a 90-day service JWT minted on the cabal this run brought up | +| `cabal-token::` | a 90-day service JWT minted on the cabal this run brought up; scope `operator` is the operator token the run logged in with (cabal mints no long-lived operator tokens), which lasts `[cabal] operator_token_ttl_seconds` of cabal's identity file | | `literal:` | the text itself; for names, never for secrets | An app with `cluster_objects` names files in its repo (cloned under `--repos`) diff --git a/examples/stack/cabal-identity.toml b/examples/stack/cabal-identity.toml index 577a404..fc9e83d 100644 --- a/examples/stack/cabal-identity.toml +++ b/examples/stack/cabal-identity.toml @@ -3,6 +3,11 @@ host = "0.0.0.0" port = 7400 data_dir = "/data" operator_id = "operator" # the name cabal gives the first operator login +# How long an operator login lasts. kobo holds the operator token the install +# gives it (CABAL_OPERATOR_TOKEN) and does not renew it, and cabal mints no +# long-lived operator tokens over HTTP (cabal#403): 90 days, like the service +# tokens the install mints. +operator_token_ttl_seconds = 7776000 [litellm] api_base = "http://litellm.litellm.svc.cluster.local" diff --git a/stack/clients.py b/stack/clients.py index f52a8ad..1ff44ef 100644 --- a/stack/clients.py +++ b/stack/clients.py @@ -724,6 +724,7 @@ def tags(self, repo) -> list[str]: class CabalClient(Protocol): def login(self, code: str) -> None: ... def mint(self, sub: str, scope: str, ttl_days: int) -> str: ... + def operator_token(self) -> str: ... # the token login got: cabal mints no long-lived operator tokens (cabal#403) class HttpCabal: @@ -791,6 +792,15 @@ def login(self, code) -> None: if not self._token: raise ToolError("cabal login did not return a token") + def operator_token(self) -> str: + """The operator token the bootstrap code was traded for. Since cabal 0.5.2 + (#403) `mint-service` refuses operator scope; an app that must act as the + operator (kobo's switchboard) gets this token, which lives as long as + cabal's `[cabal] operator_token_ttl_seconds` says.""" + if not self._token: + raise ToolError("cabal: not logged in (the bootstrap code was never traded)") + return self._token + def mint(self, sub, scope, ttl_days) -> str: self.ensure_tunnel() if not self._token: diff --git a/stack/steps.py b/stack/steps.py index 1eab3c1..65a37f5 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -444,12 +444,25 @@ def wait_provisioned(self, row: AppRow) -> AppRow: return row def apply_configmaps(self, app: App) -> None: + """Each configmap the stack file names: created when absent, updated when + a key's value differs from what the file now says (and the app restarted + to read it, when it is running), left alone when equal. Configmaps carry + no secrets, so comparing them is plain reading.""" for name, keys in app.configmaps.items(): + data = {k: self.resolve(app, s, f"configmap {name}/{k}") for k, s in keys.items()} if self.c.kubectl.configmap_exists(app.namespace, name): - self.report.note(f"{app.name}: configmap {name} exists", self.o.say) + changed = [k for k, v in data.items() if self.c.kubectl.configmap_value(app.namespace, name, k) != v] + if not changed: + self.report.note(f"{app.name}: configmap {name} exists", self.o.say) + continue + self.c.kubectl.apply_configmap(app.namespace, name, data) + self.report.note(f"{app.name}: configmap {name} updated ({', '.join(changed)})", self.o.say) + _, total = self.c.kubectl.pods_ready(app.namespace) + if total: + self.c.kubectl.restart(app.namespace, app.name) + self.report.note(f"{app.name}: restarted to read configmap {name}", self.o.say) continue - self.c.kubectl.apply_configmap(app.namespace, name, - {k: self.resolve(app, s, f"configmap {name}/{k}") for k, s in keys.items()}) + self.c.kubectl.apply_configmap(app.namespace, name, data) self.report.note(f"{app.name}: configmap {name} created", self.o.say) def apply_secrets(self, app: App) -> None: @@ -811,6 +824,13 @@ def resolve(self, app: App, s: Source, label: str = "") -> str: if s.kind == "cabal-token": if self.c.cabal is None: raise ToolError(f"{app.name}: needs a cabal token but cabal is not up yet") + if s.cabal_scope == "operator": + # cabal 0.5.2 (#403): operator tokens come from bootstrap only. The app + # gets the one this run logged in with; its life is cabal's + # [cabal] operator_token_ttl_seconds (the stranger file says 90 days). + self.o.say(f" {app.name}: {label or s.arg} is the operator token this run logged in with " + "(cabal mints no long-lived operator tokens; it lasts operator_token_ttl_seconds)") + return self.c.cabal.operator_token() return self.c.cabal.mint(s.cabal_sub, s.cabal_scope, self.o.token_ttl_days) raise ToolError(f"unknown source {s.kind}") diff --git a/tests/fakes.py b/tests/fakes.py index eaa8199..7db6413 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -326,9 +326,16 @@ def login(self, code): self.logged_in = code def mint(self, sub, scope, ttl_days): + if scope == "operator": + raise ToolError("cabal mint failed: mint-service doesn't mint operator tokens; use bootstrap or POST /auth/renew") self.minted.append((sub, scope, ttl_days)) return f"h.{sub.replace(':', '-')}-{scope}.s" + def operator_token(self): + if not self.logged_in: + raise ToolError("cabal: not logged in (the bootstrap code was never traded)") + return f"h.operator-{self.logged_in}.s" + class FakeGcloud: """gcloud as the profile's env-file page sees it: the account, and the diff --git a/tests/test_site.py b/tests/test_site.py index b8ec83a..f615ae4 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -47,6 +47,8 @@ def test_the_stranger_file_loads_only_with_the_four_and_then_holds_no_token(): assert s.apps[0].contract["env"]["VERTEX_PROJECT"] == "my-proj" assert "acme" not in path.read_text(), "the example carries tokens, not a sample org to edit" assert "file:{app_pem}" in path.read_text(), "the App's key is wherever the App card stored it" + # kobo's operator token is the login's; the stranger's cabal identity makes that login last + assert "operator_token_ttl_seconds = 7776000" in (ROOT / "examples" / "stack" / "cabal-identity.toml").read_text() # the kobo template carries the same four plus the App's two, nothing to edit by hand tmpl = (ROOT / "examples" / "stack" / "kobo-config.template.yaml").read_text() for token in ("{org}", "{project}", "{app_id}", "{installation_id}", "{gojira_token}"): diff --git a/tests/test_steps.py b/tests/test_steps.py index 12991a4..f2be712 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -67,7 +67,9 @@ def test_the_dogfood_order_from_nothing(home): assert kubectl.secrets[("litellm", "litellm-secrets")] == {"LITELLM_MASTER_KEY": "sk-lite"} assert len(kubectl.secrets[("cabal", "cabal-secrets")]["CABAL_MASTER_KEY"]) == 44 # 32 bytes, base64 assert cabal.logged_in == "ABC123" - assert cabal.minted == [("service:liminal", "secrets-fetch", 90), ("service:kobo", "operator", 90)] + assert cabal.minted == [("service:liminal", "secrets-fetch", 90)] # operator scope is not minted + assert kubectl.secrets[("kobo", "kobo-cabal")]["CABAL_OPERATOR_TOKEN"] == "h.operator-ABC123.s" # the login's token + assert any("operator token this run logged in with" in ln for ln in lines) assert kubectl.secrets[("kobo", "kobo-config")]["config.yaml"].startswith('gojira_token: "tok-123"') assert kubectl.applied == [str(home / "repos" / "kobo" / "k8s" / "cluster" / "rbac.yaml")] assert [c for c in github.calls if c.startswith("merge")] == [f"merge:https://github.com/o/{a}/pull/1" @@ -76,6 +78,33 @@ def test_the_dogfood_order_from_nothing(home): assert "kobo: 1/1 pods ready" in "\n".join(lines) +def test_a_changed_configmap_is_updated_and_the_app_restarted_to_read_it(home): + """The stranger run: cabal's identity file gained operator_token_ttl_seconds + after cabal was already up with the old one; "configmap exists" would have + left the one-hour identity in place and kobo's token dead within the hour.""" + (home / "identity.toml").write_text("[cabal]\noperator_token_ttl_seconds = 3600\n") + stack = _stack(home, [{"name": "cabal", "repo": "o/cabal", "bootstrap": "cabal", + "configmaps": {"cabal-config": {"identity.toml": f"file:{home}/identity.toml"}}, + "secrets": {"cabal-secrets": {"CABAL_MASTER_KEY": "generate:32"}}}]) + kubectl = FakeKubectl() + _, _, lines = _run(home, stack, kubectl=kubectl, cabal=FakeCabal(), merge_setup_prs=True) + assert "cabal: configmap cabal-config created" in "\n".join(lines) + assert not any(c.startswith("restart:") for c in kubectl.calls) + # the same again: exists, nothing restarted + kubectl.calls.clear() + _, _, lines = _run(home, stack, kubectl=kubectl, cabal=FakeCabal(), merge_setup_prs=True) + assert "cabal: configmap cabal-config exists" in "\n".join(lines) + assert not any(c.startswith("restart:") for c in kubectl.calls) + # the file changed: updated, and cabal restarted to read it + (home / "identity.toml").write_text("[cabal]\noperator_token_ttl_seconds = 7776000\n") + kubectl.calls.clear() + _, _, lines = _run(home, stack, kubectl=kubectl, cabal=FakeCabal(), merge_setup_prs=True) + assert "cabal: configmap cabal-config updated (identity.toml)" in "\n".join(lines) + assert "cabal: restarted to read configmap cabal-config" in "\n".join(lines) + assert kubectl.configmaps[("cabal", "cabal-config")]["identity.toml"].endswith("7776000") + assert "restart:cabal/cabal" in kubectl.calls + + def test_a_second_run_changes_nothing(home): stack = _stack(home, [ {"name": "cabal", "repo": "o/cabal", "bootstrap": "cabal", From fdb3760685a67495a59a990bb5b73c4680ed16f4 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 21:10:07 -0500 Subject: [PATCH 15/17] A base file Gojira rewrote is left alone; a restart waits as long as it asks Two more from the stranger's run 11. Every press rewrote one file in each deploy repo and provisioned the app again. Each upstream's k8s/base/deployment.yaml carries an arm64 node selector from the dogfood on spark; Gojira's setup PR strips it, since placement is Gojira's, and the installer copied the upstream's file back on the next press. A base file the deploy repo already has is Gojira's now and is left alone on reruns; gojira.yaml stays the installer's and is kept current; a base file the repo lacks is added. The restart after cabal's ConfigMap changed stopped the run with "did not answer in 60s": restart asked kubectl to wait five minutes for the rollout and the wrapper around kubectl allowed sixty, while cabal's pod sat Pending for a node on Autopilot. The wait gets the time it asks for. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 10 ++++++++++ stack/clients.py | 10 +++++++--- stack/steps.py | 14 ++++++++++++++ tests/test_clients_timeouts.py | 18 ++++++++++++++++++ tests/test_steps.py | 26 ++++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 tests/test_clients_timeouts.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e2b1762..5a07155 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -148,6 +148,16 @@ releases yet; everything is under Unreleased. file says terraform makes it. Check says the same in plain words ("no cluster yet: Install Gojira makes in ()") instead of failing with a KUBECONFIG riddle. +- **A restart was cut off at sixty seconds.** `restart` asked kubectl to wait five minutes for + the rollout and the wrapper around kubectl allowed sixty; cabal's pod was Pending for a node + on Autopilot and the run stopped with "did not answer in 60s". The wait now gets the time + it asks for. +- **Every press rewrote one deploy-repo file and provisioned again.** Each upstream's + `k8s/base/deployment.yaml` carries an arm64 node selector from the dogfood; Gojira's setup + PR strips it (placement is Gojira's), and the installer copied the upstream's file back on + the next press, so every rerun re-provisioned every app. A base file the deploy repo already + has is Gojira's now and is left alone; `gojira.yaml` stays the installer's; a base file the + repo lacks is added. - **kobo's cabal token stopped the install on cabal 0.5.2.** `cabal-token:service:kobo:operator` asked cabal to mint a long-lived operator token, which cabal 0.5.2 refuses (its #403: "use bootstrap or POST /auth/renew"); the old `cbl` path had hidden it. Scope `operator` is now diff --git a/stack/clients.py b/stack/clients.py index 1ff44ef..9baed90 100644 --- a/stack/clients.py +++ b/stack/clients.py @@ -246,8 +246,8 @@ def __init__(self, context: str = "", env: dict[str, str] | None = None): # 2026-10-14). Not on port-forward, which is meant to live. self._base = ["kubectl", *self._ctx, "--request-timeout=20s"] - def _k(self, *args: str, stdin: str | None = None, check: bool = True) -> str: - return _run([*self._base, *args], stdin=stdin, check=check, timeout=60, env=self._env) + def _k(self, *args: str, stdin: str | None = None, check: bool = True, timeout: int = 60) -> str: + return _run([*self._base, *args], stdin=stdin, check=check, timeout=timeout, env=self._env) def _exists(self, ns: str, kind: str, name: str) -> bool: return subprocess.run([*self._base, "-n", ns, "get", kind, name], capture_output=True, timeout=60, @@ -338,8 +338,12 @@ def deployed_image(self, ns, deploy) -> str: "jsonpath={.spec.template.spec.containers[0].image}", check=False).strip() def restart(self, ns, deploy) -> None: + """Restart the deployment and wait for it to come back. The wait is given + five minutes by kubectl and a little more by us: a Recreate pod on + Autopilot can sit Pending for a node (the stranger run: cabal's restart + was cut off at the wrapper's sixty seconds while its pod was Pending).""" self._k("-n", ns, "rollout", "restart", f"deploy/{deploy}") - self._k("-n", ns, "rollout", "status", f"deploy/{deploy}", "--timeout=300s") + self._k("-n", ns, "rollout", "status", f"deploy/{deploy}", "--timeout=300s", timeout=330) def exec(self, ns, deploy, args) -> str: """Run `args` in the deployment's pod and return what it printed (both diff --git a/stack/steps.py b/stack/steps.py index 65a37f5..a25991e 100644 --- a/stack/steps.py +++ b/stack/steps.py @@ -322,6 +322,20 @@ def ensure_deploy_repo(self, app: App) -> int: if not self.c.github.repo_exists(app.deploy_repo): self.c.github.create_repo(app.deploy_repo) self.report.note(f"{app.name}: created deploy repo {app.deploy_repo}", self.o.say) + else: + # A k8s/base file the repo already has is Gojira's now: its setup PR + # rewrites what it owns there (node placement, probes, resources), and + # copying the upstream's copy back would undo that on every press and + # provision again (the stranger run: an arm64 selector in every + # upstream, stripped by Gojira, re-imposed by the installer, forever). + # gojira.yaml is the installer's and is kept current; a base file the + # repo lacks is added. + try: + present = set(self.c.github.list_dir(app.deploy_repo, "k8s/base")) + except ToolError: + present = set() + files = {p: t for p, t in files.items() + if not (p.startswith("k8s/base/") and p[len("k8s/base/"):] in present)} changed = self.c.github.push_files(app.deploy_repo, files, f"deploy {app.image}") self.report.note(f"{app.name}: deploy repo {app.deploy_repo} " + (f"updated ({changed} files)" if changed else "current"), self.o.say) diff --git a/tests/test_clients_timeouts.py b/tests/test_clients_timeouts.py new file mode 100644 index 0000000..64fe031 --- /dev/null +++ b/tests/test_clients_timeouts.py @@ -0,0 +1,18 @@ +"""The kubectl wrapper's per-call timeout versus the waits kubectl is asked for.""" + +from stack import clients + + +def test_restart_waits_as_long_as_it_asks_kubectl_to(monkeypatch): + """`rollout status --timeout=300s` under a sixty-second wrapper stopped the + stranger's run with "did not answer in 60s" while cabal's pod was Pending.""" + seen = [] + + def fake_run(args, *, stdin=None, check=True, timeout=60, env=None): + seen.append((args[-2:], timeout)) + return "" + monkeypatch.setattr(clients, "_run", fake_run) + monkeypatch.setattr(clients.shutil, "which", lambda name: "/usr/bin/kubectl") + clients.KubectlCLI("ctx", env={}).restart("cabal", "cabal") + waits = [t for args, t in seen if "--timeout=300s" in args] + assert waits and waits[0] >= 300 diff --git a/tests/test_steps.py b/tests/test_steps.py index f2be712..7431fa9 100644 --- a/tests/test_steps.py +++ b/tests/test_steps.py @@ -456,6 +456,32 @@ def test_a_deploy_repo_rerun_pushes_nothing(home): assert "cabal: deploy repo acme/cabal-deploy current" in "\n".join(lines) +def test_a_base_file_gojira_rewrote_in_the_deploy_repo_is_left_alone(home): + """Every upstream's k8s/base/deployment.yaml carried an arm64 node selector + from the dogfood; Gojira's setup PR strips it (placement is Gojira's), and the + next press copied the upstream's file back and provisioned again, every + time. A base file the repo already has is Gojira's; gojira.yaml stays the + installer's; a base file the repo lacks is added.""" + _upstream(home) + entry = {"name": "cabal", "repo": "tenishai/cabal", "image": "r/x:1", "deploy_repo": "acme/d"} + gojira, github = FakeGojira(), FakeGitHub() + _run(home, _stack(home, [entry]), gojira=gojira, github=github, merge_setup_prs=True) + # Gojira's setup PR rewrote the deployment (stripped the selector) + github.repos["acme/d"]["k8s/base/deployment.yaml"] = "kind: Deployment\n# rewritten by Gojira\n" + github.calls.clear() + gojira.calls.clear() + _, _, lines = _run(home, _stack(home, [entry]), gojira=gojira, github=github, merge_setup_prs=True) + assert github.repos["acme/d"]["k8s/base/deployment.yaml"] == "kind: Deployment\n# rewritten by Gojira\n" + assert not [c for c in github.calls if c.startswith("push")] and not [c for c in gojira.calls if c.startswith("provision")] + assert "cabal: deploy repo acme/d current" in "\n".join(lines) + # a contract change still reaches gojira.yaml; a new upstream base file is added + entry["contract"] = {"env": {"PORT": "8080"}} + (home / "repos" / "cabal" / "k8s" / "base" / "newfile.yaml").write_text("kind: ConfigMap\n") + _run(home, _stack(home, [entry]), gojira=gojira, github=github, merge_setup_prs=True) + assert "PORT" in github.repos["acme/d"]["gojira.yaml"] and github.repos["acme/d"]["k8s/base/newfile.yaml"] == "kind: ConfigMap\n" + assert github.repos["acme/d"]["k8s/base/deployment.yaml"] == "kind: Deployment\n# rewritten by Gojira\n" + + def test_a_changed_contract_on_a_live_app_is_provisioned_again(home): """A rerun that changes the deploy repo (bab's BAB_PORT, 2026-11-06) must press provision: the push's CI fails the contract check by design, and an From 760c74750e2845d6a09f5d8101f4cf8f1c5d0bb3 Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 21:28:48 -0500 Subject: [PATCH 16/17] The stranger's kobo config names the switchboard Found while reading the org.yaml kobo's bootstrap wrote on the stranger's cluster: cabal_url and agent_endpoint_template were null. The kobo config template named the tool gateway (liminal) but never cabal, so a shared thread between two agents would have said "the switchboard is not configured" (the dogfood set both by hand in its org repo, 2026-10-08). Both are in the template now; {name} there is kobo's own token, which the install's filler leaves alone. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 3 +++ examples/stack/kobo-config.template.yaml | 4 ++++ tests/test_site.py | 2 ++ 3 files changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a07155..09b1c2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -148,6 +148,9 @@ releases yet; everything is under Unreleased. file says terraform makes it. Check says the same in plain words ("no cluster yet: Install Gojira makes in ()") instead of failing with a KUBECONFIG riddle. +- **The stranger's kobo had no switchboard.** The kobo config template named the tool gateway but + not cabal (`cabal_url`, `agent_endpoint_template`), so a shared thread between two agents would + have said "the switchboard is not configured". Both are in the template now. - **A restart was cut off at sixty seconds.** `restart` asked kubectl to wait five minutes for the rollout and the wrapper around kubectl allowed sixty; cabal's pod was Pending for a node on Autopilot and the run stopped with "did not answer in 60s". The wait now gets the time diff --git a/examples/stack/kobo-config.template.yaml b/examples/stack/kobo-config.template.yaml index 8c0159d..cb6397a 100644 --- a/examples/stack/kobo-config.template.yaml +++ b/examples/stack/kobo-config.template.yaml @@ -31,6 +31,10 @@ api_base_url: http://kobo.kobo.svc.cluster.local # liminal_admin_url and gateway_config_repo stay empty here: grants are then yours # to write on the gateway (kobo's docs/adding-a-vendor.md). liminal_url: http://liminal.liminal.svc.cluster.local +# The switchboard (cabal in stack.yaml): shared threads between agents go through it. +# {name} is each agent's own name, filled by kobo, not by the install. +cabal_url: http://cabal.cabal.svc.cluster.local +agent_endpoint_template: "http://{name}.{name}.svc.cluster.local" workdir: /data/work db_url: sqlite:////data/kobo.db ui_dist: /srv/ui diff --git a/tests/test_site.py b/tests/test_site.py index f615ae4..5a7b704 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -53,6 +53,8 @@ def test_the_stranger_file_loads_only_with_the_four_and_then_holds_no_token(): tmpl = (ROOT / "examples" / "stack" / "kobo-config.template.yaml").read_text() for token in ("{org}", "{project}", "{app_id}", "{installation_id}", "{gojira_token}"): assert token in tmpl, token + # the switchboard (cabal) is wired, or shared threads say "not configured"; {name} is kobo's own token + assert "cabal_url: http://cabal.cabal.svc.cluster.local" in tmpl and "agent_endpoint_template" in tmpl assert "acme" not in tmpl and "" not in tmpl doc = yaml.safe_load(fill(tmpl, {**FOUR, "app_id": "7", "installation_id": "9", "gojira_token": "t"})) assert doc["org_repo"] == "myorg/kobo-config" and doc["gcp_project"] == "my-proj" From e9ec867b1f3a558ef876cde5109a7f4a7abc866c Mon Sep 17 00:00:00 2001 From: Shahzad Chaudhri Date: Mon, 30 Nov 2026 22:05:33 -0500 Subject: [PATCH 17/17] Check names the org config repo kobo reads at boot Shaz, after the room read another cluster's org.yaml: "there's nothing in the installer that tells me what needs to be there". kobo reads /kobo-config when it starts and makes one only when the name answers nothing. On the stranger's cluster the name answered: an archived repo from another cluster, renamed, still forwarded by GitHub, and the room merged its values over the install's own and wrote them into the fresh repo it then made. Check now has a row for every app whose config template names an org_repo: absent, and the app's first run makes it; present and naming this install's project and cluster; present and naming another's, with what it says and what to do; or a rename forward, which is a stop, since a clone follows it. GitHubClient.repo_resolves answers the name GitHub gives after any forward. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shahzad Chaudhri --- CHANGELOG.md | 6 ++++ stack/clients.py | 7 +++++ stack/preflight.py | 67 ++++++++++++++++++++++++++++++++++++++++- tests/fakes.py | 4 +++ tests/test_preflight.py | 31 +++++++++++++++++++ 5 files changed, 114 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09b1c2b..c8cfad2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,12 @@ releases yet; everything is under Unreleased. release the stack file names; the example's placeholder id and pem path are never shown as an App (a file seeded from `gojira.env.example` starts with both blank). The apps table's column is "Version", not "Running": it is what the stack file names. +- **Check names the org config repo kobo reads at boot.** kobo reads `/kobo-config` when it + starts and only makes one when the name answers nothing; the stranger run met a renamed, + archived repo still answering the old name through GitHub's forward, and the room read + another cluster's file. Check now has a row for every app whose config template names an + `org_repo`: absent (the app's first run makes it), this install's, another install's with the + project and cluster it names, or a rename forward, which is a stop. - **The page before a cluster exists.** A kubeconfig with nothing to read used to be "unknown": no App card, no Install Gojira, though terraform would make the cluster. When the env file says `GOJIRA_TERRAFORM=1` and names a `CLUSTER`, the page now says "no cluster diff --git a/stack/clients.py b/stack/clients.py index 9baed90..ce0682c 100644 --- a/stack/clients.py +++ b/stack/clients.py @@ -420,6 +420,10 @@ def last_run(self, repo: str, workflow: str) -> tuple[str, str]: ... def login(self) -> str: ... def org_access(self, org: str) -> str: ... def orgs(self) -> list[str]: ... # the organizations gh's account belongs to; [] when not logged in + # The full name GitHub answers for `repo` after any rename forward: the same + # name when it exists as such, the renamed repo's name when the old name + # forwards to it, "" when nothing answers. A clone follows the forward. + def repo_resolves(self, repo: str) -> str: ... # Slice 4 (the GitHub App pause card, criterion 3): the card's Done button runs # three checks. (a) the pem parses as a private key and (b) a JWT signed with it # answers GET /app with that id; both in one call so the card names a failure. @@ -481,6 +485,9 @@ def repo_exists(self, repo) -> bool: return subprocess.run(["gh", "repo", "view", repo, "--json", "name"], capture_output=True, env=self._env).returncode == 0 + def repo_resolves(self, repo) -> str: + return self._gh("api", f"repos/{repo}", "--jq", ".full_name", check=False).strip() + def create_repo(self, repo) -> None: self._gh("repo", "create", repo, "--private", "--description", "Deploy repo for a published image, managed by the stack installer (Gojira image:)") diff --git a/stack/preflight.py b/stack/preflight.py index 18d19d6..d66387e 100644 --- a/stack/preflight.py +++ b/stack/preflight.py @@ -91,6 +91,69 @@ def check_tools(stack: Stack, target: Target, which: Callable[[str], str | None] return out +def _org_repos(stack: Stack, target: Target) -> list[tuple[str, str]]: + """(app, org repo) for every app whose config template names an `org_repo`: + the repo the app reads its org-wide config from at boot and makes on its + first run when it is not there (kobo's /kobo-config).""" + import yaml + + from stack.site import fill + out = [] + base = target.stack_file.parent + for app in stack.apps: + for obj in (*app.configmaps.values(), *app.secrets.values()): + for src in obj.values(): + if src.kind != "template": + continue + path = src.path if src.path.is_absolute() else base / src.path + if not path.exists(): + continue + try: + doc = yaml.safe_load(fill(path.read_text(), target.values)) or {} + except (ValueError, yaml.YAMLError): + continue # the four are not set yet, or not YAML: nothing to name + repo = doc.get("org_repo") if isinstance(doc, dict) else None + if isinstance(repo, str) and "/" in repo: + out.append((app.name, repo)) + return out + + +def check_org_repos(stack: Stack, target: Target, github: GitHubClient) -> list[Check]: + """The org config repo an app reads at boot (kobo: /kobo-config). Absent, + the app makes it on its first run. Present, the app reads it and never makes a + fresh one: the row says what it names so another install's is told apart (the + stranger run, 2026-11-30: an archived repo of that name from another cluster, + renamed, still answered the old name through GitHub's forward; the room read + it at boot and wrote its values into the new repo it then made).""" + out = [] + for app, repo in _org_repos(stack, target): + what = f"{app}: org config {repo}" + answers = github.repo_resolves(repo) + if not answers: + out.append(Check(what, "ok", f"not there yet; {app}'s first run makes it")) + continue + if answers != repo: + out.append(Check(what, "fail", f"the name forwards to {answers} (renamed): {app} clones the old name and reads " + f"that file at boot. Delete {answers}, or make {repo} first")) + continue + try: + import yaml + doc = yaml.safe_load(github.read_file(repo, "org.yaml")) or {} + names = {k: str(doc.get(k, "")) for k in ("gcp_project", "gojira_cluster")} + except (ToolError, yaml.YAMLError): + names = {} + mine = {"gcp_project": target.values.get("project", ""), "gojira_cluster": target.values.get("cluster", "")} + if names and all(names[k] == mine[k] for k in names if mine[k]): + out.append(Check(what, "ok", f"exists and names this install ({names['gcp_project']}, {names['gojira_cluster']}); " + f"{app} reads it at boot")) + else: + said = ", ".join(f"{k}={v or '?'}" for k, v in names.items()) or "its org.yaml could not be read" + out.append(Check(what, "warn", f"exists already and {app} reads it at boot instead of making a fresh one; " + f"it says {said}. Another install's? Edit it, or delete it so {app} makes " + "one (a rename keeps forwarding the old name)")) + return out + + def check_github(stack: Stack, github: GitHubClient) -> list[Check]: out = [] try: @@ -227,7 +290,9 @@ def _app_pem_in(env_file: Path | None) -> str: def preflight(stack: Stack, target: Target, which: Callable[[str], str | None] = shutil.which) -> list[Check]: out = check_tools(stack, target, which) + check_files(stack, target) try: - out += check_github(stack, GhCLI(target.env)) + gh = GhCLI(target.env) + out += check_github(stack, gh) + out += check_org_repos(stack, target, gh) except ToolError as exc: out.append(Check("gh login", "fail", str(exc))) # The cluster row: a missing namespace is a different case from an unreadable diff --git a/tests/fakes.py b/tests/fakes.py index 7db6413..8105989 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -171,6 +171,7 @@ def __init__(self, states: dict[str, str] | None = None, runs: dict[str, tuple[s self.pr_files: dict[str, dict[str, str]] = {} self.user = "tester" # "" = not logged in self.user_orgs: list[str] = [] # what orgs() offers the four-things pick + self.forwards: dict[str, str] = {} # old name -> renamed repo GitHub forwards it to self.org_denied: dict[str, str] = {} # org -> why gh cannot see it self.refuse_merges = 0 # merge_pr: rule refusals before one succeeds self.merge_error: ToolError | None = None @@ -190,6 +191,9 @@ def orgs(self): def repo_exists(self, repo): return repo in self.repos + def repo_resolves(self, repo): + return repo if repo in self.repos else self.forwards.get(repo, "") + def create_repo(self, repo): self.calls.append(f"create:{repo}") self.repos[repo] = {} diff --git a/tests/test_preflight.py b/tests/test_preflight.py index 2d5b821..2dce82a 100644 --- a/tests/test_preflight.py +++ b/tests/test_preflight.py @@ -136,6 +136,37 @@ def test_the_whole_preflight_turns_a_strangers_shell_into_rows_not_tracebacks(tm assert not any(c.what.startswith("kobo: Gojira") for c in checks) +def test_the_org_config_repo_an_app_reads_at_boot_is_a_row(tmp_path): + """Shaz: "there's nothing in the installer that tells me what needs to be + there". kobo reads /kobo-config at boot and never makes a fresh one when + the name answers; Check says whether it is absent (kobo makes it), this + install's, another install's (with what it names), or a rename forward.""" + from stack.preflight import check_org_repos + (tmp_path / "kobo.tmpl").write_text('github_org: "{org}"\norg_repo: "{org}/kobo-config"\ngcp_project: "{project}"\n') + stack, target = _stack(tmp_path, """ +apps: + - {name: kobo, repo: o/kobo, image: r/kobo:v1, deploy_repo: "{org}/infra-kobo-deploy", + secrets: {kobo-config: {config.yaml: "template:kobo.tmpl"}}} +""".replace("{org}", "acme")) + target.values = {"org": "acme", "project": "acme-agents", "region": "us-central1", "cluster": "gojira-sandbox"} + gh = FakeGitHub() + row = _by(check_org_repos(stack, target, gh), "kobo: org config acme/kobo-config") + assert row.status == "ok" and "first run makes it" in row.detail + gh.repos["acme/kobo-config"] = {"org.yaml": "gcp_project: acme-agents\ngojira_cluster: gojira-sandbox\n"} + row = _by(check_org_repos(stack, target, gh), "kobo: org config acme/kobo-config") + assert row.status == "ok" and "names this install" in row.detail + gh.repos["acme/kobo-config"] = {"org.yaml": "gcp_project: other-project\ngojira_cluster: other-cluster\n"} + row = _by(check_org_repos(stack, target, gh), "kobo: org config acme/kobo-config") + assert row.status == "warn" and "gcp_project=other-project" in row.detail and "reads it at boot" in row.detail + del gh.repos["acme/kobo-config"] + gh.forwards["acme/kobo-config"] = "acme/kobo-config-old-2026-08" + row = _by(check_org_repos(stack, target, gh), "kobo: org config acme/kobo-config") + assert row.status == "fail" and "forwards to acme/kobo-config-old-2026-08" in row.detail + # the four not set yet: nothing to name, no row, no error + target.values = {} + assert check_org_repos(stack, target, gh) == [] + + def test_no_cluster_yet_is_a_warn_naming_what_install_gojira_makes(tmp_path, monkeypatch): """The stranger's Check before the cluster exists said FAIL "has no namespace 'gojira'. Is KUBECONFIG the install's…": a riddle for a cluster terraform has

AppRepoRunningReleases
AppRepoVersionReleases