Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions .github/scripts/gke/README.md
Original file line number Diff line number Diff line change
@@ -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://<app>.pr-<number>.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 <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-<n>.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=<org id> GCP_BILLING_ACCOUNT=<billing id> \
.github/scripts/gke/setup-gcp.sh <owner>/<repo>
```

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 <new owner>/<new repo>`.
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.
34 changes: 34 additions & 0 deletions .github/scripts/gke/cluster-up.sh
Original file line number Diff line number Diff line change
@@ -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 <pr-number>
set -euo pipefail
cd "$(dirname "$0")"
source ./lib.sh
set_pr "${1:?usage: cluster-up.sh <pr-number>}"

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
72 changes: 72 additions & 0 deletions .github/scripts/gke/deploy.sh
Original file line number Diff line number Diff line change
@@ -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 <pr-number> (run cluster-up.sh first)
set -euo pipefail
cd "$(dirname "$0")"
source ./lib.sh
set_pr "${1:?usage: deploy.sh <pr-number>}"

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
57 changes: 57 additions & 0 deletions .github/scripts/gke/lib.sh
Original file line number Diff line number Diff line change
@@ -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 <name>.pr-<number>.<BASE_DOMAIN>, 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 <number>: 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; }
40 changes: 40 additions & 0 deletions .github/scripts/gke/platform.tmpl.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading