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
25 changes: 14 additions & 11 deletions .github/scripts/gke/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# 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.
Every pull request that touches the deployment is deployed to its own small GKE
cluster and left running, so reviewers can open the services in a browser. The
stack is HAPI FHIR, OpenSearch and NiFi, deployed by
`deployment/scripts/minimum_deployment.sh` and nothing else.

| | |
|---|---|
| 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>` |
| URLs | `https://<service>.pr-<number>.platform.cogstack.dev` for `hapi`, `opensearch`, `nifi` |
| Login | user `admin`, password `admin` |
| Auth to Google Cloud | GitHub OIDC (Workload Identity Federation). No keys are stored anywhere. |

## How it works
Expand All @@ -17,16 +19,17 @@ 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.
at the load balancer, obtains a wildcard certificate, then runs
`minimum_deployment.sh` from the PR with `INGRESS_DOMAIN` set and waits for
the workloads.
3. `smoke-test.sh` requests every service 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.
Every route asks for the same fixed login. Traefik passes it on, and the
OpenSearch `admin` user is given the same password, so one login opens all three.

## Teardown

Expand Down Expand Up @@ -66,6 +69,6 @@ To move the test to another repository:
## Limits

- Pull requests from forks and from Dependabot are skipped: they cannot obtain an OIDC token.
- Pull requests that change nothing under `deployment/charts/`, `.github/scripts/` or
`.github/workflows/gke_*` are not deployed; the check is skipped and counts as passing.
- Pull requests that change nothing under `deployment/charts/`, `deployment/scripts/`,
`deployment/env/`, `.github/scripts/` or `.github/workflows/gke_*` are not deployed; the check is skipped and counts as passing.
- The charts deploy published images, so this tests the charts, not unreleased application code.
37 changes: 15 additions & 22 deletions .github/scripts/gke/deploy.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/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.
# Deploy this checkout's minimum stack (HAPI FHIR, OpenSearch, NiFi) to the PR's
# cluster, behind HTTPS, with deployment/scripts/minimum_deployment.sh.
# Safe to re-run: a later push to the PR applies the manifests again.
# Usage: deploy.sh <pr-number> (run cluster-up.sh first)
set -euo pipefail
cd "$(dirname "$0")"
Expand Down Expand Up @@ -42,31 +43,23 @@ else
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")" \
--from-literal=users="${BASIC_AUTH_USER}:$(openssl passwd -apr1 "$BASIC_AUTH_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")
log "Deploying the minimum stack"
# The script takes its OpenSearch users from this file instead of the passwords
# committed in deployment/env/authentication.env.
printf 'OPENSEARCH_ADMIN_PASSWORD=%s\nOPENSEARCH_KIBANA_PASSWORD=%s\n' \
"$BASIC_AUTH_PASSWORD" "$(openssl rand -hex 16)" > "$WORK/authentication.env"
OPENSEARCH_AUTH_FILE="$WORK/authentication.env" INGRESS_DOMAIN="$DOMAIN" \
bash "$REPO_ROOT/deployment/scripts/minimum_deployment.sh"

# 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
log "Waiting for the workloads"
for workload in $(kubectl -n "$NAMESPACE" get deployment,statefulset -o name); do
kubectl -n "$NAMESPACE" rollout status "$workload" --timeout=20m
done
14 changes: 9 additions & 5 deletions .github/scripts/gke/lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,23 @@ 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"
# Traefik asks for this login on every route and passes it on, and deploy.sh
# gives the same password to the OpenSearch user of the same name. One login
# therefore opens all three services.
export BASIC_AUTH_USER="admin"
export BASIC_AUTH_PASSWORD="admin"

export RELEASE_NAME="cogstack"
export RELEASE_NAMESPACE="cogstack"
# The namespace minimum_deployment.sh deploys to.
NAMESPACE="$(source ../../../deployment/env/general.env && echo "$KUBE_NAMESPACE")"
export NAMESPACE

# 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"
export APPS="hapi:/fhir/metadata opensearch:/ nifi:/nifi/"

# set_pr <number>: derive the per-PR names.
set_pr() {
Expand Down
4 changes: 2 additions & 2 deletions .github/scripts/gke/platform.tmpl.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ metadata:
spec:
basicAuth:
secret: basic-auth-users
# Do not pass the browser's Basic credentials on to the apps.
removeHeader: true
# OpenSearch needs the credentials too; see BASIC_AUTH_USER in lib.sh.
removeHeader: false
18 changes: 6 additions & 12 deletions .github/scripts/gke/pr-status.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
# Usage: pr-status.sh <pr-number> <deploying|live|failed|removed>
# 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.
# Needs GH_TOKEN, and GH_REPO or GITHUB_REPOSITORY.
set -uo pipefail
cd "$(dirname "$0")" || exit 1
source ./lib.sh
Expand All @@ -27,12 +27,9 @@ 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)" ;;
hapi) echo "HAPI FHIR (API)" ;;
opensearch) echo "OpenSearch (API)" ;;
nifi) echo "NiFi" ;;
*) echo "$1" ;;
esac
}
Expand Down Expand Up @@ -62,15 +59,13 @@ app_title() {
echo "<sub>Updated ${now}${run_link}</sub>"
;;
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)"
code="$(curl -s -L -o /dev/null -m 20 -w '%{http_code}' -u "${BASIC_AUTH_USER}:${BASIC_AUTH_PASSWORD}" "$url" || true)"
total=$((total + 1))
if [[ "$code" =~ ^2 ]]; then
dot="🟢"
Expand All @@ -90,8 +85,7 @@ app_title() {
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 "**Sign in** with user \`${BASIC_AUTH_USER}\` and password \`${BASIC_AUTH_PASSWORD}\`."
echo
echo "<sub>Commit \`${commit}\` · checked ${now} · removed when the PR closes or after ${MAX_AGE_HOURS:-24} hours${run_link}</sub>"
;;
Expand Down
82 changes: 82 additions & 0 deletions .github/scripts/gke/raise-quotas.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Ask Google to double the quotas that limit how many PR environments the GKE
# deployment test can run at once. Run it by hand as a project owner; CI never
# runs this.
#
# Usage: raise-quotas.sh
#
# Each quota's current limit is read from the project and a request is filed for
# twice that, so every run doubles again. An increase is a request: Google
# grants it at once or reviews it first. See what happened with:
#
# gcloud quotas preferences list --project <project>
#
# Environment:
# GCP_PROJECT_ID project to change (default cogstack-platform-ci)
# GCP_ZONE zone the PR clusters run in (default europe-west2-a)
# QUOTA_CONTACT_EMAIL address Google writes to about the request; Google
# refuses an increase without one (default
# andrew@cogstack.org). Its Google account must be
# allowed to change quotas on the project.
# DRY_RUN=1 validate the requests without filing them
#
# Commands: https://docs.cloud.google.com/docs/quotas/gcloud-cli-examples
# Requirements: gcloud, jq.
set -euo pipefail

QUOTA_CONTACT_EMAIL="${QUOTA_CONTACT_EMAIL:-andrew@cogstack.org}"

PROJECT_ID="${GCP_PROJECT_ID:-cogstack-platform-ci}"
ZONE="${GCP_ZONE:-europe-west2-a}"
REGION="${ZONE%-*}"

# <service> <quota id> <dimension, or - for none>
# One PR environment is a zonal cluster of two e2-standard-4 nodes, with SSD
# boot disks and volumes and a load balancer.
QUOTAS="
compute.googleapis.com SSD-TOTAL-GB-per-project-region region=$REGION
compute.googleapis.com CPUS-ALL-REGIONS-per-project -
compute.googleapis.com IN-USE-ADDRESSES-per-project-region region=$REGION
container.googleapis.com ClustersPerZone zone=$ZONE
"

log() { echo "==> $*" >&2; }

# current_limit <service> <quota id> <dimension>: the limit set for that
# dimension, or the quota's default where the project has none of its own.
current_limit() {
local key="${3%%=*}" value="${3#*=}"
gcloud quotas info describe "$2" --service "$1" --project "$PROJECT_ID" --format json |
jq -r --arg key "$key" --arg value "$value" '
.dimensionsInfos
| (map(select(.dimensions[$key]? == $value)) + map(select((.dimensions // {}) == {})))
| .[0].details.value // empty'
}

extra=(--email "$QUOTA_CONTACT_EMAIL")
[[ -n "${DRY_RUN:-}" ]] && extra+=(--validate-only)

while read -r service quota dimension; do
[[ -n "$service" ]] || continue
limit="$(current_limit "$service" "$quota" "$dimension")"
if ! [[ "$limit" =~ ^[0-9]+$ ]]; then
echo "Could not read the current limit of $quota (got '$limit')" >&2
exit 1
fi

args=()
id="pr-environments-${quota}"
if [[ "$dimension" != "-" ]]; then
args+=(--dimensions "$dimension")
id+="-${dimension#*=}"
fi

log "$quota ${dimension/#-/}: $limit -> $((limit * 2))"
# "update --allow-missing" creates the request, or changes the one an earlier
# run filed under the same ID.
gcloud quotas preferences update "$(tr '[:upper:]' '[:lower:]' <<< "$id")" \
--service "$service" --project "$PROJECT_ID" \
--quota-id "$quota" --preferred-value "$((limit * 2))" \
--justification "More concurrent per-pull-request GKE test environments" \
--allow-missing ${args[@]+"${args[@]}"} ${extra[@]+"${extra[@]}"}
done <<< "$QUOTAS"
14 changes: 1 addition & 13 deletions .github/scripts/gke/setup-gcp.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ 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; }
Expand Down Expand Up @@ -61,7 +60,7 @@ PROJECT_NUMBER="$(gcloud projects describe "$PROJECT_ID" --format='value(project
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
cloudresourcemanager.googleapis.com

log "DNS zone for $BASE_DOMAIN"
gc dns managed-zones describe "$DNS_ZONE_NAME" >/dev/null 2>&1 ||
Expand Down Expand Up @@ -101,14 +100,6 @@ fi
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"
Expand All @@ -131,7 +122,4 @@ $(for repo in "$@"; do
echo " gh variable set GCP_WORKLOAD_IDENTITY_PROVIDER -R ${repo} -b ${provider_name}"
echo " gh variable set GCP_SERVICE_ACCOUNT -R ${repo} -b ${CI_SA}"
done)

3. Password for the PR environments (user "cogstack"):
gcloud secrets versions access latest --secret ${SECRET} --project ${PROJECT_ID}
EOF
5 changes: 1 addition & 4 deletions .github/scripts/gke/smoke-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ cd "$(dirname "$0")"
source ./lib.sh
set_pr "${1:?usage: smoke-test.sh <pr-number>}"

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
Expand All @@ -19,7 +16,7 @@ for app in $APPS; do
# 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")"
authed="$(status -L -u "${BASIC_AUTH_USER}:${BASIC_AUTH_PASSWORD}" "$url")"
if [[ "$anon" == "401" && "$authed" =~ ^2 ]]; then
ok=1
break
Expand Down
3 changes: 1 addition & 2 deletions .github/scripts/gke/teardown.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ if [[ -n "$status" ]]; then
# 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
kubectl delete namespace "$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
Expand Down
Loading