diff --git a/CHANGELOG.md b/CHANGELOG.md
index f637e75..c8cfad2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,7 +16,42 @@ 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`; nor is the kubeconfig:
+ the machine's own for a cluster it already knows, `~/.kube-/config` for one the
+ install makes. Profile settings still name other files. The add form is Name, Cluster,
+ Google account, and a reload no longer restores a removed box's text into the one now in
+ its place (the kubeconfig path appeared in the Google account box after a pull). The
+ repo-clones box (`--repos`, for developers building the apps from source) is on the
+ settings form only. The Google account is a pick of the accounts gcloud is logged in as,
+ the one it uses now picked (a box to type into on a machine without gcloud).
+- **The four-things card speaks to a stranger.** The profile page met him with a red box
+ ("needs values for {org}… or pass --set") above the card about to ask for exactly those,
+ a paragraph about tokens, env files and contracts, a button that wrote "the env file", and a
+ table of GOJIRA_* keys "not written yet". Now: no red box while the card asks; one sentence;
+ the GitHub organization and the GCP project are picks (the orgs gh belongs to, the projects
+ the Google account sees; a box to type into when the tool offers none; a saved value no
+ 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
+ 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
@@ -75,6 +110,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
@@ -101,7 +143,63 @@ releases yet; everything is under Unreleased.
### Fixed
+- **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 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
+ 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
+ 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
+ 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
+ (`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
+ 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.
+### 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..c02b81e 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
@@ -23,8 +22,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 +33,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=…
```
@@ -77,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`)
@@ -160,16 +158,19 @@ 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 (the machine's own
+for a cluster it knows, `~/.kube-/config` for one the install makes) 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:
- **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
@@ -200,8 +201,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, `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.
@@ -240,7 +240,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..3a27b95 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -27,9 +27,8 @@ 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. |
-| 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
@@ -41,27 +40,30 @@ 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
```
`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); the Gojira checkout `../gojira`; and cabal's `cbl`, the one box to
-type. Picking an existing GKE cluster instead fills its project, region and
-name on the next page.
+cluster: this install makes it". The one other box, your Google account, is a
+pick of the accounts gcloud is logged in as, with the one it uses now picked.
+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), writes Gojira's values to `~/.config/stack//gojira.env`,
+and keeps the new cluster's address in a kubeconfig of its own
+(`~/.kube-/config`, written when the cluster exists) so it stays out of
+your other kubectl work; 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
-The profile page opens on one card: your GitHub organization, your GCP project,
-the region and the cluster name. Press **Save and write the env file**. The
-page writes Gojira's values file from them and from the stack file, and shows
-what the file now holds:
+The profile page opens on one card: your GitHub organization (a pick of the
+ones gh belongs to), your GCP project (a pick of the ones your Google account
+can see), the region and the cluster name. Press **Save**. The page saves them
+on the profile and writes Gojira's values file from them and from the stack
+file; "What was written for Gojira" under the card shows what the file holds:
| Written | From |
|---|---|
@@ -108,7 +110,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 +122,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/examples/stack.yaml b/examples/stack.yaml
index 30b7029..710c4a0 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}
@@ -85,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/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/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/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 6c875d6..ce0682c 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 []
@@ -224,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,
@@ -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)
@@ -310,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
@@ -387,6 +419,11 @@ def dispatch(self, repo: str, workflow: str) -> None: ...
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.
@@ -414,6 +451,12 @@ def login(self) -> str:
raise ToolError("gh is not logged in (gh auth login)")
return out
+ def orgs(self) -> list[str]:
+ """The organizations gh's account belongs to, for the four-things pick;
+ empty when gh is not logged in."""
+ out = self._gh("api", "user/orgs", "--paginate", "--jq", ".[].login", check=False)
+ return [ln.strip() for ln in out.splitlines() if ln.strip()]
+
def org_access(self, org: str) -> str:
"""Why gh cannot see `org`'s repos, or "" when it can. SAML SSO never
says 401: a token without the org's SSO grant lists none of its repos
@@ -442,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:)")
@@ -683,34 +729,31 @@ 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):
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 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)
@@ -739,21 +782,44 @@ 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 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()
- 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/model.py b/stack/model.py
index 6dbb116..2bef0a0 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:
@@ -274,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 93c8c62..d66387e 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:
@@ -76,14 +88,69 @@ 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}"))
+ 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:
- out.append(Check("cbl", "ok", target.cbl))
+ 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
@@ -196,10 +263,36 @@ 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:
- 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
@@ -213,6 +306,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/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..066140d 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
@@ -65,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)
@@ -76,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:
@@ -90,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":
@@ -100,14 +101,11 @@ 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,
+ 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:
@@ -200,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
@@ -218,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/site.py b/stack/site.py
index 2df8483..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")\}")
@@ -118,6 +118,9 @@ def write_env(path: str | Path, values: dict[str, str], example_text: str = "")
if not p.exists() and example_text:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(example_text)
+ # the example's App lines are placeholders (1234567, ./github-app.pem):
+ # a fresh file starts with no App, so the card asks instead of showing them
+ values = {"GOJIRA_GITHUB_APP_ID": "", "GOJIRA_GITHUB_APP_PEM": "", **values}
return envfile.save_env_file(p, values)
diff --git a/stack/steps.py b/stack/steps.py
index 227e155..a25991e 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)
@@ -315,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)
@@ -419,22 +440,43 @@ 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:
+ """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:
@@ -485,14 +527,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 +577,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)
@@ -563,7 +615,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:
@@ -575,11 +627,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 +754,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,15 +794,22 @@ 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)
- 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.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" \
@@ -773,6 +838,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}")
@@ -815,20 +887,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/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/templates/_profile_form.html b/stack/templates/_profile_form.html
index f9c4f09..94446f5 100644
--- a/stack/templates/_profile_form.html
+++ b/stack/templates/_profile_form.html
@@ -1,12 +1,19 @@
{% 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. #}
-
-
-
In the env file now
Value
-
- {% for k, v in env_has.items() %}
-
{{ k }}
{% if v %}{{ v }}{% else %}not written yet{% endif %}
- {% endfor %}
-
-
+ {% set written = env_has.values() | select | list %}
+ {% if written %}
+
+ What was written for Gojira ({{ profile.env_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. #}
Check
the install will act as is verified. Done runs the three checks and stores
only the id and the pem path in the install's env file. #}
-
Gojira installs as a GitHub App that acts on your repos — clones, pushes the setup branch, opens PRs. It is not installed yet, and this profile's env file has no verified App id + pem. Set it up once; the page will then show the install.
+
Gojira acts on your GitHub repos as a GitHub App: it clones them, pushes setup branches and
+ opens pull requests. Make the App once, in your organization; the page then shows Install Gojira.
Name it gojira-{{ stack_org }}; give it the repository permissions below and no account permissions; leave the webhook off
+
On the App's page, generate a private key: your browser downloads a .pem. Keep it somewhere on this machine (~/.config/stack/{{ profile.name }}/ is a good place) and put its path below
+
Install the App on your organization, for all repositories (the install makes new ones)
{% if app_setup.found %}
@@ -70,18 +73,21 @@
Check
{% endfor %}
-
The full walkthrough — permissions, why each, the webhook secret, verification — is in {{ app_setup.doc }}.
+
The full walkthrough, with why each permission, is
+ {% if app_doc_url.startswith('http') %}github-app-setup.md{% else %}in {{ app_doc_url }}{% endif %}.
{% 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 %}
-
+
-
-
-
+
+
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
@@ -91,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
- {% 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
{% if a.image %}{% set tag, digest = a.image | image_parts %}
diff --git a/stack/ui.py b/stack/ui.py
index 8bab19c..35f5c0f 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,70 @@ 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 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 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
+
+
+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:
@@ -96,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
@@ -169,7 +238,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 +247,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 +272,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 +283,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,26 +319,22 @@ 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
- kubeconfig knows, and the accounts gcloud is logged in as. Each is a
+ that ships with the installer, the kubeconfig kubectl uses by default, the clusters that
+ kubeconfig knows, and the accounts gcloud is logged in as (and which one it uses now). 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"
+ kc = default_kubeconfig()
try:
contexts = kubectl(env={}).list_contexts()
except Exception:
contexts = []
try:
accounts = gcloud(env={}).accounts()
+ active = gcloud(env={}).account()
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}
+ accounts, active = [], ""
+ return {"stack_file": shipped_stack_file(), "default_kubeconfig": kc, "contexts": contexts,
+ "accounts": accounts, "account": active if active in accounts else ""}
def index_rows():
rows = []
@@ -260,9 +349,9 @@ 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(""),
- 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
@@ -270,10 +359,19 @@ 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 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.strip(), stack_file=stack_file.strip(), kubeconfig=kubeconfig.strip(),
- cloud_account=cloud_account.strip(), repos=repos.strip(), cbl=cbl.strip(),
- env_file=env_file.strip(), gojira_repo=gojira_repo.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(),
cluster=cluster.strip())
except ValueError as exc:
@@ -282,6 +380,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")
@@ -315,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:
@@ -347,6 +458,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
@@ -354,23 +471,46 @@ 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)
+ 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
# 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, app_doc_url=app_doc_url,
tokens=_site.TOKENS, defaults=form_defaults())
@app.post("/p/{name}/values")
@@ -400,7 +540,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 "
@@ -460,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")
@@ -532,7 +672,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}
@@ -627,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))
@@ -656,7 +796,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 +803,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()
@@ -679,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:
@@ -761,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/fakes.py b/tests/fakes.py
index e742fd8..8105989 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):
@@ -160,6 +170,8 @@ 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.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
@@ -173,9 +185,15 @@ 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
+ 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] = {}
@@ -308,13 +326,20 @@ 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):
+ 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_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_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_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_env_page.py b/tests/test_env_page.py
index 43aa359..acf8c13 100644
--- a/tests/test_env_page.py
+++ b/tests/test_env_page.py
@@ -8,9 +8,10 @@
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
+from tests.fakes import FakeGcloud, FakeGitHub, FakeKubectl
ROOT = Path(__file__).parent.parent
GOJIRA = ROOT.parent / "gojira"
@@ -50,9 +51,10 @@ 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"
# 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,17 +121,25 @@ 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
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_gojira_checkout.py b/tests/test_gojira_checkout.py
new file mode 100644
index 0000000..0ae0294
--- /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, FakeGitHub, 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, github=lambda **kw: FakeGitHub())
+ 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_install_gojira.py b/tests/test_install_gojira.py
index 46cfb7e..c559963 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),
@@ -226,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
@@ -256,7 +273,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_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
diff --git a/tests/test_no_cluster_yet.py b/tests/test_no_cluster_yet.py
index 6029e24..1141ad1 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,41 @@ 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
+ "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_preflight.py b/tests/test_preflight.py
index 5d30f3f..2dce82a 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):
@@ -140,6 +136,86 @@ 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
+ 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_profile_form.py b/tests/test_profile_form.py
index 2caedcf..5def95c 100644
--- a/tests/test_profile_form.py
+++ b/tests/test_profile_form.py
@@ -12,20 +12,20 @@
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"
GKE = "gke_acme-agents_us-central1_gojira-sandbox"
-def _site(tmp_path, contexts=(GKE, "kind-kind"), accounts=("me@example.com",)):
+def _site(tmp_path, contexts=(GKE, "kind-kind"), accounts=("me@example.com",), account="me@example.com"):
k = FakeKubectl()
k.contexts = list(contexts)
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(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
@@ -35,12 +35,34 @@ 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'