diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml new file mode 100644 index 000000000..bc5deb52a --- /dev/null +++ b/.github/workflows/cloudharness-test.yaml @@ -0,0 +1,416 @@ +# Generated with: harness-deployment . -i samples -e test -ci github +name: CloudHarness test +on: + pull_request: + branches: + - develop + workflow_dispatch: + inputs: + force_build: + description: Comma-separated image names to rebuild even if their tag already exists, or `all` + type: string + default: '' + skip_tests: + description: Set to `true` to skip the tests + type: string + default: '' +permissions: + contents: read + packages: write +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false +jobs: + prepare: + name: Prepare and build + env: + NAMESPACE: test-${{ vars.NAMESPACE_BASENAME }} + DOMAIN: ${{ vars.DOMAIN }} + REGISTRY: ${{ vars.REGISTRY }} + REGISTRY_SECRET: ${{ vars.REGISTRY_SECRET }} + IMAGE_CACHE_URL: ${{ vars.IMAGE_CACHE_URL }} + CHART_NAME: ${{ vars.CHART_NAME }} + CHART_VERSION: ${{ vars.CHART_VERSION }} + APP_VERSION: ${{ vars.APP_VERSION }} + PUBLISH_TAG: ${{ inputs.publish_tag || vars.DEPLOYMENT_PUBLISH_TAG }} + DEPLOYMENT_TAG: ${{ inputs.deployment_tag || (github.ref_type == 'tag' && github.ref_name) || '' }} + SKIP_TESTS: ${{ inputs.skip_tests || vars.SKIP_TESTS }} + FORCE_BUILD: ${{ inputs.force_build }} + outputs: + branch_tag: ${{ steps.env.outputs.branch_tag }} + short_sha: ${{ steps.env.outputs.short_sha }} + registry_host: ${{ steps.env.outputs.registry_host }} + namespace: ${{ steps.env.outputs.namespace }} + publish_tag: ${{ steps.env.outputs.publish_tag }} + deployment_tag: ${{ steps.env.outputs.deployment_tag }} + skip_tests: ${{ steps.env.outputs.skip_tests }} + force_build: ${{ steps.env.outputs.force_build }} + ACCOUNTS_TAG: ${{ steps.images.outputs.ACCOUNTS_TAG }} + ACCOUNTS_TAG_EXISTS: ${{ steps.images.outputs.ACCOUNTS_TAG_EXISTS }} + COMMON_TAG: ${{ steps.images.outputs.COMMON_TAG }} + COMMON_TAG_EXISTS: ${{ steps.images.outputs.COMMON_TAG_EXISTS }} + JUPYTERHUB_TAG: ${{ steps.images.outputs.JUPYTERHUB_TAG }} + JUPYTERHUB_TAG_EXISTS: ${{ steps.images.outputs.JUPYTERHUB_TAG_EXISTS }} + NFSSERVER_TAG: ${{ steps.images.outputs.NFSSERVER_TAG }} + NFSSERVER_TAG_EXISTS: ${{ steps.images.outputs.NFSSERVER_TAG_EXISTS }} + SAMPLES_TAG: ${{ steps.images.outputs.SAMPLES_TAG }} + SAMPLES_TAG_EXISTS: ${{ steps.images.outputs.SAMPLES_TAG_EXISTS }} + SAMPLES_INSTANCE1_TAG: ${{ steps.images.outputs.SAMPLES_INSTANCE1_TAG }} + SAMPLES_INSTANCE1_TAG_EXISTS: ${{ steps.images.outputs.SAMPLES_INSTANCE1_TAG_EXISTS }} + VOLUMEMANAGER_TAG: ${{ steps.images.outputs.VOLUMEMANAGER_TAG }} + VOLUMEMANAGER_TAG_EXISTS: ${{ steps.images.outputs.VOLUMEMANAGER_TAG_EXISTS }} + WORKFLOWS_TAG: ${{ steps.images.outputs.WORKFLOWS_TAG }} + WORKFLOWS_TAG_EXISTS: ${{ steps.images.outputs.WORKFLOWS_TAG_EXISTS }} + CLOUDHARNESS_FLASK_TAG: ${{ steps.images.outputs.CLOUDHARNESS_FLASK_TAG }} + CLOUDHARNESS_FLASK_TAG_EXISTS: ${{ steps.images.outputs.CLOUDHARNESS_FLASK_TAG_EXISTS }} + CLOUDHARNESS_BASE_TAG: ${{ steps.images.outputs.CLOUDHARNESS_BASE_TAG }} + CLOUDHARNESS_BASE_TAG_EXISTS: ${{ steps.images.outputs.CLOUDHARNESS_BASE_TAG_EXISTS }} + CLOUDHARNESS_DJANGO_TAG: ${{ steps.images.outputs.CLOUDHARNESS_DJANGO_TAG }} + CLOUDHARNESS_DJANGO_TAG_EXISTS: ${{ steps.images.outputs.CLOUDHARNESS_DJANGO_TAG_EXISTS }} + CLOUDHARNESS_FRONTEND_BUILD_TAG: ${{ steps.images.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} + CLOUDHARNESS_FRONTEND_BUILD_TAG_EXISTS: ${{ steps.images.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG_EXISTS }} + SAMPLES_PRINT_FILE_TAG: ${{ steps.images.outputs.SAMPLES_PRINT_FILE_TAG }} + SAMPLES_PRINT_FILE_TAG_EXISTS: ${{ steps.images.outputs.SAMPLES_PRINT_FILE_TAG_EXISTS }} + SAMPLES_SUM_TAG: ${{ steps.images.outputs.SAMPLES_SUM_TAG }} + SAMPLES_SUM_TAG_EXISTS: ${{ steps.images.outputs.SAMPLES_SUM_TAG_EXISTS }} + SAMPLES_SECRET_TAG: ${{ steps.images.outputs.SAMPLES_SECRET_TAG }} + SAMPLES_SECRET_TAG_EXISTS: ${{ steps.images.outputs.SAMPLES_SECRET_TAG_EXISTS }} + WORKFLOWS_NOTIFY_QUEUE_TAG: ${{ steps.images.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} + WORKFLOWS_NOTIFY_QUEUE_TAG_EXISTS: ${{ steps.images.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG_EXISTS }} + WORKFLOWS_SEND_RESULT_EVENT_TAG: ${{ steps.images.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} + WORKFLOWS_SEND_RESULT_EVENT_TAG_EXISTS: ${{ steps.images.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG_EXISTS }} + WORKFLOWS_EXTRACT_DOWNLOAD_TAG: ${{ steps.images.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} + WORKFLOWS_EXTRACT_DOWNLOAD_TAG_EXISTS: ${{ steps.images.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG_EXISTS }} + TEST_API_TAG: ${{ steps.images.outputs.TEST_API_TAG }} + TEST_API_TAG_EXISTS: ${{ steps.images.outputs.TEST_API_TAG_EXISTS }} + TEST_E2E_TAG: ${{ steps.images.outputs.TEST_E2E_TAG }} + TEST_E2E_TAG_EXISTS: ${{ steps.images.outputs.TEST_E2E_TAG_EXISTS }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: azure/setup-helm@v4 + - name: Install cloud-harness tools + run: bash ./install.sh + - name: Resolve pipeline variables + id: env + run: | + branch_tag=$(echo "$GITHUB_REF_NAME" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | cut -c1-128) + { + echo "branch_tag=$branch_tag" + echo "short_sha=${GITHUB_SHA::7}" + echo "registry_host=${REGISTRY%%/*}" + echo "namespace=$NAMESPACE" + echo "publish_tag=$PUBLISH_TAG" + echo "deployment_tag=$DEPLOYMENT_TAG" + echo "skip_tests=$SKIP_TESTS" + echo "force_build=$FORCE_BUILD" + } >> "$GITHUB_OUTPUT" + - name: Prepare helm chart + id: images + run: | + HELM_META_ARGS="" + if [ -n "$CHART_NAME" ]; then HELM_META_ARGS="$HELM_META_ARGS --name $CHART_NAME"; fi + if [ -n "$CHART_VERSION" ]; then HELM_META_ARGS="$HELM_META_ARGS --chart-version $CHART_VERSION"; fi + APP_VERSION_RESOLVED="${APP_VERSION:-$DEPLOYMENT_TAG}" + if [ -n "$APP_VERSION_RESOLVED" ]; then HELM_META_ARGS="$HELM_META_ARGS --app-version $APP_VERSION_RESOLVED"; fi + TAG_ARG="" + if [ -n "$DEPLOYMENT_TAG" ]; then TAG_ARG="-t $DEPLOYMENT_TAG"; fi + harness-deployment . -d "$DOMAIN" -r "$REGISTRY" -rsn "$REGISTRY_SECRET" -n "$NAMESPACE" -e test $TAG_ARG --write-env --write-skaffold-ci --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS -i samples + cat deployment/.env >> "$GITHUB_OUTPUT" + - name: View helm chart + run: helm template ./deployment/helm --debug -n "$NAMESPACE" + - name: Share the deployment with the other jobs + uses: actions/upload-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + include-hidden-files: true + if-no-files-found: error + overwrite: true + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ steps.env.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Install skaffold + env: + SKAFFOLD_VERSION: v2.25.0 + SKAFFOLD_SHA256: 42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20 + run: | + mkdir -p "$RUNNER_TEMP/bin" + curl -fsSLo "$RUNNER_TEMP/bin/skaffold" "https://github.com/GoogleContainerTools/skaffold/releases/download/$SKAFFOLD_VERSION/skaffold-linux-amd64" + echo "$SKAFFOLD_SHA256 $RUNNER_TEMP/bin/skaffold" | sha256sum -c - + chmod +x "$RUNNER_TEMP/bin/skaffold" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + - name: Build and push the images + env: + NOCACHE: ${{ github.run_id }} + CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} + run: skaffold build --filename deployment/skaffold-ci.yaml --cache-artifacts=false --update-check=false --interactive=false + - name: Run the unit tests + run: skaffold test --filename deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json --update-check=false --interactive=false + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + deploy: + name: Deploy + needs: + - prepare + environment: test + steps: + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: azure/setup-helm@v4 + - uses: azure/setup-kubectl@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + if [ -n "$KUBECONFIG_DATA" ]; then + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + elif [ -n "$KUBERNETES_SERVICE_HOST" ] || kubectl config current-context > /dev/null 2>&1; then + echo "Using the runner's ambient cluster access" + else + echo "::error::No cluster access: set the KUBECONFIG secret (base64 kubeconfig) where this job can read it, or run on a runner inside the target cluster" + exit 1 + fi + - name: Write the secret values + env: + ASECRET: ${{ secrets.ASECRET }} + run: | + set -e + secrets_dir="$HOME/.cloudharness/secrets" + mkdir -p "$secrets_dir" + chmod 700 "$secrets_dir" + printf '%s' "$ASECRET" > "$secrets_dir/ASECRET" + - name: Install skaffold + env: + SKAFFOLD_VERSION: v2.25.0 + SKAFFOLD_SHA256: 42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20 + run: | + mkdir -p "$RUNNER_TEMP/bin" + curl -fsSLo "$RUNNER_TEMP/bin/skaffold" "https://github.com/GoogleContainerTools/skaffold/releases/download/$SKAFFOLD_VERSION/skaffold-linux-amd64" + echo "$SKAFFOLD_SHA256 $RUNNER_TEMP/bin/skaffold" | sha256sum -c - + chmod +x "$RUNNER_TEMP/bin/skaffold" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + - name: Deploy and wait for the rollout + run: skaffold deploy --filename deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json --label skaffold.dev/run-id=cloudharness --update-check=false --interactive=false + if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + tests-api-common: + name: API tests common + needs: + - prepare + - deploy + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.deploy.result == 'success') }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run common API tests + env: + APP_URL: https://common.${{ vars.DOMAIN }}/api + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} + CH_TEST_COMMANDS: | + set -e + st --pre-run cloudharness_test.apitest_init run api/openapi.yaml --base-url https://common.${{ vars.DOMAIN }}/api -c all + run: |- + docker run --rm \ + -e APP_URL \ + -v "$GITHUB_WORKSPACE/applications/common:/home/test" \ + -v "$GITHUB_WORKSPACE/deployment/helm/values.yaml:/opt/cloudharness/resources/allvalues.yaml" \ + -w /home/test \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + tests-api-samples: + name: API tests samples + needs: + - prepare + - deploy + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.deploy.result == 'success') }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run samples API tests + env: + APP_URL: https://www.${{ vars.DOMAIN }}/api + USERNAME: sample@testuser.com + PASSWORD: test + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} + CH_TEST_COMMANDS: | + set -e + st --pre-run cloudharness_test.apitest_init run api/openapi.yaml --base-url https://www.${{ vars.DOMAIN }}/api -c all --skip-deprecated-operations --exclude-operation-id=submit_sync --exclude-operation-id=submit_sync_with_results --exclude-operation-id=error --hypothesis-suppress-health-check=too_slow --hypothesis-deadline=180000 --request-timeout=180000 --hypothesis-max-examples=2 --show-trace --exclude-checks=ignored_auth + pytest -v test/api + run: |- + docker run --rm \ + -e APP_URL \ + -e USERNAME \ + -e PASSWORD \ + -v "$GITHUB_WORKSPACE/applications/samples:/home/test" \ + -v "$GITHUB_WORKSPACE/deployment/helm/values.yaml:/opt/cloudharness/resources/allvalues.yaml" \ + -w /home/test \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + tests-api-workflows: + name: API tests workflows + needs: + - prepare + - deploy + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.deploy.result == 'success') }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run workflows API tests + env: + APP_URL: https://workflows.${{ vars.DOMAIN }}/api + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} + CH_TEST_COMMANDS: | + set -e + st --pre-run cloudharness_test.apitest_init run api/openapi.yaml --base-url https://workflows.${{ vars.DOMAIN }}/api -c all + run: |- + docker run --rm \ + -e APP_URL \ + -v "$GITHUB_WORKSPACE/applications/workflows:/home/test" \ + -v "$GITHUB_WORKSPACE/deployment/helm/values.yaml:/opt/cloudharness/resources/allvalues.yaml" \ + -w /home/test \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + tests-e2e-jupyterhub: + name: E2E tests jupyterhub + needs: + - prepare + - deploy + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.deploy.result == 'success') }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run jupyterhub E2E tests + env: + APP_URL: https://hub.${{ vars.DOMAIN }} + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} + CH_TEST_COMMANDS: | + set -e + npx puppeteer browsers install chrome + yarn test + run: |- + docker run --rm \ + -e APP_URL \ + -v "$GITHUB_WORKSPACE/applications/jupyterhub/test/e2e:/home/test/__tests__/jupyterhub" \ + -w /home/test \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + tests-e2e-samples: + name: E2E tests samples + needs: + - prepare + - deploy + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.deploy.result == 'success') }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run samples E2E tests + env: + APP_URL: https://www.${{ vars.DOMAIN }} + USERNAME: sample@testuser.com + PASSWORD: test + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} + CH_TEST_COMMANDS: | + set -e + npx puppeteer browsers install chrome + yarn test + run: |- + docker run --rm \ + -e APP_URL \ + -e USERNAME \ + -e PASSWORD \ + -v "$GITHUB_WORKSPACE/applications/samples/test/e2e:/home/test/__tests__/samples" \ + -w /home/test \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} + cleanup: + name: Delete the test deployment + needs: + - prepare + - deploy + - tests-api-common + - tests-api-samples + - tests-api-workflows + - tests-e2e-jupyterhub + - tests-e2e-samples + if: ${{ always() && needs.deploy.result == 'success' }} + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + WAIT_ON_FAIL: ${{ vars.WAIT_ON_FAIL || '0' }} + FAILED: ${{ contains(needs.*.result, 'failure') }} + steps: + - uses: azure/setup-helm@v4 + - uses: azure/setup-kubectl@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + if [ -n "$KUBECONFIG_DATA" ]; then + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + elif [ -n "$KUBERNETES_SERVICE_HOST" ] || kubectl config current-context > /dev/null 2>&1; then + echo "Using the runner's ambient cluster access" + else + echo "::error::No cluster access: set the KUBECONFIG secret (base64 kubeconfig) where this job can read it, or run on a runner inside the target cluster" + exit 1 + fi + - name: Uninstall the release and delete the namespace + run: | + if [ "$FAILED" = "true" ] && [ "$WAIT_ON_FAIL" != "0" ]; then + echo "Tests failed: keeping the deployment for $WAIT_ON_FAIL minutes for inspection" + sleep $((WAIT_ON_FAIL * 60)) + fi + helm uninstall "$NAMESPACE" -n "$NAMESPACE" || true + kubectl delete namespace "$NAMESPACE" --ignore-not-found + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} diff --git a/.gitignore b/.gitignore index d79f6d7f8..b8629105b 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,8 @@ node_modules *.DS_Store deployment/helm deployment/compose +deployment/skaffold-ci.yaml +deployment/skaffold-images.json /docker-compose.yaml *.egg-info *.idea diff --git a/CLAUDE.md b/CLAUDE.md index cb72fb9dd..9ecfc0775 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,8 +58,8 @@ Always activate `conda activate ch` before any backend command. ## Key Scripts -- `harness-generate` — generate code -- `harness-deployment` — generate deployment files (Helm charts, CI/CD files, etc.) +- `harness-generate` — generate code; `harness-generate ci-cd` generates the CI/CD pipelines +- `harness-deployment` — generate deployment files (Helm charts, Skaffold, etc.) - `harness-application` — generate application code (e.g. Django apps) - `harness-migrate` — migration helper - `ch_cli_tools` — Python package for deployment and other tools diff --git a/deployment-configuration/README.md b/deployment-configuration/README.md index 83ae83b8e..9b379bf07 100644 --- a/deployment-configuration/README.md +++ b/deployment-configuration/README.md @@ -10,8 +10,14 @@ Those files are used by the script `harness-deployment` script. custom `values.yaml` to your application over changing this file. - `values-template-[env].yaml` / `value-template-[env].yaml`: environment specific overrides of the above, loaded when the environment is selected with `harness-deployment -e [env]`. See [environments](../docs/build-deploy/environments.md) -- `codefresh-template-[dev|prod].yaml`: base for `codefresh/codefresh-[dev|prod].yaml`. Modify this file if you want to - change the build steps inside codefresh +- `codefresh-template-[dev|prod].yaml`: base for `deployment/ci--[NAME]--[dev|prod].yaml`, generated with + `harness-generate ci-cd`. Modify this file if you want to change the build steps inside codefresh - `codefresh-build-template.yaml`: base for a single build entry in `codefresh.yaml` - `codefresh-publish-template.yaml`: base for a single publish (image tagging) entry in `codefresh.yaml` +- `github-template.yaml`: base for the GitHub Actions workflows (`.github/workflows/ci--[NAME]--[env].yaml`), + generated with `harness-generate ci-cd`: the job prototypes expanded per image/app and the shared steps +- `github-template-[dev|stage|prod|test].yaml`: per-environment workflow name, triggers and deltas, merged over + the base template. Override any part from the same files in your project's `deployment-configuration/`: a + project gets a pipeline only for the environments it has a `codefresh-template-[env].yaml` or + `github-template-[env].yaml` for (an empty file inherits everything) diff --git a/deployment-configuration/codefresh-template-prod.yaml b/deployment-configuration/codefresh-template-prod.yaml index e2f3d0b82..705b9f9b1 100644 --- a/deployment-configuration/codefresh-template-prod.yaml +++ b/deployment-configuration/codefresh-template-prod.yaml @@ -34,7 +34,7 @@ steps: - export HELM_CHART_VERSION_ARG="$( [ -n "${{CHART_VERSION}}" ] && printf -- "--chart-version %s" "${{CHART_VERSION}}" )" - export HELM_APP_VERSION_ARG="$( APP_VERSION_RESOLVED="${{APP_VERSION}}"; [ -z "$APP_VERSION_RESOLVED" ] && APP_VERSION_RESOLVED="${{DEPLOYMENT_TAG}}"; [ -n "$APP_VERSION_RESOLVED" ] && printf -- "--app-version %s" "$APP_VERSION_RESOLVED" )" - export HELM_META_ARGS="$HELM_NAME_ARG $HELM_CHART_VERSION_ARG $HELM_APP_VERSION_ARG" - - harness-deployment $PATHS -t ${{DEPLOYMENT_TAG}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn '${{REGISTRY_SECRET}}' -n ${{NAMESPACE}} -e $ENV --no-cd $HELM_META_ARGS $PARAMS + - harness-deployment $PATHS -t ${{DEPLOYMENT_TAG}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn '${{REGISTRY_SECRET}}' -n ${{NAMESPACE}} -e $ENV $HELM_META_ARGS $PARAMS prepare_deployment_view: commands: - "helm template ./deployment/helm --debug -n ${{NAMESPACE}}" diff --git a/deployment-configuration/codefresh-template-stage.yaml b/deployment-configuration/codefresh-template-stage.yaml index d812a79f7..f773c8e59 100644 --- a/deployment-configuration/codefresh-template-stage.yaml +++ b/deployment-configuration/codefresh-template-stage.yaml @@ -37,7 +37,7 @@ steps: - export HELM_CHART_VERSION_ARG="$( [ -n "${{CHART_VERSION}}" ] && printf -- "--chart-version %s" "${{CHART_VERSION}}" )" - export HELM_APP_VERSION_ARG="$( APP_VERSION_RESOLVED="${{APP_VERSION}}"; [ -z "$APP_VERSION_RESOLVED" ] && APP_VERSION_RESOLVED="${{DEPLOYMENT_TAG}}"; [ -n "$APP_VERSION_RESOLVED" ] && printf -- "--app-version %s" "$APP_VERSION_RESOLVED" )" - export HELM_META_ARGS="$HELM_NAME_ARG $HELM_CHART_VERSION_ARG $HELM_APP_VERSION_ARG" - - harness-deployment $PATHS -t ${{DEPLOYMENT_TAG}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn ${{REGISTRY_SECRET}} -n ${{NAMESPACE}} -e $ENV --no-cd $HELM_META_ARGS $PARAMS + - harness-deployment $PATHS -t ${{DEPLOYMENT_TAG}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn ${{REGISTRY_SECRET}} -n ${{NAMESPACE}} -e $ENV $HELM_META_ARGS $PARAMS prepare_deployment_view: commands: - "helm template ./deployment/helm --debug -n ${{NAMESPACE}}" diff --git a/deployment-configuration/codefresh-template-test.yaml b/deployment-configuration/codefresh-template-test.yaml index bc34913cd..5f3a3ef84 100644 --- a/deployment-configuration/codefresh-template-test.yaml +++ b/deployment-configuration/codefresh-template-test.yaml @@ -37,7 +37,7 @@ steps: - export HELM_CHART_VERSION_ARG="$( [ -n "${{CHART_VERSION}}" ] && printf -- "--chart-version %s" "${{CHART_VERSION}}" )" - export HELM_APP_VERSION_ARG="$( APP_VERSION_RESOLVED="${{APP_VERSION}}"; [ -z "$APP_VERSION_RESOLVED" ] && APP_VERSION_RESOLVED="${{DEPLOYMENT_TAG}}"; [ -n "$APP_VERSION_RESOLVED" ] && printf -- "--app-version %s" "$APP_VERSION_RESOLVED" )" - export HELM_META_ARGS="$HELM_NAME_ARG $HELM_CHART_VERSION_ARG $HELM_APP_VERSION_ARG" - - harness-deployment $PATHS -n test-${{NAMESPACE_BASENAME}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn ${{REGISTRY_SECRET}} -e $ENV --write-env --cache-url '${{IMAGE_CACHE_URL}}' -N $HELM_META_ARGS $PARAMS + - harness-deployment $PATHS -n test-${{NAMESPACE_BASENAME}} -d ${{DOMAIN}} -r ${{REGISTRY}} -rsn ${{REGISTRY_SECRET}} -e $ENV --write-env --cache-url '${{IMAGE_CACHE_URL}}' $HELM_META_ARGS $PARAMS - cat deployment/.env >> ${{CF_VOLUME_PATH}}/env_vars_to_export - cat ${{CF_VOLUME_PATH}}/env_vars_to_export prepare_deployment_view: diff --git a/deployment-configuration/github-template-dev.yaml b/deployment-configuration/github-template-dev.yaml new file mode 100644 index 000000000..a0a7b4271 --- /dev/null +++ b/deployment-configuration/github-template-dev.yaml @@ -0,0 +1,104 @@ +# Development pipeline: build, unit tests, deployment and API/E2E tests. Its runs are promoted with the +# workflow in `cloudharness.promote`, written next to this one as cloudharness-promote.yaml. +name: CloudHarness $ENV +on: + push: + branches: [develop] + workflow_dispatch: + inputs: + force_build: + description: Comma-separated image names to rebuild even if their tag already exists, or `all` + type: string + default: "" + skip_tests: + description: Set to `true` to skip the tests + type: string + default: "" +cloudharness: + # Promotes the images of one run of this workflow, started by hand after approval (protect the `publish` + # environment with required reviewers): every image the run deployed - deployment/skaffold-images.json in + # its cloudharness-deployment artifact - gets the given tag (and `latest` where it is published), then the + # run's commit gets the git tag, which starts the staging pipeline. A tag pushed with the workflow's own + # token starts no workflow: set the GH_PAT secret (contents: write) for that. + promote: + name: CloudHarness promote + on: + workflow_dispatch: + inputs: + tag: + description: Tag to give the images and the repository + type: string + required: true + run_id: + description: Run of $WORKFLOW whose images to promote (default its latest successful run on the default branch) + type: string + default: "" + permissions: + contents: write + actions: read + jobs: + promote: + name: Promote the images + environment: publish + env: + TAG: ${{ inputs.tag }} + REGISTRY: ${{ vars.REGISTRY }} + REGISTRY_PUBLISH_URL: ${{ vars.REGISTRY_PUBLISH_URL }} + steps: + - name: Find the run to promote + id: run + env: + GH_TOKEN: ${{ github.token }} + RUN_ID: ${{ inputs.run_id }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + if [ -z "$RUN_ID" ]; then + RUN_ID=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow $WORKFLOW --branch "$DEFAULT_BRANCH" --status success --limit 1 --json databaseId --jq '.[0].databaseId') + fi + if [ -z "$RUN_ID" ]; then + echo "::error::No successful run of $WORKFLOW to promote" + exit 1 + fi + sha=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$RUN_ID" --jq .head_sha) + echo "id=$RUN_ID" >> "$GITHUB_OUTPUT" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + echo "Promoting run $RUN_ID (commit $sha) as $TAG" >> "$GITHUB_STEP_SUMMARY" + - name: Download the images of the run + uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + run-id: ${{ steps.run.outputs.id }} + github-token: ${{ github.token }} + - uses: docker/login-action@v3 + with: + registry: ${{ vars.REGISTRY }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Log in to the publish registry + if: ${{ vars.REGISTRY_PUBLISH_URL != '' }} + env: + USERNAME: ${{ secrets.REGISTRY_PUBLISH_USERNAME || secrets.REGISTRY_USERNAME }} + PASSWORD: ${{ secrets.REGISTRY_PUBLISH_PASSWORD || secrets.REGISTRY_PASSWORD }} + run: echo "$PASSWORD" | docker login "${REGISTRY_PUBLISH_URL%%/*}" -u "$USERNAME" --password-stdin + # each image keeps its content-hash tag and gets the new one in the registry the pipelines deploy + # from; the publish registry (REGISTRY_PUBLISH_URL, default the same) also gets `latest` + - name: Tag the images + run: | + set -e + target="${REGISTRY_PUBLISH_URL:-$REGISTRY}" + jq -r '.builds[] | "\(.imageName) \(.tag)"' deployment/skaffold-images.json | while read -r image source; do + published="$target/${image#"$REGISTRY"/}" + tags="-t $image:$TAG -t $published:latest" + if [ "$published" != "$image" ]; then tags="$tags -t $published:$TAG"; fi + echo "$source -> $tags" + docker buildx imagetools create $tags "$source" + done + - uses: actions/checkout@v4 + with: + ref: ${{ steps.run.outputs.sha }} + token: ${{ secrets.GH_PAT || github.token }} + - name: Tag the repository + run: | + git tag "$TAG" + git push origin "refs/tags/$TAG" diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml new file mode 100644 index 000000000..eb830db12 --- /dev/null +++ b/deployment-configuration/github-template-prod.yaml @@ -0,0 +1,18 @@ +# Production pipeline: deploys the images promoted with the given tag, nothing else. +# Protect the `prod` environment with required reviewers to get an approval step. +name: CloudHarness $ENV +on: + workflow_dispatch: + inputs: + deployment_tag: + description: Tag of the images to deploy (a tag given by the promote workflow) + type: string + required: true +# deploys the promoted images: builds nothing +cloudharness: + build: null +jobs: + prepare: + name: Prepare helm chart + tests-api: null + tests-e2e: null diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml new file mode 100644 index 000000000..e2287f466 --- /dev/null +++ b/deployment-configuration/github-template-stage.yaml @@ -0,0 +1,22 @@ +# Staging pipeline: started by a git tag (the promote workflow pushes one), deploys the images with that tag +# and runs the API/E2E tests. It can also be started by hand for a tag. +name: CloudHarness $ENV +on: + push: + tags: ["*"] + workflow_dispatch: + inputs: + deployment_tag: + description: Tag of the images to deploy (a tag given by the promote workflow) + type: string + required: true + skip_tests: + description: Set to `true` to skip the tests + type: string + default: "" +# deploys the promoted images: builds nothing +cloudharness: + build: null +jobs: + prepare: + name: Prepare helm chart diff --git a/deployment-configuration/github-template-test.yaml b/deployment-configuration/github-template-test.yaml new file mode 100644 index 000000000..6422f7c59 --- /dev/null +++ b/deployment-configuration/github-template-test.yaml @@ -0,0 +1,43 @@ +# Testing pipeline: deploys the current code in its own namespace, runs every test and removes the deployment. +name: CloudHarness $ENV +on: + pull_request: + branches: [develop] + workflow_dispatch: + inputs: + force_build: + description: Comma-separated image names to rebuild even if their tag already exists, or `all` + type: string + default: "" + skip_tests: + description: Set to `true` to skip the tests + type: string + default: "" +jobs: + prepare: + env: + NAMESPACE: test-${{ vars.NAMESPACE_BASENAME }} + # Deleting the deployment waits for approval: protect the `cleanup` environment with required reviewers + # (no deployment is recorded for it). The `test` environment needs none, so the deployment does not wait. + cleanup: + name: Delete the test deployment + needs: [prepare, deploy, tests-api, tests-e2e] + if: ${{ always() && needs.deploy.result == 'success' }} + environment: + name: cleanup + deployment: false + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + WAIT_ON_FAIL: ${{ vars.WAIT_ON_FAIL || '0' }} + FAILED: ${{ contains(needs.*.result, 'failure') }} + steps: + - uses: azure/setup-helm@v4 + - $KUBE_AUTH + - name: Uninstall the release and delete the namespace + run: | + if [ "$FAILED" = "true" ] && [ "$WAIT_ON_FAIL" != "0" ]; then + echo "Tests failed: keeping the deployment for $WAIT_ON_FAIL minutes for inspection" + sleep $((WAIT_ON_FAIL * 60)) + fi + helm uninstall "$NAMESPACE" -n "$NAMESPACE" || true + kubectl delete namespace "$NAMESPACE" --ignore-not-found diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml new file mode 100644 index 000000000..cd110b0aa --- /dev/null +++ b/deployment-configuration/github-template.yaml @@ -0,0 +1,204 @@ +# Base of the GitHub Actions workflows generated by `harness-generate ci-cd` (.github/workflows/ci----.yaml) +# github-template-.yaml adds the workflow name, the triggers and the per-environment deltas; a project +# overrides any part from its own deployment-configuration/github-template[-].yaml (dicts merge key by +# key, lists are replaced, `null` removes a job). +# `tests-api` and `tests-e2e` are prototypes, expanded into one job per app ($CH_NAME, $CH_IMAGE and $CH_TAG +# stand for the app's image). A `$...` item in a steps list is a fragment the generator fills in. +# Every job without `runs-on` runs on the runner named by the CH_GITHUB_RUNNER repository/organization variable +# (prepare, when it builds the images: CH_GITHUB_BUILD_RUNNER first), falling back to the runner given at +# generation time (CH_GITHUB_RUNNER environment variable, default ubuntu-latest). +permissions: + contents: read + packages: write +# Generator-only settings, never part of the workflow. +cloudharness: + # The skaffold the build and deploy steps use (a YAML anchor, repeated where it is aliased). + install_skaffold: &install-skaffold + name: Install skaffold + env: + SKAFFOLD_VERSION: v2.25.0 + SKAFFOLD_SHA256: 42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20 + run: | + mkdir -p "$RUNNER_TEMP/bin" + curl -fsSLo "$RUNNER_TEMP/bin/skaffold" "https://github.com/GoogleContainerTools/skaffold/releases/download/$SKAFFOLD_VERSION/skaffold-linux-amd64" + echo "$SKAFFOLD_SHA256 $RUNNER_TEMP/bin/skaffold" | sha256sum -c - + chmod +x "$RUNNER_TEMP/bin/skaffold" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + # Steps building and pushing the images whose tag is not in the registry yet, then running the unit tests, + # inserted where prepare says `- $BUILD_STEPS`. prepare's harness-deployment lists just those images in + # deployment/skaffold-ci.yaml, each one a `docker buildx build --push` with its registry cache + # (:buildcache, mode=max): skaffold runs them in parallel, a base image before the images built on it. + # A bigger build runner (CH_GITHUB_BUILD_RUNNER) means more parallel builds. The same file's `test` section + # holds every app's unit tests, run by `skaffold test` against every image of the deployment + # (deployment/skaffold-images.json), rebuilt or not. null builds and tests nothing (stage and prod deploy + # promoted images). + build: + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ steps.env.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - *install-skaffold + - name: Build and push the images + env: + NOCACHE: ${{ github.run_id }} + CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} + run: skaffold build --filename deployment/skaffold-ci.yaml --cache-artifacts=false --update-check=false --interactive=false + - name: Run the unit tests + run: skaffold test --filename deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json --update-check=false --interactive=false + # Steps giving kubectl and helm access to the cluster, inserted where a job says `- $KUBE_AUTH`. + # Default: a kubeconfig from the KUBECONFIG secret (base64) when it is set, otherwise the ambient + # configuration (the service account of a runner that lives in the target cluster). Replace the list + # for another method, e.g. google-github-actions/auth + get-gke-credentials with workload identity + # (which also needs `permissions: {contents: read, packages: write, id-token: write}` on the jobs + # using it: id-token is deliberately not granted to the whole workflow). + kube_auth: + - uses: azure/setup-kubectl@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + if [ -n "$KUBECONFIG_DATA" ]; then + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + elif [ -n "$KUBERNETES_SERVICE_HOST" ] || kubectl config current-context > /dev/null 2>&1; then + echo "Using the runner's ambient cluster access" + else + echo "::error::No cluster access: set the KUBECONFIG secret (base64 kubeconfig) where this job can read it, or run on a runner inside the target cluster" + exit 1 + fi +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false +jobs: + # prepare also builds the images and runs the unit tests ($BUILD_STEPS): a re-run asks the registry again, so + # after a failure it only builds what the failed attempt did not push, and tests everything again. + prepare: + name: Prepare and build + env: + NAMESPACE: ${{ vars.NAMESPACE }} + DOMAIN: ${{ vars.DOMAIN }} + REGISTRY: ${{ vars.REGISTRY }} + REGISTRY_SECRET: ${{ vars.REGISTRY_SECRET }} + IMAGE_CACHE_URL: ${{ vars.IMAGE_CACHE_URL }} + CHART_NAME: ${{ vars.CHART_NAME }} + CHART_VERSION: ${{ vars.CHART_VERSION }} + APP_VERSION: ${{ vars.APP_VERSION }} + DEPLOYMENT_TAG: ${{ inputs.deployment_tag || (github.ref_type == 'tag' && github.ref_name) || '' }} + SKIP_TESTS: ${{ inputs.skip_tests || vars.SKIP_TESTS }} + FORCE_BUILD: ${{ inputs.force_build }} + outputs: + branch_tag: ${{ steps.env.outputs.branch_tag }} + short_sha: ${{ steps.env.outputs.short_sha }} + registry_host: ${{ steps.env.outputs.registry_host }} + namespace: ${{ steps.env.outputs.namespace }} + deployment_tag: ${{ steps.env.outputs.deployment_tag }} + skip_tests: ${{ steps.env.outputs.skip_tests }} + force_build: ${{ steps.env.outputs.force_build }} + steps: + - uses: actions/checkout@v4 + - $CLONE_CLOUDHARNESS + - $GIT_CLONES + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: azure/setup-helm@v4 + - name: Install cloud-harness tools + run: bash $CLOUDHARNESS_PATH/install.sh + - name: Resolve pipeline variables + id: env + run: | + branch_tag=$(echo "$GITHUB_REF_NAME" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | cut -c1-128) + { + echo "branch_tag=$branch_tag" + echo "short_sha=${GITHUB_SHA::7}" + echo "registry_host=${REGISTRY%%/*}" + echo "namespace=$NAMESPACE" + echo "deployment_tag=$DEPLOYMENT_TAG" + echo "skip_tests=$SKIP_TESTS" + echo "force_build=$FORCE_BUILD" + } >> "$GITHUB_OUTPUT" + - name: Prepare helm chart + id: images + run: | + HELM_META_ARGS="" + if [ -n "$CHART_NAME" ]; then HELM_META_ARGS="$HELM_META_ARGS --name $CHART_NAME"; fi + if [ -n "$CHART_VERSION" ]; then HELM_META_ARGS="$HELM_META_ARGS --chart-version $CHART_VERSION"; fi + APP_VERSION_RESOLVED="${APP_VERSION:-$DEPLOYMENT_TAG}" + if [ -n "$APP_VERSION_RESOLVED" ]; then HELM_META_ARGS="$HELM_META_ARGS --app-version $APP_VERSION_RESOLVED"; fi + TAG_ARG="" + if [ -n "$DEPLOYMENT_TAG" ]; then TAG_ARG="-t $DEPLOYMENT_TAG"; fi + harness-deployment $PATHS -d "$DOMAIN" -r "$REGISTRY" -rsn "$REGISTRY_SECRET" -n "$NAMESPACE" -e $ENV $TAG_ARG --write-env --write-skaffold-ci --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" $HELM_META_ARGS $PARAMS + cat deployment/.env >> "$GITHUB_OUTPUT" + - name: View helm chart + run: helm template ./deployment/helm --debug -n "$NAMESPACE" + - name: Share the deployment with the other jobs + uses: actions/upload-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + include-hidden-files: true + if-no-files-found: error + # a re-run of prepare (e.g. after a failed build) uploads it again + overwrite: true + - $BUILD_STEPS + # deploy targets the GitHub environment named after the CloudHarness environment: its protection rules + # (required reviewers on stage/prod, none on dev/test) approve the deployment. The cluster credentials + # come from repository/organization secrets (an environment secret of the same name overrides them). + # skaffold deploy installs or upgrades the helm chart prepare wrote (deployment/skaffold-ci.yaml) and waits + # until its deployments and statefulsets are rolled out. It labels every pod template with its run id: a + # constant one keeps the apps whose image did not change from restarting. + deploy: + name: Deploy + needs: [prepare] + environment: $ENV + steps: + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: azure/setup-helm@v4 + - $KUBE_AUTH + - $HELM_SECRETS_STEPS + - *install-skaffold + - name: Deploy and wait for the rollout + run: skaffold deploy --filename deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json --label skaffold.dev/run-id=cloudharness --update-check=false --interactive=false + tests-api: + name: API tests + needs: [prepare, deploy] + if: ${{ needs.prepare.outputs.skip_tests != 'true' }} + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - $CLONE_CLOUDHARNESS + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: deployment + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - $TEST_STEPS + tests-e2e: + name: End to end tests + needs: [prepare, deploy] + if: ${{ needs.prepare.outputs.skip_tests != 'true' }} + commands: + - npx puppeteer browsers install chrome + - yarn test + steps: + - name: Give the certificates time to settle + run: sleep 60 + - uses: actions/checkout@v4 + - $CLONE_CLOUDHARNESS + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - $TEST_STEPS diff --git a/deployment-configuration/skaffold-template.yaml b/deployment-configuration/skaffold-template.yaml index 2b2a3a25f..aed8c06fb 100644 --- a/deployment-configuration/skaffold-template.yaml +++ b/deployment-configuration/skaffold-template.yaml @@ -1,4 +1,4 @@ -apiVersion: skaffold/v2beta28 +apiVersion: skaffold/v4beta14 kind: Config build: tagPolicy: {} @@ -21,8 +21,6 @@ deploy: #valuesFiles: #- helm-skaffold-values.yaml skipBuildDependencies: true # Skip helm dep build - artifactOverrides: - apps: {} overrides: apps: {} test: [] \ No newline at end of file diff --git a/docs/applications/harness-generate.md b/docs/applications/harness-generate.md index c065cbe93..847f12c15 100644 --- a/docs/applications/harness-generate.md +++ b/docs/applications/harness-generate.md @@ -30,6 +30,7 @@ harness-generate [mode] [-h] [-i] [-a APP_NAME] [-cn CLIENT_NAME] [-t | -p] [pat - **clients** – Generates only client libraries. - **servers** – Generates only server stubs. - **models** – Regenerates only model libraries. +- **ci-cd** – Generates the CI/CD pipelines (Codefresh, GitHub Actions), see [below](#generate-the-cicd-pipelines). ## harness-generate Examples @@ -81,9 +82,33 @@ harness-generate all -p harness-generate all -i ``` +### Generate the CI/CD pipelines + +```sh +harness-generate ci-cd [paths ...] [-i APP ...] [-ex APP ...] [-e ENV ...] [--name NAME] [-u] [-rsn SECRET] +``` + +`paths` are the deployment layers, lowest priority first, as `harness-deployment` takes them (omit them to use +the subdirectories with a `deployment-configuration`, then the current directory). A pipeline is generated for +each environment with a template in the `deployment-configuration` of the last path: + +- `codefresh-template-[ENV].yaml` → `deployment/ci--[NAME]--[ENV].yaml` +- `github-template-[ENV].yaml` → `.github/workflows/ci--[NAME]--[ENV].yaml` (and + `.github/workflows/ci--[NAME]--promote.yaml` when the template has a `cloudharness.promote` workflow) + +The templates of the other layers (e.g. cloud-harness) are merged in, but a pipeline is only generated for an +environment the project has a template file for, even an empty one. `[NAME]` is `--name`, by default the +included applications joined with dashes (`all` when there is no `-i`). `-e` restricts the environments; combine +several with dashes (`-e research-dev`), each needing its template. For example, from the cloud-harness root: + +```sh +harness-generate ci-cd . -i samples +``` + ## harness-generate Notes -- The tool scans the `./applications` directory for available applications. +- The tool scans the `./applications` directory for available applications (`ci-cd` takes its own arguments, + `-i` there selects the applications to deploy). - If `path` is provided, `-a/--app-name` is ignored. - The `models` mode is a special flag used when regenerating only model libraries (deprecated). - The tool supports interactive mode to confirm before generating clients. diff --git a/docs/build-deploy/README.md b/docs/build-deploy/README.md index c54a233b0..909726dea 100644 --- a/docs/build-deploy/README.md +++ b/docs/build-deploy/README.md @@ -48,7 +48,8 @@ CI/CD generation and build parameters - `--registry`, `-r`: set the Docker registry where images are pushed on build - `-we', '--write-env`: Write build env to .env file with variables about the generated image tags. - `-cu`, `--cache-url`: Specify a custom cache URL for the docker images. This is used to speed up builds by caching layers. Example: https://cache.cloudharness.io?repository=[REGISTRY]/[IMAGE_NAME]&tag=[TAG] -- `-N`, `--no-cd`: Do not generate ci/cd files +- `-N`, `--no-cd`: deprecated, no effect. The CI/CD pipelines are generated with + [`harness-generate ci-cd`](../applications/harness-generate.md#generate-the-cicd-pipelines) Other diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index 3d5f2de9a..cbfc7b260 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -19,6 +19,92 @@ All you need to to is: When defining an applications values you can provide details on dockerfile configuration such as build arguments. This feature is intended to support useful development use cases (e.g. conditionally running unit tests via build arguments) and should be used with caution as it can lead to different images in different deployment environments. +## Generating the pipelines + +`harness-generate ci-cd [paths] [-i APP ...]` writes one pipeline per CI provider and environment the project has +a template for in its own `deployment-configuration` (an empty file inherits the cloud-harness template): +`codefresh-template-[ENV].yaml` gives `deployment/ci--[NAME]--[ENV].yaml`, `github-template-[ENV].yaml` gives +`.github/workflows/ci--[NAME]--[ENV].yaml`. `[NAME]` is `--name`, by default the included applications joined with +dashes. Run it once per set of applications deployed together, and again whenever applications, their +dependencies or the templates change. See [harness-generate](../../applications/harness-generate.md#generate-the-cicd-pipelines). + ## CI/CD with Codefresh -[Codefresh](https://codefresh.io/) is a nice platform for CI/CD see details in the [dedicated document](./codefresh.md). \ No newline at end of file +[Codefresh](https://codefresh.io/) is a nice platform for CI/CD see details in the [dedicated document](./codefresh.md). + +## CI/CD with GitHub Actions + +`harness-generate ci-cd` generates `.github/workflows/ci--[NAME]--[ENV].yaml` from `github-template-[ENV].yaml`, a +workflow with the stages of the Codefresh pipeline: image build, unit tests, helm deployment, rollout wait and +API/E2E tests. Build, unit tests and deployment run with [Skaffold](https://skaffold.dev/), from the +`deployment/skaffold-ci.yaml` the pipeline writes. + +- Build: the `prepare` job runs `harness-deployment --write-env --write-skaffold-ci`, which asks the + registry for every image's content-hash tag and writes `deployment/skaffold-ci.yaml` with only the images + whose tag is missing (or forced). The same job then runs `skaffold build` on it: every image is a + `docker buildx build --push` with its registry cache (`[image]:buildcache`), skaffold runs them in parallel and + builds a base image before the images built on it, while base images that are already published are pulled. + The more CPUs the build runner has, the more images build at once. `skaffold test` then runs the unit tests of + every app (the `test` section of the same file) against every image of the deployment, rebuilt or not + (`deployment/skaffold-images.json`). A re-run after a failure asks the registry again, only builds what is + still missing and tests everything again. The steps live under `cloudharness.build` in the template (`null` + in stage and prod, which deploy published images). +- Deployment: the `deploy` job runs `skaffold deploy` on the same file, which installs or upgrades the helm + chart (release and namespace named after the deployment namespace) and waits until its deployments and + statefulsets are rolled out, tolerating restarts for up to 15 minutes. Skaffold labels every pod template + with its run id: the workflow sets a constant one, so the apps whose image did not change are not restarted. + Secret values reach helm with `--set-file`, from files the job writes under `~/.cloudharness/secrets`. +- Templates: `deployment-configuration/github-template.yaml` (job prototypes and shared steps) plus + `github-template-[dev|stage|prod|test].yaml` (name, triggers, per-environment deltas), layered and overridable + from your project's `deployment-configuration/` like the Codefresh ones. A `jobs.tests-api-[app]` or + `jobs.tests-e2e-[app]` entry in your template is merged over that app's generated job. +- Runner: set the `CH_GITHUB_RUNNER` repository or organization variable to the runner label (for ARC, the + runner scale set name); `prepare`, which builds the images, reads `CH_GITHUB_BUILD_RUNNER` first, so images can + build on a bigger runner. Both are read when the workflow runs, so changing runners needs no regeneration. When neither is + set, jobs use the runner given at generation time by the `CH_GITHUB_RUNNER` environment variable (default + `ubuntu-latest`, comma-separated labels allowed). A `runs-on` in the template always wins. +- Configuration: the generator logs the repository variables (`REGISTRY`, `DOMAIN`, `NAMESPACE`, ...) and + secrets (`REGISTRY_USERNAME`, `REGISTRY_PASSWORD`, `KUBECONFIG`, the application secrets with the same names + as the Codefresh variables) the workflow expects. Approvals are GitHub environment protection rules (required + reviewers): on `publish` (promotion), on `cleanup` (deleting the test deployment) and on `prod`/`stage` + (deploying); dev and test deploy without approval. `workflow_dispatch` inputs replace the `DEPLOYMENT_TAG`, + `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. A project's jobs clone and install + the cloud-harness branch named by the `CLOUDHARNESS_BRANCH` variable (default `develop`); cloud-harness' own + workflow builds and tests the branch that triggered it, tools included, and does not read that variable. +- Cluster credentials: the `deploy` and test `cleanup` jobs run the steps listed under + `cloudharness.kube_auth` in the template. The default step uses a base64 `KUBECONFIG` secret when present and + the runner's own cluster access otherwise (a runner inside the target cluster with a service account bound to + the deployment namespaces needs no secret at all); with neither, the job fails immediately. `deploy` + targets the GitHub environment named after the CloudHarness environment and `cleanup` the `cleanup` + environment, so environment secrets of the CloudHarness environment reach `deploy` only: keep the cluster + credentials in repository or organization secrets. For GKE with workload identity + federation, replace the list in your project's `github-template.yaml` and grant `id-token: write` to the jobs + using it (it is not granted to the whole workflow; a job-level `permissions` replaces the workflow-level one): + + ```yaml + cloudharness: + kube_auth: + - uses: google-github-actions/auth@v2 + with: + workload_identity_provider: ${{ vars.GCP_WORKLOAD_IDENTITY_PROVIDER }} + service_account: ${{ vars.GCP_DEPLOY_SERVICE_ACCOUNT }} + - uses: google-github-actions/get-gke-credentials@v2 + with: + cluster_name: ${{ vars.GKE_CLUSTER }} + location: ${{ vars.GKE_LOCATION }} + jobs: + deploy: + permissions: {contents: read, packages: write, id-token: write} + cleanup: + permissions: {contents: read, packages: write, id-token: write} + ``` +- Promotion: generating the dev workflow also writes `.github/workflows/ci--[NAME]--promote.yaml` (from + `cloudharness.promote` in `github-template-dev.yaml`), started by hand with a tag and, optionally, the dev run + to promote (default: its latest successful run on the default branch). After the approval of the `publish` + environment it gives the tag to the exact images that run deployed (`deployment/skaffold-images.json` in its + `cloudharness-deployment` artifact), also in `REGISTRY_PUBLISH_URL` with `latest` when set, and pushes the git + tag on the run's commit. The tag starts the staging pipeline, which deploys and tests the images with that + tag; production deploys a tag by hand. A tag pushed with the workflow's own token starts no workflow: set a + `GH_PAT` secret (a token with contents write access) for the staging pipeline to start by itself. +- Test failures: unit tests gate the deployment, as in Codefresh. The API/E2E tests run after the deployment + and never block it; a run whose tests failed is simply not promoted. diff --git a/docs/build-deploy/ci-cd/codefresh.md b/docs/build-deploy/ci-cd/codefresh.md index 3e691334f..02d9fc47a 100644 --- a/docs/build-deploy/ci-cd/codefresh.md +++ b/docs/build-deploy/ci-cd/codefresh.md @@ -1,13 +1,14 @@ # Continuous deployment with Codefresh -Codefresh pipelines are generated as `deployment/codefresh-[ENV].yaml`. +Codefresh pipelines are generated as `deployment/ci--[NAME]--[ENV].yaml` by `harness-generate ci-cd`, `[NAME]` being +the included applications joined with dashes (or `--name`). These files can be loaded from codefresh as documented [here](https://codefresh.io/docs/docs/configure-ci-cd-pipeline/pipelines/). The pipeline will take care of building the images from the source code and deploy the helm chart. Log in to codefresh and run the pipeline associated to the repository. -- To setup a new dev pipeline, indicate the remote yaml path `./deployment/codefresh-dev.yaml` -- To setup a new production pipeline, indicate the remote yaml path `./deployment/codefresh-prod.yaml` +- To setup a new dev pipeline, indicate the remote yaml path `./deployment/ci--[NAME]--dev.yaml` +- To setup a new production pipeline, indicate the remote yaml path `./deployment/ci--[NAME]--prod.yaml` ## Preconfigured pipelines @@ -56,17 +57,19 @@ Variables are used to customize the deployment The deployment must be updated whenever new build artifacts are added/removed, or opon changes in the templates. -To update a pipeline for a specific env, run +To update the pipelines, run ``` -harness-deployment . -e [ENV] +harness-generate ci-cd [paths] -i [APP] ``` -A file `./deployment/codefresh-dev.yaml` is created, provided that a file `./deployment/codefresh-[ENV].yaml` exists either as a preconfigured pipeline on cloudharness or as a custom pipeline in your application. +A file `./deployment/ci--[APP]--[ENV].yaml` is created for every `./deployment-configuration/codefresh-template-[ENV].yaml` +of your project: the file can be empty to use the preconfigured pipeline of cloudharness as it is. Add `-e [ENV]` to +update one pipeline only. ## Override Codefresh pipeline templates Edit `./deployment-configuration/codefresh-template-[ENV].yaml` to override any helm chart values file. -Notice that Codefresh templates will be generated only if a specific environment file is defined. -By default, the *dev* and *prod* environments are defined. +Notice that a pipeline is generated only for the environments your project has a template file for: cloudharness +predefines *dev*, *stage*, *prod* and *test*, each inherited through an (even empty) file of the same name. To override the single image build template, edit `deployment-configuration/codefresh-build-template.yaml` diff --git a/docs/testing.md b/docs/testing.md index 0a941f901..e307cc821 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -179,7 +179,7 @@ after the deployment is established, tests for each application are executed in The suggested usage for the test pipeline is to trigger the tests on pull requests and integrate the results on Github (or equivalent) PRs. -> Note: To regenerate the test pipeline, run `harness-deployment ... -e test`. +> Note: To regenerate the test pipeline, run `harness-generate ci-cd ... -e test`. ## Run API and E2E tests tests manually diff --git a/tools/deployment-cli-tools/CLAUDE.md b/tools/deployment-cli-tools/CLAUDE.md index 6df5535fc..05b326086 100644 --- a/tools/deployment-cli-tools/CLAUDE.md +++ b/tools/deployment-cli-tools/CLAUDE.md @@ -7,8 +7,8 @@ ## Key Scripts -- `harness-generate` — generate code -- `harness-deployment` — generate deployment files (Helm charts, CI/CD files, etc.) +- `harness-generate` — generate code; `harness-generate ci-cd` generates the CI/CD pipelines +- `harness-deployment` — generate deployment files (Helm charts, Skaffold, etc.) - `harness-application` — generate application code (e.g. Django apps) - `harness-migrate` — migration helper - `ch_cli_tools` — Python package for deployment and other tools diff --git a/tools/deployment-cli-tools/ch_cli_tools/__init__.py b/tools/deployment-cli-tools/ch_cli_tools/__init__.py index cf0a5894b..e2c929fa8 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/__init__.py +++ b/tools/deployment-cli-tools/ch_cli_tools/__init__.py @@ -15,7 +15,7 @@ CH_ROOT = os.getenv("CH_ROOT") or dn(dn(dn(dn(os.path.realpath(__file__))))).replace(os.path.sep, '/') # Imported for their @register_file side effect, not for re-export. -from . import codefresh, dockercompose, helm, skaffold, tilt, vscode # noqa: F401,E402 +from . import codefresh, dockercompose, github_actions, helm, skaffold, tilt, vscode # noqa: F401,E402 from .model import CHDeployConfig, CHProject # noqa: E402 diff --git a/tools/deployment-cli-tools/ch_cli_tools/api.py b/tools/deployment-cli-tools/ch_cli_tools/api.py index b9879919f..e00cd45ff 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/api.py +++ b/tools/deployment-cli-tools/ch_cli_tools/api.py @@ -12,13 +12,16 @@ ConfigurationGenerator/HarnessMainConfig machinery. """ +import dataclasses import logging import subprocess from pathlib import Path +from cloudharness_utils.constants import DEPLOYMENT_CONFIGURATION_PATH + from ch_cli_tools.utils import get_cluster_ip # type: ignore -from . import migration +from . import ci, migration from .model import CHDeployConfig, CHProject logger = logging.getLogger(__name__) @@ -228,6 +231,56 @@ def write_env_file(helm_values, filename, image_cache_endpoint_url=None): return project.codefresh.write_env_file(filename, image_cache_endpoint_url) +# --- CI/CD pipelines (harness-generate ci-cd) --- + +# The CHProject attribute generating each provider's pipelines -> the name of its templates +CI_GENERATORS = {"codefresh": "codefresh-template", "github_actions": "github-template"} + + +def generate_ci_cd(root_paths, config: CHDeployConfig, envs=()) -> list[Path]: + """Writes the CI/CD pipelines of the project layered from root_paths (lowest priority first) + and returns the files written. + + A provider gets one pipeline per environment with a template in the last root's own + deployment-configuration (`codefresh-template-.yaml`, `github-template-.yaml`, even + empty): the templates of the layers below are merged in, but never add a pipeline by + themselves. `envs` restricts the environments; one can combine several (`research-dev`), + each of which needs a template. + """ + folder = Path(root_paths[-1]) / DEPLOYMENT_CONFIGURATION_PATH + written: list[Path] = [] + for generator, template in CI_GENERATORS.items(): + available = ci.template_environments(folder, template) + if not available: + continue + for env in envs or available: + parts = env.split("-") + missing = [part for part in parts if part not in available] + if missing: + logger.warning( + "No %s pipeline for %s: add %s", + template, + env, + ", ".join(str(folder / f"{template}-{part}.yaml") for part in missing), + ) + continue + project = CHProject.init(root_paths, config=dataclasses.replace(config, env=parts)) + pipeline = getattr(project, generator) + if not pipeline.generate(): + continue + written.append(pipeline.file_path) + if getattr(pipeline, "promote", None): + if pipeline.promote_file_path in written: + logger.warning( + "More than one environment defines cloudharness.promote: %s promotes %s", + pipeline.promote_file_path.name, + pipeline.file_path.name, + ) + else: + written.append(pipeline.promote_file_path) + return written + + # --- ch_cli_tools/preprocessing.py --- # preprocess_build_overrides physically merges overlapping app/base-image # directories across root_paths into one filesystem tree, so a Docker build diff --git a/tools/deployment-cli-tools/ch_cli_tools/ci.py b/tools/deployment-cli-tools/ch_cli_tools/ci.py new file mode 100644 index 000000000..adb0e6def --- /dev/null +++ b/tools/deployment-cli-tools/ch_cli_tools/ci.py @@ -0,0 +1,405 @@ +"""Provider-neutral pieces shared by the CI/CD generators (Codefresh, GitHub Actions). + +Both pipelines skip the build of an image whose content-hash tag already exists +in the registry. The facts needed for that decision - the tag of every image the +deployment references and whether that tag is already published - can only be +known at pipeline run time, so they are computed by `harness-deployment +--write-env` inside the pipeline's prepare step and handed to the following +steps as `_TAG` / `_TAG_EXISTS` variables (`image_tag_env`). +""" + +import logging +import re +from dataclasses import dataclass +from pathlib import Path + +from ch_cli_tools.configuration.secrets import ( + is_cloudharness_managed, + is_secret_config, + secret_value, +) +from ch_cli_tools.utils import check_image_exists_in_registry # type: ignore + +from .model import KEY_APPS, KEY_TASK_IMAGES + +logger = logging.getLogger(__name__) + +FORCE_BUILD_ALL = "all" +DOCKER_HUB_REGISTRY = "docker.io" +TEST_IMAGE_API = "test-api" +TEST_IMAGE_E2E = "test-e2e" + +PIPELINE_FILE_PREFIX = "ci" +PIPELINE_FILE_SEPARATOR = "--" +DEFAULT_PIPELINE_NAME = "all" +_PIPELINE_NAME = re.compile(r"^[A-Za-z0-9._-]+$") + + +def pipeline_name(config) -> str: + """The name of a pipeline in its file names: the configured one, else the included apps joined + with dashes, else `all`.""" + name = config.pipeline or "-".join(config.includes) or DEFAULT_PIPELINE_NAME + if not _PIPELINE_NAME.match(name): + raise ValueError(f"Invalid pipeline name {name!r}: use letters, digits, `.`, `_` and `-`") + return name + + +def pipeline_file_name(config, suffix: str | None = None) -> str: + """`ci----.yaml`; the suffix defaults to the environments joined with dashes, + as `-e` takes them.""" + if suffix is None: + suffix = "-".join(config.envs) + parts = [PIPELINE_FILE_PREFIX, pipeline_name(config), suffix] + return PIPELINE_FILE_SEPARATOR.join(part for part in parts if part) + ".yaml" + + +def template_environments(folder: Path, template: str) -> list[str]: + """The environments with a `