diff --git a/.github/workflows/k8s-preview.yaml b/.github/workflows/k8s-preview.yaml new file mode 100644 index 00000000..915c0247 --- /dev/null +++ b/.github/workflows/k8s-preview.yaml @@ -0,0 +1,375 @@ +name: Deploy Preview +# See docs: docs/src/content/docs/pr-preview-workflow.md + +on: + pull_request: + types: [labeled, unlabeled, synchronize] + +# Only runs that change the preview share the PR's group: a push while +# deploy-preview is on, or a person adding or removing deploy-preview. A run +# in the group cancels the one in progress and starts only after that one, +# cleanup steps included, has finished. Every other event (extend-preview, +# unrelated labels, a push without the label) gets a group of its own, so it +# can neither cancel the preview nor replace a queued stop or redeploy (a +# group keeps one pending run). Label changes this workflow makes with +# GITHUB_TOKEN start no runs. +concurrency: + group: ${{ ((github.event.action == 'synchronize' && contains(github.event.pull_request.labels.*.name, 'deploy-preview')) || github.event.label.name == 'deploy-preview') && format('k8s-preview-{0}', github.event.pull_request.number) || format('k8s-preview-{0}-{1}', github.event.pull_request.number, github.run_id) }} + cancel-in-progress: true + +env: + PYTHONUNBUFFERED: "1" + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + PREVIEW_DOMAIN: ${{ vars.PREVIEW_DOMAIN }} + PREVIEW_HOSTNAME: pr-${{ github.event.pull_request.number }}-data-science-pack.${{ vars.PREVIEW_DOMAIN }} + KEYCLOAK_HOSTNAME: keycloak-pr-${{ github.event.pull_request.number }}-data-science-pack.${{ vars.PREVIEW_DOMAIN }} + CLOUDFLARED_VERSION: "2026.7.3" + CLOUDFLARED_SHA256: "9d71c677db00134c1bd4144b7783486b654ad281b1ea62b4972098d19f770f17" + +jobs: + deploy-preview: + # Fork PRs are skipped: workflow runs from forked repositories do not + # receive repository secrets. + if: >- + github.event.pull_request.head.repo.fork == false && + contains(github.event.pull_request.labels.*.name, 'deploy-preview') && + github.event.action != 'unlabeled' && + (github.event.action != 'labeled' || github.event.label.name == 'deploy-preview') + name: Deploy preview + runs-on: ubuntu-24.04 + timeout-minutes: 90 + permissions: + contents: read + pull-requests: write + issues: write + deployments: write + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Ensure the extend-preview label exists + run: gh label create extend-preview -R ${{ github.repository }} --color BFD4F2 --description "Push this preview's expiry back 20 minutes" --force + + # The run this one replaced removed the label in its cleanup; this run + # owns the preview now, so it puts the label back. + - name: Put the deploy-preview label back + run: gh api "repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/labels" -f "labels[]=deploy-preview" --silent + + - name: Render the deploying comment body + id: render_deploying + run: python -m scripts.preview.comment render-deploying --run-url "$RUN_URL" + + - name: Comment that the preview is deploying + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_deploying.outputs.body }} + + - name: Install kind + uses: helm/kind-action@06c1ae10762d3b9c1644e7fe69596ae519e015a2 # v1.15.0 + with: + version: v0.33.0 + install_only: true + + - name: Provision sandbox (kind + full NIC platform stack) + id: sandbox + uses: nebari-dev/action-nebari-sandbox@9ac369ebf87ac2ae217504dcbf824c77f70e429a # v3.0.0 + with: + cluster-name: pr-preview-${{ github.event.pull_request.number }} + resource-summary: "true" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0 + + - name: Build hub image from this PR + uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0 + with: + context: images/ + target: jupyterhub + tags: nebari-data-science-pack-jupyterhub:preview + load: true + cache-from: type=gha,scope=k8s-preview-jupyterhub + cache-to: type=gha,scope=k8s-preview-jupyterhub,mode=max + + - name: Side-load hub image into the sandbox cluster + run: kind load docker-image nebari-data-science-pack-jupyterhub:preview --name ${{ steps.sandbox.outputs.cluster-name }} + + - name: Fetch chart dependencies + run: | + helm repo add jupyterhub https://hub.jupyter.org/helm-chart/ + helm dependency build . + + - name: Create + label the preview namespace for the operator + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + kubectl create namespace pr-preview --dry-run=client -o yaml | kubectl apply -f - + kubectl label namespace pr-preview nebari.dev/managed=true --overwrite + + # The sandbox boots Keycloak on its stock local hostname; browser login needs the public one. + - name: Point Keycloak's own hostname at the public tunnel route + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + python -m scripts.preview.keycloak_gitops patch \ + --gitops-dir "$HOME/.nic/gitops/${{ steps.sandbox.outputs.cluster-name }}" \ + --kc-public-url "https://$KEYCLOAK_HOSTNAME" + + - name: Point the preview at this PR's own JupyterLab image build, if one exists + run: pipx run scripts/preview/pr_image.py set-tag --tag "pr-${{ github.event.pull_request.number }}" + + - name: Deploy chart + id: deploy + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + helm upgrade --install preview . -f values.preview.yaml \ + --namespace pr-preview --create-namespace \ + --set nebariapp.hostname="$PREVIEW_HOSTNAME" --set jupyterhub.custom.external-url="$PREVIEW_HOSTNAME" + + - name: Wait for operator to provision the Keycloak client secret + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + python -m scripts.preview.k8s_wait wait-for-secret-key \ + --namespace pr-preview --secret preview-nebari-data-science-pack-oidc-client \ + --key issuer-url --timeout-s 180 --poll-interval-s 5 + + - name: Restart hub until it picks up the operator secret + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + python -m scripts.preview.k8s_wait restart-until-ready \ + --namespace pr-preview --deployment hub --rollout-timeout-s 90 --max-attempts 5 + + - name: Wait for proxy + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: kubectl -n pr-preview rollout status deployment/proxy --timeout=180s + + - name: Port-forward JupyterHub proxy + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + kubectl -n pr-preview port-forward svc/proxy-public 8000:80 \ + > /tmp/port-forward.log 2>&1 & + echo "PORT_FORWARD_PID=$!" >> "$GITHUB_ENV" + sleep 3 + + - name: Port-forward Keycloak + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + kubectl -n keycloak port-forward svc/keycloak-keycloakx-http 8001:8080 \ + > /tmp/port-forward-keycloak.log 2>&1 & + echo "KEYCLOAK_PORT_FORWARD_PID=$!" >> "$GITHUB_ENV" + sleep 3 + + - name: Create a test login user in Keycloak + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + admin_password=$(kubectl -n keycloak get secret keycloak-admin-credentials -o jsonpath='{.data.admin-password}' | base64 -d) + echo "KC_ADMIN_PASSWORD=$admin_password" >> "$GITHUB_ENV" + KC_ADMIN_PASSWORD="$admin_password" python -m scripts.preview.keycloak create-reviewer-user \ + --base-url "http://localhost:8001" --realm nebari + + - name: Smoke-test jhub-apps service + if: always() + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + curl -sS -o /tmp/japps-root.html -w 'japps HTTP %{http_code}\n' http://localhost:8000/services/japps/ || true; head -c 2000 /tmp/japps-root.html || true + kubectl -n pr-preview exec deploy/hub -- ps aux | grep -i "uvicorn\|japps" || true + + - name: Install cloudflared + run: | + curl -fsSL -o /tmp/cloudflared \ + "https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/cloudflared-linux-amd64" + echo "${CLOUDFLARED_SHA256} /tmp/cloudflared" | sha256sum -c - + chmod +x /tmp/cloudflared + + - name: Create Cloudflare Tunnel for this PR + id: cf_tunnel + env: + CF_API_TOKEN: ${{ secrets.CLOUDFLARE_TUNNEL_API_TOKEN }} + CF_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_TUNNEL_ACCOUNT_ID }} + run: | + python -m scripts.preview.cloudflare create-tunnel \ + --account-id "$CF_ACCOUNT_ID" --api-token "$CF_API_TOKEN" --name "pr-${{ github.event.pull_request.number }}-${{ github.run_id }}" \ + --preview-hostname "$PREVIEW_HOSTNAME" --preview-service "http://localhost:8000" \ + --keycloak-hostname "$KEYCLOAK_HOSTNAME" --keycloak-service "http://localhost:8001" + + - name: Point DNS at the tunnel + id: cf_dns + env: + CF_API_TOKEN: ${{ secrets.CLOUDFLARE_TUNNEL_API_TOKEN }} + run: | + python -m scripts.preview.cloudflare create-dns \ + --api-token "$CF_API_TOKEN" --domain "$PREVIEW_DOMAIN" --target "${TUNNEL_ID}.cfargotunnel.com" \ + --preview-hostname "$PREVIEW_HOSTNAME" --keycloak-hostname "$KEYCLOAK_HOSTNAME" + + - name: Compute deployment timestamps + id: timestamps + run: | + echo "deployed_at=$(date -u +'%Y-%m-%d %H:%M UTC')" >> "$GITHUB_OUTPUT" + echo "expires_at=$(date -u -d '+20 minutes' +'%Y-%m-%d %H:%M UTC')" >> "$GITHUB_OUTPUT" + echo "deployed_at_iso=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_OUTPUT" + echo "expires_at_iso=$(date -u -d '+20 minutes' +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_OUTPUT" + + - name: Create GitHub deployment + run: | + id=$(gh api repos/${{ github.repository }}/deployments --jq .id --input - <<< '{"ref":"${{ github.event.pull_request.head.sha }}","environment":"pr-${{ github.event.pull_request.number }}-preview","task":"deploy:preview","description":"PR preview","auto_merge":false,"transient_environment":true,"production_environment":false,"required_contexts":[]}') + echo "DEPLOYMENT_ID=$id" >> "$GITHUB_ENV" + gh api repos/${{ github.repository }}/deployments/$id/statuses -f state=success -f description="Live for 20 minutes" \ + -f environment_url="${{ steps.cf_dns.outputs.url }}" -f log_url="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + - name: Render the ready-preview comment body + id: render_ready + run: | + python -m scripts.preview.comment render-ready \ + --url "${{ steps.cf_dns.outputs.url }}" --keycloak-url "${{ steps.cf_dns.outputs.keycloak_url }}" --run-url "$RUN_URL" \ + --deployed-at "${{ steps.timestamps.outputs.deployed_at }}" --deployed-at-iso "${{ steps.timestamps.outputs.deployed_at_iso }}" \ + --expires-at "${{ steps.timestamps.outputs.expires_at }}" --expires-at-iso "${{ steps.timestamps.outputs.expires_at_iso }}" + + - name: Comment preview link on PR + id: comment_preview + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_ready.outputs.body }} + + # tunnel.py takes over the port-forwards: it restarts one that exits after + # it was forwarding and fails this step if one exits before it forwarded. + - name: Run tunnel until it times out (extend via the extend-preview label) + id: tunnel + env: + KUBECONFIG: ${{ steps.sandbox.outputs.kubeconfig }} + run: | + kill "$PORT_FORWARD_PID" "$KEYCLOAK_PORT_FORWARD_PID" || true + for pid in "$PORT_FORWARD_PID" "$KEYCLOAK_PORT_FORWARD_PID"; do tail --pid="$pid" -f /dev/null; done + cat /tmp/port-forward.log /tmp/port-forward-keycloak.log + python -m scripts.preview.tunnel run \ + --cloudflared /tmp/cloudflared --token "${TUNNEL_TOKEN}" --repo "${{ github.repository }}" --pr "${{ github.event.pull_request.number }}" \ + --url "${{ steps.cf_dns.outputs.url }}" --keycloak-url "${{ steps.cf_dns.outputs.keycloak_url }}" --run-url "$RUN_URL" \ + --deployed-at "${{ steps.timestamps.outputs.deployed_at }}" --deployed-at-iso "${{ steps.timestamps.outputs.deployed_at_iso }}" \ + --port-forward pr-preview svc/proxy-public 8000:80 \ + --port-forward keycloak svc/keycloak-keycloakx-http 8001:8080 + + # The label means "a preview is deploying or live". Label present: this + # run owns the comment and label, including when a push or re-added + # label cancelled it (the newer run starts only after this one has + # finished, then puts the label back and takes the comment over). + # Label absent: a person removed it and the "Stop preview" job owns both. + - name: Check whether this run still owns the preview comment and label + id: owner + if: always() + run: | + labeled=$(gh api "repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/labels" --jq '[.[].name] | index("deploy-preview") != null') + echo "deploy-preview label present: $labeled" + echo "owner=$labeled" | tee -a "$GITHUB_OUTPUT" + + - name: Mark GitHub deployment inactive + if: always() && env.DEPLOYMENT_ID != '' + run: gh api repos/${{ github.repository }}/deployments/$DEPLOYMENT_ID/statuses -f state=inactive -f description="Preview expired" + + - name: Render the expired-preview comment body + id: render_expired + if: always() && steps.comment_preview.outcome == 'success' && steps.tunnel.outcome != 'failure' && steps.owner.outputs.owner == 'true' + run: | + python -m scripts.preview.comment render-expired \ + --expires-at "${{ steps.timestamps.outputs.expires_at }}" \ + --expires-at-iso "${{ steps.timestamps.outputs.expires_at_iso }}" + + - name: Comment that the preview expired + if: always() && steps.comment_preview.outcome == 'success' && steps.tunnel.outcome != 'failure' && steps.owner.outputs.owner == 'true' + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_expired.outputs.body }} + + - name: Render the failed-preview comment body + id: render_failed + if: failure() && (steps.comment_preview.outcome != 'success' || steps.tunnel.outcome == 'failure') && steps.owner.outputs.owner == 'true' + run: python -m scripts.preview.comment render-failed --run-url "$RUN_URL" + + - name: Comment that the preview failed + if: failure() && (steps.comment_preview.outcome != 'success' || steps.tunnel.outcome == 'failure') && steps.owner.outputs.owner == 'true' + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_failed.outputs.body }} + + - name: Render the cancelled-preview comment body + id: render_cancelled + if: cancelled() && steps.comment_preview.outcome != 'success' && steps.owner.outputs.owner == 'true' + run: python -m scripts.preview.comment render-cancelled --run-url "$RUN_URL" + + - name: Comment that the preview was cancelled + if: cancelled() && steps.comment_preview.outcome != 'success' && steps.owner.outputs.owner == 'true' + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_cancelled.outputs.body }} + + - name: Delete DNS record + if: always() + env: + CF_API_TOKEN: ${{ secrets.CLOUDFLARE_TUNNEL_API_TOKEN }} + run: | + python -m scripts.preview.cloudflare delete-dns \ + --api-token "$CF_API_TOKEN" --zone-id "${ZONE_ID:-}" \ + --record-id "${DNS_RECORD_ID:-}" --record-id "${KEYCLOAK_DNS_RECORD_ID:-}" + + - name: Delete Cloudflare Tunnel + if: always() + env: + CF_API_TOKEN: ${{ secrets.CLOUDFLARE_TUNNEL_API_TOKEN }} + CF_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_TUNNEL_ACCOUNT_ID }} + run: | + python -m scripts.preview.cloudflare delete-tunnel \ + --account-id "$CF_ACCOUNT_ID" --api-token "$CF_API_TOKEN" --tunnel-id "${TUNNEL_ID:-}" + + - name: Remove the deploy-preview label now the preview is gone + if: always() && steps.owner.outputs.owner == 'true' + run: gh api -X DELETE "repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/labels/deploy-preview" || true + + cleanup-preview: + if: github.event.pull_request.head.repo.fork == false && github.event.action == 'unlabeled' && github.event.label.name == 'deploy-preview' && github.event.sender.login != 'github-actions[bot]' + name: Stop preview + runs-on: ubuntu-latest + permissions: + pull-requests: write + actions: write + deployments: write + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Cancel the in-flight preview run for this PR + run: | + gh api "repos/${{ github.repository }}/actions/runs?event=pull_request&status=in_progress" \ + --jq '.workflow_runs[] | select(.name == "Deploy Preview" and any(.pull_requests[]; .number == ${{ github.event.pull_request.number }})) | .id' \ + | xargs -r -I{} gh api -X POST repos/${{ github.repository }}/actions/runs/{}/cancel + + - name: Mark GitHub deployment inactive + run: | + id=$(gh api "repos/${{ github.repository }}/deployments?environment=pr-${{ github.event.pull_request.number }}-preview&per_page=1" --jq '.[0].id // empty') + [ -z "$id" ] || gh api repos/${{ github.repository }}/deployments/$id/statuses -f state=inactive -f description="Preview stopped (label removed)" + + - name: Render the stopped-preview comment body + id: render_stopped + run: python -m scripts.preview.comment render-stopped + + - name: Comment that the preview stopped + uses: marocchino/sticky-pull-request-comment@5770ad5eb8f42dd2c4f34da00c94c5381e49af88 # v3.0.5 + with: + header: k8s-preview + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + message: ${{ steps.render_stopped.outputs.body }} diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index fcc1eada..5b3ed302 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -57,6 +57,10 @@ export default defineConfig({ { label: 'NebariApp Integration', slug: 'nebariapp-integration' }, ], }, + { + label: 'Development', + items: [{ label: 'PR Preview Environments', slug: 'pr-preview-workflow' }], + }, ], }), ], diff --git a/docs/src/content/docs/pr-preview-workflow.md b/docs/src/content/docs/pr-preview-workflow.md new file mode 100644 index 00000000..99b27d8e --- /dev/null +++ b/docs/src/content/docs/pr-preview-workflow.md @@ -0,0 +1,173 @@ +--- +title: PR Preview Environments +description: How the k8s-preview CI workflow deploys and exposes an ephemeral per-PR environment. +--- + +The `k8s-preview` GitHub Actions workflow +(`.github/workflows/k8s-preview.yaml`) deploys this PR's chart into an +ephemeral kind cluster running the full Nebari platform stack (Keycloak + +Nebari Operator + Envoy Gateway, via `nebari-dev/action-nebari-sandbox`), +then exposes it through a per-PR Cloudflare Tunnel behind Cloudflare Access +(GitHub SSO). + +## How it works + +```mermaid +flowchart TB + Label(["deploy-preview label added"]) --> Runner + subgraph Runner["GitHub Actions runner"] + Build["Build hub image\nfrom this PR"] --> Kind["kind cluster +\nKeycloak, Operator, Envoy Gateway"] + Kind --> Deploy["helm install\nthis PR's chart"] + Deploy --> PF["port-forward hub + Keycloak\nto runner localhost"] + PF --> Tunnel["cloudflared tunnel"] + end + Tunnel --> DNS["Cloudflare DNS record\npr-<n>-....<domain>"] + DNS --> Access["Cloudflare Access\n(GitHub SSO gate)"] + Runner -. posts .-> Comment["PR comment +\nGitHub Deployment"] + Reviewer(["Reviewer's browser"]) -->|opens the link| Access --> Tunnel +``` + +1. Labeling the PR `deploy-preview` starts the `deploy-preview` job. +2. It builds the hub image from this PR and boots a kind cluster running + Keycloak, the Nebari Operator, and Envoy Gateway + (`nebari-dev/action-nebari-sandbox`), then side-loads the built image + into it. +3. It points the chart's JupyterLab image at this PR's own build (see + "JupyterLab image" below), then installs the chart with + `helm upgrade --install`, patches Keycloak's own hostname to match the + public route, and waits for the Operator to finish provisioning the + OIDC client. +4. It port-forwards the hub and Keycloak services from the cluster to the + runner's `localhost`, starts a `cloudflared` tunnel mapping the public + preview hostnames to those local ports, and points a Cloudflare DNS + record at the tunnel. The tunnel step shows kubectl's output in its + log, restarts a port-forward that exits after it was forwarding (lost + connection to the pod), and fails the run if one exits before it ever + forwarded (kubectl's error says why). +5. It posts the preview URL as a GitHub Deployment and a PR comment. +6. A reviewer opening the link authenticates through Cloudflare Access + (GitHub SSO) before any request reaches the tunnel. Past Access, traffic + flows tunnel -> runner port-forward -> cluster service -> pod, and the + hub runs its own OAuth flow against Keycloak so it knows who signed in. +7. After 20 minutes (or on `extend-preview`/label removal), the tunnel + closes, the DNS record and tunnel are deleted, and the runner (with its + kind cluster) is torn down when the job ends. + +## Triggering it + +Add the `deploy-preview` label to a PR. That label gates who can trigger a +deploy (GitHub label permissions). Fork PRs are skipped: workflow runs +from forked repositories do not receive repository secrets. Removing the +label runs the `cleanup-preview` job, which cancels any in-flight deploy +for that PR, marks the GitHub deployment inactive, and posts a "stopped" +comment. +Pushing a new commit while the label is on cancels the in-flight deploy +and starts a fresh one. The fresh run starts only after the cancelled +run's cleanup (which updates the comment and drops the label) has +finished; it then puts the label back and takes the comment over. A +deploy cancelled any other way posts a "cancelled" comment and drops the +label. + +Whether a finishing run updates the comment and drops the label depends +only on the label: present means the run still owns the preview, absent +means a person removed it and the `cleanup-preview` job owns it. + +## Lifetime and the `extend-preview` label + +A preview is live for 20 minutes by default (the tunnel step's own +timeout, kept under the job's 90-minute timeout so it self-ends cleanly +instead of GitHub reporting a false "cancelled" run). Adding the +`extend-preview` label resets the deadline to 20 minutes from that moment; +it can be added any number of times, but each add is a reset, not an +addition on top of what's left. The label is polled from inside the running +tunnel step (`scripts/preview/tunnel.py`), not by the workflow run the +label event starts. Only a push while `deploy-preview` is on, or a person +adding or removing `deploy-preview`, shares the PR's concurrency group. +Every other event gets a group of its own, so it can neither cancel the +live preview nor replace a queued stop or redeploy (a group keeps one +pending run). Label changes the workflow makes itself start no runs. + +## Hostnames and TLS + +Preview hostnames stay single-level +(`pr--data-science-pack.`): the free Cloudflare Universal +SSL certificate on the preview zone only covers the zone itself plus one +wildcard level. + +## Authentication + +`nebariapp.enabled=true` routes login through a real Operator-provisioned +Keycloak client, the same auth path production deployments use. The preview +Keycloak is a fresh realm with no users and no link to any external identity +provider, so the workflow seeds one account, `reviewer` / `admin`, for the +hub login. Cloudflare Access (GitHub sign-in) in front of the tunnel is the +actual security boundary, so a simple known password for that account is +acceptable. + +## JupyterLab image + +The hub image is built and side-loaded locally by this workflow, but the +JupyterLab image users actually spawn is built separately by +`build-images.yaml` (multi-arch, pushed to ghcr.io/quay.io on the same PR +trigger). `scripts/preview/pr_image.py` rewrites `values.yaml`'s +singleuser and per-profile image refs, in the ephemeral checkout only, to +that PR's `pr-` tag before the chart deploys. If no such tag exists +on the registry, `values.yaml` is left as is and the preview runs the +pinned image. + +The two builds aren't ordered against each other. A pod only pulls the +image when a reviewer actually spawns a server, by which point +`build-images.yaml` has usually finished; if not, kubelet retries the pull +automatically once the tag exists; no action is needed either way. + +## Tunnel and GitHub visibility + +- **Named Tunnel**: each PR gets its own named Cloudflare Tunnel sitting + behind Access, rather than an anonymous quick tunnel. +- **GitHub Deployment**: a Vercel-style deployment box is created via the + GitHub Deployments API, separate from the sticky PR comment (which + doesn't move once posted). `required_contexts: []` keeps this preview + link from gating on unrelated checks like lint or test. +- **Comment timestamps**: rendered with GitHub's `` web + component, so "Expires in 12 minutes" keeps ticking client-side with no + manual timezone math or re-editing needed. +- **On expiry**: the deployment is marked inactive and, if a "ready" + comment was posted, it's re-rendered to the expired state. +- **On failure**: if the deploy dies before a "ready" comment exists, or + the tunnel step fails after it (cloudflared exits, or a port-forward + cannot be restarted), the comment is re-rendered to a failed state linking + the run. + +## One-time Cloudflare setup + +Configured once in the Cloudflare Zero Trust dashboard for this repository: + +- Repository variable `PREVIEW_DOMAIN`: the zone name (e.g. + `openteams.app`). +- A Cloudflare Access application for `*.`, GitHub as the + identity provider, and a policy scoped to this org. +- Secret `CLOUDFLARE_TUNNEL_ACCOUNT_ID`: that Cloudflare account's ID. +- Secret `CLOUDFLARE_TUNNEL_API_TOKEN`: `Tunnel:Edit` + `Zone:Read` + + `DNS:Edit`, scoped to the `PREVIEW_DOMAIN` zone/account only. This is + separate from `CLOUDFLARE_API_TOKEN`, which belongs to the Pages account + used by `docs.yml`. + +## Security model + +- **Public exposure is gated before it reaches the cluster**: Cloudflare + Access sits in front of the tunnel and requires a GitHub SSO login plus + an org policy match before any request reaches `cloudflared`. Nothing in + the preview cluster is reachable without passing that gate. +- **kind shares the runner's Docker daemon**: a container escaping its pod + gets host-level Docker access on that ephemeral runner only, not on any + shared or production infrastructure, and the runner is destroyed with + the job. +- **Fork PRs are skipped**: workflow runs from forked repositories do not + receive repository secrets. +- **Token scope**: `GITHUB_TOKEN` is limited to `contents:read`, + `pull-requests:write`, `issues:write`, `deployments:write` for this job. + The Cloudflare API token can only edit Tunnels and DNS and read the zone, + scoped to the single `PREVIEW_DOMAIN` zone, not account-wide. +- **Nothing outlives the run**: the tunnel, its DNS record, the Keycloak + reviewer account, and the kind cluster all exist only for the job's + lifetime, or until the preview expires or is stopped early. diff --git a/scripts/preview/cloudflare.py b/scripts/preview/cloudflare.py new file mode 100644 index 00000000..83142451 --- /dev/null +++ b/scripts/preview/cloudflare.py @@ -0,0 +1,234 @@ +"""Cloudflare Tunnel + DNS API calls for the k8s preview environment. + +One per-PR named Tunnel (not the anonymous quick-tunnel) so it can sit +behind a Cloudflare Access application and each PR gets its own hostname. + +Usage (each subcommand mirrors one k8s-preview.yaml workflow step): + python -m scripts.preview.cloudflare create-tunnel --account-id ID \\ + --api-token TOKEN --name NAME \\ + --preview-hostname HOST --preview-service URL \\ + --keycloak-hostname HOST --keycloak-service URL + python -m scripts.preview.cloudflare create-dns --api-token TOKEN \\ + --domain DOMAIN --preview-hostname HOST --keycloak-hostname HOST \\ + --target TUNNEL_ID.cfargotunnel.com + python -m scripts.preview.cloudflare delete-dns --api-token TOKEN \\ + --zone-id ID --record-id ID [--record-id ID ...] + python -m scripts.preview.cloudflare delete-tunnel --account-id ID \\ + --api-token TOKEN --tunnel-id ID +""" + +from __future__ import annotations + +import argparse +import base64 +import secrets +import sys + +from . import gha +from .http import HTTPRequestError, request_json + +API_ROOT = "https://api.cloudflare.com/client/v4" + + +class TunnelCreationError(RuntimeError): + pass + + +class ZoneNotFoundError(RuntimeError): + pass + + +def _headers(api_token: str) -> dict[str, str]: + return {"Authorization": f"Bearer {api_token}"} + + +def create_or_reuse_tunnel(account_id: str, api_token: str, tunnel_name: str) -> str: + """Create a named Tunnel, or reuse one already created under this name. + + A GitHub Actions retry reuses the same run id (only run_attempt changes), + so a re-run after an attempt that already created this tunnel (and didn't + get to clean it up) hits a name conflict. Reuse the existing tunnel by + name instead of failing -- it doesn't need the original tunnel secret, + just a fresh token from ``get_tunnel_token``. + """ + tunnel_secret = base64.b64encode(secrets.token_bytes(32)).decode() + try: + result = request_json( + "POST", + f"{API_ROOT}/accounts/{account_id}/cfd_tunnel", + headers=_headers(api_token), + body={"name": tunnel_name, "config_src": "cloudflare", "tunnel_secret": tunnel_secret}, + ) + return result["result"]["id"] + except HTTPRequestError: + existing = request_json( + "GET", + f"{API_ROOT}/accounts/{account_id}/cfd_tunnel?name={tunnel_name}&is_deleted=false", + headers=_headers(api_token), + ) + matches = existing.get("result") or [] + if not matches: + raise TunnelCreationError( + f"tunnel creation failed and no existing tunnel named {tunnel_name!r} was found" + ) from None + return matches[0]["id"] + + +def get_tunnel_token(account_id: str, api_token: str, tunnel_id: str) -> str: + result = request_json( + "GET", + f"{API_ROOT}/accounts/{account_id}/cfd_tunnel/{tunnel_id}/token", + headers=_headers(api_token), + ) + return result["result"] + + +def configure_ingress( + account_id: str, api_token: str, tunnel_id: str, hostname_services: list[tuple[str, str]] +) -> None: + """Point each (hostname, service-url) pair at the tunnel, 404 for everything else.""" + ingress = [{"hostname": host, "service": service} for host, service in hostname_services] + ingress.append({"service": "http_status:404"}) + request_json( + "PUT", + f"{API_ROOT}/accounts/{account_id}/cfd_tunnel/{tunnel_id}/configurations", + headers=_headers(api_token), + body={"config": {"ingress": ingress}}, + ) + + +def delete_tunnel(account_id: str, api_token: str, tunnel_id: str) -> None: + # cascade: drop lingering connections from the just-terminated cloudflared, else the delete is refused. + request_json( + "DELETE", + f"{API_ROOT}/accounts/{account_id}/cfd_tunnel/{tunnel_id}?cascade=true", + headers=_headers(api_token), + ) + + +def resolve_zone_id(api_token: str, domain: str) -> str: + result = request_json("GET", f"{API_ROOT}/zones?name={domain}", headers=_headers(api_token)) + matches = result.get("result") or [] + if not matches: + raise ZoneNotFoundError(f"could not resolve a zone id for {domain!r}") + return matches[0]["id"] + + +def create_dns_record(api_token: str, zone_id: str, hostname: str, target: str) -> str: + result = request_json( + "POST", + f"{API_ROOT}/zones/{zone_id}/dns_records", + headers=_headers(api_token), + body={"type": "CNAME", "name": hostname, "content": target, "proxied": True}, + ) + return result["result"]["id"] + + +def delete_dns_record(api_token: str, zone_id: str, record_id: str) -> None: + request_json( + "DELETE", + f"{API_ROOT}/zones/{zone_id}/dns_records/{record_id}", + headers=_headers(api_token), + ) + + +def _cmd_create_tunnel(args: argparse.Namespace) -> int: + try: + tunnel_id = create_or_reuse_tunnel(args.account_id, args.api_token, args.name) + token = get_tunnel_token(args.account_id, args.api_token, tunnel_id) + configure_ingress( + args.account_id, args.api_token, tunnel_id, + [(args.preview_hostname, args.preview_service), (args.keycloak_hostname, args.keycloak_service)], + ) + except (TunnelCreationError, HTTPRequestError) as exc: + gha.error(f"Cloudflare Tunnel setup failed: {exc}") + return 1 + gha.mask(token) + gha.write_env("TUNNEL_ID", tunnel_id) + gha.write_env("TUNNEL_TOKEN", token) + return 0 + + +def _cmd_create_dns(args: argparse.Namespace) -> int: + try: + zone_id = resolve_zone_id(args.api_token, args.domain) + record_id = create_dns_record(args.api_token, zone_id, args.preview_hostname, args.target) + keycloak_record_id = create_dns_record(args.api_token, zone_id, args.keycloak_hostname, args.target) + except (ZoneNotFoundError, HTTPRequestError) as exc: + gha.error(f"DNS record creation failed: {exc}") + return 1 + gha.write_env("ZONE_ID", zone_id) + gha.write_env("DNS_RECORD_ID", record_id) + gha.write_env("KEYCLOAK_DNS_RECORD_ID", keycloak_record_id) + gha.write_output("url", f"https://{args.preview_hostname}") + gha.write_output("keycloak_url", f"https://{args.keycloak_hostname}") + return 0 + + +def _cmd_delete_dns(args: argparse.Namespace) -> int: + """Best-effort: cleanup steps must never fail the job.""" + if not args.zone_id: + return 0 + for record_id in args.record_id: + if not record_id: + continue + try: + delete_dns_record(args.api_token, args.zone_id, record_id) + print(f"deleted DNS record {record_id}") + except HTTPRequestError as exc: + print(f"::warning::DNS record {record_id} not deleted: {exc}") + return 0 + + +def _cmd_delete_tunnel(args: argparse.Namespace) -> int: + """Best-effort: cleanup steps must never fail the job.""" + if not args.tunnel_id: + return 0 + try: + delete_tunnel(args.account_id, args.api_token, args.tunnel_id) + print(f"deleted tunnel {args.tunnel_id}") + except HTTPRequestError as exc: + print(f"::warning::tunnel {args.tunnel_id} not deleted: {exc}") + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="cloudflare") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("create-tunnel") + p.add_argument("--account-id", required=True) + p.add_argument("--api-token", required=True) + p.add_argument("--name", required=True) + p.add_argument("--preview-hostname", required=True) + p.add_argument("--preview-service", required=True) + p.add_argument("--keycloak-hostname", required=True) + p.add_argument("--keycloak-service", required=True) + p.set_defaults(func=_cmd_create_tunnel) + + p = sub.add_parser("create-dns") + p.add_argument("--api-token", required=True) + p.add_argument("--domain", required=True) + p.add_argument("--preview-hostname", required=True) + p.add_argument("--keycloak-hostname", required=True) + p.add_argument("--target", required=True) + p.set_defaults(func=_cmd_create_dns) + + p = sub.add_parser("delete-dns") + p.add_argument("--api-token", required=True) + p.add_argument("--zone-id", required=True) + p.add_argument("--record-id", action="append", default=[]) + p.set_defaults(func=_cmd_delete_dns) + + p = sub.add_parser("delete-tunnel") + p.add_argument("--account-id", required=True) + p.add_argument("--api-token", required=True) + p.add_argument("--tunnel-id", required=True) + p.set_defaults(func=_cmd_delete_tunnel) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/comment.py b/scripts/preview/comment.py new file mode 100644 index 00000000..730065e8 --- /dev/null +++ b/scripts/preview/comment.py @@ -0,0 +1,190 @@ +"""PR-comment body builders for the k8s preview environment. + +Pure string-building functions -- the actual find-or-edit-in-place +mechanics stay in marocchino/sticky-pull-request-comment (an already-vetted +action doing exactly what it's for); only the message *content* lives here. +Uses GitHub's own web component (used all over its UI for +"3 minutes ago") instead of a static UTC string the reader has to convert +by hand -- confirmed via `gh api /markdown` to survive comment sanitization +unstripped. + +Usage: + python -m scripts.preview.comment render-deploying --run-url URL + KC_ADMIN_PASSWORD=... python -m scripts.preview.comment render-ready --url URL \\ + --keycloak-url URL --run-url URL \\ + --deployed-at STR --deployed-at-iso ISO \\ + --expires-at STR --expires-at-iso ISO + python -m scripts.preview.comment render-expired \\ + --expires-at STR --expires-at-iso ISO + python -m scripts.preview.comment render-failed --run-url URL + python -m scripts.preview.comment render-stopped + +render-ready takes the Keycloak admin password from KC_ADMIN_PASSWORD (see +keycloak.admin_password_from_env for why it is not an argv flag). +""" + +from __future__ import annotations + +import argparse +import sys +import time + +from . import gha +from .keycloak import admin_password_from_env + +PROJECT = "nebari-data-science-pack" + + +def _now_relative_time() -> str: + now = time.gmtime() + human = time.strftime("%Y-%m-%d %H:%M UTC", now) + iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", now) + return f'{human}' + + +def render_deploying(run_url: str) -> str: + return ( + "The latest preview for this PR.\n\n" + "| Project | Deployment | Actions | Updated |\n" + "| --- | --- | --- | --- |\n" + f"| `{PROJECT}` | 🟡 [Deploying]({run_url}) | [CI run]({run_url}) | {_now_relative_time()} |\n\n" + "Should be ready in a few minutes." + ) + + +def render_failed(run_url: str) -> str: + return ( + "The preview for this PR failed.\n\n" + "| Project | Deployment | Actions | Updated |\n" + "| --- | --- | --- | --- |\n" + f"| `{PROJECT}` | 🔴 [Failed]({run_url}) | [CI run]({run_url}) | {_now_relative_time()} |\n\n" + "Re-add the `deploy-preview` label to retry." + ) + + +def render_cancelled(run_url: str) -> str: + return ( + "The preview for this PR was cancelled.\n\n" + "| Project | Deployment | Actions | Updated |\n" + "| --- | --- | --- | --- |\n" + f"| `{PROJECT}` | ⚫ [Cancelled]({run_url}) | [CI run]({run_url}) | {_now_relative_time()} |\n\n" + "Re-add the `deploy-preview` label to redeploy." + ) + + +def render_ready( + url: str, + keycloak_url: str, + run_url: str, + kc_admin_password: str, + deployed_at: str, + deployed_at_iso: str, + expires_at: str, + expires_at_iso: str, +) -> str: + return ( + "The latest preview for this PR.\n\n" + "| Project | Deployment | Actions | Updated |\n" + "| --- | --- | --- | --- |\n" + f"| `{PROJECT}` | 🟢 [Ready]({url}) | [Preview]({url}) · [Keycloak]({keycloak_url}) · [CI run]({run_url}) | " + f'{deployed_at} |\n\n' + f"Sign in with `reviewer` / `admin`. Keycloak admin: `admin` / `{kc_admin_password}`.\n\n" + f'Expires {expires_at}. ' + "Add the `extend-preview` label any time before then to reset it to 20 minutes from that moment, " + "or push a new commit or re-add `deploy-preview` to redeploy from scratch." + ) + + +def render_expired(expires_at: str, expires_at_iso: str) -> str: + return ( + "The preview for this PR has expired.\n\n" + "| Project | Deployment | Actions | Updated |\n" + "| --- | --- | --- | --- |\n" + f"| `{PROJECT}` | ⚫ Expired | - | " + f'{expires_at} |\n\n' + "Re-add the `deploy-preview` label to redeploy." + ) + + +def render_stopped() -> str: + return ( + "**Preview** stopped: the `deploy-preview` label was removed.\n\n" + "Add it again to redeploy." + ) + + +def _cmd_render_deploying(args: argparse.Namespace) -> int: + gha.write_output("body", render_deploying(args.run_url)) + return 0 + + +def _cmd_render_ready(args: argparse.Namespace) -> int: + body = render_ready( + args.url, args.keycloak_url, args.run_url, admin_password_from_env(), + args.deployed_at, args.deployed_at_iso, + args.expires_at, args.expires_at_iso, + ) + gha.write_output("body", body) + return 0 + + +def _cmd_render_expired(args: argparse.Namespace) -> int: + gha.write_output("body", render_expired(args.expires_at, args.expires_at_iso)) + return 0 + + +def _cmd_render_failed(args: argparse.Namespace) -> int: + gha.write_output("body", render_failed(args.run_url)) + return 0 + + +def _cmd_render_cancelled(args: argparse.Namespace) -> int: + gha.write_output("body", render_cancelled(args.run_url)) + return 0 + + +def _cmd_render_stopped(args: argparse.Namespace) -> int: + gha.write_output("body", render_stopped()) + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="comment") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("render-deploying") + p.add_argument("--run-url", required=True) + p.set_defaults(func=_cmd_render_deploying) + + p = sub.add_parser("render-ready") + p.add_argument("--url", required=True) + p.add_argument("--keycloak-url", required=True) + p.add_argument("--run-url", required=True) + p.add_argument("--deployed-at", required=True) + p.add_argument("--deployed-at-iso", required=True) + p.add_argument("--expires-at", required=True) + p.add_argument("--expires-at-iso", required=True) + p.set_defaults(func=_cmd_render_ready) + + p = sub.add_parser("render-expired") + p.add_argument("--expires-at", required=True) + p.add_argument("--expires-at-iso", required=True) + p.set_defaults(func=_cmd_render_expired) + + p = sub.add_parser("render-failed") + p.add_argument("--run-url", required=True) + p.set_defaults(func=_cmd_render_failed) + + p = sub.add_parser("render-cancelled") + p.add_argument("--run-url", required=True) + p.set_defaults(func=_cmd_render_cancelled) + + p = sub.add_parser("render-stopped") + p.set_defaults(func=_cmd_render_stopped) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/gha.py b/scripts/preview/gha.py new file mode 100644 index 00000000..72292672 --- /dev/null +++ b/scripts/preview/gha.py @@ -0,0 +1,32 @@ +"""GitHub Actions step outputs, env vars, log masks and error annotations.""" + +from __future__ import annotations + +import os +import uuid + + +def _write_kv(path: str, name: str, value: str) -> None: + if "\n" in value: + delimiter = f"ghadelim_{uuid.uuid4().hex}" + block = f"{name}<<{delimiter}\n{value}\n{delimiter}\n" + else: + block = f"{name}={value}\n" + with open(path, "a", encoding="utf-8") as f: + f.write(block) + + +def write_output(name: str, value: str) -> None: + _write_kv(os.environ["GITHUB_OUTPUT"], name, value) + + +def write_env(name: str, value: str) -> None: + _write_kv(os.environ["GITHUB_ENV"], name, value) + + +def mask(value: str) -> None: + print(f"::add-mask::{value}") + + +def error(message: str) -> None: + print(f"::error::{message}") diff --git a/scripts/preview/http.py b/scripts/preview/http.py new file mode 100644 index 00000000..23aa05fd --- /dev/null +++ b/scripts/preview/http.py @@ -0,0 +1,58 @@ +"""Shared JSON HTTP helper for scripts/preview/*.py. + +Thin wrapper over ``urllib.request`` (stdlib, no new dependency -- matches +config/jupyterhub/01-spawner.py's existing convention for this same kind of +Keycloak/GitHub/Cloudflare-style REST call). Raises HTTPRequestError with the +response body on a non-2xx status, so callers get an actual error message +instead of urllib's bare HTTPError. +""" + +from __future__ import annotations + +import json +import urllib.error +import urllib.request +from typing import Any + + +class HTTPRequestError(RuntimeError): + """Raised when a JSON HTTP request returns a non-2xx status.""" + + def __init__(self, method: str, url: str, status: int, body: str): + self.status = status + self.body = body + super().__init__(f"{method} {url} -> HTTP {status}: {body}") + + +def request_json( + method: str, + url: str, + headers: dict[str, str] | None = None, + body: Any = None, + timeout: float = 15, +) -> Any: + """Send an HTTP request, returning the parsed JSON response body. + + ``body``, if a ``str``, is sent as-is (the caller sets its own + Content-Type, e.g. for a form-urlencoded Keycloak token request); any + other value is JSON-encoded with an application/json Content-Type. + Returns ``{}`` for an empty (e.g. 204) response body. + """ + data = None + req_headers = dict(headers or {}) + if isinstance(body, str): + data = body.encode("utf-8") + elif body is not None: + data = json.dumps(body).encode("utf-8") + req_headers.setdefault("Content-Type", "application/json") + + request = urllib.request.Request(url, data=data, headers=req_headers, method=method) + try: + with urllib.request.urlopen(request, timeout=timeout) as resp: + raw = resp.read() + except urllib.error.HTTPError as exc: + raise HTTPRequestError(method, url, exc.code, exc.read().decode("utf-8", errors="replace")) from exc + + if not raw: + return {} + return json.loads(raw) diff --git a/scripts/preview/k8s_wait.py b/scripts/preview/k8s_wait.py new file mode 100644 index 00000000..bbb0b2ad --- /dev/null +++ b/scripts/preview/k8s_wait.py @@ -0,0 +1,130 @@ +"""kubectl readiness retry loops for the k8s preview environment. + +Usage: + python -m scripts.preview.k8s_wait wait-for-secret-key --namespace NS \\ + --secret NAME --key KEY [--timeout-s 180] [--poll-interval-s 5] + python -m scripts.preview.k8s_wait restart-until-ready --namespace NS \\ + --deployment NAME [--rollout-timeout-s 90] [--max-attempts 5] +""" + +from __future__ import annotations + +import argparse +import subprocess +import sys +import time +from collections.abc import Callable + +from . import gha + + +def wait_for_secret_key( + get_value: Callable[[], str], + timeout_s: int = 180, + poll_interval_s: int = 5, +) -> bool: + """Poll ``get_value()`` until it returns a non-empty string, or timeout. + + The operator creates the Secret with client-id/client-secret on its + first reconcile pass, then patches in the issuer-url key on a later + pass -- checking the Secret merely EXISTS isn't enough, a hub restart + right after its first appearance still crashes on the not-yet-populated + key. + """ + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + if get_value(): + return True + time.sleep(poll_interval_s) + return False + + +def restart_until_ready( + restart: Callable[[], None], + check_status: Callable[[], bool], + max_attempts: int = 5, +) -> tuple[bool, int]: + """Restart, then check readiness; repeat until ready or ``max_attempts``. + + A single restart isn't reliable here even when the API server confirms + the Secret is fully populated: kubelet's own Secret volume cache + (node-local, ~1min TTL) can still hand a freshly-restarted pod the + pre-population snapshot it fetched for the pod's first, crash-looped + attempt. Retrying gives the kubelet cache time to expire between + attempts. + + Returns (became_ready, attempts_used). + """ + for attempt in range(1, max_attempts + 1): + restart() + if check_status(): + return True, attempt + return False, max_attempts + + +def _cmd_wait_for_secret_key(args: argparse.Namespace) -> int: + def get_value() -> str: + result = subprocess.run( + ["kubectl", "-n", args.namespace, "get", "secret", args.secret, + "-o", f"jsonpath={{.data.{args.key}}}"], + text=True, capture_output=True, check=False, + ) + return result.stdout.strip() if result.returncode == 0 else "" + + ok = wait_for_secret_key(get_value, timeout_s=args.timeout_s, poll_interval_s=args.poll_interval_s) + if not ok: + gha.error( + f"operator never populated {args.key!r} on secret {args.secret!r} " + f"within {args.timeout_s}s" + ) + subprocess.run(["kubectl", "-n", args.namespace, "get", "nebariapp", "-o", "yaml"], check=False) + return 1 + return 0 + + +def _cmd_restart_until_ready(args: argparse.Namespace) -> int: + target = f"deployment/{args.deployment}" + + def restart() -> None: + subprocess.run(["kubectl", "-n", args.namespace, "rollout", "restart", target], check=False) + + def check_status() -> bool: + result = subprocess.run([ + "kubectl", "-n", args.namespace, "rollout", "status", target, + f"--timeout={args.rollout_timeout_s}s", + ], check=False) + return result.returncode == 0 + + ok, attempts = restart_until_ready(restart, check_status, max_attempts=args.max_attempts) + if ok: + print(f"{args.deployment} ready on attempt {attempts}") + return 0 + gha.error(f"{args.deployment} never became ready after {args.max_attempts} restart attempts") + return 1 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="k8s_wait") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("wait-for-secret-key") + p.add_argument("--namespace", required=True) + p.add_argument("--secret", required=True) + p.add_argument("--key", required=True) + p.add_argument("--timeout-s", type=int, default=180) + p.add_argument("--poll-interval-s", type=int, default=5) + p.set_defaults(func=_cmd_wait_for_secret_key) + + p = sub.add_parser("restart-until-ready") + p.add_argument("--namespace", required=True) + p.add_argument("--deployment", required=True) + p.add_argument("--rollout-timeout-s", type=int, default=90) + p.add_argument("--max-attempts", type=int, default=5) + p.set_defaults(func=_cmd_restart_until_ready) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/keycloak.py b/scripts/preview/keycloak.py new file mode 100644 index 00000000..9cc39322 --- /dev/null +++ b/scripts/preview/keycloak.py @@ -0,0 +1,102 @@ +"""Keycloak admin API calls for the k8s preview environment's test user. + +Cloudflare Access is the real security boundary for this preview (only +allow-listed accounts reach the tunnel at all), so a simple, known password +for the Keycloak-side login is fine -- reviewers don't need to hunt for real +credentials on a throwaway cluster. + +The master-realm admin password is read from the KC_ADMIN_PASSWORD +environment variable, never argv: NIC generates it as URL-safe base64, so it +can start with '-', which argparse would take for a flag. + +Usage: + KC_ADMIN_PASSWORD=... python -m scripts.preview.keycloak create-reviewer-user \\ + --base-url URL --realm REALM +""" + +from __future__ import annotations + +import argparse +import os +import sys +from urllib.parse import urlencode + +from . import gha +from .http import request_json + + +class KeycloakAuthError(RuntimeError): + pass + + +def admin_password_from_env() -> str: + """Master-realm admin password from KC_ADMIN_PASSWORD; fails loudly if unset or empty.""" + value = os.environ.get("KC_ADMIN_PASSWORD", "") + if not value: + raise KeycloakAuthError("KC_ADMIN_PASSWORD is unset or empty") + return value + + +def get_admin_token(base_url: str, admin_password: str) -> str: + body = urlencode( + { + "grant_type": "password", + "client_id": "admin-cli", + "username": "admin", + "password": admin_password, + } + ) + result = request_json( + "POST", + f"{base_url}/realms/master/protocol/openid-connect/token", + headers={"Content-Type": "application/x-www-form-urlencoded"}, + body=body, + ) + token = result.get("access_token") + if not token: + raise KeycloakAuthError(f"no access_token in Keycloak admin token response: {result}") + return token + + +def create_reviewer_user(base_url: str, realm: str, admin_token: str) -> None: + request_json( + "POST", + f"{base_url}/admin/realms/{realm}/users", + headers={"Authorization": f"Bearer {admin_token}"}, + body={ + "username": "reviewer", + "enabled": True, + "email": "reviewer@example.com", + "emailVerified": True, + "firstName": "Preview", + "lastName": "Reviewer", + "credentials": [{"type": "password", "value": "admin", "temporary": False}], + }, + ) + + +def _cmd_create_reviewer_user(args: argparse.Namespace) -> int: + try: + token = get_admin_token(args.base_url, admin_password_from_env()) + create_reviewer_user(args.base_url, args.realm, token) + except Exception as exc: # noqa: BLE001 - report and fail the step either way + gha.error(f"Failed to create the Keycloak reviewer user: {exc}") + return 1 + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="keycloak") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("create-reviewer-user") + p.add_argument("--base-url", required=True) + p.add_argument("--realm", required=True) + p.set_defaults(func=_cmd_create_reviewer_user) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/keycloak_gitops.py b/scripts/preview/keycloak_gitops.py new file mode 100644 index 00000000..446ddcf3 --- /dev/null +++ b/scripts/preview/keycloak_gitops.py @@ -0,0 +1,163 @@ +"""Repoint Keycloak's own hostname via NIC's local GitOps repo. + +Needed because the sandbox boots the platform with no input for a public +Keycloak hostname; browser login needs the tunnel hostname instead. + +Keycloak's own KC_HOSTNAME (codecentric/keycloakx, via NIC's +values/keycloak/base.yaml) is fixed to NIC's internal keycloak.nebari.local +by default -- every self-referencing URL Keycloak renders (login form +action, issuer, redirects) is absolute and uses that value regardless of +the incoming Host header. + +A direct `kubectl set env` patch onto the live StatefulSet/Deployment DOES +apply immediately but gets silently reverted: both Keycloak and +nebari-operator are ArgoCD Applications with selfHeal: true, continuously +reconciled against NIC's auto-created local GitOps repo +(~/.nic/gitops/). Editing the GitOps repo itself and forcing +a hard refresh lets selfHeal work for this change instead of against it. + +Usage: + python -m scripts.preview.keycloak_gitops patch \\ + --gitops-dir DIR --kc-public-url URL +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +import time +from collections.abc import Callable +from pathlib import Path + +from . import gha + +OLD_HOSTNAME_URL = "https://keycloak.nebari.local" +GITOPS_FILES = ("values/keycloak/base.yaml", "manifests/nebari-operator/deployment-patch.yaml") + + +class OperatorNotFoundError(RuntimeError): + pass + + +def rewrite_hostname(text: str, old_url: str, new_url: str) -> str: + """Replace every literal occurrence of ``old_url`` with ``new_url``.""" + return text.replace(old_url, new_url) + + +def find_operator_deployment(deployments_json: dict) -> tuple[str, str]: + """Return (namespace, name) of the deployment whose name contains "operator".""" + for item in deployments_json.get("items", []): + name = item["metadata"]["name"] + if re.search("operator", name): + return item["metadata"]["namespace"], name + raise OperatorNotFoundError("no deployment with 'operator' in its name was found") + + +def extract_env_value(env: list[dict], var_name: str) -> str: + """Return the value of ``var_name`` in a container env list, or "" if absent.""" + for entry in env: + if entry.get("name") == var_name: + return entry.get("value", "") + return "" + + +def wait_until_both_match( + get_values: Callable[[], tuple[str, str]], + expected: str, + timeout_s: int = 120, + poll_interval_s: int = 5, +) -> tuple[bool, tuple[str, str]]: + """Poll ``get_values()`` until both returned values equal ``expected``. + + `rollout status` alone can return instantly if ArgoCD hasn't actually + applied the refreshed spec yet (nothing new requested from kubectl's + point of view) -- poll for the live values to actually change before + trusting rollout status to mean anything. + """ + deadline = time.monotonic() + timeout_s + values = ("", "") + while time.monotonic() < deadline: + values = get_values() + if values[0] == expected and values[1] == expected: + return True, values + time.sleep(poll_interval_s) + return False, values + + +def _run(cmd: list[str]) -> subprocess.CompletedProcess: + return subprocess.run(cmd, check=True, text=True, capture_output=True) + + +def _cmd_patch(args: argparse.Namespace) -> int: + gitops_dir = Path(args.gitops_dir) + + for relative_path in GITOPS_FILES: + path = gitops_dir / relative_path + original = path.read_text() + print(f"--- {relative_path}: {original.count(OLD_HOSTNAME_URL)} occurrence(s) of {OLD_HOSTNAME_URL} ---") + path.write_text(rewrite_hostname(original, OLD_HOSTNAME_URL, args.kc_public_url)) + + _run([ + "git", "-C", str(gitops_dir), + "-c", "user.email=ci@example.com", "-c", "user.name=k8s-preview-ci", + "commit", "-am", "Point Keycloak hostname at the public preview tunnel route", + ]) + + _run([ + "kubectl", "-n", "argocd", "annotate", + "application/keycloak", "application/nebari-operator", + "argocd.argoproj.io/refresh=hard", "--overwrite", + ]) + + deployments = json.loads(_run(["kubectl", "get", "deploy", "-A", "-o", "json"]).stdout) + try: + operator_namespace, operator_name = find_operator_deployment(deployments) + except OperatorNotFoundError as exc: + gha.error(str(exc)) + return 1 + + def get_values() -> tuple[str, str]: + kc_env = json.loads(_run([ + "kubectl", "-n", "keycloak", "get", "statefulset", "keycloak-keycloakx", + "-o", "jsonpath={.spec.template.spec.containers[0].env}", + ]).stdout or "[]") + op_env = json.loads(_run([ + "kubectl", "-n", operator_namespace, "get", "deploy", operator_name, + "-o", "jsonpath={.spec.template.spec.containers[0].env}", + ]).stdout or "[]") + return ( + extract_env_value(kc_env, "KC_HOSTNAME"), + extract_env_value(op_env, "KEYCLOAK_EXTERNAL_URL"), + ) + + matched, (kc_live, op_live) = wait_until_both_match(get_values, args.kc_public_url) + if not matched: + gha.error( + "ArgoCD never applied the GitOps hostname change within 2m " + f"(keycloak={kc_live}, operator={op_live})" + ) + return 1 + + _run(["kubectl", "-n", "keycloak", "rollout", "status", "statefulset/keycloak-keycloakx", "--timeout=180s"]) + _run(["kubectl", "-n", operator_namespace, "rollout", "status", f"deployment/{operator_name}", "--timeout=180s"]) + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="keycloak_gitops") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("patch") + p.add_argument("--gitops-dir", required=True) + p.add_argument("--kc-public-url", required=True) + p.set_defaults(func=_cmd_patch) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/pr_image.py b/scripts/preview/pr_image.py new file mode 100644 index 00000000..039ecb46 --- /dev/null +++ b/scripts/preview/pr_image.py @@ -0,0 +1,120 @@ +"""Point the preview deploy's JupyterLab image at this PR's own build. + +build-images.yaml pushes a `pr-` tag of the JupyterLab image for +PRs that change it. If that tag exists on the registry, every jupyterlab +image ref in values.yaml is rewritten to it and the pinned image is kept +as a second choice in each profile's image selector. If not, values.yaml +is left alone and the preview runs the pinned image. + +values.preview.yaml's profiles carry no image refs of their own; this +fills in the same image and selector so the pin lives in one place. + +Usage: + pipx run scripts/preview/pr_image.py set-tag --tag pr-205 [values.yaml ...] +""" + +# /// script +# dependencies = ["ruamel.yaml==0.19.1"] +# /// + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from ruamel.yaml import YAML + +REPO_ROOT = Path(__file__).resolve().parents[2] +# Run as a file by pipx: the repo isn't on sys.path, and this directory is, +# where http.py would shadow the stdlib `http` that urllib needs. +sys.path.remove(str(Path(__file__).resolve().parent)) +sys.path.insert(0, str(REPO_ROOT)) +from scripts.bump_image_tags import DEFAULT_VALUES, JUPYTERLAB_IMAGE, _bump_profile_list +from scripts.preview.http import request_json + +PREVIEW_VALUES = REPO_ROOT / "values.preview.yaml" + + +def tag_exists(image: str, tag: str) -> bool: + """True if ``image:tag`` is an active tag on quay.io.""" + registry, repo = image.split("/", 1) + if registry != "quay.io": + raise ValueError(f"only quay.io images are supported, got {image!r}") + body = request_json("GET", f"https://quay.io/api/v1/repository/{repo}/tag/?specificTag={tag}&onlyActiveTags=true") + return bool(body.get("tags")) + + +def _choice(ref: str, suffix: str = "") -> dict: + return {"display_name": ref.rsplit("/", 1)[-1] + suffix, "kubespawner_override": {"image": ref}} + + +def set_image(values_path: Path, ref: str, pinned_ref: str) -> bool: + """Point ``values_path``'s singleuser image (if any) and every profile at ``ref``. + + Profiles without an image get one plus an image selector; when ``ref`` + differs from ``pinned_ref`` the selector also offers the pinned image. + """ + yaml = YAML(typ="rt") + yaml.preserve_quotes = True + yaml.width = 4096 + yaml.indent(mapping=2, sequence=4, offset=2) + + data = yaml.load(values_path) + tag = ref.rsplit(":", 1)[1] + changed = False + singleuser = data["jupyterhub"].get("singleuser", {}).get("image") + if singleuser and singleuser["tag"] != tag: + singleuser["tag"] = tag + changed = True + changed = _bump_profile_list(data, tag) | changed + + for profile in data["jupyterhub"]["custom"]["profiles"]: + outer = profile.setdefault("kubespawner_override", {}) + if not outer.get("image", "").startswith(JUPYTERLAB_IMAGE + ":"): + outer["image"] = ref + profile.setdefault("profile_options", {})["image"] = { + "display_name": "Image", + "choices": {"default": {**_choice(ref), "default": True}}, + } + changed = True + choices = profile.get("profile_options", {}).get("image", {}).get("choices") + if ref != pinned_ref and choices is not None and "main" not in choices: + choices["main"] = _choice(pinned_ref, " (main)") + changed = True + + if changed: + yaml.dump(data, values_path) + return changed + + +def _cmd_set_tag(args: argparse.Namespace) -> int: + paths = [Path(v) for v in args.values] or [DEFAULT_VALUES, PREVIEW_VALUES] + singleuser = YAML(typ="safe").load(DEFAULT_VALUES)["jupyterhub"]["singleuser"]["image"] + pinned_ref = f'{singleuser["name"]}:{singleuser["tag"]}' + if tag_exists(JUPYTERLAB_IMAGE, args.tag): + ref = f"{JUPYTERLAB_IMAGE}:{args.tag}" + else: + ref = pinned_ref + print(f"{JUPYTERLAB_IMAGE}:{args.tag} not on registry, using pinned {pinned_ref}") + for values_path in paths: + changed = set_image(values_path, ref, pinned_ref) + print(f"{'updated' if changed else 'unchanged'}: {values_path} -> {ref}") + return 0 + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="pr_image") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("set-tag") + p.add_argument("--tag", required=True) + p.add_argument("values", nargs="*") + p.set_defaults(func=_cmd_set_tag) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/scripts/preview/tunnel.py b/scripts/preview/tunnel.py new file mode 100644 index 00000000..e95896b6 --- /dev/null +++ b/scripts/preview/tunnel.py @@ -0,0 +1,195 @@ +"""Runs cloudflared for INITIAL_SECONDS; an extend-preview label on the PR +resets the deadline to now + EXTEND_SECONDS and is removed once consumed. +Each extend re-renders the PR comment's expiry (best-effort). + +Also runs the `kubectl port-forward`s cloudflared sends traffic to, with +their output in this step's log. A port-forward that exits after it was +forwarding is restarted; one that exits before it ever forwarded fails the run. + +Usage: + KC_ADMIN_PASSWORD=... python -m scripts.preview.tunnel run \\ + --cloudflared PATH --token TOKEN \\ + --repo OWNER/REPO --pr N --run-url URL \\ + --url URL --keycloak-url URL \\ + --deployed-at STR --deployed-at-iso ISO \\ + --port-forward NAMESPACE RESOURCE LOCAL:REMOTE [--port-forward ...] + +The Keycloak admin password (re-rendered into the PR comment on each extend) +comes from KC_ADMIN_PASSWORD, not argv; see keycloak.admin_password_from_env. +""" + +from __future__ import annotations + +import argparse +import os +import subprocess +import sys +import threading +import time + +from .comment import render_ready +from .http import request_json +from .keycloak import admin_password_from_env + +STICKY_MARKER = "" +INITIAL_SECONDS = 1200 +EXTEND_SECONDS = 1200 +POLL_SECONDS = 15 +CHECK_SECONDS = 1 +EXTEND_LABEL = "extend-preview" + + +def _api(method: str, path: str, body: dict | None = None) -> dict | list: + """GitHub REST call, authenticated with the workflow's GH_TOKEN.""" + headers = { + "Authorization": f"Bearer {os.environ['GH_TOKEN']}", + "Accept": "application/vnd.github+json", + } + return request_json(method, f"https://api.github.com/{path}", headers=headers, body=body) + + +def _pr_labels(repo: str, pr_number: int) -> list[str]: + return [item["name"] for item in _api("GET", f"repos/{repo}/issues/{pr_number}/labels")] + + +def _remove_label(repo: str, pr_number: int, label: str) -> None: + _api("DELETE", f"repos/{repo}/issues/{pr_number}/labels/{label}") + + +def _sticky_comment_id(repo: str, pr_number: int) -> int | None: + comments = _api("GET", f"repos/{repo}/issues/{pr_number}/comments?per_page=100") + return next((c["id"] for c in comments if STICKY_MARKER in c.get("body", "")), None) + + +def _update_comment(repo: str, comment_id: int, body: str) -> None: + _api("PATCH", f"repos/{repo}/issues/comments/{comment_id}", body={"body": body}) + + +def _stop(proc: subprocess.Popen) -> None: + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + + +class PortForward: + """One `kubectl port-forward`, restarted each time it exits after forwarding. + + kubectl prints "Forwarding from ..." only once it has connected to the pod + and is listening locally; after that it exits when the pod connection + closes ("lost connection to pod"). Exiting without that line means it + could not set the forward up at all, and its error says why. + """ + + def __init__(self, namespace: str, resource: str, ports: str) -> None: + self.name = f"{namespace}/{resource} {ports}" + self._cmd = ["kubectl", "-n", namespace, "port-forward", resource, ports] + self._start() + + def _start(self) -> None: + self._forwarding = False + self._proc = subprocess.Popen(self._cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + self._relay = threading.Thread(target=self._relay_output, args=(self._proc,), daemon=True) + self._relay.start() + + def _relay_output(self, proc: subprocess.Popen) -> None: + # kubectl prints "Handling connection for N" per connection; drop it, keep the rest. + for line in proc.stdout: + if line.startswith("Forwarding from"): + self._forwarding = True + if not line.startswith("Handling connection for"): + print(f"[port-forward {self.name}] {line.rstrip()}") + + def ensure_running(self) -> bool: + """Restart kubectl if it exited after forwarding. False if it exited before it ever forwarded.""" + code = self._proc.poll() + if code is None: + return True + self._relay.join() # kubectl's output is closed once it exits; the relay has seen every line + if not self._forwarding: + print(f"port-forward {self.name} exited with code {code} before it started forwarding, giving up") + return False + print(f"port-forward {self.name} exited with code {code}, restarting") + self._start() + return True + + def stop(self) -> None: + _stop(self._proc) + + +def _refresh_comment_expiry(args: argparse.Namespace, seconds_remaining: float) -> None: + """Rewrite the sticky comment's Expires line for the new deadline. Best-effort.""" + deadline = time.gmtime(time.time() + seconds_remaining) + expires_at = time.strftime("%Y-%m-%d %H:%M UTC", deadline) + expires_at_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", deadline) + print(f"{EXTEND_LABEL} seen -- new deadline: {expires_at}") + try: + comment_id = _sticky_comment_id(args.repo, args.pr) + if comment_id is not None: + body = render_ready( + args.url, args.keycloak_url, args.run_url, admin_password_from_env(), + args.deployed_at, args.deployed_at_iso, expires_at, expires_at_iso, + ) + _update_comment(args.repo, comment_id, body + "\n" + STICKY_MARKER) + except Exception as exc: # noqa: BLE001 - the tunnel staying up matters more than the comment being exact + print(f"warning: failed to update the PR comment after extend: {exc}") + + +def run(args: argparse.Namespace) -> int: + """Run the port-forwards and cloudflared until the deadline, extending it + when the label appears. + + Returns cloudflared's exit code if it crashed, 1 if a port-forward could + not be kept running, 0 on a clean deadline stop. + """ + forwards = [PortForward(*spec) for spec in args.port_forward] + proc = subprocess.Popen([args.cloudflared, "tunnel", "--no-autoupdate", "run", "--token", args.token]) + deadline = time.monotonic() + INITIAL_SECONDS + next_label_check = time.monotonic() + try: + while proc.poll() is None and time.monotonic() < deadline: + if not all(forward.ensure_running() for forward in forwards): + return 1 + if time.monotonic() >= next_label_check: + if EXTEND_LABEL in _pr_labels(args.repo, args.pr): + deadline = time.monotonic() + EXTEND_SECONDS + _remove_label(args.repo, args.pr, EXTEND_LABEL) + _refresh_comment_expiry(args, deadline - time.monotonic()) + next_label_check = time.monotonic() + POLL_SECONDS + time.sleep(CHECK_SECONDS) + if proc.poll() is not None: + return proc.returncode + return 0 + finally: + for forward in forwards: + forward.stop() + if proc.poll() is None: + _stop(proc) + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(prog="tunnel") + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("run") + p.add_argument("--cloudflared", required=True) + p.add_argument("--token", required=True) + p.add_argument("--repo", required=True) + p.add_argument("--pr", required=True, type=int) + p.add_argument("--run-url", required=True) + p.add_argument("--url", required=True) + p.add_argument("--keycloak-url", required=True) + p.add_argument("--deployed-at", required=True) + p.add_argument("--deployed-at-iso", required=True) + p.add_argument("--port-forward", nargs=3, action="append", default=[], + metavar=("NAMESPACE", "RESOURCE", "LOCAL:REMOTE")) + p.set_defaults(func=run) + + args = parser.parse_args(argv[1:]) + return args.func(args) + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/values.preview.yaml b/values.preview.yaml new file mode 100644 index 00000000..589244e3 --- /dev/null +++ b/values.preview.yaml @@ -0,0 +1,54 @@ +# Static overrides for k8s-preview.yaml's ephemeral deploy. PR-specific +# values (hostname, external-url) are passed as --set flags at deploy time. +jupyterhub: + hub: + image: + name: nebari-data-science-pack-jupyterhub + tag: preview + # jupyterhub.hub.extraVolumes in values.yaml hardcodes secretName for + # a "data-science-pack" release; override for this release ("preview"). + extraVolumes: + - name: custom-config + configMap: + name: nebari-data-science-pack-hub-config + - name: oauth-client + secret: + secretName: preview-nebari-data-science-pack-oidc-client + optional: true + - name: org-ca + configMap: + name: nebari-trust-bundle + optional: true + - name: ca-merged + emptyDir: {} + # Blocks install on pre-pulling the singleuser image; the PR's + # jupyterlab tag may not exist yet -- disable so deploy doesn't fail + # outright, image pulls lazily on spawn instead. + prePuller: + hook: + enabled: false + custom: + profiles: + - slug: micro-instance + display_name: "Micro Instance" + description: "0.5 CPU / 1 GB RAM: quick checks, smoke tests, reviewing a change." + default: true + kubespawner_override: + cpu_limit: 0.5 + cpu_guarantee: 0.25 + mem_limit: "1G" + mem_guarantee: "512M" + - slug: small-instance + display_name: "Small Instance" + description: "1 CPU / 2 GB RAM: interactive notebooks, light data exploration." + kubespawner_override: + cpu_limit: 1 + cpu_guarantee: 0.5 + mem_limit: "2G" + mem_guarantee: "1G" +nebariapp: + enabled: true +keycloak: + # hub's own token exchange can't go through Cloudflare Access (no + # browser session) -- route it in-cluster instead. + backchannelURL: "http://keycloak-keycloakx-http.keycloak.svc.cluster.local:8080" diff --git a/values.yaml b/values.yaml index 30b5f940..419ce73a 100644 --- a/values.yaml +++ b/values.yaml @@ -628,6 +628,10 @@ jupyterhub: # # here to add more or replace the default. # startup_apps: [] hub: + # jhub-apps runs inside the hub pod and calls the hub API through the + # hub Service; the hub NetworkPolicy only admits pods with this label. + labels: + hub.jupyter.org/network-access-hub: "true" # Custom Nebari hub image with jhub-apps pre-installed. # Tag below is the PR-53 merge-commit SHA at the moment of pinning; the # corresponding immutable digest is