diff --git a/.github/scripts/gke/README.md b/.github/scripts/gke/README.md new file mode 100644 index 00000000..a692f80f --- /dev/null +++ b/.github/scripts/gke/README.md @@ -0,0 +1,69 @@ +# GKE deployment test + +Every pull request that touches the Helm charts is deployed to its own small GKE +cluster and left running, so reviewers can open the apps in a browser. + +| | | +|---|---| +| Workflows | `.github/workflows/gke_deploy_test.yml`, `.github/workflows/gke_teardown.yml` | +| URLs | `https://.pr-.platform.cogstack.dev` for `trainer`, `jupyter`, `dashboards`, `medcat`, `anoncat`, `ocr` | +| Login | user `cogstack`; password: `gcloud secrets versions access latest --secret preview-basic-auth-password --project ` | +| Auth to Google Cloud | GitHub OIDC (Workload Identity Federation). No keys are stored anywhere. | + +## How it works + +There is no state file. The cluster for PR 123 is always called `pr-123`, and +every script derives what it needs from the PR number. + +1. `cluster-up.sh` creates the cluster, or reuses it if a previous push already did. +2. `deploy.sh` installs Traefik and cert-manager, points `*.pr-.platform.cogstack.dev` + at the load balancer, obtains a wildcard certificate, then installs or upgrades + `cogstack-ce-helm` (`deployment/charts/ce`) from the PR and runs `helm test`. +3. `smoke-test.sh` requests every app over public HTTPS. +4. `pr-status.sh` writes a panel at the top of the PR description: a link and a + green or red dot per app. It shows "deploying", "failed" and "removed" too, + and the hourly job re-checks the dots for environments that are still up. +5. The check goes green and the cluster stays up. + +Every route sits behind basic auth, because the charts ship demo passwords and +the URLs are public. + +## Teardown + +`teardown.sh` removes the workloads first (so Google deletes the load balancer +and disks), then the cluster, then the PR's DNS records. It runs: + +- when the PR is closed or merged; +- by hand: run the `gke_teardown` workflow with a PR number, or `all`; +- hourly, for any environment whose PR is closed or that is older than + `GKE_PR_MAX_AGE_HOURS` (repository variable, default 24). Re-run the deploy + job to bring an expired environment back. + +## Setup, and moving between repositories + +`setup-gcp.sh` builds the Google Cloud project and is safe to re-run. Its +arguments are the repositories allowed to authenticate; each run replaces the +previous list. + +```bash +GCP_ORG_ID= GCP_BILLING_ACCOUNT= \ + .github/scripts/gke/setup-gcp.sh / +``` + +It prints the NS record to add to the parent DNS zone (needed once) and the +three `gh variable set` commands for the repository. The workflows do nothing +in a repository where those variables are not set. + +To move the test to another repository: + +1. Run the `gke_teardown` workflow with `all` in the old repository. PR numbers + differ between repositories, so old environments must not be left behind. +2. Run `setup-gcp.sh /`. +3. Run the three `gh variable set` commands it prints. +4. To make the test block merging, add **GKE deployment test** as a required + status check on the default branch. + +## Limits + +- Pull requests from forks and from Dependabot are skipped: they cannot obtain an OIDC token. +- The charts deploy published images, so this tests the charts, not unreleased application code. diff --git a/.github/scripts/gke/cluster-up.sh b/.github/scripts/gke/cluster-up.sh new file mode 100755 index 00000000..ce0f8d8c --- /dev/null +++ b/.github/scripts/gke/cluster-up.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Create the GKE cluster for a PR if it does not exist yet, then fetch credentials. +# Usage: cluster-up.sh +set -euo pipefail +cd "$(dirname "$0")" +source ./lib.sh +set_pr "${1:?usage: cluster-up.sh }" + +status="$(cluster_status)" +case "$status" in + "") + log "Creating cluster $CLUSTER_NAME in $GCP_ZONE" + gc container clusters create "$CLUSTER_NAME" \ + --zone "$GCP_ZONE" \ + --release-channel regular \ + --num-nodes "$NODE_COUNT" \ + --machine-type "$NODE_MACHINE_TYPE" \ + --disk-type pd-balanced \ + --disk-size 50 \ + --service-account "$NODE_SERVICE_ACCOUNT" \ + --workload-pool "${GCP_PROJECT_ID}.svc.id.goog" \ + --labels "${CLUSTER_LABEL},pr=${PR_NUMBER}" + ;; + RUNNING | RECONCILING) + log "Reusing existing cluster $CLUSTER_NAME ($status)" + ;; + *) + echo "Cluster $CLUSTER_NAME is in state $status. Run the teardown workflow for PR $PR_NUMBER, then re-run this job." >&2 + exit 1 + ;; +esac + +get_credentials +kubectl wait --for=condition=Ready nodes --all --timeout=300s diff --git a/.github/scripts/gke/deploy.sh b/.github/scripts/gke/deploy.sh new file mode 100755 index 00000000..37d08b83 --- /dev/null +++ b/.github/scripts/gke/deploy.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Deploy this checkout of cogstack-ce-helm to the PR's cluster, behind HTTPS. +# Safe to re-run: a later push to the PR upgrades the existing release. +# Usage: deploy.sh (run cluster-up.sh first) +set -euo pipefail +cd "$(dirname "$0")" +source ./lib.sh +set_pr "${1:?usage: deploy.sh }" + +REPO_ROOT="$(git rev-parse --show-toplevel)" +WORK="$(mktemp -d)" + +log "Installing cert-manager $CERT_MANAGER_CHART_VERSION" +helm upgrade --install cert-manager oci://quay.io/jetstack/charts/cert-manager \ + --version "$CERT_MANAGER_CHART_VERSION" \ + --namespace cert-manager --create-namespace \ + --set crds.enabled=true \ + --wait --timeout 10m + +log "Installing Traefik $TRAEFIK_CHART_VERSION" +helm upgrade --install traefik oci://ghcr.io/traefik/helm/traefik \ + --version "$TRAEFIK_CHART_VERSION" \ + --namespace traefik --create-namespace \ + -f traefik-values.yaml \ + --wait --timeout 10m + +log "Waiting for the load balancer address" +LB_IP="" +for _ in $(seq 1 60); do + LB_IP="$(kubectl -n traefik get svc traefik -o jsonpath='{.status.loadBalancer.ingress[0].ip}')" + [[ -n "$LB_IP" ]] && break + sleep 5 +done +[[ -n "$LB_IP" ]] || { echo "Traefik service never received an external IP" >&2; exit 1; } + +log "Pointing *.${DOMAIN} at ${LB_IP}" +record="*.${DOMAIN}." +if gc dns record-sets describe "$record" --type A --zone "$DNS_ZONE_NAME" >/dev/null 2>&1; then + gc dns record-sets update "$record" --type A --zone "$DNS_ZONE_NAME" --ttl 60 --rrdatas "$LB_IP" >/dev/null +else + gc dns record-sets create "$record" --type A --zone "$DNS_ZONE_NAME" --ttl 60 --rrdatas "$LB_IP" >/dev/null +fi + +log "Configuring basic auth" +password="$(gc secrets versions access latest --secret "$BASIC_AUTH_SECRET")" +[[ -n "${GITHUB_ACTIONS:-}" ]] && echo "::add-mask::${password}" +kubectl -n traefik create secret generic basic-auth-users \ + --from-literal=users="${BASIC_AUTH_USER}:$(openssl passwd -apr1 "$password")" \ + --dry-run=client -o yaml | kubectl apply -f - + +log "Requesting the wildcard certificate for *.${DOMAIN}" +envsubst '${GCP_PROJECT_ID} ${DOMAIN}' < platform.tmpl.yaml | kubectl apply -f - +kubectl -n traefik wait --for=condition=Ready certificate/wildcard --timeout=15m + +log "Deploying cogstack-ce-helm" +envsubst '${DOMAIN}' < values.tmpl.yaml > "$WORK/values.yaml" +(cd "$REPO_ROOT/deployment/charts" && "$REPO_ROOT/.github/scripts/helm-recursive-dependency-update.py") + +# A release left failed or half-applied by an earlier run blocks upgrades; start it clean. +release_status="$(helm status "$RELEASE_NAME" -n "$RELEASE_NAMESPACE" -o json 2>/dev/null | jq -r '.info.status' || true)" +if [[ -n "$release_status" && "$release_status" != "deployed" ]]; then + log "Release is '$release_status'; uninstalling before reinstall" + helm uninstall "$RELEASE_NAME" -n "$RELEASE_NAMESPACE" --wait --timeout 10m +fi + +helm upgrade --install "$RELEASE_NAME" "$REPO_ROOT/deployment/charts/ce" \ + --namespace "$RELEASE_NAMESPACE" --create-namespace \ + -f "$WORK/values.yaml" \ + --wait --timeout 30m + +log "Running helm tests" +helm test "$RELEASE_NAME" -n "$RELEASE_NAMESPACE" --logs --timeout 15m diff --git a/.github/scripts/gke/lib.sh b/.github/scripts/gke/lib.sh new file mode 100755 index 00000000..2a76849b --- /dev/null +++ b/.github/scripts/gke/lib.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Shared settings for the GKE deployment test scripts. Source this file. +# +# There is no state file: everything is derived from the PR number, so any job +# can find (or clean up) the resources belonging to a PR. + +: "${GCP_PROJECT_ID:?GCP_PROJECT_ID must be set}" + +export GCP_ZONE="${GCP_ZONE:-europe-west2-a}" +# Cloud DNS managed zone name, and the domain it serves. +export DNS_ZONE_NAME="${DNS_ZONE_NAME:-platform}" +export BASE_DOMAIN="${BASE_DOMAIN:-platform.cogstack.dev}" + +export NODE_COUNT="${NODE_COUNT:-2}" +export NODE_MACHINE_TYPE="${NODE_MACHINE_TYPE:-e2-standard-4}" +export NODE_SERVICE_ACCOUNT="gke-node@${GCP_PROJECT_ID}.iam.gserviceaccount.com" + +# Label carried by every cluster this test creates; the reaper selects on it. +export CLUSTER_LABEL="purpose=pr-deploy-test" + +export BASIC_AUTH_USER="cogstack" +export BASIC_AUTH_SECRET="preview-basic-auth-password" + +export RELEASE_NAME="cogstack" +export RELEASE_NAMESPACE="cogstack" + +# Pinned so that an upstream chart release cannot break a required check. +export TRAEFIK_CHART_VERSION="42.4.1" +export CERT_MANAGER_CHART_VERSION="v1.21.3" + +# Apps exposed per PR as .pr-., with the path the +# smoke test requests. +export APPS="trainer:/ jupyter:/ dashboards:/ medcat:/api/health/live anoncat:/api/health/live ocr:/api/health" + +# set_pr : derive the per-PR names. +set_pr() { + if ! [[ "$1" =~ ^[0-9]+$ ]]; then + echo "PR number must be numeric, got: '$1'" >&2 + return 1 + fi + export PR_NUMBER="$1" + export CLUSTER_NAME="pr-${PR_NUMBER}" + export DOMAIN="pr-${PR_NUMBER}.${BASE_DOMAIN}" +} + +gc() { gcloud --project "$GCP_PROJECT_ID" --quiet "$@"; } + +cluster_status() { + gc container clusters describe "$CLUSTER_NAME" --zone "$GCP_ZONE" \ + --format='value(status)' 2>/dev/null || true +} + +get_credentials() { + gc container clusters get-credentials "$CLUSTER_NAME" --zone "$GCP_ZONE" +} + +log() { echo "==> $*" >&2; } diff --git a/.github/scripts/gke/platform.tmpl.yaml b/.github/scripts/gke/platform.tmpl.yaml new file mode 100644 index 00000000..56ffea16 --- /dev/null +++ b/.github/scripts/gke/platform.tmpl.yaml @@ -0,0 +1,40 @@ +# Cluster plumbing for a PR environment: a wildcard certificate for the PR's +# domain and basic auth in front of every route. Rendered with envsubst. +apiVersion: cert-manager.io/v1 +kind: ClusterIssuer +metadata: + name: letsencrypt +spec: + acme: + server: https://acme-v02.api.letsencrypt.org/directory + privateKeySecretRef: + name: letsencrypt-account-key + solvers: + - dns01: + cloudDNS: + # No key: cert-manager authenticates with GKE Workload Identity. + project: ${GCP_PROJECT_ID} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: wildcard + namespace: traefik +spec: + secretName: wildcard-tls + issuerRef: + kind: ClusterIssuer + name: letsencrypt + dnsNames: + - "*.${DOMAIN}" +--- +apiVersion: traefik.io/v1alpha1 +kind: Middleware +metadata: + name: basic-auth + namespace: traefik +spec: + basicAuth: + secret: basic-auth-users + # Do not pass the browser's Basic credentials on to the apps. + removeHeader: true diff --git a/.github/scripts/gke/pr-status.sh b/.github/scripts/gke/pr-status.sh new file mode 100755 index 00000000..38acc2f2 --- /dev/null +++ b/.github/scripts/gke/pr-status.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Keep a status panel at the top of the PR description: one line per app with a +# link and a green or red dot, so a reviewer sees straight away what to click +# and whether it is up. +# +# Usage: pr-status.sh +# live probes every app over public HTTPS and shows a dot per app +# the others only change the headline +# Needs GH_TOKEN, and GH_REPO or GITHUB_REPOSITORY. "live" also needs gcloud. +set -uo pipefail +cd "$(dirname "$0")" || exit 1 +source ./lib.sh +set_pr "${1:?usage: pr-status.sh }" || exit 1 +STATE="${2:?usage: pr-status.sh }" + +REPO="${GH_REPO:-${GITHUB_REPOSITORY:?GH_REPO or GITHUB_REPOSITORY must be set}}" +START="" +END="" +WORK="$(mktemp -d)" + +run_link="" +if [[ -n "${GITHUB_RUN_ID:-}" ]]; then + run_link=" · [workflow run](${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID})" +fi +commit="$(gh api "repos/${REPO}/pulls/${PR_NUMBER}" --jq '.head.sha[0:7]')" +now="$(date -u '+%Y-%m-%d %H:%M UTC')" + +app_title() { + case "$1" in + trainer) echo "MedCAT Trainer" ;; + jupyter) echo "JupyterHub" ;; + dashboards) echo "OpenSearch Dashboards" ;; + medcat) echo "MedCAT Service (API)" ;; + anoncat) echo "AnonCAT Service (API)" ;; + ocr) echo "OCR Service (API)" ;; + *) echo "$1" ;; + esac +} + +{ + echo "$START" + case "$STATE" in + deploying) + echo "## 🟡 Test environment is deploying" + echo + echo "Commit \`${commit}\` is being deployed to \`${DOMAIN}\`. Links appear here when it is ready (about 20 minutes for a new environment, 7 for an update)." + echo + echo "Updated ${now}${run_link}" + ;; + failed) + echo "## 🔴 Test environment failed to deploy" + echo + echo "Commit \`${commit}\` did not deploy. The cluster is left running for debugging; see the workflow run for the reason." + echo + echo "Updated ${now}${run_link}" + ;; + removed) + echo "## ⚪ Test environment removed" + echo + echo "The environment for this PR has been torn down. If the PR is still open, re-run the **GKE deployment test** job or push a commit to bring it back." + echo + echo "Updated ${now}${run_link}" + ;; + live) + password="$(gc secrets versions access latest --secret "$BASIC_AUTH_SECRET")" + [[ -n "${GITHUB_ACTIONS:-}" ]] && echo "::add-mask::${password}" >&2 + rows="" + down=0 + total=0 + for app in $APPS; do + name="${app%%:*}" + url="https://${name}.${DOMAIN}${app#*:}" + code="$(curl -s -L -o /dev/null -m 20 -w '%{http_code}' -u "${BASIC_AUTH_USER}:${password}" "$url" || true)" + total=$((total + 1)) + if [[ "$code" =~ ^2 ]]; then + dot="🟢" + else + dot="🔴" + down=$((down + 1)) + fi + rows+="| ${dot} | **$(app_title "$name")** | ${url} |"$'\n' + done + if ((down == 0)); then + echo "## 🟢 Test environment is live" + else + echo "## 🔴 Test environment: ${down} of ${total} apps not responding" + fi + echo + echo "| | App | Link |" + echo "|---|---|---|" + printf '%s' "$rows" + echo + echo "**Sign in** with user \`${BASIC_AUTH_USER}\`. Get the password with:" + echo "\`gcloud secrets versions access latest --secret ${BASIC_AUTH_SECRET} --project ${GCP_PROJECT_ID}\`" + echo + echo "Commit \`${commit}\` · checked ${now} · removed when the PR closes or after ${MAX_AGE_HOURS:-24} hours${run_link}" + ;; + *) + echo "unknown state: $STATE" >&2 + exit 1 + ;; + esac + echo "$END" +} > "$WORK/panel.md" + +# Replace the existing panel, or put a new one above the author's description. +gh api "repos/${REPO}/pulls/${PR_NUMBER}" --jq '.body // ""' > "$WORK/body.md" +python3 - "$WORK/body.md" "$WORK/panel.md" "$START" "$END" > "$WORK/new.md" <<'EOF' +import re, sys +body, panel = open(sys.argv[1]).read(), open(sys.argv[2]).read().strip() +start, end = sys.argv[3], sys.argv[4] +pattern = re.compile(re.escape(start) + r".*?" + re.escape(end), re.S) +if pattern.search(body): + print(pattern.sub(lambda _: panel, body, count=1).strip()) +else: + print((panel + "\n\n" + body.strip()).strip()) +EOF +gh api -X PATCH "repos/${REPO}/pulls/${PR_NUMBER}" -F "body=@${WORK}/new.md" --silent || exit 1 + +if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then + cat "$WORK/panel.md" >> "$GITHUB_STEP_SUMMARY" +fi +log "PR ${PR_NUMBER} status panel set to '${STATE}'" diff --git a/.github/scripts/gke/reap.sh b/.github/scripts/gke/reap.sh new file mode 100755 index 00000000..68fc00ff --- /dev/null +++ b/.github/scripts/gke/reap.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Tear down PR environments that should no longer exist: the PR is closed, or +# the cluster is older than MAX_AGE_HOURS. With "all", tear down every one. +# Usage: reap.sh [all] (needs GH_TOKEN and GH_REPO for the PR lookup) +set -uo pipefail +cd "$(dirname "$0")" || exit 1 +source ./lib.sh + +MODE="${1:-stale}" +MAX_AGE_HOURS="${MAX_AGE_HOURS:-24}" +now="$(date +%s)" +failed=0 + +while read -r pr created; do + [[ -n "$pr" ]] || continue + age_hours=$(((now - $(date -d "$created" +%s)) / 3600)) + state="$(gh pr view "$pr" --json state --jq .state 2>/dev/null || echo UNKNOWN)" + + reason="" + if [[ "$MODE" == "all" ]]; then + reason="teardown of all environments requested" + elif [[ "$state" == "CLOSED" || "$state" == "MERGED" ]]; then + reason="PR is $state" + elif ((age_hours >= MAX_AGE_HOURS)); then + reason="cluster is ${age_hours}h old (limit ${MAX_AGE_HOURS}h)" + fi + + if [[ -n "$reason" ]]; then + log "Reaping PR $pr: $reason" + ./teardown.sh "$pr" || failed=1 + else + log "Keeping PR $pr (state $state, ${age_hours}h old); refreshing its status" + ./pr-status.sh "$pr" live || true + fi +done < <(gc container clusters list --filter="resourceLabels.${CLUSTER_LABEL}" \ + --format='value(resourceLabels.pr,createTime)') + +exit "$failed" diff --git a/.github/scripts/gke/setup-gcp.sh b/.github/scripts/gke/setup-gcp.sh new file mode 100755 index 00000000..18a820f0 --- /dev/null +++ b/.github/scripts/gke/setup-gcp.sh @@ -0,0 +1,137 @@ +#!/usr/bin/env bash +# One-off (and re-runnable) setup of the Google Cloud project used by the GKE +# deployment test. Run it by hand as a project owner; CI never runs this. +# +# Usage: setup-gcp.sh [ ...] +# +# The repositories listed are the ONLY ones whose GitHub Actions runs may +# authenticate to the project. Re-running with a different list replaces the +# old one, which is how the test is moved between a fork and the main repo. +# +# Environment: +# GCP_PROJECT_ID project to create or reuse (default cogstack-platform-ci) +# GCP_ORG_ID organisation, needed only when the project is created +# GCP_BILLING_ACCOUNT billing account, needed only when the project is created +# BASE_DOMAIN domain delegated to the project (default platform.cogstack.dev) +# DNS_ZONE_NAME Cloud DNS zone name (default platform) +set -euo pipefail + +[[ $# -ge 1 ]] || { sed -n '2,17p' "$0"; exit 1; } + +PROJECT_ID="${GCP_PROJECT_ID:-cogstack-platform-ci}" +BASE_DOMAIN="${BASE_DOMAIN:-platform.cogstack.dev}" +DNS_ZONE_NAME="${DNS_ZONE_NAME:-platform}" +POOL="github" +PROVIDER="github" +CI_SA="gha-deploy-test@${PROJECT_ID}.iam.gserviceaccount.com" +NODE_SA="gke-node@${PROJECT_ID}.iam.gserviceaccount.com" +SECRET="preview-basic-auth-password" + +gc() { gcloud --project "$PROJECT_ID" --quiet "$@"; } +log() { echo "==> $*" >&2; } + +# Repositories are matched on their numeric ID, which survives renames. +ids=() +for repo in "$@"; do + ids+=("'$(gh api "repos/${repo}" --jq .id)'") +done +condition="assertion.repository_id in [$(IFS=,; echo "${ids[*]}")]" + +if ! gcloud projects describe "$PROJECT_ID" >/dev/null 2>&1; then + log "Creating project $PROJECT_ID" + gcloud projects create "$PROJECT_ID" --organization "${GCP_ORG_ID:?GCP_ORG_ID is needed to create the project}" + # gcloud calls the billing API on a quota shared with all gcloud users, which + # is often exhausted for a minute at a time. + linked="" + for _ in 1 2 3 4 5 6 7 8; do + if gcloud billing projects link "$PROJECT_ID" \ + --billing-account "${GCP_BILLING_ACCOUNT:?GCP_BILLING_ACCOUNT is needed to create the project}" >/dev/null 2>&1; then + linked=1 + break + fi + sleep 15 + done + [[ -n "$linked" ]] || { + echo "Could not link billing. Link it by hand, then re-run: gcloud billing projects link $PROJECT_ID --billing-account $GCP_BILLING_ACCOUNT" >&2 + exit 1 + } +fi +PROJECT_NUMBER="$(gcloud projects describe "$PROJECT_ID" --format='value(projectNumber)')" + +log "Enabling APIs" +gc services enable container.googleapis.com compute.googleapis.com dns.googleapis.com \ + iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com \ + secretmanager.googleapis.com cloudresourcemanager.googleapis.com + +log "DNS zone for $BASE_DOMAIN" +gc dns managed-zones describe "$DNS_ZONE_NAME" >/dev/null 2>&1 || + gc dns managed-zones create "$DNS_ZONE_NAME" --dns-name "${BASE_DOMAIN}." \ + --description "PR deployment test environments" + +log "Service accounts" +for sa in "gha-deploy-test:GitHub Actions deployment test" "gke-node:GKE node service account"; do + gc iam service-accounts describe "${sa%%:*}@${PROJECT_ID}.iam.gserviceaccount.com" >/dev/null 2>&1 || + gc iam service-accounts create "${sa%%:*}" --display-name "${sa#*:}" +done + +grant() { gc projects add-iam-policy-binding "$PROJECT_ID" --member "$1" --role "$2" --condition None >/dev/null; } + +grant "serviceAccount:${NODE_SA}" roles/container.defaultNodeServiceAccount +# The CI identity: manage clusters, DNS records and leftover disks in this project only. +grant "serviceAccount:${CI_SA}" roles/container.admin +grant "serviceAccount:${CI_SA}" roles/dns.admin +grant "serviceAccount:${CI_SA}" roles/compute.storageAdmin +gc iam service-accounts add-iam-policy-binding "$NODE_SA" \ + --member "serviceAccount:${CI_SA}" --role roles/iam.serviceAccountUser >/dev/null + +log "GitHub OIDC: allowing $*" +gc iam workload-identity-pools describe "$POOL" --location global >/dev/null 2>&1 || + gc iam workload-identity-pools create "$POOL" --location global --display-name "GitHub Actions" +provider_args=(--location global --workload-identity-pool "$POOL" + --attribute-mapping "google.subject=assertion.sub,attribute.repository_id=assertion.repository_id,attribute.repository=assertion.repository" + --attribute-condition "$condition") +if gc iam workload-identity-pools providers describe "$PROVIDER" --location global \ + --workload-identity-pool "$POOL" >/dev/null 2>&1; then + gc iam workload-identity-pools providers update-oidc "$PROVIDER" "${provider_args[@]}" >/dev/null +else + gc iam workload-identity-pools providers create-oidc "$PROVIDER" "${provider_args[@]}" \ + --issuer-uri https://token.actions.githubusercontent.com >/dev/null +fi +# The pool is used for nothing else, and the provider condition above decides who gets in. +gc iam service-accounts add-iam-policy-binding "$CI_SA" --role roles/iam.workloadIdentityUser \ + --member "principalSet://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL}/*" >/dev/null + +log "Basic auth password" +if ! gc secrets describe "$SECRET" >/dev/null 2>&1; then + gc secrets create "$SECRET" --replication-policy automatic >/dev/null + openssl rand -hex 16 | tr -d '\n' | gc secrets versions add "$SECRET" --data-file=- >/dev/null +fi +gc secrets add-iam-policy-binding "$SECRET" --member "serviceAccount:${CI_SA}" \ + --role roles/secretmanager.secretAccessor >/dev/null + +# cert-manager in every PR cluster proves domain ownership by writing DNS records. +# The Kubernetes identity pool only exists once the project has had a cluster. +log "cert-manager DNS access" +grant "principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${PROJECT_ID}.svc.id.goog/subject/ns/cert-manager/sa/cert-manager" \ + roles/dns.admin || + echo "WARNING: could not grant cert-manager DNS access yet. Re-run this script after the first cluster has been created." >&2 + +provider_name="projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL}/providers/${PROVIDER}" +cat < +set -euo pipefail +cd "$(dirname "$0")" +source ./lib.sh +set_pr "${1:?usage: smoke-test.sh }" + +password="$(gc secrets versions access latest --secret "$BASIC_AUTH_SECRET")" +[[ -n "${GITHUB_ACTIONS:-}" ]] && echo "::add-mask::${password}" + +status() { curl -sS -o /dev/null -m 20 -w '%{http_code}' "$@" || true; } + +failed=0 +for app in $APPS; do + url="https://${app%%:*}.${DOMAIN}${app#*:}" + ok=0 + # New DNS names and certificates take a little while to be visible everywhere. + for _ in $(seq 1 30); do + anon="$(status "$url")" + authed="$(status -L -u "${BASIC_AUTH_USER}:${password}" "$url")" + if [[ "$anon" == "401" && "$authed" =~ ^2 ]]; then + ok=1 + break + fi + sleep 10 + done + if [[ "$ok" == 1 ]]; then + echo "PASS $url (anonymous: $anon, authenticated: $authed)" + else + echo "FAIL $url (anonymous: $anon, want 401; authenticated: $authed, want 2xx)" + failed=1 + fi +done +exit "$failed" diff --git a/.github/scripts/gke/teardown.sh b/.github/scripts/gke/teardown.sh new file mode 100755 index 00000000..04cd1e65 --- /dev/null +++ b/.github/scripts/gke/teardown.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Remove everything belonging to a PR environment. Every step tolerates +# "already gone", so a teardown that died half way can simply be re-run. +# Usage: teardown.sh +set -uo pipefail +cd "$(dirname "$0")" || exit 1 +source ./lib.sh +set_pr "${1:?usage: teardown.sh }" || exit 1 + +status="$(cluster_status)" +if [[ -n "$status" ]]; then + # Release cloud resources owned by Kubernetes objects first. Deleting the + # cluster alone leaves the load balancer and the volume disks behind, billing. + if [[ "$status" == "RUNNING" || "$status" == "RECONCILING" ]] && get_credentials; then + log "Removing workloads, volumes and the load balancer" + helm uninstall "$RELEASE_NAME" -n "$RELEASE_NAMESPACE" --wait --timeout 10m || true + kubectl delete namespace "$RELEASE_NAMESPACE" --ignore-not-found --timeout=10m || true + helm uninstall traefik -n traefik --wait --timeout 10m || true + kubectl -n traefik delete svc --all --ignore-not-found --timeout=10m || true + else + log "Cluster is $status; skipping in-cluster cleanup" + fi + + log "Deleting cluster $CLUSTER_NAME" + gc container clusters delete "$CLUSTER_NAME" --zone "$GCP_ZONE" || { + echo "Cluster delete failed" >&2 + exit 1 + } +else + log "No cluster named $CLUSTER_NAME" +fi + +log "Deleting DNS records for ${DOMAIN}" +gc dns record-sets list --zone "$DNS_ZONE_NAME" --format='value(name,type)' \ + --filter="name ~ \.${DOMAIN}\.\$ AND type != NS AND type != SOA" | + while read -r name type; do + gc dns record-sets delete "$name" --type "$type" --zone "$DNS_ZONE_NAME" >/dev/null || true + done + +log "Deleting any volume disks the cluster left behind" +gc compute disks list --format='value(name,zone.basename())' \ + --filter="labels.goog-k8s-cluster-name=${CLUSTER_NAME} AND -users:*" | + while read -r name zone; do + gc compute disks delete "$name" --zone "$zone" || true + done + +# Tell anyone looking at the PR that its links no longer work. +if [[ -n "${GH_TOKEN:-}" ]]; then + ./pr-status.sh "$PR_NUMBER" removed || true +fi + +log "Teardown of PR ${PR_NUMBER} complete" diff --git a/.github/scripts/gke/traefik-values.yaml b/.github/scripts/gke/traefik-values.yaml new file mode 100644 index 00000000..0c574b30 --- /dev/null +++ b/.github/scripts/gke/traefik-values.yaml @@ -0,0 +1,24 @@ +# Traefik is the ingress controller for PR environments. +ingressClass: + enabled: true + isDefaultClass: true + +ports: + web: + http: + redirections: + entryPoint: + to: websecure + scheme: https + permanent: true + websecure: + http: + # Applied to every route, so no app can be exposed without it. + middlewares: + - traefik-basic-auth@kubernetescrd + +# Serve the PR's wildcard certificate for every host. +tlsStore: + default: + defaultCertificate: + secretName: wildcard-tls diff --git a/.github/scripts/gke/values.tmpl.yaml b/.github/scripts/gke/values.tmpl.yaml new file mode 100644 index 00000000..f6300624 --- /dev/null +++ b/.github/scripts/gke/values.tmpl.yaml @@ -0,0 +1,69 @@ +# Values for cogstack-ce-helm in a PR environment: the chart defaults plus an +# ingress per app. Rendered with envsubst; ${DOMAIN} is pr-.. +opensearch: + replicas: 1 + # GKE nodes ship vm.max_map_count=65530; OpenSearch refuses to start below 262144. + sysctlInit: + enabled: true + +opensearch-dashboards: + ingress: + enabled: true + ingressClassName: traefik + hosts: + - host: dashboards.${DOMAIN} + paths: + - path: / + backend: + serviceName: "" + servicePort: "" + +medcat-service: + ingress: + enabled: true + className: traefik + hosts: + - host: medcat.${DOMAIN} + paths: + - path: / + pathType: Prefix + +anoncat-service: + ingress: + enabled: true + className: traefik + hosts: + - host: anoncat.${DOMAIN} + paths: + - path: / + pathType: Prefix + +ocr-service: + ingress: + enabled: true + className: traefik + hosts: + - host: ocr.${DOMAIN} + paths: + - path: / + pathType: Prefix + +medcat-trainer: + env: + CSRF_TRUSTED_ORIGINS: "https://trainer.${DOMAIN}" + ingress: + enabled: true + className: traefik + hosts: + - host: trainer.${DOMAIN} + paths: + - path: / + pathType: Prefix + +cogstack-jupyterhub: + jupyterhub: + ingress: + enabled: true + ingressClassName: traefik + hosts: + - jupyter.${DOMAIN} diff --git a/.github/workflows/gke_deploy_test.yml b/.github/workflows/gke_deploy_test.yml new file mode 100644 index 00000000..db7712e1 --- /dev/null +++ b/.github/workflows/gke_deploy_test.yml @@ -0,0 +1,115 @@ +# Deploy the PR's cogstack-ce-helm chart to its own GKE cluster and leave it +# running at https://.pr-.platform.cogstack.dev for review. The +# links and a status dot per app are kept at the top of the PR description. +# +# - The first run for a PR creates the cluster; later pushes upgrade the release. +# - The cluster is removed by gke_teardown.yml (PR closed, manual, or too old). +# - Authentication to Google Cloud is GitHub OIDC; there are no stored keys. +# - Nothing here names a repository. The test runs wherever the three GCP_* +# repository variables are set; see .github/scripts/gke/README.md. +# +# This workflow deliberately has no `paths:` filter. A required check that never +# starts stays pending forever, so the `changes` job decides instead and a +# skipped deploy job counts as passing. +name: gke_deploy_test + +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: {} + +# One deploy or teardown at a time per PR. Runs queue rather than cancel, so a +# Helm upgrade is never killed half way. +concurrency: + group: gke-pr-${{ github.event.pull_request.number }} + cancel-in-progress: false + +jobs: + changes: + name: Detect deployment changes + runs-on: ubuntu-latest + # Forks and Dependabot get no OIDC token, and an unconfigured repository has nowhere to deploy. + if: >- + vars.GCP_WORKLOAD_IDENTITY_PROVIDER != '' && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.login != 'dependabot[bot]' + permissions: + pull-requests: read + outputs: + deploy: ${{ steps.filter.outputs.deploy }} + steps: + - name: Check changed files + id: filter + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + if gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/files" --paginate --jq '.[].filename' | + grep -qE '^(deployment/charts/|\.github/scripts/|\.github/workflows/gke_)'; then + echo "deploy=true" >> "$GITHUB_OUTPUT" + else + echo "deploy=false" >> "$GITHUB_OUTPUT" + fi + + deploy: + name: GKE deployment test + needs: changes + if: needs.changes.outputs.deploy == 'true' + runs-on: ubuntu-latest + timeout-minutes: 90 + permissions: + contents: read + id-token: write + pull-requests: write + env: + GCP_PROJECT_ID: ${{ vars.GCP_PROJECT_ID }} + PR_NUMBER: ${{ github.event.pull_request.number }} + MAX_AGE_HOURS: ${{ vars.GKE_PR_MAX_AGE_HOURS || '24' }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Show "deploying" on the PR + run: .github/scripts/gke/pr-status.sh "$PR_NUMBER" deploying + + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v3 + with: + workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ vars.GCP_SERVICE_ACCOUNT }} + + - name: Set up gcloud + uses: google-github-actions/setup-gcloud@v3 + with: + install_components: gke-gcloud-auth-plugin,kubectl + + - name: Set up Helm + uses: azure/setup-helm@v5.1.0 + with: + version: v3.17.0 + + - name: Install Python deps for chart scripts + run: pip install pyyaml + + - name: Create or reuse the cluster + run: .github/scripts/gke/cluster-up.sh "$PR_NUMBER" + + - name: Deploy + run: .github/scripts/gke/deploy.sh "$PR_NUMBER" + + - name: Smoke test over public HTTPS + run: .github/scripts/gke/smoke-test.sh "$PR_NUMBER" + + - name: Show links and app status on the PR + run: .github/scripts/gke/pr-status.sh "$PR_NUMBER" live + + - name: Diagnostics + if: failure() + run: | + .github/scripts/gke/pr-status.sh "$PR_NUMBER" failed || true + kubectl get nodes -o wide || true + kubectl get pods -A -o wide || true + kubectl get ingress,certificate,challenge -A || true + kubectl get events -A --sort-by=.lastTimestamp | tail -n 80 || true diff --git a/.github/workflows/gke_teardown.yml b/.github/workflows/gke_teardown.yml new file mode 100644 index 00000000..3465717c --- /dev/null +++ b/.github/workflows/gke_teardown.yml @@ -0,0 +1,112 @@ +# Remove the GKE clusters created by gke_deploy_test.yml. +# +# - PR closed or merged: that PR's environment is removed. +# - Manual run: give a PR number, or "all" to remove every environment. +# - Hourly: remove environments whose PR is closed, or older than +# GKE_PR_MAX_AGE_HOURS (repository variable, default 24). Environments that +# are kept get their status dots on the PR refreshed. +name: gke_teardown + +on: + pull_request: + types: [closed] + workflow_dispatch: + inputs: + pr: + description: PR number to tear down, or "all" + required: true + schedule: + - cron: "17 * * * *" + +permissions: {} + +jobs: + teardown: + name: Tear down PR environment + runs-on: ubuntu-latest + timeout-minutes: 45 + if: >- + vars.GCP_WORKLOAD_IDENTITY_PROVIDER != '' && ( + (github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.login != 'dependabot[bot]') || + (github.event_name == 'workflow_dispatch' && inputs.pr != 'all') + ) + # Shares the deploy workflow's group, so it waits for a running deploy. + concurrency: + group: gke-pr-${{ github.event.pull_request.number || inputs.pr }} + cancel-in-progress: false + permissions: + contents: read + id-token: write + pull-requests: write + env: + GCP_PROJECT_ID: ${{ vars.GCP_PROJECT_ID }} + PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v3 + with: + workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ vars.GCP_SERVICE_ACCOUNT }} + + - name: Set up gcloud + uses: google-github-actions/setup-gcloud@v3 + with: + install_components: gke-gcloud-auth-plugin,kubectl + + - name: Set up Helm + uses: azure/setup-helm@v5.1.0 + with: + version: v3.17.0 + + - name: Tear down + run: .github/scripts/gke/teardown.sh "$PR_NUMBER" + + reap: + name: Reap stale PR environments + runs-on: ubuntu-latest + timeout-minutes: 90 + if: >- + vars.GCP_WORKLOAD_IDENTITY_PROVIDER != '' && ( + github.event_name == 'schedule' || + (github.event_name == 'workflow_dispatch' && inputs.pr == 'all') + ) + concurrency: + group: gke-reap + cancel-in-progress: false + permissions: + contents: read + id-token: write + pull-requests: write + env: + GCP_PROJECT_ID: ${{ vars.GCP_PROJECT_ID }} + MAX_AGE_HOURS: ${{ vars.GKE_PR_MAX_AGE_HOURS || '24' }} + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - name: Checkout + uses: actions/checkout@v7 + + - name: Authenticate to Google Cloud + uses: google-github-actions/auth@v3 + with: + workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ vars.GCP_SERVICE_ACCOUNT }} + + - name: Set up gcloud + uses: google-github-actions/setup-gcloud@v3 + with: + install_components: gke-gcloud-auth-plugin,kubectl + + - name: Set up Helm + uses: azure/setup-helm@v5.1.0 + with: + version: v3.17.0 + + - name: Reap + run: .github/scripts/gke/reap.sh ${{ inputs.pr == 'all' && 'all' || '' }}