From 6329633f75dc87008af61ce426a94fd02639fd26 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 30 Oct 2026 12:00:46 +0100 Subject: [PATCH 01/11] CH-125 github actions files generation --- deployment-configuration/README.md | 4 + .../github-template-dev.yaml | 20 + .../github-template-prod.yaml | 22 + .../github-template-stage.yaml | 40 + .../github-template-test.yaml | 46 + deployment-configuration/github-template.yaml | 247 ++++++ docs/build-deploy/ci-cd/README.md | 21 +- .../ch_cli_tools/__init__.py | 2 +- tools/deployment-cli-tools/ch_cli_tools/ci.py | 281 ++++++ .../ch_cli_tools/codefresh.py | 202 +---- .../ch_cli_tools/github_actions.py | 800 ++++++++++++++++++ .../ch_cli_tools/model.py | 26 +- tools/deployment-cli-tools/harness-deployment | 29 +- tools/deployment-cli-tools/tests/conftest.py | 20 + .../github-template-dev.yaml | 12 + tools/deployment-cli-tools/tests/test_ci.py | 93 ++ .../tests/test_codefresh.py | 2 +- .../tests/test_content_hash_build_args.py | 49 ++ .../tests/test_github_actions.py | 438 ++++++++++ .../tests/test_github_actions_internals.py | 149 ++++ 20 files changed, 2334 insertions(+), 169 deletions(-) create mode 100644 deployment-configuration/github-template-dev.yaml create mode 100644 deployment-configuration/github-template-prod.yaml create mode 100644 deployment-configuration/github-template-stage.yaml create mode 100644 deployment-configuration/github-template-test.yaml create mode 100644 deployment-configuration/github-template.yaml create mode 100644 tools/deployment-cli-tools/ch_cli_tools/ci.py create mode 100644 tools/deployment-cli-tools/ch_cli_tools/github_actions.py create mode 100644 tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml create mode 100644 tools/deployment-cli-tools/tests/test_ci.py create mode 100644 tools/deployment-cli-tools/tests/test_content_hash_build_args.py create mode 100644 tools/deployment-cli-tools/tests/test_github_actions.py create mode 100644 tools/deployment-cli-tools/tests/test_github_actions_internals.py diff --git a/deployment-configuration/README.md b/deployment-configuration/README.md index 83ae83b8e..3bc60e951 100644 --- a/deployment-configuration/README.md +++ b/deployment-configuration/README.md @@ -14,4 +14,8 @@ Those files are used by the script `harness-deployment` script. 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/cloudharness-[env].yaml`), + generated with `harness-deployment -ci github`: 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/` diff --git a/deployment-configuration/github-template-dev.yaml b/deployment-configuration/github-template-dev.yaml new file mode 100644 index 000000000..ff61f6d1e --- /dev/null +++ b/deployment-configuration/github-template-dev.yaml @@ -0,0 +1,20 @@ +# Development pipeline: build, unit tests, deployment, API/E2E tests and, when a publish tag is given, +# publication of the images after approval (protect the `publish` environment with required reviewers). +name: CloudHarness $ENV +on: + push: + branches: [develop] + workflow_dispatch: + inputs: + publish_tag: + description: Tag to publish the images with when the run succeeds (leave empty not to publish) + type: string + default: "" + 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: "" diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml new file mode 100644 index 000000000..14e89c1ff --- /dev/null +++ b/deployment-configuration/github-template-prod.yaml @@ -0,0 +1,22 @@ +# Production pipeline: deploys images published by the development or staging pipeline, 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 published by the development or staging pipeline) + type: string + required: true +jobs: + build: null + build-test-images: null + tests-unit: null + tests-api: null + tests-e2e: null + wait-deployment: null + publish: null + deploy: + environment: $ENV + env: + HELM_FLAGS: --wait --timeout 600s --create-namespace diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml new file mode 100644 index 000000000..9f9bcd161 --- /dev/null +++ b/deployment-configuration/github-template-stage.yaml @@ -0,0 +1,40 @@ +# Staging pipeline: deploys images published by the development pipeline, runs the API/E2E tests and, +# after approval, publishes them again under the given tag and tags the repository. +name: CloudHarness $ENV +on: + workflow_dispatch: + inputs: + deployment_tag: + description: Tag of the images to deploy (a tag published by the development pipeline) + type: string + required: true + publish_tag: + description: Tag to publish the deployed images with after approval (leave empty not to publish) + type: string + default: "" + skip_tests: + description: Set to `true` to skip the tests + type: string + default: "" +jobs: + build: null + build-test-images: null + tests-unit: null + deploy: + environment: $ENV + env: + HELM_FLAGS: --wait --timeout 600s --create-namespace + git-tag: + name: Tag the repository + needs: [prepare, publish] + if: ${{ needs.prepare.outputs.publish_tag != '' }} + permissions: + contents: write + env: + PUBLISH_TAG: ${{ needs.prepare.outputs.publish_tag }} + steps: + - uses: actions/checkout@v4 + - name: Push the tag + run: | + git tag "$PUBLISH_TAG" + git push origin "refs/tags/$PUBLISH_TAG" diff --git a/deployment-configuration/github-template-test.yaml b/deployment-configuration/github-template-test.yaml new file mode 100644 index 000000000..a02ac7338 --- /dev/null +++ b/deployment-configuration/github-template-test.yaml @@ -0,0 +1,46 @@ +# 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 }} + publish: null + cleanup: + name: Delete the test deployment + needs: [prepare, deploy, tests-unit, tests-api, tests-e2e] + 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-kubectl@v4 + - uses: azure/setup-helm@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + - 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..569bfda0f --- /dev/null +++ b/deployment-configuration/github-template.yaml @@ -0,0 +1,247 @@ +# Base of the GitHub Actions workflows generated by `harness-deployment -ci github`. +# 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). +# `build`, `build-test-images`, `tests-unit`, `tests-api` and `tests-e2e` are prototypes, expanded into one +# job per image/app ($CH_NAME, $CH_IMAGE and $CH_TAG stand for the image being expanded). A `$...` item in a steps +# list is a fragment the generator fills in. Every job without `runs-on` gets the runner given at generation +# time (CH_GITHUB_RUNNER, default ubuntu-latest). +permissions: + contents: read + packages: write +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false +env: + CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} +jobs: + prepare: + name: Prepare helm chart + 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 }} + 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 }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - $GIT_CLONES + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: azure/setup-helm@v4 + - name: Install cloud-harness tools + run: bash cloud-harness/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 $PATHS -d "$DOMAIN" -r "$REGISTRY" -rsn "$REGISTRY_SECRET" -n "$NAMESPACE" -e $ENV $TAG_ARG --write-env --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $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 + .overrides + include-hidden-files: true + if-no-files-found: error + build: + name: Build + needs: [prepare] + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - $GIT_CLONES + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether $CH_NAME already exists in the registry + id: check + env: + IMAGE: $CH_IMAGE:$CH_TAG + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push $CH_NAME + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=$CH_IMAGE:buildcache + cache-to: type=registry,ref=$CH_IMAGE:buildcache,mode=max + build-test-images: + name: Build test image + tests-unit: + name: Unit tests + needs: [prepare, build] + steps: + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - $TEST_STEPS + deploy: + name: Deploy + needs: [prepare, build, tests-unit] + env: + HELM_FLAGS: --timeout 200s --create-namespace + steps: + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: azure/setup-helm@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + - $HELM_SECRETS_STEPS + - name: Install chart + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS + wait-deployment: + name: Wait for the deployment + needs: [prepare, deploy] + if: ${{ needs.prepare.outputs.skip_tests != 'true' }} + timeout-minutes: 15 + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + steps: + - uses: azure/setup-kubectl@v4 + - name: Configure kubectl + env: + KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} + run: | + mkdir -p "$HOME/.kube" + echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" + chmod 600 "$HOME/.kube/config" + kubectl config set-context --current --namespace="$NAMESPACE" + - $ROLLOUT_STEPS + tests-api: + name: API tests + needs: [prepare, wait-deployment, build-test-images] + if: ${{ needs.prepare.outputs.skip_tests != 'true' }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - 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, wait-deployment, build-test-images] + if: ${{ needs.prepare.outputs.skip_tests != 'true' }} + commands: + - npx puppeteer browsers install chrome + - yarn test + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - $TEST_STEPS + publish: + name: Publish images + needs: [prepare, deploy, tests-unit, tests-api, tests-e2e] + if: ${{ needs.prepare.outputs.publish_tag != '' }} + environment: publish + steps: + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Log in to the publish registry + if: ${{ vars.REGISTRY_PUBLISH_URL != '' }} + env: + REGISTRY_PUBLISH_URL: ${{ vars.REGISTRY_PUBLISH_URL }} + 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 + - $PUBLISH_STEPS diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index 3d5f2de9a..a407d97fc 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -21,4 +21,23 @@ When defining an applications values you can provide details on dockerfile confi ## 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-deployment -ci github -e [ENV]` generates `.github/workflows/cloudharness-[ENV].yaml`, a workflow with +the same stages as the Codefresh pipeline: one build job per image (skipped when the image's content-hash tag +already exists in the registry), unit tests, helm deployment, rollout wait, API/E2E tests and publication. +Pass `-ci codefresh -ci github` to generate both. + +- 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.build-[image]` entry in your + template is merged over that image's generated job (for instance to pick a bigger runner). +- Runner: the `CH_GITHUB_RUNNER` environment variable at generation time (default `ubuntu-latest`, + comma-separated labels allowed); any job can still set its own `runs-on` in the template. +- 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 on the + `publish` and `prod`/`stage` environments. `workflow_dispatch` inputs replace the `DEPLOYMENT_PUBLISH_TAG`, + `DEPLOYMENT_TAG`, `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. 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/ci.py b/tools/deployment-cli-tools/ch_cli_tools/ci.py new file mode 100644 index 000000000..7ae40141d --- /dev/null +++ b/tools/deployment-cli-tools/ch_cli_tools/ci.py @@ -0,0 +1,281 @@ +"""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 +from dataclasses import dataclass + +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" + + +def env_key(name: str) -> str: + """The variable-name form of an image/app name: `my-app` -> `MY_APP`.""" + return name.replace("-", "_").upper() + + +def tag_variable(name: str) -> str: + return f"{env_key(name)}_TAG" + + +def parse_force_build(value: str | None) -> tuple[str, ...]: + """The `--force-build` CLI value: a comma-separated list of image names, or `all`.""" + if not value: + return () + return tuple(item.strip() for item in value.split(",") if item.strip()) + + +def is_forced(name: str, force_build=()) -> bool: + forced = set(force_build) + return FORCE_BUILD_ALL in forced or name in forced + + +@dataclass(frozen=True) +class ImageReference: + """A `[registry/]repository[:tag]` image reference split into its parts.""" + + registry: str + repository: str + tag: str + + @classmethod + def parse(cls, image: str) -> "ImageReference": + name, tag = image, "latest" + last_segment = image.rsplit("/", 1)[-1] + if ":" in last_segment: + name, tag = image.rsplit(":", 1) + chunks = name.split("/") + first = chunks[0] + has_registry_host = len(chunks) > 1 and ( + "." in first or ":" in first or first == "localhost" + ) + if has_registry_host: + return cls(first, "/".join(chunks[1:]), tag) + return cls(DOCKER_HUB_REGISTRY, name, tag) + + +def image_tag_env(project, image_cache_endpoint_url=None, force_build=()) -> dict[str, str]: + """`_TAG` plus `_TAG_EXISTS` or `_TAG_NEW` for every image of the deployment. + + Covers the apps (instances included), the task images (tasks and build + dependencies) and the test runner images. A forced image is reported as new + without asking the registry. + """ + helm_values = project.build_final_helm_values(write_on_disk=False) + env: dict[str, str] = {} + + def record(name: str, image: str) -> None: + reference = ImageReference.parse(image) + env[tag_variable(name)] = reference.tag + exists = not is_forced(name, force_build) and check_image_exists_in_registry( + reference.registry, + reference.repository, + reference.tag, + endpoint_url=image_cache_endpoint_url, + ) + env[tag_variable(name) + ("_EXISTS" if exists else "_NEW")] = "1" + + for app_name, app in helm_values.apps.items(): + if app.harness and app.harness.deployment.image: + record(app_name, app.harness.deployment.image) + + for name, image in helm_values[KEY_TASK_IMAGES].items(): + record(name, image) + + for name, test_image in project.test_images.items(): + if not test_image.dockerfile.exists(): + continue + record(name, project.qualify_image(test_image)) + + return env + + +def write_env_file(path, env: dict[str, str]) -> None: + with open(path, "w", encoding="utf-8") as f: + f.writelines(f"{key}={value}\n" for key, value in env.items()) + logger.info("Wrote %s", path) + + +def image_tag_names(project) -> list[str]: + """The names `image_tag_env` reports on, in the same order, without touching the registry.""" + helm_values = project.build_final_helm_values(write_on_disk=False) + names = [ + app_name + for app_name, app in helm_values.apps.items() + if app.harness and app.harness.deployment.image + ] + names.extend(helm_values[KEY_TASK_IMAGES]) + names.extend( + name for name, image in project.test_images.items() if image.dockerfile.exists() + ) + return names + + +def placeholder_values(project, pipeline_path) -> dict[str, str]: + """Values for the `$ENV`, `$PARAMS` and `$PATHS` placeholders of a prepare command. + + `pipeline_path(layer_root)` renders one layer root the way the pipeline's + checkout lays it out (cloud-harness is cloned into ./cloud-harness). + """ + config = project.config + params = [f"-i {inc}" for inc in config.includes] + [ + f"-ex {exc}" for exc in config.excludes + ] + paths = " ".join( + str(pipeline_path(layer.root)) for layer in reversed(project.all_layers()) + ) + return { + "ENV": "-".join(config.envs), + "PARAMS": " ".join(params), + "PATHS": paths, + } + + +def app_domain(app, domain: str) -> str: + """`https://.`, with `domain` typically a pipeline-variable reference.""" + return f"https://{app.harness_config.get('subdomain')}.{domain}" + + +def test_environment(app, app_domain_url: str) -> dict[str, str]: + """Environment of the API/E2E test runner for an app: URL, main user credentials, test flags.""" + env: dict[str, str] = {"APP_URL": app_domain_url} + users = app.harness_config.get("accounts", {}).get("users") or [] + if users: + main_user = users[0] + env["USERNAME"] = main_user.get("username") + env["PASSWORD"] = main_user.get("password") or "test" + e2e = app.test.e2e + if not e2e.smoketest: + env["SKIP_SMOKETEST"] = "true" + if e2e.ignore_console_errors: + env["IGNORE_CONSOLE_ERRORS"] = "true" + if e2e.ignore_request_errors: + env["IGNORE_REQUEST_ERRORS"] = "true" + return env + + +def schemathesis_command(app, app_domain_url: str) -> str: + api = app.test.api + params = ["--base-url", app_domain_url] + for check in api.checks: + params += ["-c", check] + params += api.run_params + return " ".join( + [ + "st", + "--pre-run", + "cloudharness_test.apitest_init", + "run", + "api/openapi.yaml", + *params, + ] + ) + + +def api_test_commands(app, app_domain_url: str) -> list[str]: + commands = [] + if app.test.api.autotest: + commands.append(schemathesis_command(app, app_domain_url)) + if (app.path / "test" / "api").exists(): + commands.append("pytest -v test/api") + return commands + + +def api_test_url(app, domain: str) -> str | None: + """The base URL of an app's API tests, or None when the app declares no server URL.""" + server_urls = app.openapi.server_urls + if not server_urls: + return None + url = server_urls[-1] + if "http" not in url: + url = app_domain(app, domain) + url + return url + + +def has_api_tests(app) -> bool: + return bool( + app.is_buildable and app.test.api.enabled and app.harness_config.get("subdomain") + ) + + +def has_e2e_tests(app) -> bool: + return bool( + app.is_buildable and app.test.e2e.enabled and app.harness_config.get("subdomain") + ) + + +def rollout_wait_commands(project) -> list[str]: + """`kubectl rollout status` for every auto-deployed workload and gatekeeper, then a settle pause.""" + secured_gatekeepers = project.config.secured_gatekeepers + commands = [] + for app in project.involved_apps: + if isinstance(app, str): + continue + deployment = app.deployment_config + if deployment.get("auto"): + kind = "statefulset" if deployment.get("statefulset") else "deployment" + name = deployment.get("name") or app.name + commands.append(f"kubectl rollout status {kind}/{name}") + if app.harness_config.get("secured") and secured_gatekeepers: + # gatekeepers are always rendered as deployments + subdomain = app.harness_config.get("subdomain") + commands.append(f"kubectl rollout status deployment/{subdomain}-gk") + if commands: + commands.append("sleep 60") # give the certificates time to settle + return commands + + +@dataclass(frozen=True) +class HelmSecretValue: + """A helm value the pipeline must supply from one of its own secret variables.""" + + path: tuple[str, ...] # helm value path, e.g. ("apps", "myapp", "harness", "secrets", "token") + variable: str # pipeline variable holding the value, e.g. TOKEN + + +def deployment_secret_values(project) -> list[HelmSecretValue]: + """CloudHarness-managed secrets, auto-generated DB connect strings and the registry + secret, each as the helm value path to set and the pipeline variable to take it from. + + Secrets handled by another manager, or whose value is already set, are left alone. + Variable names follow the Codefresh convention: upper case, `_` doubled. + """ + values = [] + for app in project.involved_apps: + if isinstance(app, str): + continue + for secret, definition in app.secrets.items(): + if not is_cloudharness_managed(definition) or secret_value(definition) == "": + continue + path: tuple[str, ...] = (KEY_APPS, app.name, "harness", "secrets", secret) + # the rich form nests the value under `default` + if is_secret_config(definition): + path += ("default",) + values.append(HelmSecretValue(path, secret.replace("_", "__").upper())) + if app.database.get("connect_string") == "": + values.append( + HelmSecretValue( + (KEY_APPS, app.name, "harness", "database", "connect_string"), + f"{env_key(app.name)}_DB_CONNECT_STRING", + ) + ) + if project.config.registry_secret_name: + values.append(HelmSecretValue(("registry", "secret", "value"), "K8S_SA_JSON")) + return values diff --git a/tools/deployment-cli-tools/ch_cli_tools/codefresh.py b/tools/deployment-cli-tools/ch_cli_tools/codefresh.py index 1f85151f5..c744be581 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/codefresh.py +++ b/tools/deployment-cli-tools/ch_cli_tools/codefresh.py @@ -94,22 +94,13 @@ exactly the kind of fact that can't be baked into the committed file. """ -import logging import re from functools import lru_cache -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_TASK_IMAGES, CHValues, register_file +from . import ci +from .model import CHValues, register_file from .utils import dict_merge, pipeline_relative_path # type: ignore -logger = logging.getLogger(__name__) - KEY_BUILD_PARALLEL = "build_application_images" KEY_UNIT_TESTS = "tests_unit" KEY_CLONE_DEPENDENCIES = "post_main_clone" @@ -145,22 +136,14 @@ def _to_codefresh_path(path, relative_to, cloudharness_root=None) -> str: ) -def _env_key(name: str) -> str: - return name.replace("-", "_").upper() - - -def _tag_variable(name: str) -> str: - return f"{_env_key(name)}_TAG" +_env_key = ci.env_key +_tag_variable = ci.tag_variable def _tag_reference(name: str) -> str: return "${{%s}}" % _tag_variable(name) -def _extract_tag(image: str) -> str: - return image.split(":")[1] if ":" in image else "latest" - - @register_file( "codefresh_template", lambda root: root / "deployment-configuration" / "codefresh-template.yaml", @@ -182,38 +165,18 @@ class CHCodefresh(CHValues): def qualify(self, image_name): return "${{REGISTRY}}/%s" % image_name - def write_env_file(self, filename, image_cache_endpoint_url=None) -> None: - project = self.project - helm_values = project.build_final_helm_values(write_on_disk=False) - env: dict[str, int | str] = {} - - def record(name: str, image: str) -> None: - tag = _extract_tag(image) - env[_tag_variable(name)] = tag - chunks = image.split(":")[0].split("/") - has_registry_host = "." in chunks[0] - registry = chunks[0] if has_registry_host else "docker.io" - image_name = "/".join(chunks[1:] if has_registry_host else chunks) - exists = check_image_exists_in_registry( - registry, image_name, tag, endpoint_url=image_cache_endpoint_url - ) - env[_tag_variable(name) + ("_EXISTS" if exists else "_NEW")] = 1 - - for app_name, app in helm_values.apps.items(): - if app.harness and app.harness.deployment.image: - record(app_name, app.harness.deployment.image) - - for name, image in helm_values[KEY_TASK_IMAGES].items(): - record(name, image) - - for name, test_image in project.test_images.items(): - if not test_image.dockerfile.exists(): - continue - record(name, project.qualify_image(test_image)) - - with open(filename, "w", encoding="utf-8") as f: - f.writelines(f"{key}={value}\n" for key, value in env.items()) - logger.info("Wrote %s", filename) + def write_env_file(self, filename, image_cache_endpoint_url=None, force_build=()) -> None: + """Write the per-image TAG/EXISTS variables consumed by the build steps' skip conditions. + + Run at pipeline time (prepare step), never at generation time: whether a + tag already exists in the registry is exactly the kind of fact that cannot + be baked into the committed file. Images listed in `force_build` (or all of + them, with `all`) are reported as new so their build runs regardless. + """ + ci.write_env_file( + filename, + ci.image_tag_env(self.project, image_cache_endpoint_url, force_build), + ) def _context_for(self, entity): return entity.dockerfile.resolve_context(self.path.parent).resolve_for_build( @@ -377,73 +340,29 @@ def _collect_unit_test_steps(self, project): return steps def _collect_rollout_wait_commands(self, project) -> list[str]: - secured_gatekeepers = project.config.secured_gatekeepers - commands = [] - for app in project.involved_apps: - if isinstance(app, str): - continue - deployment = app.deployment_config - if deployment.get("auto"): - kind = "statefulset" if deployment.get("statefulset") else "deployment" - name = deployment.get("name") or app.name - commands.append(f"kubectl rollout status {kind}/{name}") - if app.harness_config.get("secured") and secured_gatekeepers: - # gatekeepers are always rendered as deployments - subdomain = app.harness_config.get("subdomain") - commands.append(f"kubectl rollout status deployment/{subdomain}-gk") - if commands: - commands.append("sleep 60") # give the certificates time to settle - return commands + return ci.rollout_wait_commands(project) def _collect_deployment_secret_values(self, project) -> list[str]: - values = [] - for app in project.involved_apps: - if isinstance(app, str): - continue - app_key = app.name.replace("_", "__") - for secret, definition in app.secrets.items(): - if ( - not is_cloudharness_managed(definition) or - secret_value(definition) == "" - ): - continue - secret_name = secret.replace("_", "__") - # the rich form nests the value under `default` - value_path = ( - f"{secret_name}_default" - if is_secret_config(definition) - else secret_name - ) - values.append( - 'apps_%s_harness_secrets_%s="${{%s}}"' - % (app_key, value_path, secret_name.upper()) - ) - if app.database.get("connect_string") == "": - var_name = f"{_env_key(app.name)}_DB_CONNECT_STRING" - values.append( - 'apps_%s_harness_database_connect__string="${{%s}}"' - % (app_key, var_name) - ) - if project.config.registry_secret_name: - values.append('registry_secret_value="${{K8S_SA_JSON}}"') - return values + """custom_values entries of Codefresh's helm step: `_` separates the value path, + `__` escapes a literal underscore.""" + def helm_step_key(path): + return "_".join(segment.replace("_", "__") for segment in path) + + return [ + '%s="${{%s}}"' % (helm_step_key(value.path), value.variable) + for value in ci.deployment_secret_values(project) + ] def _substitute_prepare_deployment_placeholders( self, project, commands ) -> list[str]: - config = project.config - params = [f"-i {inc}" for inc in config.includes] + [ - f"-ex {exc}" for exc in config.excludes - ] cloudharness_root = project.all_layers()[-1].root - paths = " ".join( - _to_codefresh_path(layer.root, project.root, cloudharness_root) - for layer in reversed(project.all_layers()) - ) replacements = { - "$ENV": "-".join(config.envs), - "$PARAMS": " ".join(params), - "$PATHS": paths, + f"${key}": value + for key, value in ci.placeholder_values( + project, + lambda root: _to_codefresh_path(root, project.root, cloudharness_root), + ).items() } result = [] for command in commands: @@ -453,49 +372,15 @@ def _substitute_prepare_deployment_placeholders( return result def _app_domain(self, app) -> str: - subdomain = app.harness_config.get("subdomain") - return f"https://{subdomain}." + "${{DOMAIN}}" + return ci.app_domain(app, "${{DOMAIN}}") def _test_environment(self, app, app_domain: str) -> list[str]: - env: dict[str, str] = {"APP_URL": app_domain} - users = app.harness_config.get("accounts", {}).get("users") or [] - if users: - main_user = users[0] - env["USERNAME"] = main_user.get("username") - env["PASSWORD"] = main_user.get("password") or "test" - e2e = app.test.e2e - if not e2e.smoketest: - env["SKIP_SMOKETEST"] = "true" - if e2e.ignore_console_errors: - env["IGNORE_CONSOLE_ERRORS"] = "true" - if e2e.ignore_request_errors: - env["IGNORE_REQUEST_ERRORS"] = "true" - return [f"{key}={value}" for key, value in env.items()] - - def _schemathesis_command(self, app, app_domain: str) -> str: - api = app.test.api - params = ["--base-url", app_domain] - for check in api.checks: - params += ["-c", check] - params += api.run_params - return " ".join( - [ - "st", - "--pre-run", - "cloudharness_test.apitest_init", - "run", - "api/openapi.yaml", - *params, - ] - ) + return [ + f"{key}={value}" for key, value in ci.test_environment(app, app_domain).items() + ] def _api_test_commands(self, app, app_domain: str) -> list[str]: - commands = [] - if app.test.api.autotest: - commands.append(self._schemathesis_command(app, app_domain)) - if (app.path / "test" / "api").exists(): - commands.append("pytest -v test/api") - return commands + return ci.api_test_commands(app, app_domain) def _api_test_volumes(self, app) -> list[str]: app_path = self._repo_relative(app.path) @@ -514,16 +399,11 @@ def _e2e_test_volumes(self, app) -> list[str]: def _collect_api_test_steps(self, project) -> dict: scale = {} for app in project.involved_apps: - if isinstance(app, str) or not app.is_buildable: - continue - if not (app.test.api.enabled and app.harness_config.get("subdomain")): + if isinstance(app, str) or not ci.has_api_tests(app): continue - server_urls = app.openapi.server_urls - if not server_urls: + app_domain = ci.api_test_url(app, "${{DOMAIN}}") + if app_domain is None: continue - app_domain = server_urls[-1] - if "http" not in app_domain: - app_domain = self._app_domain(app) + app_domain scale[f"{app.name}_api_test"] = { "title": f"{app.name} api test", "volumes": self._api_test_volumes(app), @@ -535,9 +415,7 @@ def _collect_api_test_steps(self, project) -> dict: def _collect_e2e_test_steps(self, project) -> dict: scale = {} for app in project.involved_apps: - if isinstance(app, str) or not app.is_buildable: - continue - if not (app.test.e2e.enabled and app.harness_config.get("subdomain")): + if isinstance(app, str) or not ci.has_e2e_tests(app): continue app_domain = self._app_domain(app) scale[f"{app.name}_e2e_test"] = { diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py new file mode 100644 index 000000000..15b159fa7 --- /dev/null +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -0,0 +1,800 @@ +"""Generates GitHub Actions workflows from a CHProject. + +The GitHub Actions pipeline does what the Codefresh one does - build every image +the deployment needs, run the unit tests, deploy the helm chart, wait for the +rollout, run the API/E2E tests, publish (re-tag) the images - with the same +content-hash skip: the `prepare` job runs `harness-deployment --write-env` and +turns `deployment/.env` into job outputs, and every `build-` job is only +scheduled when `_TAG_EXISTS` is not set. Like codefresh.yaml, the +workflow is generated once and committed, so everything only known at run time +stays a `${{ ... }}` expression (vars, secrets, prepare outputs). + +What differs from Codefresh, and shapes the template: +- GitHub only runs workflows found in .github/workflows/, so that is where the + file goes: `.github/workflows/cloudharness-.yaml` in the project root. +- Triggers (`on:`) are part of the file, hence of the per-environment template. +- Every job runs on a fresh runner: each one checks out what it needs, images + travel between jobs through the registry, the helm chart and the merged + `.overrides/` contexts travel as a workflow artifact. +- A job whose `needs` were skipped is skipped too unless its `if` says + otherwise; since build jobs are skipped on purpose, every dependent job gets + a guard (`apply_needs_guards`) that tolerates skipped builds but not failures. + +Template mechanics (`github-template.yaml` + `github-template-.yaml`, layered +across cloud-harness and the project exactly like the Codefresh templates): +- `jobs.build`, `jobs.build-test-images`, `jobs.tests-unit`, `jobs.tests-api` + and `jobs.tests-e2e` are prototypes, expanded into one job per image/app at + their position; a `null` or missing prototype means that kind of job is not + generated. Inside a prototype `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for + the image being expanded. +- A string item in a `steps` list is a fragment the generator fills: + `$GIT_CLONES`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, + `$TEST_STEPS`. +- `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. +- A template key matching an expanded job id (`jobs.build-myapp`) is merged over + the generated job, so one image can get a bigger runner or extra steps; such a + key is dropped when its image is not part of the deployment being generated. +- `runs-on` defaults to CHDeployConfig.ci_runner (`CH_GITHUB_RUNNER` on the CLI). +""" + +import copy +import logging +import re +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path + +from ruamel.yaml.scalarstring import LiteralScalarString + +from . import ci +from .model import CHValues, register_file +from .utils import GeneratedYAML, dict_merge, pipeline_relative_path # type: ignore + +WORKFLOW_FILE_NAME = "cloudharness.yaml" +DEFAULT_RUNNER = "ubuntu-latest" + +JOB_PREPARE = "prepare" +JOB_BUILD = "build" +JOB_BUILD_TEST_IMAGES = "build-test-images" +JOB_UNIT_TESTS = "tests-unit" +JOB_API_TESTS = "tests-api" +JOB_E2E_TESTS = "tests-e2e" +JOB_DEPLOY = "deploy" +JOB_WAIT_DEPLOYMENT = "wait-deployment" +JOB_PUBLISH = "publish" +PROTOTYPE_JOBS = (JOB_BUILD, JOB_BUILD_TEST_IMAGES, JOB_UNIT_TESTS, JOB_API_TESTS, JOB_E2E_TESTS) + +FRAGMENT_GIT_CLONES = "$GIT_CLONES" +FRAGMENT_PUBLISH_STEPS = "$PUBLISH_STEPS" +FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" +FRAGMENT_ROLLOUT = "$ROLLOUT_STEPS" +FRAGMENT_TEST = "$TEST_STEPS" + +STEP_IMAGES = "images" # prepare step appending deployment/.env to $GITHUB_OUTPUT +STEP_CHECK = "check" # build step asking the registry whether the image exists +STEP_BUILD = "build" # build step running docker/build-push-action + +TEST_IMAGE_API = "test-api" +TEST_IMAGE_E2E = "test-e2e" +TEST_HOME = "/home/test" +DEFAULT_E2E_COMMANDS = ("npx puppeteer browsers install chrome", "yarn test") + +_INVALID_JOB_ID_CHARS = re.compile(r"[^A-Za-z0-9_-]") +_INVALID_SECRET_CHARS = re.compile(r"[^A-Z0-9_]") +_EXPRESSION = re.compile(r"^\$\{\{(.*)\}\}$", re.DOTALL) +_STATUS_FUNCTION = re.compile(r"\b(always|cancelled)\(\)") +_GITHUB_REPOSITORY = re.compile( + r"^(?:https?://github\.com/|git@github\.com:|ssh://git@github\.com/)" + r"([^/\s]+/[^/\s]+?)(?:\.git)?/?$" +) +_CONTEXT_REFERENCE = re.compile(r"(? str: + """A valid GitHub job id: `[A-Za-z_][A-Za-z0-9_-]*`.""" + cleaned = _INVALID_JOB_ID_CHARS.sub("-", name) + return cleaned if re.match(r"[A-Za-z_]", cleaned) else f"_{cleaned}" + + +def substitute_vars(node, mapping: dict[str, str]): + """Replace word-bounded `$KEY` placeholders in every string of a nested structure.""" + if not mapping: + return node + pattern = re.compile(r"\$(" + "|".join(re.escape(key) for key in mapping) + r")\b") + + def visit(value): + if isinstance(value, str): + return pattern.sub(lambda match: mapping[match.group(1)], value) + if isinstance(value, dict): + return {key: visit(item) for key, item in value.items()} + if isinstance(value, list): + return [visit(item) for item in value] + return value + + return visit(node) + + +def expand_steps(steps, fragments: dict[str, list]) -> list: + """Replace string items of a steps list by the fragment steps they name.""" + expanded = [] + for step in steps or []: + if isinstance(step, str): + if step not in fragments: + raise ValueError( + f"Unknown step fragment {step!r}; known fragments: {sorted(fragments)}" + ) + expanded.extend(copy.deepcopy(fragments[step])) + else: + expanded.append(step) + return expanded + + +def step_by_id(steps, step_id: str): + return next( + (step for step in steps if isinstance(step, dict) and step.get("id") == step_id), + None, + ) + + +def strip_expression(value) -> str: + value = str(value).strip() + match = _EXPRESSION.match(value) + return match.group(1).strip() if match else value + + +def combine_conditions(*parts) -> str: + """AND the given `if` expressions, with or without their `${{ }}` wrapper.""" + conditions = [strip_expression(part) for part in parts if part not in (None, "")] + conditions = [condition for condition in conditions if condition] + if not conditions: + return "" + if len(conditions) == 1: + return "${{ %s }}" % conditions[0] + return "${{ %s }}" % " && ".join(f"({condition})" for condition in conditions) + + +def normalize_needs(value) -> list[str]: + if value is None: + return [] + if isinstance(value, str): + return [value] + return list(value) + + +def needs_guard(needs, skippable) -> str: + """The condition letting a job run after skipped (but never failed) dependencies. + + Jobs without an `if` of their own are expected to succeed; the others + (build jobs skipped when their image exists, tests skipped on request) may + be skipped. + """ + guard = [ + "!cancelled()", + "!contains(needs.*.result, 'failure')", + "!contains(needs.*.result, 'cancelled')", + ] + guard += [f"needs.{need}.result == 'success'" for need in needs if need not in skippable] + return " && ".join(guard) + + +def rewrite_needs(jobs: dict, expansions: dict[str, list[str]]) -> None: + """Replace prototype ids in every `needs` by the ids they expanded to; unknown ids raise.""" + for name, job in jobs.items(): + if "needs" not in job: + continue + needs = [] + for dependency in normalize_needs(job["needs"]): + targets = [dependency] if dependency in jobs else expansions.get(dependency) + if targets is None: + raise ValueError(f"Job {name!r} needs unknown job {dependency!r}") + for target in targets: + if target != name and target not in needs: + needs.append(target) + if needs: + job["needs"] = needs + else: + del job["needs"] + + +def apply_needs_guards(jobs: dict) -> None: + """Add the `needs_guard` to every job with dependencies, except those that + already decide themselves with always()/cancelled().""" + skippable = {name for name, job in jobs.items() if job.get("if")} + for job in jobs.values(): + needs = normalize_needs(job.get("needs")) + if not needs: + continue + own = job.get("if") + if own and _STATUS_FUNCTION.search(str(own)): + continue + job["if"] = combine_conditions(own, needs_guard(needs, skippable)) + + +def as_literal_blocks(node): + """Multi-line strings as `|` blocks (trailing spaces stripped), tuples as lists.""" + if isinstance(node, dict): + return {key: as_literal_blocks(value) for key, value in node.items()} + if isinstance(node, (list, tuple)): + return [as_literal_blocks(value) for value in node] + if isinstance(node, str) and "\n" in node: + text = "\n".join(line.rstrip() for line in node.splitlines()) + if node.endswith("\n"): + text += "\n" + return LiteralScalarString(text) + return node + + +RESERVED_SECRET_PREFIX = "GITHUB_" +SECRET_PREFIX = "CH_" + + +def github_secret_name(variable: str) -> str: + """The GitHub secret holding a pipeline variable: the Codefresh variable name + with invalid characters replaced, prefixed with `CH_` when it starts with the + `GITHUB_` prefix GitHub reserves (e.g. a `github_client_id` secret).""" + name = _INVALID_SECRET_CHARS.sub("_", variable.upper()) + if name.startswith(RESERVED_SECRET_PREFIX): + renamed = f"{SECRET_PREFIX}{name}" + logging.warning( + "Secret variable %s starts with the prefix GitHub reserves: the workflow reads it " + "from the %s secret instead", + name, + renamed, + ) + return renamed + return name + + +def github_repository(url: str) -> str | None: + """`owner/repo` of a github.com clone URL (https or ssh), None for any other host.""" + match = _GITHUB_REPOSITORY.match(url.strip()) + return match.group(1) if match else None + + +def referenced_names(workflow) -> dict[str, set[str]]: + """The `vars.*` and `secrets.*` names a workflow references.""" + found: dict[str, set[str]] = {"vars": set(), "secrets": set()} + + def visit(value): + if isinstance(value, str): + for context, name in _CONTEXT_REFERENCE.findall(value): + found[context].add(name) + elif isinstance(value, dict): + for item in value.values(): + visit(item) + elif isinstance(value, list): + for item in value: + visit(item) + + visit(workflow) + return found + + +def prepare_output(key: str) -> str: + return "${{ needs.%s.outputs.%s }}" % (JOB_PREPARE, key) + + +def tag_output(name: str) -> str: + return prepare_output(ci.tag_variable(name)) + + +@dataclass(frozen=True) +class BuildContext: + path: str # docker build context, relative to the workflow's checkout root + dockerfile: str # Dockerfile, relative to the context + + +# --- generator ------------------------------------------------------------------ + + +@register_file( + "github_template", + lambda root: root / "deployment-configuration" / "github-template.yaml", +) +class CHGithubActionsTemplate(CHValues): + @lru_cache + def all_values(self): + layer = self.containing_project + own = self.merge_with_envs(self.project.config.envs) + if layer.base is None: + return own + return dict_merge(layer.base.github_template.all_values(), own) + + +@register_file( + "github_actions", + lambda root: root / ".github" / "workflows" / WORKFLOW_FILE_NAME, + only_env=True, +) +class CHGithubActions(CHValues): + def qualify(self, image_name: str) -> str: + return "${{ vars.REGISTRY }}/%s" % image_name + + def _runner(self): + runner = self.project.config.ci_runner or DEFAULT_RUNNER + if isinstance(runner, str) and "," in runner: + return [label.strip() for label in runner.split(",") if label.strip()] + return runner + + def _pipeline_path(self, path) -> str: + """A path as the workflow sees it: relative to the project checkout, with + cloud-harness under ./cloud-harness.""" + project = self.project + return str( + pipeline_relative_path( + Path(path), + project.root, + boundary=project.root, + cloudharness_root=project.all_layers()[-1].root, + ) + ) + + def _context_for(self, entity) -> BuildContext: + root = self.project.root + context = entity.dockerfile.resolve_context(root).resolve_for_build(root) + return BuildContext( + self._pipeline_path(root / context.path), str(context.dockerfile.path) + ) + + def _dependencies(self, entity) -> list: + dependencies = [] + for dependency in self.project._combined_dependencies(entity): + if isinstance(dependency, str): + continue + if dependency.name not in {d.name for d in dependencies}: + dependencies.append(dependency) + return dependencies + + def _buildable_apps(self) -> list: + return [ + app + for app in self.project.involved_apps + if not isinstance(app, str) and app.is_buildable + ] + + def _entities(self) -> dict: + """Every image to build: buildable involved apps, their tasks and the + build dependencies the deployment needs - the same set helm's + `task-images` and `write_env_file` cover.""" + project = self.project + entities = {} + for app in project.involved_apps: + if isinstance(app, str): + continue + if app.is_buildable: + entities[app.name] = app + for task in app.buildable_tasks: + entities[task.name] = task + app_names = {app.name for app in project.involved_apps if not isinstance(app, str)} + for name, dependency in project.all_build_dependencies(app_names).items(): + entities.setdefault(name, dependency) + return entities + + # --- generated fragments --- + + def _git_clone_steps(self, entities) -> list[dict]: + steps = [] + for entity in entities: + for dependency in getattr(entity, "git_dependencies", None) or []: + url = dependency["url"] + ref = dependency.get("branch_tag") + repo_name = Path(url).name.split(".")[0] + destination = Path(self._pipeline_path(entity.path)) / "dependencies" + if dependency.get("path"): + destination = destination / dependency["path"] + destination = destination / repo_name + repository = github_repository(url) + if repository: + with_ = { + "repository": repository, + "path": str(destination), + "token": "${{ secrets.GH_PAT || github.token }}", + } + if ref: + with_["ref"] = ref + steps.append( + { + "name": f"Clone {repo_name}", + "uses": "actions/checkout@v4", + "with": with_, + } + ) + else: + branch = f' --branch "{ref}"' if ref else "" + steps.append( + { + "name": f"Clone {repo_name}", + "run": f'git clone --depth 1{branch} "{url}" "{destination}"', + } + ) + return steps + + def _publish_steps(self, entities: dict) -> list[dict]: + steps = [] + for name, entity in entities.items(): + steps.append( + { + "name": f"Publish {name}", + "if": "${{ vars.%s_PUBLISH_SKIP == '' }}" % ci.env_key(name), + "env": { + "SOURCE": f"{self.qualify(entity.image_name)}:{tag_output(name)}", + "TARGET": "${{ vars.REGISTRY_PUBLISH_URL || vars.REGISTRY }}/%s" + % entity.image_name, + "PUBLISH_TAG": prepare_output("publish_tag"), + }, + "run": 'docker buildx imagetools create -t "$TARGET:$PUBLISH_TAG" ' + '-t "$TARGET:latest" "$SOURCE"', + } + ) + return steps + + def _helm_secrets_steps(self) -> list[dict]: + """One step writing every pipeline-supplied secret to a file and exporting the + matching `--set-file` arguments as HELM_SET_ARGS: no quoting or escaping of the + values is needed, and no secret ever appears on a command line.""" + values = ci.deployment_secret_values(self.project) + if not values: + return [] + env: dict[str, str] = {} + lines = [ + "set -e", + 'secrets_dir="$RUNNER_TEMP/ch-secrets"', + 'mkdir -p "$secrets_dir"', + 'args=""', + ] + for index, value in enumerate(values): + secret = github_secret_name(value.variable) + env[secret] = "${{ secrets.%s }}" % secret + key = ".".join(segment.replace(".", "\\.") for segment in value.path) + lines.append(f"printf '%s' \"${secret}\" > \"$secrets_dir/{index}\"") + lines.append(f'args="$args --set-file {key}=$secrets_dir/{index}"') + lines.append('echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV"') + return [{"name": "Collect secret values", "env": env, "run": "\n".join(lines) + "\n"}] + + def _rollout_steps(self) -> list[dict]: + commands = ci.rollout_wait_commands(self.project) + if not commands: + return [] + return [{"name": "Wait for the rollouts", "run": "\n".join(commands) + "\n"}] + + def _docker_run_step(self, name, image, commands, env=None, volumes=(), workdir=None): + env = dict(env or {}) + parts = ["docker run --rm"] + parts += [f"-e {key}" for key in env] + parts += [f'-v "{volume}"' for volume in volumes] + if workdir: + parts.append(f"-w {workdir}") + parts.append('"$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS"') + env["CH_TEST_IMAGE"] = image + env["CH_TEST_COMMANDS"] = "\n".join(["set -e", *commands]) + "\n" + return {"name": name, "env": env, "run": " \\\n ".join(parts)} + + # --- expanded jobs --- + + def _prototype(self, prototype, name, image_name): + job = copy.deepcopy(prototype) + job.pop("commands", None) + return substitute_vars( + job, + { + "CH_NAME": name, + "CH_IMAGE": self.qualify(image_name), + "CH_TAG": tag_output(name), + }, + ) + + def _specific_needs(self, prototype, replacements: dict[str, list]) -> list[str]: + needs = [] + for need in normalize_needs(prototype.get("needs")): + for target in replacements.get(need, [need]): + if target and target not in needs: + needs.append(target) + return needs + + def _build_args(self, entity) -> list[str]: + project = self.project + args = {"NOCACHE": "${{ github.run_id }}"} + if project.config.local or project.config.debug: + args["DEBUG"] = "true" + for dependency in self._dependencies(entity): + args[ci.env_key(dependency.name)] = ( + f"{self.qualify(dependency.image_name)}:{tag_output(dependency.name)}" + ) + args.update(project.all_source_images()) + args.update(getattr(entity, "build_args", None) or {}) + return [f"{key}={value}" for key, value in args.items()] + + def _build_job(self, prototype, entity, build_ids, fragments, extra_tags=()): + name = entity.name + image = self.qualify(entity.image_name) + tag_var = ci.tag_variable(name) + job = self._prototype(prototype, name, entity.image_name) + job["name"] = f"Build {name}" + job["needs"] = self._specific_needs( + prototype, + { + JOB_BUILD: [], + JOB_BUILD_TEST_IMAGES: [], + JOB_PREPARE: [JOB_PREPARE], + }, + ) or [JOB_PREPARE] + if JOB_PREPARE not in job["needs"]: + job["needs"].insert(0, JOB_PREPARE) + for dependency in self._dependencies(entity): + dependency_job = build_ids.get(dependency.name) + if dependency_job and dependency_job not in job["needs"]: + job["needs"].append(dependency_job) + job["if"] = combine_conditions( + prototype.get("if"), f"needs.{JOB_PREPARE}.outputs.{tag_var}_EXISTS != '1'" + ) + steps = expand_steps( + job.get("steps"), + {**fragments, FRAGMENT_GIT_CLONES: self._git_clone_steps([entity])}, + ) + build = step_by_id(steps, STEP_BUILD) + if build is not None: + context = self._context_for(entity) + with_ = build.setdefault("with", {}) + with_["context"] = f"./{context.path}" + with_["file"] = f"./{context.path}/{context.dockerfile}" + with_["build-args"] = "\n".join(self._build_args(entity)) + tags = [ + f"{image}:{tag_output(name)}", + f"{image}:{prepare_output('branch_tag')}", + *(f"{image}:{tag}" for tag in extra_tags), + ] + with_["tags"] = "\n".join(tags) + forced = ( + f"needs.{JOB_PREPARE}.outputs.force_build == 'all' || " + f"contains(format(',{{0}},', needs.{JOB_PREPARE}.outputs.force_build), ',{name},')" + ) + build["if"] = combine_conditions( + build.get("if"), f"steps.{STEP_CHECK}.outputs.exists != 'true' || {forced}" + ) + job["steps"] = steps + return job + + def _unit_test_job(self, prototype, app, build_ids, fragments): + job = self._prototype(prototype, app.name, app.image_name) + job["name"] = f"Unit tests {app.name}" + job["needs"] = self._specific_needs(prototype, {JOB_BUILD: [build_ids.get(app.name)]}) + test_step = self._docker_run_step( + f"Run {app.name} unit tests", + f"{self.qualify(app.image_name)}:{tag_output(app.name)}", + app.test.unit.commands, + ) + job["steps"] = expand_steps(job.get("steps"), {**fragments, FRAGMENT_TEST: [test_step]}) + return job + + def _test_image_reference(self, name) -> str | None: + test_image = self.project.test_images.get(name) + if test_image is None or not test_image.dockerfile.exists(): + return None + return f"{self.qualify(test_image.image_name)}:{tag_output(name)}" + + def _api_test_job(self, prototype, app, build_ids, fragments): + url = ci.api_test_url(app, "${{ vars.DOMAIN }}") + image = self._test_image_reference(TEST_IMAGE_API) + if url is None or image is None: + return None + job = self._prototype(prototype, app.name, app.image_name) + job["name"] = f"API tests {app.name}" + job["needs"] = self._specific_needs( + prototype, {JOB_BUILD_TEST_IMAGES: [build_ids.get(TEST_IMAGE_API)]} + ) + app_path = self._pipeline_path(app.path) + test_step = self._docker_run_step( + f"Run {app.name} API tests", + image, + ci.api_test_commands(app, url), + env=ci.test_environment(app, url), + volumes=[ + f"$GITHUB_WORKSPACE/{app_path}:{TEST_HOME}", + "$GITHUB_WORKSPACE/deployment/helm/values.yaml:/opt/cloudharness/resources/allvalues.yaml", + ], + workdir=TEST_HOME, + ) + job["steps"] = expand_steps(job.get("steps"), {**fragments, FRAGMENT_TEST: [test_step]}) + return job + + def _e2e_test_job(self, prototype, app, build_ids, fragments): + image = self._test_image_reference(TEST_IMAGE_E2E) + if image is None: + return None + url = ci.app_domain(app, "${{ vars.DOMAIN }}") + job = self._prototype(prototype, app.name, app.image_name) + job["name"] = f"E2E tests {app.name}" + job["needs"] = self._specific_needs( + prototype, {JOB_BUILD_TEST_IMAGES: [build_ids.get(TEST_IMAGE_E2E)]} + ) + app_path = self._pipeline_path(app.path) + test_step = self._docker_run_step( + f"Run {app.name} E2E tests", + image, + list(prototype.get("commands") or DEFAULT_E2E_COMMANDS), + env=ci.test_environment(app, url), + volumes=[f"$GITHUB_WORKSPACE/{app_path}/test/e2e:{TEST_HOME}/__tests__/{app.name}"], + workdir=TEST_HOME, + ) + job["steps"] = expand_steps(job.get("steps"), {**fragments, FRAGMENT_TEST: [test_step]}) + return job + + def _prepare_outputs(self) -> dict[str, str]: + outputs = {} + for name in ci.image_tag_names(self.project): + variable = ci.tag_variable(name) + for key in (variable, f"{variable}_EXISTS"): + outputs[key] = "${{ steps.%s.outputs.%s }}" % (STEP_IMAGES, key) + return outputs + + def _expand_jobs(self, jobs: dict) -> dict: + project = self.project + removed = [key for key, job in jobs.items() if job is None] + jobs = {key: job for key, job in jobs.items() if job is not None} + + entities = self._entities() + apps = self._buildable_apps() + unit_apps = [app for app in apps if app.test.unit.commands] + api_apps = ( + [app for app in apps if ci.has_api_tests(app) and app.openapi.server_urls] + if JOB_API_TESTS in jobs + else [] + ) + e2e_apps = [app for app in apps if ci.has_e2e_tests(app)] if JOB_E2E_TESTS in jobs else [] + test_entities = {} + if JOB_BUILD_TEST_IMAGES in jobs and JOB_BUILD in jobs: + for name, users in ((TEST_IMAGE_API, api_apps), (TEST_IMAGE_E2E, e2e_apps)): + image = project.test_images.get(name) + if users and image is not None and image.dockerfile.exists(): + test_entities[name] = image + + build_ids = {name: job_id(f"{JOB_BUILD}-{name}") for name in [*entities, *test_entities]} + unit_ids = {app.name: job_id(f"{JOB_UNIT_TESTS}-{app.name}") for app in unit_apps} + api_ids = {app.name: job_id(f"{JOB_API_TESTS}-{app.name}") for app in api_apps} + e2e_ids = {app.name: job_id(f"{JOB_E2E_TESTS}-{app.name}") for app in e2e_apps} + generated_ids = {*build_ids.values(), *unit_ids.values(), *api_ids.values(), *e2e_ids.values()} + + fragments = { + FRAGMENT_GIT_CLONES: self._git_clone_steps(apps), + FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_entities}), + FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), + FRAGMENT_ROLLOUT: self._rollout_steps(), + FRAGMENT_TEST: [], + } + + overlays = {key: job for key, job in jobs.items() if key in generated_ids} + overlay_prefixes = tuple(f"{prototype}-" for prototype in PROTOTYPE_JOBS) + # a prototype left out or removed with null expands to nothing: the jobs + # needing it simply drop the dependency + expansions: dict[str, list[str]] = {key: [] for key in [*PROTOTYPE_JOBS, *removed]} + result: dict[str, dict] = {} + + def expand(key, items, make): + ids = [] + for item in items: + expanded_id, job = make(item) + if job is None: + continue + result[expanded_id] = job + ids.append(expanded_id) + expansions[key] = ids + + for key, job in jobs.items(): + if key in overlays: + continue + if key == JOB_BUILD: + expand( + key, + entities.items(), + lambda item: ( + build_ids[item[0]], + self._build_job(job, item[1], build_ids, fragments), + ), + ) + elif key == JOB_BUILD_TEST_IMAGES: + prototype = dict_merge(jobs[JOB_BUILD], job) if JOB_BUILD in jobs else None + expand( + key, + test_entities.items() if prototype else [], + lambda item: ( + build_ids[item[0]], + self._build_job( + prototype, item[1], build_ids, fragments, extra_tags=("latest",) + ), + ), + ) + elif key == JOB_UNIT_TESTS: + expand( + key, + unit_apps, + lambda app: ( + unit_ids[app.name], + self._unit_test_job(job, app, build_ids, fragments), + ), + ) + elif key == JOB_API_TESTS: + expand( + key, + api_apps, + lambda app: ( + api_ids[app.name], + self._api_test_job(job, app, build_ids, fragments), + ), + ) + elif key == JOB_E2E_TESTS: + expand( + key, + e2e_apps, + lambda app: ( + e2e_ids[app.name], + self._e2e_test_job(job, app, build_ids, fragments), + ), + ) + elif key.startswith(overlay_prefixes): + # an overlay for an image/app that is not part of this deployment + continue + else: + job = copy.deepcopy(job) + if key == JOB_PREPARE: + outputs = dict(job.get("outputs") or {}) + for output, value in self._prepare_outputs().items(): + outputs.setdefault(output, value) + job["outputs"] = outputs + job["steps"] = expand_steps(job.get("steps"), fragments) + result[key] = job + + for key, overlay in overlays.items(): + if key in result: + result[key] = dict_merge(result[key], overlay) + + rewrite_needs(result, expansions) + apply_needs_guards(result) + return result + + def generate(self, write_on_disk=True, output_path=None): + project = self.project + + base = copy.deepcopy(project.github_template.all_values()) + if not base: + logging.warning( + "No GitHub Actions template found for environments %s: workflow not generated", + project.config.envs, + ) + return {} + + base = substitute_vars(base, ci.placeholder_values(project, self._pipeline_path)) + base["jobs"] = self._expand_jobs(base.get("jobs") or {}) + # the env template contributes name/on after the base keys: put them first + base = {key: base[key] for key in ("name", "on") if key in base} | { + key: value for key, value in base.items() if key not in ("name", "on") + } + + runner = self._runner() + for job in base["jobs"].values(): + job.setdefault("runs-on", runner) + + references = referenced_names(base) + logging.info( + "GitHub Actions workflow %s expects repository variables %s and secrets %s", + self.path.name, + ", ".join(sorted(references["vars"])) or "-", + ", ".join(sorted(references["secrets"])) or "-", + ) + + if write_on_disk: + self.write(base, output_path=output_path) + + return base + + @classmethod + def write_on_disk(cls, path, data) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + yaml = GeneratedYAML() + yaml.width = 4096 + yaml.indent(mapping=2, sequence=4, offset=2) + with path.open("w", encoding="utf-8") as f: + yaml.dump(as_literal_blocks(data), f) diff --git a/tools/deployment-cli-tools/ch_cli_tools/model.py b/tools/deployment-cli-tools/ch_cli_tools/model.py index 54fc64b71..380081ac0 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/model.py +++ b/tools/deployment-cli-tools/ch_cli_tools/model.py @@ -79,6 +79,7 @@ class CHTemplate import copy import hashlib import itertools +import json import logging import re import shutil @@ -1381,6 +1382,20 @@ def _hashable_entities(self) -> dict[str, CHApp | CHBaseImage | CHAppTask]: entities.update(self.test_images) return entities + def _hashed_build_args(self, entity) -> dict[str, str]: + """Build args that change an image without changing its context: the pinned + source images its own Dockerfile FROMs (as resolved project-wide) and the + app's own dockerfile.buildArgs. Folded into the content hash so bumping a + base image version invalidates the tag.""" + source_images = self.all_source_images() + args = { + key: source_images[key] + for key in entity.dockerfile.base_images + if key in source_images + } + args.update(getattr(entity, "build_args", None) or {}) + return {key: str(value) for key, value in args.items()} + @lru_cache def _content_hash_tags(self) -> dict[str, str]: """Content-hash tags per entity, folding in each dependency's own hash; cycle-safe.""" @@ -1391,9 +1406,13 @@ def _content_hash_tags(self) -> dict[str, str]: def own_hash(entity) -> str: if entity.name not in own_hashes: - own_hashes[entity.name] = content_hash( - entity.dockerfile.app.build_context - ) + digest = content_hash(entity.dockerfile.app.build_context) + build_args = self._hashed_build_args(entity) + if build_args: + digest = hashlib.sha1( + (digest + json.dumps(build_args, sort_keys=True)).encode("utf-8") + ).hexdigest() + own_hashes[entity.name] = digest return own_hashes[entity.name] def resolve(entity) -> str: @@ -1601,6 +1620,7 @@ class CHDeployConfig: chart_name: str | None = field(default=None, kw_only=True) chart_version: str | None = field(default=None, kw_only=True) app_version: str | None = field(default=None, kw_only=True) + ci_runner: str | None = field(default=None, kw_only=True) @property def envs(self) -> list[str]: diff --git a/tools/deployment-cli-tools/harness-deployment b/tools/deployment-cli-tools/harness-deployment index 38a65da48..914482d5a 100644 --- a/tools/deployment-cli-tools/harness-deployment +++ b/tools/deployment-cli-tools/harness-deployment @@ -1,10 +1,12 @@ #!/usr/bin/env python +import os import sys from pathlib import Path from cloudharness_utils.constants import DEPLOYMENT_PATH from ch_cli_tools.api import deploy, hosts_info, perform_migration +from ch_cli_tools.ci import parse_force_build from ch_cli_tools.model import CHDeployConfig, CHProject from ch_cli_tools.utils import generation_argv @@ -160,6 +162,25 @@ if __name__ == "__main__": const=True, help=f"Do not generate ci/cd files", ) + parser.add_argument( + "-ci", + "--ci-provider", + dest="ci_providers", + action="append", + choices=["codefresh", "github"], + default=None, + help="CI/CD system to generate the pipeline for; repeat to generate more than one " + "(default: codefresh). github writes .github/workflows/cloudharness-[ENV].yaml and takes " + "the runner from the CH_GITHUB_RUNNER environment variable (default: ubuntu-latest)", + ) + parser.add_argument( + "--force-build", + dest="force_build", + action="store", + default=None, + help="With --write-env, report these images (comma-separated, or `all`) as not built yet " + "so the pipeline rebuilds them even if their tag already exists in the registry", + ) parser.add_argument( "-we", "--write-env", @@ -236,6 +257,7 @@ if __name__ == "__main__": chart_name=args.name, chart_version=args.chart_version, app_version=args.app_version, + ci_runner=os.environ.get("CH_GITHUB_RUNNER"), ) if args.docker_compose: @@ -249,13 +271,18 @@ if __name__ == "__main__": project.helm_chart.generate() helm_values = project.build_final_helm_values() + ci_providers = args.ci_providers or ["codefresh"] if not args.no_cd_gen and envs and not args.docker_compose: - project.codefresh.generate() + if "codefresh" in ci_providers: + project.codefresh.generate() + if "github" in ci_providers: + project.github_actions.generate() if args.write_env: project.codefresh.write_env_file( root_paths[-1] / DEPLOYMENT_PATH / ".env", args.image_cache_url, + force_build=parse_force_build(args.force_build), ) project.skaffold.generate() diff --git a/tools/deployment-cli-tools/tests/conftest.py b/tools/deployment-cli-tools/tests/conftest.py index aed4ba26a..38df85508 100644 --- a/tools/deployment-cli-tools/tests/conftest.py +++ b/tools/deployment-cli-tools/tests/conftest.py @@ -28,3 +28,23 @@ def minimal_project(tmp_path, **config_kwargs): FROM scratch """) return chain(tmp_path, tmp_path, config=CHDeployConfig(**config_kwargs)) + + +def deployable_project(tmp_path, **config_kwargs): + """Like minimal_project, but with the values the final Helm model requires + (`mainapp`), so build_final_helm_values() and everything on top of it work.""" + write_tree_from_yaml(tmp_path, """ + deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: myapp + applications: + myapp: + Dockerfile: | + FROM scratch + tasks: + mytask: + Dockerfile: | + FROM scratch + """) + return chain(tmp_path, config=CHDeployConfig(**config_kwargs)) diff --git a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml new file mode 100644 index 000000000..ef32d8b4d --- /dev/null +++ b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml @@ -0,0 +1,12 @@ +# Test fixture: a project overlay of the dev workflow template. +test_step: dev +jobs: + prepare: + name: Overridden + build-myapp: + runs-on: big-runner + custom-job: + name: Custom + needs: [deploy] + steps: + - run: echo custom diff --git a/tools/deployment-cli-tools/tests/test_ci.py b/tools/deployment-cli-tools/tests/test_ci.py new file mode 100644 index 000000000..24c19a8b2 --- /dev/null +++ b/tools/deployment-cli-tools/tests/test_ci.py @@ -0,0 +1,93 @@ +"""ch_cli_tools.ci: the pieces shared by the Codefresh and GitHub Actions generators.""" + +from unittest.mock import patch + +import pytest +from conftest import deployable_project + +from ch_cli_tools.ci import ( + ImageReference, + env_key, + image_tag_env, + is_forced, + parse_force_build, + tag_variable, +) + + +def test_env_key_and_tag_variable(): + assert env_key("my-app") == "MY_APP" + assert tag_variable("cloudharness-base") == "CLOUDHARNESS_BASE_TAG" + + +@pytest.mark.parametrize( + "image, expected", + [ + ("reg.io/proj/myapp:abc", ("reg.io", "proj/myapp", "abc")), + ("localhost:5000/proj/myapp:abc", ("localhost:5000", "proj/myapp", "abc")), + ("proj/myapp:abc", ("docker.io", "proj/myapp", "abc")), + ("proj/myapp", ("docker.io", "proj/myapp", "latest")), + ("reg.io/proj/myapp", ("reg.io", "proj/myapp", "latest")), + ], +) +def test_image_reference_parse(image, expected): + reference = ImageReference.parse(image) + assert (reference.registry, reference.repository, reference.tag) == expected + + +def test_parse_force_build(): + assert parse_force_build(None) == () + assert parse_force_build("") == () + assert parse_force_build("myapp, other,,") == ("myapp", "other") + assert is_forced("myapp", ("myapp",)) + assert is_forced("anything", ("all",)) + assert not is_forced("myapp", ()) + + +def test_image_tag_env_marks_existing_and_new_images(tmp_path): + project = deployable_project(tmp_path, registry="reg.io/proj", tag="1") + + with patch( + "ch_cli_tools.ci.check_image_exists_in_registry", side_effect=[True, False] + ) as check: + env = image_tag_env(project, image_cache_endpoint_url="https://cache") + + assert env["MYAPP_TAG"] == "1" + assert env["MYAPP_TAG_EXISTS"] == "1" + assert env["MYAPP_MYTASK_TAG"] == "1" + assert env["MYAPP_MYTASK_TAG_NEW"] == "1" + registry, repository, tag = check.call_args_list[0].args + assert (registry, repository, tag) == ("reg.io", "proj/testproj/myapp", "1") + assert check.call_args_list[0].kwargs == {"endpoint_url": "https://cache"} + + +def test_image_tag_env_forced_images_skip_the_registry_check(tmp_path): + project = deployable_project(tmp_path, registry="reg.io/proj", tag="1") + + with patch( + "ch_cli_tools.ci.check_image_exists_in_registry", return_value=True + ) as check: + env = image_tag_env(project, force_build=("myapp",)) + + assert env["MYAPP_TAG_NEW"] == "1" + assert "MYAPP_TAG_EXISTS" not in env + assert env["MYAPP_MYTASK_TAG_EXISTS"] == "1" + assert check.call_count == 1 + + with patch("ch_cli_tools.ci.check_image_exists_in_registry") as check: + env = image_tag_env(project, force_build=("all",)) + assert check.call_count == 0 + assert env["MYAPP_TAG_NEW"] == "1" + assert env["MYAPP_MYTASK_TAG_NEW"] == "1" + + +def test_codefresh_write_env_file_accepts_force_build(tmp_path): + project = deployable_project(tmp_path, registry="reg.io/proj", tag="1") + env_file = tmp_path / "build.env" + + with patch("ch_cli_tools.ci.check_image_exists_in_registry", return_value=True): + project.codefresh.write_env_file(env_file, force_build=("all",)) + + lines = env_file.read_text().splitlines() + assert "MYAPP_TAG=1" in lines + assert "MYAPP_TAG_NEW=1" in lines diff --git a/tools/deployment-cli-tools/tests/test_codefresh.py b/tools/deployment-cli-tools/tests/test_codefresh.py index d230a0361..27bf51541 100644 --- a/tools/deployment-cli-tools/tests/test_codefresh.py +++ b/tools/deployment-cli-tools/tests/test_codefresh.py @@ -1109,7 +1109,7 @@ def test_write_env_file(tmp_path): env_file = tmp_path / "test.env" with patch( - "ch_cli_tools.codefresh.check_image_exists_in_registry", + "ch_cli_tools.ci.check_image_exists_in_registry", side_effect=[True, False, True, False, True, False, True, False], ) as mock_check: write_env_file(values, str(env_file)) diff --git a/tools/deployment-cli-tools/tests/test_content_hash_build_args.py b/tools/deployment-cli-tools/tests/test_content_hash_build_args.py new file mode 100644 index 000000000..6ad8e0999 --- /dev/null +++ b/tools/deployment-cli-tools/tests/test_content_hash_build_args.py @@ -0,0 +1,49 @@ +"""The content-hash tag must change when a pinned source image or a declared +build arg changes, even though the build context itself did not.""" + +from conftest import chain +from test_util import write_tree_from_yaml + +from ch_cli_tools import CHDeployConfig + +TREE = """ +deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: myapp + {source_images} +applications: + myapp: + Dockerfile: | + ARG PYTHON=python:3.12 + FROM $PYTHON + deploy: + values.yaml: | + harness: + dockerfile: + buildArgs: + FLAVOUR: {flavour} + other: + Dockerfile: | + ARG NODE=node:22 + FROM $NODE +""" + + +def _tag(tmp_path, source_images="", flavour="a"): + root = tmp_path / f"{len(list(tmp_path.iterdir()))}" + write_tree_from_yaml(root, TREE.format(source_images=source_images, flavour=flavour)) + project = chain(root, config=CHDeployConfig(registry="reg")) + return project.qualify_image(project["myapp"]).rsplit(":", 1)[1] + + +def test_source_image_and_build_args_change_the_tag(tmp_path): + baseline = _tag(tmp_path) + assert _tag(tmp_path) == baseline, "the tag is stable" + assert _tag(tmp_path, source_images='source_images: {PYTHON: "python:3.13"}') != baseline + assert _tag(tmp_path, flavour="b") != baseline + + +def test_unrelated_source_image_keeps_the_tag(tmp_path): + baseline = _tag(tmp_path) + assert _tag(tmp_path, source_images='source_images: {NODE: "node:24"}') == baseline diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py new file mode 100644 index 000000000..a4265212f --- /dev/null +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -0,0 +1,438 @@ +"""End-to-end tests of the GitHub Actions workflow generator, over the same +[CLOUDHARNESS_ROOT, RESOURCES] chain and arguments test_codefresh.py uses.""" + +import os +import re +import shutil +import tempfile + +from conftest import CLOUDHARNESS_ROOT, RESOURCES, chain +from ruamel.yaml import YAML +from test_util import write_tree_from_yaml + +from ch_cli_tools import CHDeployConfig +from ch_cli_tools.api import create_helm_chart +from ch_cli_tools.github_actions import DEFAULT_RUNNER + +JOB_ID = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$") + + +def _generate(tmp_path, include, envs=("dev",), **helm_chart_kwargs): + values = create_helm_chart( + [CLOUDHARNESS_ROOT, RESOURCES], + output_path=tmp_path / "deployment", + include=include, + exclude=["events"], + domain="my.local", + namespace="test", + env=list(envs), + local=False, + tag="1", + registry="reg", + **helm_chart_kwargs, + ) + project = values._ch_project + return project.github_actions.generate(write_on_disk=False), project + + +def _step(job, step_id): + return next(step for step in job["steps"] if step.get("id") == step_id) + + +def _steps(job, name_prefix): + return [step for step in job["steps"] if str(step.get("name", "")).startswith(name_prefix)] + + +def _run_strings(workflow): + for job in workflow["jobs"].values(): + for step in job["steps"]: + if "run" in step: + yield step["run"] + + +def test_template_layering(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + + # cloud-harness base + env template, then the project's own dev overlay + assert wf["name"] == "CloudHarness dev" + assert wf["on"]["push"]["branches"] == ["develop"] + assert "workflow_dispatch" in wf["on"] + assert wf["permissions"]["packages"] == "write" + assert wf["test_step"] == "dev" + assert wf["jobs"]["prepare"]["name"] == "Overridden" + # a job the project adds gets the dependency guard like any other + custom = wf["jobs"]["custom-job"] + assert custom["needs"] == ["deploy"] + assert "needs.deploy.result == 'success'" in custom["if"] + # an overlay for an expanded job id is merged over the generated job + assert wf["jobs"]["build-myapp"]["runs-on"] == "big-runner" + + +def test_build_jobs_follow_the_dependency_graph(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + jobs = wf["jobs"] + + for name in ("cloudharness-base", "cloudharness-flask", "myapp", "myapp-mytask", "my-common", "samples"): + assert f"build-{name}" in jobs, name + # only what the deployment needs is built: no excluded app, no unused base image + assert "build-events" not in jobs + assert "build-cloudharness-base-debian" not in jobs + + assert jobs["build-cloudharness-base"]["needs"] == ["prepare"] + assert jobs["build-myapp"]["needs"][:2] == ["prepare", "build-cloudharness-flask"] + assert jobs["build-cloudharness-flask"]["needs"] == ["prepare", "build-cloudharness-base"] + + condition = jobs["build-myapp"]["if"] + assert "needs.prepare.outputs.MYAPP_TAG_EXISTS != '1'" in condition + assert "!cancelled()" in condition + assert "needs.prepare.result == 'success'" in condition + # a skipped dependency build must not skip the dependant + assert "needs.build-cloudharness-flask.result ==" not in condition + + +def test_build_step_inputs(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + jobs = wf["jobs"] + + build = _step(jobs["build-myapp"], "build") + with_ = build["with"] + assert with_["context"] == "./applications/myapp" + assert with_["file"] == "./applications/myapp/dev.Dockerfile", "env Dockerfile preferred" + assert isinstance(with_["build-args"], str) and isinstance(with_["tags"], str) + build_args = with_["build-args"].splitlines() + assert build_args[0] == "NOCACHE=${{ github.run_id }}" + assert ( + "CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/testprojectname/cloudharness-flask:" + "${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }}" in build_args + ) + tags = with_["tags"].splitlines() + assert tags[0] == "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + assert tags[1].endswith(":${{ needs.prepare.outputs.branch_tag }}") + assert with_["push"] is True + assert with_["cache-from"] == "type=registry,ref=${{ vars.REGISTRY }}/testprojectname/myapp:buildcache" + assert "steps.check.outputs.exists != 'true'" in build["if"] + assert "',myapp,'" in build["if"] + + check = _step(jobs["build-myapp"], "check") + assert check["env"]["IMAGE"] == ( + "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + ) + assert 'imagetools inspect "$IMAGE"' in check["run"] + + # cloudharness-base is overridden by RESOURCES: built from the merged .overrides context + base = _step(jobs["build-cloudharness-base"], "build")["with"] + assert base["context"] == "./.overrides/cloudharness-base" + assert base["file"] == ( + "./.overrides/cloudharness-base/infrastructure/base-images/cloudharness-base/Dockerfile" + ) + # samples lives in cloud-harness, cloned into ./cloud-harness by the workflow + samples = _step(jobs["build-samples"], "build")["with"] + assert samples["context"] == "./cloud-harness/applications/samples" + assert samples["file"] == "./cloud-harness/applications/samples/Dockerfile" + # a test image gets the extra latest tag + assert "${{ vars.REGISTRY }}/testprojectname/test-e2e:latest" in ( + _step(jobs["build-test-e2e"], "build")["with"]["tags"].splitlines() + ) + + +def test_git_dependency_checkouts(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + jobs = wf["jobs"] + + clones = _steps(jobs["build-myapp"], "Clone ") + clones = [step for step in clones if step["name"] != "Clone cloud-harness"] + assert len(clones) == 2, "myapp declares two git dependencies" + assert clones[0]["uses"] == "actions/checkout@v4" + assert clones[0]["with"]["repository"] == "a/b" + assert clones[0]["with"]["ref"] == "master" + assert clones[0]["with"]["path"] == "applications/myapp/dependencies/b" + step_names = [step.get("name") for step in jobs["build-myapp"]["steps"]] + assert step_names.index("Clone b") < step_names.index("Build and push myapp") + # prepare clones them too (the content hash needs them); samples has none + assert len([s for s in _steps(jobs["prepare"], "Clone ") if s["name"] != "Clone cloud-harness"]) == 2 + assert not [s for s in _steps(jobs["build-samples"], "Clone ") if s["name"] != "Clone cloud-harness"] + + +def test_prepare_outputs_cover_every_build(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + outputs = wf["jobs"]["prepare"]["outputs"] + + assert list(outputs)[0] == "branch_tag", "template outputs come first" + for job_name in wf["jobs"]: + if not job_name.startswith("build-"): + continue + variable = job_name[len("build-"):].replace("-", "_").upper() + "_TAG" + assert outputs[variable] == "${{ steps.images.outputs.%s }}" % variable + assert outputs[f"{variable}_EXISTS"] == "${{ steps.images.outputs.%s_EXISTS }}" % variable + # instances share their parent's image but still get their variables + assert "MYAPP_INST1_TAG" in outputs + + +def test_unit_test_jobs(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + jobs = wf["jobs"] + + unit_jobs = [name for name in jobs if name.startswith("tests-unit-")] + assert sorted(unit_jobs) == ["tests-unit-myapp", "tests-unit-samples"] + job = jobs["tests-unit-myapp"] + assert job["needs"] == ["prepare", "build-myapp"] + assert "needs.prepare.result == 'success'" in job["if"] + step = _steps(job, "Run myapp unit tests")[0] + assert step["env"]["CH_TEST_IMAGE"] == ( + "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + ) + assert step["env"]["CH_TEST_COMMANDS"].startswith("set -e\ntox\n") + assert step["run"].startswith("docker run --rm") + assert '"$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS"' in step["run"] + # deploy waits for the unit tests, as the Codefresh unittest stage precedes deploy + assert "tests-unit-myapp" in jobs["deploy"]["needs"] + + +def test_api_and_e2e_test_jobs(tmp_path): + wf, _ = _generate(tmp_path, ["samples"]) + jobs = wf["jobs"] + + api = jobs["tests-api-samples"] + assert "wait-deployment" in api["needs"] and "build-test-api" in api["needs"] + assert "needs.prepare.outputs.skip_tests != 'true'" in api["if"] + # wait-deployment may be skipped (it has its own `if`), but must not have failed + assert "needs.wait-deployment.result ==" not in api["if"] + assert "!contains(needs.*.result, 'failure')" in api["if"] + step = _steps(api, "Run samples API tests")[0] + assert step["env"]["APP_URL"] == "https://www.${{ vars.DOMAIN }}/api" + assert step["env"]["CH_TEST_IMAGE"] == ( + "${{ vars.REGISTRY }}/testprojectname/test-api:${{ needs.prepare.outputs.TEST_API_TAG }}" + ) + assert "-e APP_URL" in step["run"] + assert '-v "$GITHUB_WORKSPACE/cloud-harness/applications/samples:/home/test"' in step["run"] + assert "/opt/cloudharness/resources/allvalues.yaml" in step["run"] + assert "-w /home/test" in step["run"] + commands = step["env"]["CH_TEST_COMMANDS"].splitlines() + assert "--pre-run cloudharness_test.apitest_init" in commands[1] + assert "--base-url https://www.${{ vars.DOMAIN }}/api" in commands[1] + assert commands[2] == "pytest -v test/api" + + e2e = jobs["tests-e2e-samples"] + assert "build-test-e2e" in e2e["needs"] + step = _steps(e2e, "Run samples E2E tests")[0] + assert step["env"]["APP_URL"] == "https://www.${{ vars.DOMAIN }}" + assert ( + '-v "$GITHUB_WORKSPACE/cloud-harness/applications/samples/test/e2e:/home/test/__tests__/samples"' + in step["run"] + ) + assert step["env"]["CH_TEST_COMMANDS"] == "set -e\nnpx puppeteer browsers install chrome\nyarn test\n" + assert "commands" not in e2e, "the prototype's commands key never reaches the workflow" + + # the test runner images are built with the build prototype + assert jobs["build-test-api"]["needs"] == ["prepare", "build-cloudharness-base"] + assert "build-test-api" not in jobs["deploy"]["needs"] + + +def test_no_api_e2e_jobs_when_not_enabled(tmp_path): + wf, _ = _generate(tmp_path, ["myapp"]) + names = list(wf["jobs"]) + assert not [n for n in names if n.startswith(("tests-api", "tests-e2e", "build-test-"))] + assert "wait-deployment" in names + # nothing references the removed prototypes any more + for job in wf["jobs"].values(): + for need in job.get("needs", []): + assert need in wf["jobs"], need + + +def test_deploy_secret_values(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"], registry_secret_name="my-pull-secret") + deploy = wf["jobs"]["deploy"] + + step = _steps(deploy, "Collect secret values")[0] + assert step["env"]["ASECRET"] == "${{ secrets.ASECRET }}" + assert step["env"]["MYAPP_DB_CONNECT_STRING"] == "${{ secrets.MYAPP_DB_CONNECT_STRING }}" + assert step["env"]["K8S_SA_JSON"] == "${{ secrets.K8S_SA_JSON }}" + assert "--set-file apps.samples.harness.secrets.asecret=$secrets_dir/" in step["run"] + assert "--set-file apps.myapp.harness.database.connect_string=$secrets_dir/" in step["run"] + assert "--set-file registry.secret.value=$secrets_dir/" in step["run"] + assert 'echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV"' in step["run"] + install = _steps(deploy, "Install chart")[0] + assert "$HELM_SET_ARGS" in install["run"] + assert "helm upgrade --install" in install["run"] + # secrets only ever travel through env, never inline in a script + assert not [run for run in _run_strings(wf) if "${{ secrets." in run] + + +def test_rollout_wait_and_publish_steps(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + jobs = wf["jobs"] + + rollout = _steps(jobs["wait-deployment"], "Wait for the rollouts")[0] + lines = rollout["run"].splitlines() + assert any(line.startswith("kubectl rollout status deployment/") for line in lines) + assert lines[-1] == "sleep 60" + + publish = jobs["publish"] + assert "needs.prepare.outputs.publish_tag != ''" in publish["if"] + assert "deploy" in publish["needs"] and "tests-e2e-samples" in publish["needs"] + assert publish["environment"] == "publish" + published = {step["name"][len("Publish "):] for step in _steps(publish, "Publish ")} + built = {name[len("build-"):] for name in jobs if name.startswith("build-")} + assert published == built + step = _steps(publish, "Publish myapp")[0] + assert step["if"] == "${{ vars.MYAPP_PUBLISH_SKIP == '' }}" + assert step["env"]["SOURCE"] == ( + "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + ) + assert step["env"]["TARGET"] == "${{ vars.REGISTRY_PUBLISH_URL || vars.REGISTRY }}/testprojectname/myapp" + assert "imagetools create" in step["run"] + + +def test_prepare_command_placeholders(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + run = _step(wf["jobs"]["prepare"], "images")["run"] + assert 'harness-deployment cloud-harness . -d "$DOMAIN"' in run + assert "-e dev " in run + assert "-i samples -i myapp -ex events" in run + assert "$PATHS" not in run and "$ENV " not in run and "$PARAMS" not in run + assert "--write-env" in run and "--force-build" in run + + +def test_multienv_test_overlay(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"], envs=("dev", "test")) + jobs = wf["jobs"] + + assert wf["name"] == "CloudHarness dev-test" + assert "pull_request" in wf["on"] + assert "publish" not in jobs + assert jobs["prepare"]["env"]["NAMESPACE"] == "test-${{ vars.NAMESPACE_BASENAME }}" + assert "-e dev-test " in _step(jobs["prepare"], "images")["run"] + cleanup = jobs["cleanup"] + assert cleanup["if"] == "${{ always() && needs.deploy.result == 'success' }}" + assert "tests-unit-myapp" in cleanup["needs"] and "tests-e2e-samples" in cleanup["needs"] + + +def test_prod_deploys_only(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"], envs=("prod",)) + jobs = wf["jobs"] + + assert list(jobs) == ["prepare", "deploy"] + assert jobs["deploy"]["needs"] == ["prepare"] + assert jobs["deploy"]["environment"] == "prod" + assert jobs["deploy"]["env"]["HELM_FLAGS"].startswith("--wait") + assert wf["on"]["workflow_dispatch"]["inputs"]["deployment_tag"]["required"] is True + + +def test_stage_keeps_tests_and_tags_the_repository(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"], envs=("stage",)) + jobs = wf["jobs"] + + assert not [name for name in jobs if name.startswith("build-")] + assert "tests-api-samples" in jobs and "tests-unit-samples" not in jobs + assert jobs["tests-api-samples"]["needs"] == ["prepare", "wait-deployment"] + assert jobs["git-tag"]["needs"] == ["prepare", "publish"] + assert jobs["git-tag"]["permissions"] == {"contents": "write"} + + +def test_runner_configuration(tmp_path): + wf, _ = _generate(tmp_path, ["myapp"]) + assert all(job["runs-on"] == DEFAULT_RUNNER for name, job in wf["jobs"].items() if name != "build-myapp") + assert wf["jobs"]["build-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" + + project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig( + env="dev", includes=["myapp"], excludes=["events"], registry="reg", tag="1", + output_path=str(tmp_path / "deployment"), ci_runner="self-hosted, linux", + )) + wf = project.github_actions.generate(write_on_disk=False) + assert wf["jobs"]["prepare"]["runs-on"] == ["self-hosted", "linux"] + + +def test_workflow_invariants(tmp_path): + wf, _ = _generate(tmp_path, ["samples", "myapp"], envs=("dev", "test")) + jobs = wf["jobs"] + + def walk(node): + yield node + if isinstance(node, dict): + for value in node.values(): + yield from walk(value) + elif isinstance(node, list): + for value in node: + yield from walk(value) + + for name, job in jobs.items(): + assert JOB_ID.match(name), name + for need in job.get("needs", []): + assert need in jobs, f"{name} needs unknown job {need}" + if "if" in job: + assert job["if"].startswith("${{") and job["if"].endswith("}}"), job["if"] + assert job["steps"], name + for step in job["steps"]: + assert isinstance(step, dict), f"unexpanded fragment {step!r} in {name}" + assert "uses" in step or "run" in step, step + assert not [node for node in walk(wf) if isinstance(node, tuple)] + assert not [node for node in walk(wf) if type(node).__module__ == "ch_cli_tools.model"] + + +def test_paths_are_cwd_independent(tmp_path): + sibling_dir = tempfile.mkdtemp(dir=str(CLOUDHARNESS_ROOT.parent)) + old_cwd = os.getcwd() + try: + os.chdir(sibling_dir) + wf, _ = _generate(tmp_path, ["samples"]) + finally: + os.chdir(old_cwd) + shutil.rmtree(sibling_dir, ignore_errors=True) + + for name, job in wf["jobs"].items(): + if not name.startswith("build-"): + continue + context = _step(job, "build")["with"]["context"] + assert not context.startswith("./..") and "/../" not in context, (name, context) + assert not os.path.isabs(context), (name, context) + assert "../cloud-harness" not in _step(wf["jobs"]["prepare"], "images")["run"] + + +def test_generate_writes_the_workflow_under_github_workflows(tmp_path): + write_tree_from_yaml( + tmp_path, + """ + deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: myapp + applications: + myapp: + Dockerfile: | + FROM scratch + """, + ) + project = chain( + CLOUDHARNESS_ROOT, + tmp_path, + config=CHDeployConfig(env="dev", registry="reg", tag="1", output_path=str(tmp_path / "deployment")), + ) + project.github_actions.generate() + + workflow = tmp_path / ".github" / "workflows" / "cloudharness-dev.yaml" + assert workflow.exists() + text = workflow.read_text() + assert text.startswith("name: CloudHarness dev\n") and text.splitlines()[1].startswith("on:") + assert "build-args: |" in text, "multi-line inputs are written as literal blocks" + assert "run: |" in text + loaded = YAML(typ="safe").load(text) + assert "on" in loaded and "build-myapp" in loaded["jobs"] + + +def test_no_template_means_no_workflow(tmp_path): + write_tree_from_yaml( + tmp_path, + """ + deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: myapp + applications: + myapp: + Dockerfile: | + FROM scratch + """, + ) + project = chain(tmp_path, config=CHDeployConfig(env="dev", registry="reg", tag="1")) + assert project.github_actions.generate() == {} + assert not (tmp_path / ".github").exists() diff --git a/tools/deployment-cli-tools/tests/test_github_actions_internals.py b/tools/deployment-cli-tools/tests/test_github_actions_internals.py new file mode 100644 index 000000000..906bc3e9d --- /dev/null +++ b/tools/deployment-cli-tools/tests/test_github_actions_internals.py @@ -0,0 +1,149 @@ +"""ch_cli_tools.github_actions: the pure helpers the generator is built from.""" + +import pytest +from ruamel.yaml.scalarstring import LiteralScalarString + +from ch_cli_tools.github_actions import ( + apply_needs_guards, + as_literal_blocks, + combine_conditions, + expand_steps, + github_repository, + github_secret_name, + job_id, + needs_guard, + referenced_names, + rewrite_needs, + step_by_id, + substitute_vars, +) + + +def test_job_id_is_valid_for_github(): + assert job_id("build-my.app/x") == "build-my-app-x" + assert job_id("9lives") == "_9lives" + assert job_id("build-cloudharness-base") == "build-cloudharness-base" + + +def test_substitute_vars_is_word_bounded_and_recursive(): + node = { + "run": "harness-deployment $PATHS -e $ENV $PARAMS; echo $ENV_FILE $PATH", + "list": ["$ENV", {"nested": "x-$ENV-y"}], + "number": 3, + } + result = substitute_vars(node, {"ENV": "dev", "PATHS": "cloud-harness .", "PARAMS": "-i a"}) + assert result["run"] == "harness-deployment cloud-harness . -e dev -i a; echo $ENV_FILE $PATH" + assert result["list"] == ["dev", {"nested": "x-dev-y"}] + assert result["number"] == 3 + # the input is left untouched + assert node["list"][0] == "$ENV" + + +def test_expand_steps_replaces_fragments_and_rejects_unknown_ones(): + fragment = [{"run": "a"}, {"run": "b"}] + steps = expand_steps([{"uses": "x"}, "$F", {"run": "c"}], {"$F": fragment}) + assert steps == [{"uses": "x"}, {"run": "a"}, {"run": "b"}, {"run": "c"}] + assert steps[1] is not fragment[0], "fragments are copied, never shared" + assert expand_steps(None, {}) == [] + with pytest.raises(ValueError, match="Unknown step fragment"): + expand_steps(["$NOPE"], {"$F": fragment}) + + +def test_step_by_id(): + steps = [{"run": "a"}, {"id": "build", "uses": "x"}] + assert step_by_id(steps, "build") == {"id": "build", "uses": "x"} + assert step_by_id(steps, "missing") is None + + +def test_combine_conditions(): + assert combine_conditions() == "" + assert combine_conditions(None, "") == "" + assert combine_conditions("${{ a }}") == "${{ a }}" + assert combine_conditions("a") == "${{ a }}" + assert combine_conditions("${{ a }}", None, "b || c") == "${{ (a) && (b || c) }}" + + +def test_needs_guard_requires_success_of_non_skippable_jobs(): + guard = needs_guard(["prepare", "build-a"], skippable={"build-a"}) + assert "!cancelled()" in guard + assert "!contains(needs.*.result, 'failure')" in guard + assert "needs.prepare.result == 'success'" in guard + assert "needs.build-a.result" not in guard + + +def test_rewrite_needs_expands_placeholders(): + jobs = { + "prepare": {}, + "build-a": {"needs": "prepare"}, + "build-b": {"needs": ["prepare", "build-a"]}, + "deploy": {"needs": ["prepare", "build", "tests-unit"]}, + "publish": {"needs": ["tests-e2e"]}, + } + rewrite_needs(jobs, {"build": ["build-a", "build-b"], "tests-unit": [], "tests-e2e": []}) + assert jobs["build-a"]["needs"] == ["prepare"] + assert jobs["deploy"]["needs"] == ["prepare", "build-a", "build-b"] + assert "needs" not in jobs["publish"] + + +def test_rewrite_needs_rejects_unknown_jobs(): + with pytest.raises(ValueError, match="unknown job 'approval'"): + rewrite_needs({"a": {}, "b": {"needs": ["a", "approval"]}}, {}) + + +def test_apply_needs_guards(): + jobs = { + "prepare": {}, + "build-a": {"needs": ["prepare"], "if": "${{ needs.prepare.outputs.A_TAG_EXISTS != '1' }}"}, + "deploy": {"needs": ["prepare", "build-a"]}, + "tests": {"needs": ["deploy"], "if": "${{ vars.SKIP_TESTS != 'true' }}"}, + "cleanup": {"needs": ["deploy"], "if": "${{ always() }}"}, + } + apply_needs_guards(jobs) + + assert "if" not in jobs["prepare"] + # build-a is skippable (own if), prepare is not + assert jobs["deploy"]["if"] == ( + "${{ !cancelled() && !contains(needs.*.result, 'failure') && " + "!contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }}" + ) + # the template's own condition is kept and the guard is ANDed to it + assert jobs["tests"]["if"].startswith("${{ (vars.SKIP_TESTS != 'true') && (!cancelled()") + assert "needs.deploy.result == 'success'" in jobs["tests"]["if"] + # build-a keeps its exists check plus the guard on prepare + assert "A_TAG_EXISTS != '1'" in jobs["build-a"]["if"] + assert "needs.prepare.result == 'success'" in jobs["build-a"]["if"] + # a job deciding with always() is left alone + assert jobs["cleanup"]["if"] == "${{ always() }}" + + +def test_as_literal_blocks(): + result = as_literal_blocks({"a": "one\nline two \n", "b": "single", "c": ("x", "y")}) + assert isinstance(result["a"], LiteralScalarString) + assert result["a"] == "one\nline two\n" + assert not isinstance(result["b"], LiteralScalarString) + assert result["c"] == ["x", "y"] + + +def test_github_secret_name(): + assert github_secret_name("DB__PASSWORD") == "DB__PASSWORD" + assert github_secret_name("google__bucket__credentials.json") == "GOOGLE__BUCKET__CREDENTIALS_JSON" + # GitHub reserves the GITHUB_ prefix for its own secrets + assert github_secret_name("GITHUB__CLIENTID") == "CH_GITHUB__CLIENTID" + + +def test_github_repository(): + assert github_repository("https://github.com/MetaCell/cloud-harness.git") == "MetaCell/cloud-harness" + assert github_repository("https://github.com/MetaCell/cloud-harness") == "MetaCell/cloud-harness" + assert github_repository("git@github.com:MetaCell/cloud-harness.git") == "MetaCell/cloud-harness" + assert github_repository("https://gitlab.com/group/project.git") is None + + +def test_referenced_names(): + names = referenced_names( + { + "a": "${{ vars.REGISTRY }}/x:${{ secrets.TOKEN }}", + "b": [{"c": "${{ secrets.GH_PAT || github.token }}"}], + "d": "--set-file apps.myapp.harness.secrets.asecret=/tmp/0", + } + ) + assert names == {"vars": {"REGISTRY"}, "secrets": {"TOKEN", "GH_PAT"}} From fe844cc1fec318be880ae1144c7ac79c2708726e Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 30 Oct 2026 18:42:47 +0100 Subject: [PATCH 02/11] Linting fix --- .../ch_cli_tools/model.py | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/tools/deployment-cli-tools/ch_cli_tools/model.py b/tools/deployment-cli-tools/ch_cli_tools/model.py index 380081ac0..156f1ecfa 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/model.py +++ b/tools/deployment-cli-tools/ch_cli_tools/model.py @@ -395,9 +395,9 @@ def hard_dependencies(self) -> list["CHApp | str"]: def build_dependencies(self) -> list["CHApp | CHBaseImage | CHAppTask | str"]: """Build dependencies, resolved against apps, base images and tasks.""" return [ - self.project.scanned_apps.get(dep) - or self.project.base_images.get(dep) - or self.project.all_buildable_tasks().get(dep, dep) + self.project.scanned_apps.get(dep) or + self.project.base_images.get(dep) or + self.project.all_buildable_tasks().get(dep, dep) for dep in cast( list[str], resolve_path(self.harness_config, "dependencies.build", default=[]), @@ -605,9 +605,9 @@ def _build_values(self, app_values: dict, instance_values: dict) -> dict: volume = (harness.get("deployment") or {}).get("volume") or {} if ( - volume.get("name") - and volume.get("auto", True) - and not self._instance_sets( + volume.get("name") and + volume.get("auto", True) and + not self._instance_sets( instance_values, "harness", "deployment", "volume", "name" ) ): @@ -625,9 +625,9 @@ def _build_values(self, app_values: dict, instance_values: dict) -> dict: ): for database_type, type_config in database.items(): if ( - isinstance(type_config, dict) - and type_config.get("initialdb") - and not self._instance_sets( + isinstance(type_config, dict) and + type_config.get("initialdb") and + not self._instance_sets( instance_values, "harness", "database", @@ -976,9 +976,9 @@ def base_dependencies(self) -> list["CHApp | CHBaseImage | CHAppTask | str"]: name = ref.lower().replace("_", "-") entity = ( - project.scanned_apps.get(name) - or project.base_images.get(name) - or project.all_buildable_tasks().get(name) + project.scanned_apps.get(name) or + project.base_images.get(name) or + project.all_buildable_tasks().get(name) ) dependencies.append(entity.dockerfile if entity is not None else name) return dependencies @@ -1224,8 +1224,8 @@ def involved_apps(self): instances = { instance for instance in self.all_instances().values() - if instance.parent_app.name in involved_names - and instance.name not in self.config.excludes + if instance.parent_app.name in involved_names and + instance.name not in self.config.excludes } return sorted( base | instances, key=lambda app: app if isinstance(app, str) else app.name From a8c3bfd1af6b8e4c4f4065adbc09c8567b9095d0 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 30 Oct 2026 18:50:25 +0100 Subject: [PATCH 03/11] CH-125 github action fix findings, custom runners support --- .github/workflows/cloudharness-test.yaml | 1586 +++++++++++++++++ .../github-template-prod.yaml | 1 - .../github-template-stage.yaml | 4 +- .../github-template-test.yaml | 9 +- deployment-configuration/github-template.yaml | 62 +- docs/build-deploy/ci-cd/README.md | 38 +- .../ch_cli_tools/github_actions.py | 52 +- .../ch_cli_tools/utils.py | 18 + tools/deployment-cli-tools/harness-deployment | 34 +- .../github-template-dev.yaml | 4 + .../tests/test_github_actions.py | 44 +- .../tests/test_github_actions_internals.py | 21 +- tools/deployment-cli-tools/tests/test_util.py | 54 +- 13 files changed, 1868 insertions(+), 59 deletions(-) create mode 100644 .github/workflows/cloudharness-test.yaml diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml new file mode 100644 index 000000000..ff32b02a0 --- /dev/null +++ b/.github/workflows/cloudharness-test.yaml @@ -0,0 +1,1586 @@ +# 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 +env: + CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} +jobs: + prepare: + name: Prepare helm chart + 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 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: azure/setup-helm@v4 + - name: Install cloud-harness tools + run: bash cloud-harness/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 --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 + .overrides + include-hidden-files: true + if-no-files-found: error + runs-on: ubuntu-latest + build-accounts: + name: Build accounts + needs: + - prepare + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether accounts already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.ACCOUNTS_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push accounts + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/accounts:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/accounts:buildcache,mode=max + context: ./applications/accounts + file: ./applications/accounts/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.ACCOUNTS_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',accounts,') }} + if: ${{ (needs.prepare.outputs.ACCOUNTS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-common: + name: Build common + needs: + - prepare + - build-cloudharness-flask + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether common already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.COMMON_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push common + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/common:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/common:buildcache,mode=max + context: ./applications/common + file: ./applications/common/server/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.COMMON_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',common,') }} + if: ${{ (needs.prepare.outputs.COMMON_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-jupyterhub: + name: Build jupyterhub + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether jupyterhub already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.JUPYTERHUB_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push jupyterhub + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/jupyterhub:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/jupyterhub:buildcache,mode=max + context: ./applications/jupyterhub + file: ./applications/jupyterhub/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.JUPYTERHUB_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',jupyterhub,') }} + if: ${{ (needs.prepare.outputs.JUPYTERHUB_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-nfsserver: + name: Build nfsserver + needs: + - prepare + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether nfsserver already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.NFSSERVER_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push nfsserver + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/nfsserver:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/nfsserver:buildcache,mode=max + context: ./applications/nfsserver + file: ./applications/nfsserver/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.NFSSERVER_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',nfsserver,') }} + if: ${{ (needs.prepare.outputs.NFSSERVER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-samples: + name: Build samples + needs: + - prepare + - build-cloudharness-flask + - build-cloudharness-frontend-build + - build-cloudharness-django + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether samples already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push samples + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp:buildcache,mode=max + context: ./applications/samples + file: ./applications/samples/test.Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + CLOUDHARNESS_FRONTEND_BUILD=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} + CLOUDHARNESS_DJANGO=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + TEST_ARGUMENT=example value + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples,') }} + if: ${{ (needs.prepare.outputs.SAMPLES_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-samples-print-file: + name: Build samples-print-file + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether samples-print-file already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push samples-print-file + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:buildcache,mode=max + context: ./applications/samples/tasks/print-file + file: ./applications/samples/tasks/print-file/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-print-file,') }} + if: ${{ (needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-samples-sum: + name: Build samples-sum + needs: + - prepare + - build-samples + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether samples-sum already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.SAMPLES_SUM_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push samples-sum + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:buildcache,mode=max + context: ./applications/samples/tasks/sum + file: ./applications/samples/tasks/sum/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + SAMPLES=${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.SAMPLES_SUM_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-sum,') }} + if: ${{ (needs.prepare.outputs.SAMPLES_SUM_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-samples-secret: + name: Build samples-secret + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether samples-secret already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.SAMPLES_SECRET_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push samples-secret + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:buildcache,mode=max + context: ./applications/samples/tasks/secret + file: ./applications/samples/tasks/secret/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.SAMPLES_SECRET_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-secret,') }} + if: ${{ (needs.prepare.outputs.SAMPLES_SECRET_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-volumemanager: + name: Build volumemanager + needs: + - prepare + - build-cloudharness-flask + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether volumemanager already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.VOLUMEMANAGER_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push volumemanager + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/volumemanager:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/volumemanager:buildcache,mode=max + context: ./applications/volumemanager + file: ./applications/volumemanager/server/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.VOLUMEMANAGER_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',volumemanager,') }} + if: ${{ (needs.prepare.outputs.VOLUMEMANAGER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-workflows: + name: Build workflows + needs: + - prepare + - build-cloudharness-flask + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether workflows already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.WORKFLOWS_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push workflows + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows:buildcache,mode=max + context: ./applications/workflows + file: ./applications/workflows/server/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.WORKFLOWS_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows,') }} + if: ${{ (needs.prepare.outputs.WORKFLOWS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-workflows-notify-queue: + name: Build workflows-notify-queue + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether workflows-notify-queue already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push workflows-notify-queue + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:buildcache,mode=max + context: ./applications/workflows/tasks/notify-queue + file: ./applications/workflows/tasks/notify-queue/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-notify-queue,') }} + if: ${{ (needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-workflows-send-result-event: + name: Build workflows-send-result-event + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether workflows-send-result-event already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push workflows-send-result-event + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:buildcache,mode=max + context: ./applications/workflows/tasks/send-result-event + file: ./applications/workflows/tasks/send-result-event/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-send-result-event,') }} + if: ${{ (needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-workflows-extract-download: + name: Build workflows-extract-download + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether workflows-extract-download already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push workflows-extract-download + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:buildcache,mode=max + context: ./applications/workflows/tasks/extract-download + file: ./applications/workflows/tasks/extract-download/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-extract-download,') }} + if: ${{ (needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-cloudharness-flask: + name: Build cloudharness-flask + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether cloudharness-flask already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push cloudharness-flask + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:buildcache,mode=max + context: ./infrastructure/common-images/cloudharness-flask + file: ./infrastructure/common-images/cloudharness-flask/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-flask,') }} + if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-cloudharness-base: + name: Build cloudharness-base + needs: + - prepare + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether cloudharness-base already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push cloudharness-base + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:buildcache,mode=max + context: ./. + file: ././infrastructure/base-images/cloudharness-base/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-base,') }} + if: ${{ (needs.prepare.outputs.CLOUDHARNESS_BASE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-cloudharness-django: + name: Build cloudharness-django + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether cloudharness-django already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push cloudharness-django + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:buildcache,mode=max + context: ./infrastructure/common-images/cloudharness-django + file: ./infrastructure/common-images/cloudharness-django/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-django,') }} + if: ${{ (needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-cloudharness-frontend-build: + name: Build cloudharness-frontend-build + needs: + - prepare + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether cloudharness-frontend-build already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push cloudharness-frontend-build + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:buildcache,mode=max + context: ./. + file: ././infrastructure/base-images/cloudharness-frontend-build/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.branch_tag }} + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-frontend-build,') }} + if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-test-api: + name: Build test-api + needs: + - prepare + - build-cloudharness-base + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether test-api already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push test-api + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-api:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-api:buildcache,mode=max + context: ./test/test-api + file: ./test/test-api/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.branch_tag }} + ${{ vars.REGISTRY }}/cloud-harness/test-api:latest + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-api,') }} + if: ${{ (needs.prepare.outputs.TEST_API_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + build-test-e2e: + name: Build test-e2e + needs: + - prepare + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Check whether test-e2e already exists in the registry + id: check + env: + IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} + run: | + if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then + echo "exists=true" >> "$GITHUB_OUTPUT" + else + echo "exists=false" >> "$GITHUB_OUTPUT" + fi + - name: Build and push test-e2e + id: build + uses: docker/build-push-action@v6 + with: + push: true + cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-e2e:buildcache + cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-e2e:buildcache,mode=max + context: ./test/test-e2e + file: ./test/test-e2e/Dockerfile + build-args: |- + NOCACHE=${{ github.run_id }} + KEYCLOAK=quay.io/keycloak/keycloak:26.5 + GOLANG=golang:1.26 + ROCKYLINUX=rockylinux/rockylinux:10.1-minimal + NODE=node:22-alpine + PYTHON=python:3.12-slim-trixie + GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 + tags: |- + ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} + ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.branch_tag }} + ${{ vars.REGISTRY }}/cloud-harness/test-e2e:latest + if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-e2e,') }} + if: ${{ (needs.prepare.outputs.TEST_E2E_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + runs-on: ubuntu-latest + tests-unit-samples: + name: Unit tests samples + needs: + - prepare + - build-samples + steps: + - uses: docker/login-action@v3 + with: + registry: ${{ needs.prepare.outputs.registry_host }} + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + - name: Run samples unit tests + env: + CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} + CH_TEST_COMMANDS: | + set -e + pytest /usr/src/app/samples/test + run: |- + docker run --rm \ + "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" + if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} + runs-on: ubuntu-latest + deploy: + name: Deploy + needs: + - prepare + - build-accounts + - build-common + - build-jupyterhub + - build-nfsserver + - build-samples + - build-samples-print-file + - build-samples-sum + - build-samples-secret + - build-volumemanager + - build-workflows + - build-workflows-notify-queue + - build-workflows-send-result-event + - build-workflows-extract-download + - build-cloudharness-flask + - build-cloudharness-base + - build-cloudharness-django + - build-cloudharness-frontend-build + - tests-unit-samples + environment: test + env: + HELM_FLAGS: --timeout 200s --create-namespace + steps: + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - 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: Collect secret values + env: + ASECRET: ${{ secrets.ASECRET }} + run: | + set -e + secrets_dir="$RUNNER_TEMP/ch-secrets" + mkdir -p "$secrets_dir" + args="" + printf '%s' "$ASECRET" > "$secrets_dir/0" + args="$args --set-file apps.samples.harness.secrets.asecret=$secrets_dir/0" + printf '%s' "$ASECRET" > "$secrets_dir/1" + args="$args --set-file apps.samples-instance1.harness.secrets.asecret=$secrets_dir/1" + echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV" + - name: Install chart + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS + if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.tests-unit-samples.result == 'success' }} + runs-on: ubuntu-latest + wait-deployment: + name: Wait for the deployment + 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') }} + timeout-minutes: 15 + env: + NAMESPACE: ${{ needs.prepare.outputs.namespace }} + steps: + - 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: Select the namespace + run: kubectl config set-context --current --namespace="$NAMESPACE" + - name: Wait for the rollouts + run: | + kubectl rollout status deployment/accounts + kubectl rollout status deployment/argo-gk + kubectl rollout status deployment/common + kubectl rollout status statefulset/samples + kubectl rollout status deployment/www-gk + kubectl rollout status deployment/samples-instance1 + kubectl rollout status deployment/samples1-gk + kubectl rollout status deployment/volumemanager + kubectl rollout status deployment/workflows + sleep 60 + runs-on: ubuntu-latest + tests-api-common: + name: API tests common + needs: + - prepare + - wait-deployment + - build-test-api + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - 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: ubuntu-latest + tests-api-samples: + name: API tests samples + needs: + - prepare + - wait-deployment + - build-test-api + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - 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: ubuntu-latest + tests-api-workflows: + name: API tests workflows + needs: + - prepare + - wait-deployment + - build-test-api + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - uses: actions/download-artifact@v4 + with: + name: cloudharness-deployment + path: . + - 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: ubuntu-latest + tests-e2e-jupyterhub: + name: E2E tests jupyterhub + needs: + - prepare + - wait-deployment + - build-test-e2e + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - 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: ubuntu-latest + tests-e2e-samples: + name: E2E tests samples + needs: + - prepare + - wait-deployment + - build-test-e2e + if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + steps: + - uses: actions/checkout@v4 + - name: Clone cloud-harness + uses: actions/checkout@v4 + with: + repository: MetaCell/cloud-harness + ref: ${{ env.CLOUDHARNESS_BRANCH }} + path: cloud-harness + - 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: ubuntu-latest + cleanup: + name: Delete the test deployment + needs: + - prepare + - deploy + - tests-unit-samples + - 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: ubuntu-latest diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml index 14e89c1ff..008c4f788 100644 --- a/deployment-configuration/github-template-prod.yaml +++ b/deployment-configuration/github-template-prod.yaml @@ -17,6 +17,5 @@ jobs: wait-deployment: null publish: null deploy: - environment: $ENV env: HELM_FLAGS: --wait --timeout 600s --create-namespace diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml index 9f9bcd161..63c212df1 100644 --- a/deployment-configuration/github-template-stage.yaml +++ b/deployment-configuration/github-template-stage.yaml @@ -21,13 +21,13 @@ jobs: build-test-images: null tests-unit: null deploy: - environment: $ENV env: HELM_FLAGS: --wait --timeout 600s --create-namespace + # Only once the images were actually published: publish is skipped when the deployment or a test fails. git-tag: name: Tag the repository needs: [prepare, publish] - if: ${{ needs.prepare.outputs.publish_tag != '' }} + if: ${{ needs.publish.result == 'success' && needs.prepare.outputs.publish_tag != '' }} permissions: contents: write env: diff --git a/deployment-configuration/github-template-test.yaml b/deployment-configuration/github-template-test.yaml index a02ac7338..df18e4778 100644 --- a/deployment-configuration/github-template-test.yaml +++ b/deployment-configuration/github-template-test.yaml @@ -27,15 +27,8 @@ jobs: WAIT_ON_FAIL: ${{ vars.WAIT_ON_FAIL || '0' }} FAILED: ${{ contains(needs.*.result, 'failure') }} steps: - - uses: azure/setup-kubectl@v4 - uses: azure/setup-helm@v4 - - name: Configure kubectl - env: - KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} - run: | - mkdir -p "$HOME/.kube" - echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" - chmod 600 "$HOME/.kube/config" + - $KUBE_AUTH - name: Uninstall the release and delete the namespace run: | if [ "$FAILED" = "true" ] && [ "$WAIT_ON_FAIL" != "0" ]; then diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index 569bfda0f..79523742f 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -4,11 +4,36 @@ # key, lists are replaced, `null` removes a job). # `build`, `build-test-images`, `tests-unit`, `tests-api` and `tests-e2e` are prototypes, expanded into one # job per image/app ($CH_NAME, $CH_IMAGE and $CH_TAG stand for the image being expanded). A `$...` item in a steps -# list is a fragment the generator fills in. Every job without `runs-on` gets the runner given at generation -# time (CH_GITHUB_RUNNER, default ubuntu-latest). +# 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 (build jobs: 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: + # 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 @@ -142,9 +167,15 @@ jobs: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - $TEST_STEPS + # deploy targets the GitHub environment named after the CloudHarness environment: its protection + # rules (required reviewers on stage/prod) approve the deployment. Every job naming an environment is + # gated by those rules, so wait-deployment and the test cleanup do not: they read the cluster + # credentials from repository/organization secrets (an environment secret of the same name overrides + # them for deploy). deploy: name: Deploy needs: [prepare, build, tests-unit] + environment: $ENV env: HELM_FLAGS: --timeout 200s --create-namespace steps: @@ -153,13 +184,7 @@ jobs: name: cloudharness-deployment path: . - uses: azure/setup-helm@v4 - - name: Configure kubectl - env: - KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} - run: | - mkdir -p "$HOME/.kube" - echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" - chmod 600 "$HOME/.kube/config" + - $KUBE_AUTH - $HELM_SECRETS_STEPS - name: Install chart env: @@ -173,15 +198,9 @@ jobs: env: NAMESPACE: ${{ needs.prepare.outputs.namespace }} steps: - - uses: azure/setup-kubectl@v4 - - name: Configure kubectl - env: - KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }} - run: | - mkdir -p "$HOME/.kube" - echo "$KUBECONFIG_DATA" | base64 -d > "$HOME/.kube/config" - chmod 600 "$HOME/.kube/config" - kubectl config set-context --current --namespace="$NAMESPACE" + - $KUBE_AUTH + - name: Select the namespace + run: kubectl config set-context --current --namespace="$NAMESPACE" - $ROLLOUT_STEPS tests-api: name: API tests @@ -226,10 +245,13 @@ jobs: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - $TEST_STEPS + # Runs once the tests are done, and only if nothing failed. To publish despite failing API/E2E tests + # (Codefresh's fail_fast: false), override the `if` in the project template and protect the `publish` + # environment with required reviewers. publish: name: Publish images - needs: [prepare, deploy, tests-unit, tests-api, tests-e2e] - if: ${{ needs.prepare.outputs.publish_tag != '' }} + needs: [prepare, deploy, wait-deployment, tests-unit, tests-api, tests-e2e] + if: ${{ !cancelled() && needs.prepare.outputs.publish_tag != '' && needs.deploy.result == 'success' && !contains(needs.*.result, 'failure') }} environment: publish steps: - uses: docker/login-action@v3 diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index a407d97fc..bec8818f4 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -34,10 +34,44 @@ Pass `-ci codefresh -ci github` to generate both. `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.build-[image]` entry in your template is merged over that image's generated job (for instance to pick a bigger runner). -- Runner: the `CH_GITHUB_RUNNER` environment variable at generation time (default `ubuntu-latest`, - comma-separated labels allowed); any job can still set its own `runs-on` in the template. +- Runner: set the `CH_GITHUB_RUNNER` repository or organization variable to the runner label (for ARC, the + runner scale set name); build jobs read `CH_GITHUB_BUILD_RUNNER` first, so images can build on bigger + runners. 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 on the `publish` and `prod`/`stage` environments. `workflow_dispatch` inputs replace the `DEPLOYMENT_PUBLISH_TAG`, `DEPLOYMENT_TAG`, `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. +- Cluster credentials: the `deploy`, `wait-deployment` 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. Only `deploy` + targets the GitHub environment named after the CloudHarness environment (so required reviewers on + `stage`/`prod` approve the deployment once): `wait-deployment` and `cleanup` read repository or organization + secrets, which an environment secret of the same name overrides for `deploy`. 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} + wait-deployment: + permissions: {contents: read, packages: write, id-token: write} + ``` +- Test failures: unit tests gate the deployment, as in Codefresh. The API/E2E tests run after the deployment + and never block it, but `publish` (and `git-tag` on stage) is skipped when anything failed. To publish + despite failing tests, as Codefresh's `fail_fast: false` does, override the `if` of `publish` in your + project's template and protect the `publish` environment with required reviewers. diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index 15b159fa7..677381f51 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -19,6 +19,9 @@ - A job whose `needs` were skipped is skipped too unless its `if` says otherwise; since build jobs are skipped on purpose, every dependent job gets a guard (`apply_needs_guards`) that tolerates skipped builds but not failures. + A job deciding for itself - an `if` using always()/cancelled()/failure() - is + left alone. The template uses that for `publish`, which waits for the API/E2E + tests and runs only if none failed. Template mechanics (`github-template.yaml` + `github-template-.yaml`, layered across cloud-harness and the project exactly like the Codefresh templates): @@ -29,15 +32,22 @@ the image being expanded. - A string item in a `steps` list is a fragment the generator fills: `$GIT_CLONES`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, - `$TEST_STEPS`. + `$TEST_STEPS`, and `$KUBE_AUTH`, the steps giving kubectl/helm access to the + cluster, taken from the template's own `cloudharness.kube_auth` list so a + project changes the authentication method in one place. The top-level + `cloudharness` section is for the generator only and never reaches GitHub. - `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. - A template key matching an expanded job id (`jobs.build-myapp`) is merged over the generated job, so one image can get a bigger runner or extra steps; such a key is dropped when its image is not part of the deployment being generated. -- `runs-on` defaults to CHDeployConfig.ci_runner (`CH_GITHUB_RUNNER` on the CLI). +- `runs-on` defaults to the `CH_GITHUB_RUNNER` repository/organization variable + (build jobs: `CH_GITHUB_BUILD_RUNNER` first), read when the workflow runs, + falling back to CHDeployConfig.ci_runner (`CH_GITHUB_RUNNER` in the generating + shell, default ubuntu-latest). A template `runs-on` always wins. """ import copy +import json import logging import re from dataclasses import dataclass @@ -52,6 +62,8 @@ WORKFLOW_FILE_NAME = "cloudharness.yaml" DEFAULT_RUNNER = "ubuntu-latest" +RUNNER_VARIABLE = "CH_GITHUB_RUNNER" +BUILD_RUNNER_VARIABLE = "CH_GITHUB_BUILD_RUNNER" JOB_PREPARE = "prepare" JOB_BUILD = "build" @@ -69,6 +81,10 @@ FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" FRAGMENT_ROLLOUT = "$ROLLOUT_STEPS" FRAGMENT_TEST = "$TEST_STEPS" +FRAGMENT_KUBE_AUTH = "$KUBE_AUTH" + +SETTINGS_KEY = "cloudharness" # generator-only template section, stripped from the workflow +SETTING_KUBE_AUTH = "kube_auth" STEP_IMAGES = "images" # prepare step appending deployment/.env to $GITHUB_OUTPUT STEP_CHECK = "check" # build step asking the registry whether the image exists @@ -82,7 +98,7 @@ _INVALID_JOB_ID_CHARS = re.compile(r"[^A-Za-z0-9_-]") _INVALID_SECRET_CHARS = re.compile(r"[^A-Z0-9_]") _EXPRESSION = re.compile(r"^\$\{\{(.*)\}\}$", re.DOTALL) -_STATUS_FUNCTION = re.compile(r"\b(always|cancelled)\(\)") +_STATUS_FUNCTION = re.compile(r"\b(always|cancelled|failure)\(\)") _GITHUB_REPOSITORY = re.compile( r"^(?:https?://github\.com/|git@github\.com:|ssh://git@github\.com/)" r"([^/\s]+/[^/\s]+?)(?:\.git)?/?$" @@ -201,7 +217,7 @@ def rewrite_needs(jobs: dict, expansions: dict[str, list[str]]) -> None: def apply_needs_guards(jobs: dict) -> None: """Add the `needs_guard` to every job with dependencies, except those that - already decide themselves with always()/cancelled().""" + already decide themselves with always()/cancelled()/failure().""" skippable = {name for name, job in jobs.items() if job.get("if")} for job in jobs.values(): needs = normalize_needs(job.get("needs")) @@ -273,6 +289,16 @@ def visit(value): return found +def runner_expression(variables, default) -> str: + """A `runs-on` taking the runner from the first of the given GitHub variables + that is set when the workflow runs, `default` (one label or a list) otherwise.""" + if isinstance(default, str): + fallback = "'%s'" % default.replace("'", "''") + else: + fallback = "fromJSON('%s')" % json.dumps(list(default)).replace("'", "''") + return "${{ %s }}" % " || ".join([*(f"vars.{name}" for name in variables), fallback]) + + def prepare_output(key: str) -> str: return "${{ needs.%s.outputs.%s }}" % (JOB_PREPARE, key) @@ -313,11 +339,11 @@ class CHGithubActions(CHValues): def qualify(self, image_name: str) -> str: return "${{ vars.REGISTRY }}/%s" % image_name - def _runner(self): - runner = self.project.config.ci_runner or DEFAULT_RUNNER - if isinstance(runner, str) and "," in runner: - return [label.strip() for label in runner.split(",") if label.strip()] - return runner + def _runner(self, *variables) -> str: + default = self.project.config.ci_runner or DEFAULT_RUNNER + if "," in default: + default = [label.strip() for label in default.split(",") if label.strip()] + return runner_expression([*variables, RUNNER_VARIABLE], default) def _pipeline_path(self, path) -> str: """A path as the workflow sees it: relative to the project checkout, with @@ -513,6 +539,7 @@ def _build_job(self, prototype, entity, build_ids, fragments, extra_tags=()): tag_var = ci.tag_variable(name) job = self._prototype(prototype, name, entity.image_name) job["name"] = f"Build {name}" + job.setdefault("runs-on", self._runner(BUILD_RUNNER_VARIABLE)) job["needs"] = self._specific_needs( prototype, { @@ -630,8 +657,9 @@ def _prepare_outputs(self) -> dict[str, str]: outputs[key] = "${{ steps.%s.outputs.%s }}" % (STEP_IMAGES, key) return outputs - def _expand_jobs(self, jobs: dict) -> dict: + def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: project = self.project + settings = settings or {} removed = [key for key, job in jobs.items() if job is None] jobs = {key: job for key, job in jobs.items() if job is not None} @@ -663,6 +691,7 @@ def _expand_jobs(self, jobs: dict) -> dict: FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), FRAGMENT_ROLLOUT: self._rollout_steps(), FRAGMENT_TEST: [], + FRAGMENT_KUBE_AUTH: list(settings.get(SETTING_KUBE_AUTH) or []), } overlays = {key: job for key, job in jobs.items() if key in generated_ids} @@ -766,7 +795,8 @@ def generate(self, write_on_disk=True, output_path=None): return {} base = substitute_vars(base, ci.placeholder_values(project, self._pipeline_path)) - base["jobs"] = self._expand_jobs(base.get("jobs") or {}) + settings = base.pop(SETTINGS_KEY, None) or {} + base["jobs"] = self._expand_jobs(base.get("jobs") or {}, settings) # the env template contributes name/on after the base keys: put them first base = {key: base[key] for key in ("name", "on") if key in base} | { key: value for key, value in base.items() if key not in ("name", "on") diff --git a/tools/deployment-cli-tools/ch_cli_tools/utils.py b/tools/deployment-cli-tools/ch_cli_tools/utils.py index 71ca98507..aea3948cc 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/utils.py +++ b/tools/deployment-cli-tools/ch_cli_tools/utils.py @@ -339,6 +339,24 @@ def own_dockerfile_path(path: Path) -> Path: return min(candidates, key=lambda p: (len(p.parts), str(p))) +# Scaffold copied to start a new project: its CHANGE ME values are not a layer. +_NOT_PROJECT_DIRS = {"blueprint"} + + +def discover_root_paths(path: Path) -> list[Path]: + """Project layers found at path, lowest priority first: the direct subdirectories + holding a deployment-configuration (hidden ones skipped) by name, then path itself.""" + children = sorted( + child for child in path.iterdir() if child.is_dir() and not child.name.startswith(".") + ) + for child in children: + if child.name in _NOT_PROJECT_DIRS and (child / DEPLOYMENT_CONFIGURATION_PATH).is_dir(): + logging.warning("Not using %s as a layer: it is a project scaffold", child) + candidates = [child for child in children if child.name not in _NOT_PROJECT_DIRS] + candidates.append(path) + return [p for p in candidates if (p / DEPLOYMENT_CONFIGURATION_PATH).is_dir()] + + # Legacy-derived utilities, imported as-is rather than reimplemented: write_values_overrides # is used directly by helm.py's own generate(); find_chart_images/ChartImageRef are unit-tested # directly (see tests/test_helm.py); the rest is shared with openapi.py/application_builders.py/ diff --git a/tools/deployment-cli-tools/harness-deployment b/tools/deployment-cli-tools/harness-deployment index 914482d5a..8db777d84 100644 --- a/tools/deployment-cli-tools/harness-deployment +++ b/tools/deployment-cli-tools/harness-deployment @@ -8,10 +8,7 @@ from cloudharness_utils.constants import DEPLOYMENT_PATH from ch_cli_tools.api import deploy, hosts_info, perform_migration from ch_cli_tools.ci import parse_force_build from ch_cli_tools.model import CHDeployConfig, CHProject -from ch_cli_tools.utils import generation_argv - -HERE = Path(__file__).resolve().parent -ROOT = HERE.parent +from ch_cli_tools.utils import discover_root_paths, generation_argv if __name__ == "__main__": import argparse @@ -23,11 +20,14 @@ if __name__ == "__main__": parser.add_argument( "paths", metavar="paths", - default=[ROOT], + default=[], type=Path, nargs="*", help="Base paths to start looking for applications. The paths will be processed " - "in the given order so determining the build and overriding precedence.", + "in the given order so determining the build and overriding precedence. " + "Omit to use the direct subdirectories of the current directory that contain a " + "deployment-configuration (by name, skipping hidden ones and blueprint), " + "then the current directory itself (e.g. `./cloud-harness .`)", ) parser.add_argument( @@ -170,8 +170,9 @@ if __name__ == "__main__": choices=["codefresh", "github"], default=None, help="CI/CD system to generate the pipeline for; repeat to generate more than one " - "(default: codefresh). github writes .github/workflows/cloudharness-[ENV].yaml and takes " - "the runner from the CH_GITHUB_RUNNER environment variable (default: ubuntu-latest)", + "(default: codefresh). github writes .github/workflows/cloudharness-[ENV].yaml; its jobs run on " + "the runner named by the CH_GITHUB_RUNNER GitHub variable, falling back to the CH_GITHUB_RUNNER " + "environment variable at generation time (default: ubuntu-latest)", ) parser.add_argument( "--force-build", @@ -219,8 +220,6 @@ if __name__ == "__main__": args, unknown = parser.parse_known_args(sys.argv[1:]) - root_paths = [Path.cwd() / path for path in args.paths] - envs = args.env.split("-") if args.env else () if len(sys.argv) == 1: @@ -234,6 +233,21 @@ if __name__ == "__main__": print(f"unknown: {unknown}") sys.exit(2) + if args.paths: + root_paths = [Path.cwd() / path for path in args.paths] + else: + root_paths = discover_root_paths(Path.cwd()) + if not root_paths: + parser.error( + "no deployment-configuration found in the current directory or its " + "subdirectories: pass the paths explicitly" + ) + print( + "No paths given, using (lowest priority first): " + + " ".join(str(p.relative_to(Path.cwd())) for p in root_paths), + file=sys.stderr, + ) + if args.migration_accept_all: perform_migration(root_paths, accept_all=True) elif args.migration: diff --git a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml index ef32d8b4d..d91745853 100644 --- a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml +++ b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml @@ -10,3 +10,7 @@ jobs: needs: [deploy] steps: - run: echo custom +cloudharness: + kube_auth: + - name: Custom cluster access + run: echo custom-auth diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index a4265212f..cf1283c51 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -66,6 +66,18 @@ def test_template_layering(tmp_path): assert "needs.deploy.result == 'success'" in custom["if"] # an overlay for an expanded job id is merged over the generated job assert wf["jobs"]["build-myapp"]["runs-on"] == "big-runner" + # the generator-only section is consumed, not emitted; its kube_auth steps replace + # the default ones wherever a job asks for $KUBE_AUTH + assert "cloudharness" not in wf + for name in ("deploy", "wait-deployment"): + steps = wf["jobs"][name]["steps"] + assert [s for s in steps if s.get("name") == "Custom cluster access"], name + assert not [s for s in steps if s.get("name") == "Configure kubectl"], name + assert wf["jobs"]["deploy"]["environment"] == "dev" + # only deploy is gated by the environment's protection rules, not every job using the cluster + assert "environment" not in wf["jobs"]["wait-deployment"] + # OIDC tokens are not minted for every job + assert "id-token" not in wf["permissions"] def test_build_jobs_follow_the_dependency_graph(tmp_path): @@ -271,6 +283,12 @@ def test_rollout_wait_and_publish_steps(tmp_path): assert "needs.prepare.outputs.publish_tag != ''" in publish["if"] assert "deploy" in publish["needs"] and "tests-e2e-samples" in publish["needs"] assert publish["environment"] == "publish" + # publication waits for the tests and never runs when the deployment or a test failed + assert "needs.deploy.result == 'success'" in publish["if"] + assert "!cancelled()" in publish["if"] + assert "!contains(needs.*.result, 'failure')" in publish["if"] + # the API/E2E tests run after the deployment, so they cannot block it + assert not [n for n in jobs["deploy"]["needs"] if n.startswith(("tests-api", "tests-e2e"))] published = {step["name"][len("Publish "):] for step in _steps(publish, "Publish ")} built = {name[len("build-"):] for name in jobs if name.startswith("build-")} assert published == built @@ -314,6 +332,9 @@ def test_prod_deploys_only(tmp_path): assert list(jobs) == ["prepare", "deploy"] assert jobs["deploy"]["needs"] == ["prepare"] assert jobs["deploy"]["environment"] == "prod" + # the fixture's kube_auth override lives in the dev overlay only: prod keeps the + # default step (KUBECONFIG secret or the runner's own cluster access) + assert [s for s in jobs["deploy"]["steps"] if s.get("name") == "Configure kubectl"] assert jobs["deploy"]["env"]["HELM_FLAGS"].startswith("--wait") assert wf["on"]["workflow_dispatch"]["inputs"]["deployment_tag"]["required"] is True @@ -327,19 +348,36 @@ def test_stage_keeps_tests_and_tags_the_repository(tmp_path): assert jobs["tests-api-samples"]["needs"] == ["prepare", "wait-deployment"] assert jobs["git-tag"]["needs"] == ["prepare", "publish"] assert jobs["git-tag"]["permissions"] == {"contents": "write"} + # the tag is pushed only when the images were published: a failed deployment or test + # skips publish, and a skipped publish must not let the guard through + tag_if = jobs["git-tag"]["if"] + assert "needs.publish.result == 'success'" in tag_if + assert "needs.prepare.outputs.publish_tag != ''" in tag_if + assert "needs.prepare.result == 'success'" in tag_if def test_runner_configuration(tmp_path): wf, _ = _generate(tmp_path, ["myapp"]) - assert all(job["runs-on"] == DEFAULT_RUNNER for name, job in wf["jobs"].items() if name != "build-myapp") - assert wf["jobs"]["build-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" + jobs = wf["jobs"] + # the runner is a repository variable read at run time; the generation-time runner is the fallback + default = "${{ vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER + build = "${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER + assert jobs["prepare"]["runs-on"] == default + assert jobs["deploy"]["runs-on"] == default + assert jobs["tests-unit-myapp"]["runs-on"] == default + builds = [name for name in jobs if name.startswith("build-") and name != "build-myapp"] + assert builds + assert all(jobs[name]["runs-on"] == build for name in builds) + assert jobs["build-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig( env="dev", includes=["myapp"], excludes=["events"], registry="reg", tag="1", output_path=str(tmp_path / "deployment"), ci_runner="self-hosted, linux", )) wf = project.github_actions.generate(write_on_disk=False) - assert wf["jobs"]["prepare"]["runs-on"] == ["self-hosted", "linux"] + assert wf["jobs"]["prepare"]["runs-on"] == ( + """${{ vars.CH_GITHUB_RUNNER || fromJSON('["self-hosted", "linux"]') }}""" + ) def test_workflow_invariants(tmp_path): diff --git a/tools/deployment-cli-tools/tests/test_github_actions_internals.py b/tools/deployment-cli-tools/tests/test_github_actions_internals.py index 906bc3e9d..c229c7e17 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions_internals.py +++ b/tools/deployment-cli-tools/tests/test_github_actions_internals.py @@ -14,6 +14,7 @@ needs_guard, referenced_names, rewrite_needs, + runner_expression, step_by_id, substitute_vars, ) @@ -97,6 +98,12 @@ def test_apply_needs_guards(): "deploy": {"needs": ["prepare", "build-a"]}, "tests": {"needs": ["deploy"], "if": "${{ vars.SKIP_TESTS != 'true' }}"}, "cleanup": {"needs": ["deploy"], "if": "${{ always() }}"}, + "publish": { + "needs": ["deploy", "tests"], + "if": "${{ !cancelled() && needs.deploy.result == 'success' }}", + }, + "checked": {"needs": ["prepare", "deploy"], "if": "${{ needs.deploy.result == 'success' }}"}, + "explicit": {"needs": ["prepare", "build-a"], "if": "${{ success() }}"}, } apply_needs_guards(jobs) @@ -112,8 +119,12 @@ def test_apply_needs_guards(): # build-a keeps its exists check plus the guard on prepare assert "A_TAG_EXISTS != '1'" in jobs["build-a"]["if"] assert "needs.prepare.result == 'success'" in jobs["build-a"]["if"] - # a job deciding with always() is left alone + # a job deciding with always()/cancelled() is left alone assert jobs["cleanup"]["if"] == "${{ always() }}" + assert jobs["publish"]["if"] == "${{ !cancelled() && needs.deploy.result == 'success' }}" + # success() and needs..result checks do not tolerate skipped dependencies: still guarded + assert "needs.prepare.result == 'success'" in jobs["checked"]["if"] + assert "success()" in jobs["explicit"]["if"] and "!cancelled()" in jobs["explicit"]["if"] def test_as_literal_blocks(): @@ -147,3 +158,11 @@ def test_referenced_names(): } ) assert names == {"vars": {"REGISTRY"}, "secrets": {"TOKEN", "GH_PAT"}} + + +def test_runner_expression_falls_back_through_the_variables(): + assert runner_expression(["A", "B"], "ubuntu-latest") == "${{ vars.A || vars.B || 'ubuntu-latest' }}" + assert runner_expression([], "it's") == "${{ 'it''s' }}" + assert runner_expression(["A"], ["self-hosted", "linux"]) == ( + """${{ vars.A || fromJSON('["self-hosted", "linux"]') }}""" + ) diff --git a/tools/deployment-cli-tools/tests/test_util.py b/tools/deployment-cli-tools/tests/test_util.py index fb51b0125..82741d276 100644 --- a/tools/deployment-cli-tools/tests/test_util.py +++ b/tools/deployment-cli-tools/tests/test_util.py @@ -2,7 +2,7 @@ import pytest -from ch_cli_tools.utils import get_yaml_parser +from ch_cli_tools.utils import discover_root_paths, get_yaml_parser def write_tree_from_yaml( @@ -165,3 +165,55 @@ def test_write_tree_from_yaml_rejects_both_text_and_path(tmp_path): def test_write_tree_from_yaml_rejects_neither_text_nor_path(tmp_path): with pytest.raises(ValueError): write_tree_from_yaml(tmp_path) + + +def test_discover_root_paths_puts_subdirectories_before_current(tmp_path): + write_tree( + tmp_path, + { + "deployment-configuration": {}, + "cloud-harness": {"deployment-configuration": {}}, + "applications": {"myapp": {}}, + }, + ) + + assert discover_root_paths(tmp_path) == [tmp_path / "cloud-harness", tmp_path] + + +def test_discover_root_paths_orders_subdirectories_by_name(tmp_path): + write_tree( + tmp_path, + { + "zeta": {"deployment-configuration": {}}, + "alpha": {"deployment-configuration": {}}, + }, + ) + + assert discover_root_paths(tmp_path) == [tmp_path / "alpha", tmp_path / "zeta"] + + +def test_discover_root_paths_skips_hidden_blueprint_and_nested(tmp_path): + write_tree( + tmp_path, + { + "deployment-configuration": {}, + ".history": {"deployment-configuration": {}}, + "blueprint": {"deployment-configuration": {}}, + "tools": {"tests": {"resources": {"deployment-configuration": {}}}}, + }, + ) + + assert discover_root_paths(tmp_path) == [tmp_path] + + +def test_discover_root_paths_ignores_deployment_configuration_file(tmp_path): + write_tree(tmp_path, {"cloud-harness": {"deployment-configuration": "not a dir"}}) + + assert discover_root_paths(tmp_path) == [] + + +def test_discover_root_paths_warns_about_a_skipped_scaffold(tmp_path, caplog): + write_tree(tmp_path, {"blueprint": {"deployment-configuration": {}}, "deployment-configuration": {}}) + + assert discover_root_paths(tmp_path) == [tmp_path] + assert "blueprint" in caplog.text From 4de99d3be83641885a1a6b8ffa153365747f78b9 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 15:42:51 +0100 Subject: [PATCH 04/11] CH-125 github actions: merged override contexts as per-image artifacts The prepare job uploads each build context merged across layers in .overrides/ as its own artifact, downloaded only by that image's build job; the deployment artifact carries the helm chart only. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cloudharness-test.yaml | 148 +++++------------- deployment-configuration/github-template.yaml | 15 +- .../ch_cli_tools/github_actions.py | 80 ++++++++-- .../tests/test_github_actions.py | 79 ++++++++++ 4 files changed, 191 insertions(+), 131 deletions(-) diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index ff32b02a0..509240b27 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -1,4 +1,4 @@ -# Generated with: harness-deployment . -i samples -e test -ci github +# Generated with: harness-deployment . -e test -i samples -ci github name: CloudHarness test on: pull_request: @@ -133,12 +133,10 @@ jobs: uses: actions/upload-artifact@v4 with: name: cloudharness-deployment - path: | - deployment - .overrides + path: deployment include-hidden-files: true if-no-files-found: error - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} build-accounts: name: Build accounts needs: @@ -151,10 +149,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -192,8 +186,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.ACCOUNTS_TAG }} ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',accounts,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.ACCOUNTS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-common: name: Build common needs: @@ -207,10 +201,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -249,8 +239,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.COMMON_TAG }} ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',common,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.COMMON_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-jupyterhub: name: Build jupyterhub needs: @@ -264,10 +254,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -306,8 +292,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.JUPYTERHUB_TAG }} ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',jupyterhub,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.JUPYTERHUB_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-nfsserver: name: Build nfsserver needs: @@ -320,10 +306,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -361,8 +343,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.NFSSERVER_TAG }} ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',nfsserver,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.NFSSERVER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-samples: name: Build samples needs: @@ -378,10 +360,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -423,8 +401,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.SAMPLES_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-samples-print-file: name: Build samples-print-file needs: @@ -438,10 +416,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -480,8 +454,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG }} ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-print-file,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-samples-sum: name: Build samples-sum needs: @@ -495,10 +469,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -537,8 +507,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.SAMPLES_SUM_TAG }} ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-sum,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.SAMPLES_SUM_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-samples-secret: name: Build samples-secret needs: @@ -552,10 +522,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -594,8 +560,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.SAMPLES_SECRET_TAG }} ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-secret,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.SAMPLES_SECRET_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-volumemanager: name: Build volumemanager needs: @@ -609,10 +575,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -651,8 +613,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.VOLUMEMANAGER_TAG }} ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',volumemanager,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.VOLUMEMANAGER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-workflows: name: Build workflows needs: @@ -666,10 +628,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -708,8 +666,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.WORKFLOWS_TAG }} ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.WORKFLOWS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-workflows-notify-queue: name: Build workflows-notify-queue needs: @@ -723,10 +681,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -765,8 +719,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-notify-queue,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-workflows-send-result-event: name: Build workflows-send-result-event needs: @@ -780,10 +734,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -822,8 +772,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-send-result-event,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-workflows-extract-download: name: Build workflows-extract-download needs: @@ -837,10 +787,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -879,8 +825,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-extract-download,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-cloudharness-flask: name: Build cloudharness-flask needs: @@ -894,10 +840,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -936,8 +878,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-flask,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-cloudharness-base: name: Build cloudharness-base needs: @@ -950,10 +892,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -991,8 +929,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-base,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.CLOUDHARNESS_BASE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-cloudharness-django: name: Build cloudharness-django needs: @@ -1006,10 +944,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -1048,8 +982,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-django,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-cloudharness-frontend-build: name: Build cloudharness-frontend-build needs: @@ -1062,10 +996,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -1103,8 +1033,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.branch_tag }} if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-frontend-build,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-test-api: name: Build test-api needs: @@ -1118,10 +1048,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -1161,8 +1087,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.branch_tag }} ${{ vars.REGISTRY }}/cloud-harness/test-api:latest if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-api,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.TEST_API_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest build-test-e2e: name: Build test-e2e needs: @@ -1175,10 +1101,6 @@ jobs: repository: MetaCell/cloud-harness ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -1217,8 +1139,8 @@ jobs: ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.branch_tag }} ${{ vars.REGISTRY }}/cloud-harness/test-e2e:latest if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-e2e,') }} + runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} if: ${{ (needs.prepare.outputs.TEST_E2E_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - runs-on: ubuntu-latest tests-unit-samples: name: Unit tests samples needs: @@ -1240,7 +1162,7 @@ jobs: docker run --rm \ "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} deploy: name: Deploy needs: @@ -1270,7 +1192,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: azure/setup-helm@v4 - uses: azure/setup-kubectl@v4 - name: Configure kubectl @@ -1305,7 +1227,7 @@ jobs: NAMESPACE: ${{ needs.prepare.outputs.namespace }} run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.tests-unit-samples.result == 'success' }} - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} wait-deployment: name: Wait for the deployment needs: @@ -1345,7 +1267,7 @@ jobs: kubectl rollout status deployment/volumemanager kubectl rollout status deployment/workflows sleep 60 - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} tests-api-common: name: API tests common needs: @@ -1364,7 +1286,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} @@ -1384,7 +1306,7 @@ jobs: -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: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} tests-api-samples: name: API tests samples needs: @@ -1403,7 +1325,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} @@ -1428,7 +1350,7 @@ jobs: -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: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} tests-api-workflows: name: API tests workflows needs: @@ -1447,7 +1369,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} @@ -1467,7 +1389,7 @@ jobs: -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: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} tests-e2e-jupyterhub: name: E2E tests jupyterhub needs: @@ -1502,7 +1424,7 @@ jobs: -v "$GITHUB_WORKSPACE/applications/jupyterhub/test/e2e:/home/test/__tests__/jupyterhub" \ -w /home/test \ "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} tests-e2e-samples: name: E2E tests samples needs: @@ -1541,7 +1463,7 @@ jobs: -v "$GITHUB_WORKSPACE/applications/samples/test/e2e:/home/test/__tests__/samples" \ -w /home/test \ "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} cleanup: name: Delete the test deployment needs: @@ -1583,4 +1505,4 @@ jobs: fi helm uninstall "$NAMESPACE" -n "$NAMESPACE" || true kubectl delete namespace "$NAMESPACE" --ignore-not-found - runs-on: ubuntu-latest + runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index 79523742f..7685ee77b 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -111,11 +111,11 @@ jobs: uses: actions/upload-artifact@v4 with: name: cloudharness-deployment - path: | - deployment - .overrides + path: deployment include-hidden-files: true if-no-files-found: error + # one artifact per build context merged across layers in .overrides/, for that image's build job + - $UPLOAD_OVERRIDES build: name: Build needs: [prepare] @@ -128,10 +128,7 @@ jobs: ref: ${{ env.CLOUDHARNESS_BRANCH }} path: cloud-harness - $GIT_CLONES - - uses: actions/download-artifact@v4 - with: - name: cloudharness-deployment - path: . + - $DOWNLOAD_OVERRIDES - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: @@ -182,7 +179,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: azure/setup-helm@v4 - $KUBE_AUTH - $HELM_SECRETS_STEPS @@ -217,7 +214,7 @@ jobs: - uses: actions/download-artifact@v4 with: name: cloudharness-deployment - path: . + path: deployment - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index 677381f51..865b53c0e 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -14,8 +14,10 @@ file goes: `.github/workflows/cloudharness-.yaml` in the project root. - Triggers (`on:`) are part of the file, hence of the per-environment template. - Every job runs on a fresh runner: each one checks out what it needs, images - travel between jobs through the registry, the helm chart and the merged - `.overrides/` contexts travel as a workflow artifact. + travel between jobs through the registry, the helm chart travels as a + workflow artifact. An image built from a context merged across layers + (`.overrides/`, written by prepare's harness-deployment) gets its own + artifact, downloaded only by that image's build job. - A job whose `needs` were skipped is skipped too unless its `if` says otherwise; since build jobs are skipped on purpose, every dependent job gets a guard (`apply_needs_guards`) that tolerates skipped builds but not failures. @@ -31,7 +33,9 @@ generated. Inside a prototype `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for the image being expanded. - A string item in a `steps` list is a fragment the generator fills: - `$GIT_CLONES`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, + `$GIT_CLONES`, `$UPLOAD_OVERRIDES` (prepare: one artifact per merged + context), `$DOWNLOAD_OVERRIDES` (build: this image's merged context, if + any), `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, `$TEST_STEPS`, and `$KUBE_AUTH`, the steps giving kubectl/helm access to the cluster, taken from the template's own `cloudharness.kube_auth` list so a project changes the authentication method in one place. The top-level @@ -47,6 +51,7 @@ """ import copy +import dataclasses import json import logging import re @@ -58,7 +63,7 @@ from . import ci from .model import CHValues, register_file -from .utils import GeneratedYAML, dict_merge, pipeline_relative_path # type: ignore +from .utils import MERGE_DIRNAME, GeneratedYAML, dict_merge, pipeline_relative_path # type: ignore WORKFLOW_FILE_NAME = "cloudharness.yaml" DEFAULT_RUNNER = "ubuntu-latest" @@ -77,6 +82,8 @@ PROTOTYPE_JOBS = (JOB_BUILD, JOB_BUILD_TEST_IMAGES, JOB_UNIT_TESTS, JOB_API_TESTS, JOB_E2E_TESTS) FRAGMENT_GIT_CLONES = "$GIT_CLONES" +FRAGMENT_UPLOAD_OVERRIDES = "$UPLOAD_OVERRIDES" +FRAGMENT_DOWNLOAD_OVERRIDES = "$DOWNLOAD_OVERRIDES" FRAGMENT_PUBLISH_STEPS = "$PUBLISH_STEPS" FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" FRAGMENT_ROLLOUT = "$ROLLOUT_STEPS" @@ -311,6 +318,7 @@ def tag_output(name: str) -> str: class BuildContext: path: str # docker build context, relative to the workflow's checkout root dockerfile: str # Dockerfile, relative to the context + artifact: str | None = None # workflow artifact carrying a merged context from prepare # --- generator ------------------------------------------------------------------ @@ -438,6 +446,37 @@ def _git_clone_steps(self, entities) -> list[dict]: ) return steps + def _upload_overrides_steps(self, contexts: dict[str, BuildContext]) -> list[dict]: + return [ + { + "name": f"Share the merged {name} build context", + # an image whose tag exists is not built, so nobody downloads its context + "if": combine_conditions( + f"steps.{STEP_IMAGES}.outputs.{ci.tag_variable(name)}_EXISTS != '1'" + ), + "uses": "actions/upload-artifact@v4", + "with": { + "name": context.artifact, + "path": context.path, + "include-hidden-files": True, + "if-no-files-found": "error", + }, + } + for name, context in contexts.items() + if context.artifact + ] + + def _download_overrides_steps(self, name: str, context: BuildContext) -> list[dict]: + if not context.artifact: + return [] + return [ + { + "name": f"Download the merged {name} build context", + "uses": "actions/download-artifact@v4", + "with": {"name": context.artifact, "path": context.path}, + } + ] + def _publish_steps(self, entities: dict) -> list[dict]: steps = [] for name, entity in entities.items(): @@ -533,7 +572,7 @@ def _build_args(self, entity) -> list[str]: args.update(getattr(entity, "build_args", None) or {}) return [f"{key}={value}" for key, value in args.items()] - def _build_job(self, prototype, entity, build_ids, fragments, extra_tags=()): + def _build_job(self, prototype, entity, context, build_ids, fragments, extra_tags=()): name = entity.name image = self.qualify(entity.image_name) tag_var = ci.tag_variable(name) @@ -559,11 +598,15 @@ def _build_job(self, prototype, entity, build_ids, fragments, extra_tags=()): ) steps = expand_steps( job.get("steps"), - {**fragments, FRAGMENT_GIT_CLONES: self._git_clone_steps([entity])}, + { + **fragments, + # prepare clones the git dependencies before merging: a shared context has them + FRAGMENT_GIT_CLONES: [] if context.artifact else self._git_clone_steps([entity]), + FRAGMENT_DOWNLOAD_OVERRIDES: self._download_overrides_steps(name, context), + }, ) build = step_by_id(steps, STEP_BUILD) if build is not None: - context = self._context_for(entity) with_ = build.setdefault("with", {}) with_["context"] = f"./{context.path}" with_["file"] = f"./{context.path}/{context.dockerfile}" @@ -679,6 +722,18 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: if users and image is not None and image.dockerfile.exists(): test_entities[name] = image + # prepare's harness-deployment merges the contexts of apps, tasks and build dependencies + # again (skaffold, tilt), not those of test images: only the former can be shared + contexts = {} + if JOB_BUILD in jobs: + for name, entity in entities.items(): + context = self._context_for(entity) + if Path(context.path).parts[:1] == (MERGE_DIRNAME,): + context = dataclasses.replace(context, artifact=f"cloudharness-overrides-{name}") + contexts[name] = context + for name, image in test_entities.items(): + contexts[name] = self._context_for(image) + build_ids = {name: job_id(f"{JOB_BUILD}-{name}") for name in [*entities, *test_entities]} unit_ids = {app.name: job_id(f"{JOB_UNIT_TESTS}-{app.name}") for app in unit_apps} api_ids = {app.name: job_id(f"{JOB_API_TESTS}-{app.name}") for app in api_apps} @@ -687,6 +742,8 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: fragments = { FRAGMENT_GIT_CLONES: self._git_clone_steps(apps), + FRAGMENT_UPLOAD_OVERRIDES: self._upload_overrides_steps(contexts), + FRAGMENT_DOWNLOAD_OVERRIDES: [], FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_entities}), FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), FRAGMENT_ROLLOUT: self._rollout_steps(), @@ -720,7 +777,7 @@ def expand(key, items, make): entities.items(), lambda item: ( build_ids[item[0]], - self._build_job(job, item[1], build_ids, fragments), + self._build_job(job, item[1], contexts[item[0]], build_ids, fragments), ), ) elif key == JOB_BUILD_TEST_IMAGES: @@ -731,7 +788,12 @@ def expand(key, items, make): lambda item: ( build_ids[item[0]], self._build_job( - prototype, item[1], build_ids, fragments, extra_tags=("latest",) + prototype, + item[1], + contexts[item[0]], + build_ids, + fragments, + extra_tags=("latest",), ), ), ) diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index cf1283c51..23db57f8d 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -165,6 +165,82 @@ def test_git_dependency_checkouts(tmp_path): assert not [s for s in _steps(jobs["build-samples"], "Clone ") if s["name"] != "Clone cloud-harness"] +def test_merged_contexts_travel_as_their_own_artifacts(tmp_path): + # sentry overrides cloud-harness' own app, Dockerfile included: built from .overrides/sentry; + # my-base is the project's own base image, built from the project root + write_tree_from_yaml( + tmp_path, + """ + deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: sentry + infrastructure: + base-images: + my-base: + Dockerfile: | + FROM scratch + applications: + sentry: + Dockerfile: | + FROM scratch + deploy: + values.yaml: | + harness: + dependencies: + build: + - my-base + git: + - url: https://github.com/a/b.git + branch_tag: master + """, + ) + project = chain( + CLOUDHARNESS_ROOT, + tmp_path, + config=CHDeployConfig(env="dev", registry="reg", tag="1", output_path=str(tmp_path / "deployment")), + ) + jobs = project.github_actions.generate(write_on_disk=False)["jobs"] + + def artifact_steps(job, action): + return [step for step in job["steps"] if step.get("uses") == f"actions/{action}-artifact@v4"] + + deployment, upload = artifact_steps(jobs["prepare"], "upload") + assert deployment["with"]["name"] == "cloudharness-deployment" + assert deployment["with"]["path"] == "deployment" + assert upload["with"] == { + "name": "cloudharness-overrides-sentry", + "path": ".overrides/sentry", + "include-hidden-files": True, + "if-no-files-found": "error", + } + assert upload["if"] == "${{ steps.images.outputs.SENTRY_TAG_EXISTS != '1' }}" + # prepare clones the git dependency before harness-deployment merges the context + step_names = [step.get("name") for step in jobs["prepare"]["steps"]] + assert step_names.index("Clone b") < step_names.index("Prepare helm chart") + + build = jobs["build-sentry"] + assert _step(build, "build")["with"]["context"] == "./.overrides/sentry" + assert [step["with"] for step in artifact_steps(build, "download")] == [ + {"name": "cloudharness-overrides-sentry", "path": ".overrides/sentry"} + ] + assert not _steps(build, "Clone b"), "the merged context already holds the git dependency" + assert _step(jobs["build-my-base"], "build")["with"]["context"] == "./." + for name, job in jobs.items(): + if name.startswith("build-") and name != "build-sentry": + assert not artifact_steps(job, "download"), f"{name} builds from the checkout" + assert [step["with"] for step in artifact_steps(jobs["deploy"], "download")] == [ + {"name": "cloudharness-deployment", "path": "deployment"} + ] + + # prepare's harness-deployment writes .overrides/ through skaffold and tilt, not through this + # generator: every context it uploads must come out of those two + shutil.rmtree(tmp_path / ".overrides") + project.skaffold.generate(write_on_disk=False) + project.tilt.generate(write_on_disk=False) + assert (tmp_path / upload["with"]["path"] / "Dockerfile").exists() + + def test_prepare_outputs_cover_every_build(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"]) outputs = wf["jobs"]["prepare"]["outputs"] @@ -218,6 +294,9 @@ def test_api_and_e2e_test_jobs(tmp_path): assert "-e APP_URL" in step["run"] assert '-v "$GITHUB_WORKSPACE/cloud-harness/applications/samples:/home/test"' in step["run"] assert "/opt/cloudharness/resources/allvalues.yaml" in step["run"] + assert {"name": "cloudharness-deployment", "path": "deployment"} in [ + s["with"] for s in api["steps"] if s.get("uses") == "actions/download-artifact@v4" + ], "the mounted values.yaml comes from the deployment artifact" assert "-w /home/test" in step["run"] commands = step["env"]["CH_TEST_COMMANDS"].splitlines() assert "--pre-run cloudharness_test.apitest_init" in commands[1] From 9b3a8324251f7c0fef602566a1bcba4c77a4e88d Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 16:16:11 +0100 Subject: [PATCH 05/11] CH-125 github actions: build the missing images with skaffold in prepare harness-deployment --write-skaffold-build writes deployment/skaffold-build.yaml with only the images whose content-hash tag is not in the registry (or forced): each a custom artifact running docker buildx build --push with the image's registry cache (mode=max), base images built in the same run as `requires`, the others pulled by their registry tag, every image tagged from a lookup table in the tag policy. The prepare job builds it with skaffold right after harness-deployment, replacing the per-image build jobs and the merged-context artifacts; a re-run asks the registry again and only builds what is missing. Stage and prod set cloudharness.build to null. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cloudharness-test.yaml | 1037 +---------------- .gitignore | 1 + .../github-template-prod.yaml | 7 +- .../github-template-stage.yaml | 7 +- deployment-configuration/github-template.yaml | 95 +- docs/build-deploy/ci-cd/README.md | 21 +- tools/deployment-cli-tools/ch_cli_tools/ci.py | 63 + .../ch_cli_tools/github_actions.py | 349 +----- .../ch_cli_tools/skaffold.py | 118 ++ tools/deployment-cli-tools/harness-deployment | 26 +- .../github-template-dev.yaml | 2 +- .../tests/test_github_actions.py | 249 ++-- .../tests/test_github_actions_internals.py | 7 - .../tests/test_skaffold_build.py | 180 +++ 14 files changed, 594 insertions(+), 1568 deletions(-) create mode 100644 tools/deployment-cli-tools/tests/test_skaffold_build.py diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index 509240b27..857888dd1 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -24,7 +24,7 @@ env: CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} jobs: prepare: - name: Prepare helm chart + name: Prepare and build env: NAMESPACE: test-${{ vars.NAMESPACE_BASENAME }} DOMAIN: ${{ vars.DOMAIN }} @@ -125,7 +125,7 @@ jobs: 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 --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS -i samples + harness-deployment . -d "$DOMAIN" -r "$REGISTRY" -rsn "$REGISTRY_SECRET" -n "$NAMESPACE" -e test $TAG_ARG --write-env --write-skaffold-build --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" @@ -136,1016 +136,33 @@ jobs: path: deployment include-hidden-files: true if-no-files-found: error - runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - build-accounts: - name: Build accounts - needs: - - prepare - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether accounts already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.ACCOUNTS_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push accounts - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/accounts:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/accounts:buildcache,mode=max - context: ./applications/accounts - file: ./applications/accounts/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.ACCOUNTS_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/accounts:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',accounts,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.ACCOUNTS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-common: - name: Build common - needs: - - prepare - - build-cloudharness-flask - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether common already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.COMMON_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push common - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/common:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/common:buildcache,mode=max - context: ./applications/common - file: ./applications/common/server/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.COMMON_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/common:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',common,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.COMMON_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-jupyterhub: - name: Build jupyterhub - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether jupyterhub already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.JUPYTERHUB_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push jupyterhub - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/jupyterhub:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/jupyterhub:buildcache,mode=max - context: ./applications/jupyterhub - file: ./applications/jupyterhub/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.JUPYTERHUB_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/jupyterhub:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',jupyterhub,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.JUPYTERHUB_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-nfsserver: - name: Build nfsserver - needs: - - prepare - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether nfsserver already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.NFSSERVER_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push nfsserver - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/nfsserver:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/nfsserver:buildcache,mode=max - context: ./applications/nfsserver - file: ./applications/nfsserver/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.NFSSERVER_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/nfsserver:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',nfsserver,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.NFSSERVER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-samples: - name: Build samples - needs: - - prepare - - build-cloudharness-flask - - build-cloudharness-frontend-build - - build-cloudharness-django - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether samples already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push samples - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp:buildcache,mode=max - context: ./applications/samples - file: ./applications/samples/test.Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - CLOUDHARNESS_FRONTEND_BUILD=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} - CLOUDHARNESS_DJANGO=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - TEST_ARGUMENT=example value - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.SAMPLES_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-samples-print-file: - name: Build samples-print-file - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether samples-print-file already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push samples-print-file - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:buildcache,mode=max - context: ./applications/samples/tasks/print-file - file: ./applications/samples/tasks/print-file/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-print-file:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-print-file,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.SAMPLES_PRINT_FILE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-samples-sum: - name: Build samples-sum - needs: - - prepare - - build-samples - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether samples-sum already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.SAMPLES_SUM_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push samples-sum - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:buildcache,mode=max - context: ./applications/samples/tasks/sum - file: ./applications/samples/tasks/sum/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - SAMPLES=${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.SAMPLES_SUM_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-sum:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-sum,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.SAMPLES_SUM_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-samples-secret: - name: Build samples-secret - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether samples-secret already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.SAMPLES_SECRET_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push samples-secret - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:buildcache,mode=max - context: ./applications/samples/tasks/secret - file: ./applications/samples/tasks/secret/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.SAMPLES_SECRET_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/sampleapp-secret:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',samples-secret,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.SAMPLES_SECRET_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-volumemanager: - name: Build volumemanager - needs: - - prepare - - build-cloudharness-flask - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether volumemanager already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.VOLUMEMANAGER_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push volumemanager - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/volumemanager:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/volumemanager:buildcache,mode=max - context: ./applications/volumemanager - file: ./applications/volumemanager/server/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.VOLUMEMANAGER_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/volumemanager:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',volumemanager,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.VOLUMEMANAGER_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-workflows: - name: Build workflows - needs: - - prepare - - build-cloudharness-flask - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether workflows already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.WORKFLOWS_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push workflows - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows:buildcache,mode=max - context: ./applications/workflows - file: ./applications/workflows/server/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.WORKFLOWS_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/workflows:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.WORKFLOWS_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-workflows-notify-queue: - name: Build workflows-notify-queue - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness + overwrite: true - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: - registry: ${{ needs.prepare.outputs.registry_host }} + registry: ${{ steps.env.outputs.registry_host }} username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether workflows-notify-queue already exists in the registry - id: check + - name: Install skaffold env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} + SKAFFOLD_VERSION: v2.25.0 + SKAFFOLD_SHA256: 42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20 run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push workflows-notify-queue - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:buildcache,mode=max - context: ./applications/workflows/tasks/notify-queue - file: ./applications/workflows/tasks/notify-queue/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/workflows-notify-queue:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-notify-queue,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.WORKFLOWS_NOTIFY_QUEUE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-workflows-send-result-event: - name: Build workflows-send-result-event - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether workflows-send-result-event already exists in the registry - id: check + 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: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push workflows-send-result-event - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:buildcache,mode=max - context: ./applications/workflows/tasks/send-result-event - file: ./applications/workflows/tasks/send-result-event/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/workflows-send-result-event:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-send-result-event,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.WORKFLOWS_SEND_RESULT_EVENT_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-workflows-extract-download: - name: Build workflows-extract-download - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether workflows-extract-download already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push workflows-extract-download - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:buildcache,mode=max - context: ./applications/workflows/tasks/extract-download - file: ./applications/workflows/tasks/extract-download/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/workflows-extract-download:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',workflows-extract-download,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.WORKFLOWS_EXTRACT_DOWNLOAD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-cloudharness-flask: - name: Build cloudharness-flask - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether cloudharness-flask already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push cloudharness-flask - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:buildcache,mode=max - context: ./infrastructure/common-images/cloudharness-flask - file: ./infrastructure/common-images/cloudharness-flask/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-flask:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-flask,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-cloudharness-base: - name: Build cloudharness-base - needs: - - prepare - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether cloudharness-base already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push cloudharness-base - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:buildcache,mode=max - context: ./. - file: ././infrastructure/base-images/cloudharness-base/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-base,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.CLOUDHARNESS_BASE_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-cloudharness-django: - name: Build cloudharness-django - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether cloudharness-django already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push cloudharness-django - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:buildcache,mode=max - context: ./infrastructure/common-images/cloudharness-django - file: ./infrastructure/common-images/cloudharness-django/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-django:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-django,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.CLOUDHARNESS_DJANGO_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-cloudharness-frontend-build: - name: Build cloudharness-frontend-build - needs: - - prepare - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether cloudharness-frontend-build already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push cloudharness-frontend-build - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:buildcache,mode=max - context: ./. - file: ././infrastructure/base-images/cloudharness-frontend-build/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/cloudharness-frontend-build:${{ needs.prepare.outputs.branch_tag }} - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',cloudharness-frontend-build,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.CLOUDHARNESS_FRONTEND_BUILD_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-test-api: - name: Build test-api - needs: - - prepare - - build-cloudharness-base - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether test-api already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push test-api - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-api:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-api:buildcache,mode=max - context: ./test/test-api - file: ./test/test-api/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - CLOUDHARNESS_BASE=${{ vars.REGISTRY }}/cloud-harness/cloudharness-base:${{ needs.prepare.outputs.CLOUDHARNESS_BASE_TAG }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.TEST_API_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/test-api:${{ needs.prepare.outputs.branch_tag }} - ${{ vars.REGISTRY }}/cloud-harness/test-api:latest - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-api,') }} - runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.TEST_API_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} - build-test-e2e: - name: Build test-e2e - needs: - - prepare - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether test-e2e already exists in the registry - id: check - env: - IMAGE: ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push test-e2e - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-e2e:buildcache - cache-to: type=registry,ref=${{ vars.REGISTRY }}/cloud-harness/test-e2e:buildcache,mode=max - context: ./test/test-e2e - file: ./test/test-e2e/Dockerfile - build-args: |- - NOCACHE=${{ github.run_id }} - KEYCLOAK=quay.io/keycloak/keycloak:26.5 - GOLANG=golang:1.26 - ROCKYLINUX=rockylinux/rockylinux:10.1-minimal - NODE=node:22-alpine - PYTHON=python:3.12-slim-trixie - GATEKEEPER=quay.io/gogatekeeper/gatekeeper:4.6.0 - tags: |- - ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.TEST_E2E_TAG }} - ${{ vars.REGISTRY }}/cloud-harness/test-e2e:${{ needs.prepare.outputs.branch_tag }} - ${{ vars.REGISTRY }}/cloud-harness/test-e2e:latest - if: ${{ steps.check.outputs.exists != 'true' || needs.prepare.outputs.force_build == 'all' || contains(format(',{0},', needs.prepare.outputs.force_build), ',test-e2e,') }} + NOCACHE: ${{ github.run_id }} + CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} + run: skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false --update-check=false --interactive=false runs-on: ${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - if: ${{ (needs.prepare.outputs.TEST_E2E_TAG_EXISTS != '1') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} tests-unit-samples: name: Unit tests samples needs: - prepare - - build-samples steps: - uses: docker/login-action@v3 with: @@ -1167,23 +184,6 @@ jobs: name: Deploy needs: - prepare - - build-accounts - - build-common - - build-jupyterhub - - build-nfsserver - - build-samples - - build-samples-print-file - - build-samples-sum - - build-samples-secret - - build-volumemanager - - build-workflows - - build-workflows-notify-queue - - build-workflows-send-result-event - - build-workflows-extract-download - - build-cloudharness-flask - - build-cloudharness-base - - build-cloudharness-django - - build-cloudharness-frontend-build - tests-unit-samples environment: test env: @@ -1273,7 +273,6 @@ jobs: needs: - prepare - wait-deployment - - build-test-api if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} steps: - uses: actions/checkout@v4 @@ -1312,7 +311,6 @@ jobs: needs: - prepare - wait-deployment - - build-test-api if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} steps: - uses: actions/checkout@v4 @@ -1356,7 +354,6 @@ jobs: needs: - prepare - wait-deployment - - build-test-api if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} steps: - uses: actions/checkout@v4 @@ -1395,7 +392,6 @@ jobs: needs: - prepare - wait-deployment - - build-test-e2e if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} steps: - uses: actions/checkout@v4 @@ -1430,7 +426,6 @@ jobs: needs: - prepare - wait-deployment - - build-test-e2e if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} steps: - uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index d79f6d7f8..704b6b065 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ node_modules *.DS_Store deployment/helm deployment/compose +deployment/skaffold-build.yaml /docker-compose.yaml *.egg-info *.idea diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml index 008c4f788..19cb08167 100644 --- a/deployment-configuration/github-template-prod.yaml +++ b/deployment-configuration/github-template-prod.yaml @@ -8,9 +8,12 @@ on: description: Tag of the images to deploy (a tag published by the development or staging pipeline) type: string required: true -jobs: +# deploys the published images: builds nothing +cloudharness: build: null - build-test-images: null +jobs: + prepare: + name: Prepare helm chart tests-unit: null tests-api: null tests-e2e: null diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml index 63c212df1..014c63a1a 100644 --- a/deployment-configuration/github-template-stage.yaml +++ b/deployment-configuration/github-template-stage.yaml @@ -16,9 +16,12 @@ on: description: Set to `true` to skip the tests type: string default: "" -jobs: +# deploys the published images: builds nothing +cloudharness: build: null - build-test-images: null +jobs: + prepare: + name: Prepare helm chart tests-unit: null deploy: env: diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index 7685ee77b..e013f2d71 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -2,16 +2,44 @@ # 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). -# `build`, `build-test-images`, `tests-unit`, `tests-api` and `tests-e2e` are prototypes, expanded into one -# job per image/app ($CH_NAME, $CH_IMAGE and $CH_TAG stand for the image being expanded). 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 (build jobs: CH_GITHUB_BUILD_RUNNER first), falling back -# to the runner given at generation time (CH_GITHUB_RUNNER environment variable, default ubuntu-latest). +# `tests-unit`, `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: + # Steps building and pushing the images whose tag is not in the registry yet, inserted where prepare says + # `- $BUILD_STEPS`. prepare's harness-deployment lists just those images in deployment/skaffold-build.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. null builds nothing (stage and prod deploy + # published 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 }} + - 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-build.yaml --cache-artifacts=false --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 @@ -40,8 +68,10 @@ concurrency: env: CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} jobs: + # prepare also builds the images ($BUILD_STEPS): a re-run asks the registry again, so after a failure it only + # builds what the failed attempt did not push. prepare: - name: Prepare helm chart + name: Prepare and build env: NAMESPACE: ${{ vars.NAMESPACE }} DOMAIN: ${{ vars.DOMAIN }} @@ -103,7 +133,7 @@ jobs: 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 --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS $PARAMS + harness-deployment $PATHS -d "$DOMAIN" -r "$REGISTRY" -rsn "$REGISTRY_SECRET" -n "$NAMESPACE" -e $ENV $TAG_ARG --write-env --write-skaffold-build --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS $PARAMS cat deployment/.env >> "$GITHUB_OUTPUT" - name: View helm chart run: helm template ./deployment/helm --debug -n "$NAMESPACE" @@ -114,49 +144,12 @@ jobs: path: deployment include-hidden-files: true if-no-files-found: error - # one artifact per build context merged across layers in .overrides/, for that image's build job - - $UPLOAD_OVERRIDES - build: - name: Build - needs: [prepare] - steps: - - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - - $GIT_CLONES - - $DOWNLOAD_OVERRIDES - - uses: docker/setup-buildx-action@v3 - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Check whether $CH_NAME already exists in the registry - id: check - env: - IMAGE: $CH_IMAGE:$CH_TAG - run: | - if docker buildx imagetools inspect "$IMAGE" > /dev/null 2>&1; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else - echo "exists=false" >> "$GITHUB_OUTPUT" - fi - - name: Build and push $CH_NAME - id: build - uses: docker/build-push-action@v6 - with: - push: true - cache-from: type=registry,ref=$CH_IMAGE:buildcache - cache-to: type=registry,ref=$CH_IMAGE:buildcache,mode=max - build-test-images: - name: Build test image + # a re-run of prepare (e.g. after a failed build) uploads it again + overwrite: true + - $BUILD_STEPS tests-unit: name: Unit tests - needs: [prepare, build] + needs: [prepare] steps: - uses: docker/login-action@v3 with: @@ -171,7 +164,7 @@ jobs: # them for deploy). deploy: name: Deploy - needs: [prepare, build, tests-unit] + needs: [prepare, tests-unit] environment: $ENV env: HELM_FLAGS: --timeout 200s --create-namespace @@ -201,7 +194,7 @@ jobs: - $ROLLOUT_STEPS tests-api: name: API tests - needs: [prepare, wait-deployment, build-test-images] + needs: [prepare, wait-deployment] if: ${{ needs.prepare.outputs.skip_tests != 'true' }} steps: - uses: actions/checkout@v4 @@ -223,7 +216,7 @@ jobs: - $TEST_STEPS tests-e2e: name: End to end tests - needs: [prepare, wait-deployment, build-test-images] + needs: [prepare, wait-deployment] if: ${{ needs.prepare.outputs.skip_tests != 'true' }} commands: - npx puppeteer browsers install chrome diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index bec8818f4..e10ecf47c 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -26,17 +26,24 @@ When defining an applications values you can provide details on dockerfile confi ## CI/CD with GitHub Actions `harness-deployment -ci github -e [ENV]` generates `.github/workflows/cloudharness-[ENV].yaml`, a workflow with -the same stages as the Codefresh pipeline: one build job per image (skipped when the image's content-hash tag -already exists in the registry), unit tests, helm deployment, rollout wait, API/E2E tests and publication. -Pass `-ci codefresh -ci github` to generate both. +the same stages as the Codefresh pipeline: image build, unit tests, helm deployment, rollout wait, API/E2E tests +and publication. Pass `-ci codefresh -ci github` to generate both. +- Build: the `prepare` job runs `harness-deployment --write-env --write-skaffold-build`, which asks the + registry for every image's content-hash tag and writes `deployment/skaffold-build.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. A re-run after a failure asks the registry + again and only builds what is still missing. The steps live under `cloudharness.build` in the template + (`null` in stage and prod, which deploy published images). - 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.build-[image]` entry in your - template is merged over that image's generated job (for instance to pick a bigger runner). + from your project's `deployment-configuration/` like the Codefresh ones. A `jobs.tests-unit-[app]` entry (or + `tests-api-`, `tests-e2e-`) 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); build jobs read `CH_GITHUB_BUILD_RUNNER` first, so images can build on bigger - runners. Both are read when the workflow runs, so changing runners needs no regeneration. When neither is + 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 diff --git a/tools/deployment-cli-tools/ch_cli_tools/ci.py b/tools/deployment-cli-tools/ch_cli_tools/ci.py index 7ae40141d..c1b856d2f 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/ci.py +++ b/tools/deployment-cli-tools/ch_cli_tools/ci.py @@ -24,6 +24,8 @@ FORCE_BUILD_ALL = "all" DOCKER_HUB_REGISTRY = "docker.io" +TEST_IMAGE_API = "test-api" +TEST_IMAGE_E2E = "test-e2e" def env_key(name: str) -> str: @@ -107,6 +109,11 @@ def record(name: str, image: str) -> None: return env +def tag_exists(env: dict[str, str], name: str) -> bool: + """Whether `image_tag_env` found the image's tag in the registry (and it is not forced).""" + return env.get(tag_variable(name) + "_EXISTS") == "1" + + def write_env_file(path, env: dict[str, str]) -> None: with open(path, "w", encoding="utf-8") as f: f.writelines(f"{key}={value}\n" for key, value in env.items()) @@ -221,6 +228,62 @@ def has_e2e_tests(app) -> bool: ) +def buildable_apps(project) -> list: + return [ + app + for app in project.involved_apps + if not isinstance(app, str) and app.is_buildable + ] + + +def api_test_apps(project) -> list: + return [app for app in buildable_apps(project) if has_api_tests(app) and app.openapi.server_urls] + + +def e2e_test_apps(project) -> list: + return [app for app in buildable_apps(project) if has_e2e_tests(app)] + + +def build_entities(project) -> dict: + """Every image the deployment builds, by name: buildable involved apps, their + tasks and the build dependencies they need - the set helm's `task-images` and + `image_tag_env` cover.""" + entities = {} + for app in project.involved_apps: + if isinstance(app, str): + continue + if app.is_buildable: + entities[app.name] = app + for task in app.buildable_tasks: + entities[task.name] = task + app_names = {app.name for app in project.involved_apps if not isinstance(app, str)} + for name, dependency in project.all_build_dependencies(app_names).items(): + entities.setdefault(name, dependency) + return entities + + +def test_runner_images(project) -> dict: + """The test runner images (`test-api`, `test-e2e`) the tests of some involved app run in.""" + users = {TEST_IMAGE_API: api_test_apps(project), TEST_IMAGE_E2E: e2e_test_apps(project)} + images = {} + for name, apps in users.items(): + image = project.test_images.get(name) + if apps and image is not None and image.dockerfile.exists(): + images[name] = image + return images + + +def build_dependencies(project, entity) -> list: + """The images an entity's build FROMs or declares, deduplicated, in order.""" + dependencies = [] + for dependency in project._combined_dependencies(entity): + if isinstance(dependency, str): + continue + if dependency.name not in {d.name for d in dependencies}: + dependencies.append(dependency) + return dependencies + + def rollout_wait_commands(project) -> list[str]: """`kubectl rollout status` for every auto-deployed workload and gatekeeper, then a settle pause.""" secured_gatekeepers = project.config.secured_gatekeepers diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index 865b53c0e..7e900fa3b 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -3,11 +3,13 @@ The GitHub Actions pipeline does what the Codefresh one does - build every image the deployment needs, run the unit tests, deploy the helm chart, wait for the rollout, run the API/E2E tests, publish (re-tag) the images - with the same -content-hash skip: the `prepare` job runs `harness-deployment --write-env` and -turns `deployment/.env` into job outputs, and every `build-` job is only -scheduled when `_TAG_EXISTS` is not set. Like codefresh.yaml, the -workflow is generated once and committed, so everything only known at run time -stays a `${{ ... }}` expression (vars, secrets, prepare outputs). +content-hash skip. The `prepare` job runs `harness-deployment --write-env +--write-skaffold-build`: deployment/.env becomes job outputs (every image's tag) +and deployment/skaffold-build.yaml lists only the images whose tag is not in the +registry yet, which the same job then builds with skaffold (`cloudharness.build` +steps), in parallel and in dependency order. Like codefresh.yaml, the workflow +is generated once and committed, so everything only known at run time stays a +`${{ ... }}` expression (vars, secrets, prepare outputs). What differs from Codefresh, and shapes the template: - GitHub only runs workflows found in .github/workflows/, so that is where the @@ -15,55 +17,55 @@ - Triggers (`on:`) are part of the file, hence of the per-environment template. - Every job runs on a fresh runner: each one checks out what it needs, images travel between jobs through the registry, the helm chart travels as a - workflow artifact. An image built from a context merged across layers - (`.overrides/`, written by prepare's harness-deployment) gets its own - artifact, downloaded only by that image's build job. + workflow artifact. Building in `prepare` keeps the merged contexts + (`.overrides/`) and git dependencies on the runner that produced them, and + makes a re-run after a failure (or a preempted runner) ask the registry + again, so it only builds what the failed attempt did not push. - A job whose `needs` were skipped is skipped too unless its `if` says - otherwise; since build jobs are skipped on purpose, every dependent job gets - a guard (`apply_needs_guards`) that tolerates skipped builds but not failures. - A job deciding for itself - an `if` using always()/cancelled()/failure() - is - left alone. The template uses that for `publish`, which waits for the API/E2E - tests and runs only if none failed. + otherwise; since test jobs can be skipped on purpose, every dependent job + gets a guard (`apply_needs_guards`) that tolerates skipped jobs but not + failures. A job deciding for itself - an `if` using + always()/cancelled()/failure() - is left alone. The template uses that for + `publish`, which waits for the API/E2E tests and runs only if none failed. Template mechanics (`github-template.yaml` + `github-template-.yaml`, layered across cloud-harness and the project exactly like the Codefresh templates): -- `jobs.build`, `jobs.build-test-images`, `jobs.tests-unit`, `jobs.tests-api` - and `jobs.tests-e2e` are prototypes, expanded into one job per image/app at - their position; a `null` or missing prototype means that kind of job is not - generated. Inside a prototype `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for - the image being expanded. +- `jobs.tests-unit`, `jobs.tests-api` and `jobs.tests-e2e` are prototypes, + expanded into one job per app at their position; a `null` or missing + prototype means that kind of job is not generated. Inside a prototype + `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for the app's image. - A string item in a `steps` list is a fragment the generator fills: - `$GIT_CLONES`, `$UPLOAD_OVERRIDES` (prepare: one artifact per merged - context), `$DOWNLOAD_OVERRIDES` (build: this image's merged context, if - any), `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, - `$TEST_STEPS`, and `$KUBE_AUTH`, the steps giving kubectl/helm access to the - cluster, taken from the template's own `cloudharness.kube_auth` list so a - project changes the authentication method in one place. The top-level + `$GIT_CLONES`, `$BUILD_STEPS`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, + `$ROLLOUT_STEPS`, `$TEST_STEPS` and `$KUBE_AUTH`. The steps of + `$BUILD_STEPS` and `$KUBE_AUTH` come from the template's own + `cloudharness.build` and `cloudharness.kube_auth` lists, so a project + changes how images are built or how the cluster is reached in one place; + `cloudharness.build: null` builds nothing (stage, prod). The top-level `cloudharness` section is for the generator only and never reaches GitHub. - `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. -- A template key matching an expanded job id (`jobs.build-myapp`) is merged over - the generated job, so one image can get a bigger runner or extra steps; such a - key is dropped when its image is not part of the deployment being generated. +- A template key matching an expanded job id (`jobs.tests-unit-myapp`) is merged + over the generated job, so one app can get a bigger runner or extra steps; + such a key is dropped when its app is not part of the deployment being + generated. - `runs-on` defaults to the `CH_GITHUB_RUNNER` repository/organization variable - (build jobs: `CH_GITHUB_BUILD_RUNNER` first), read when the workflow runs, - falling back to CHDeployConfig.ci_runner (`CH_GITHUB_RUNNER` in the generating - shell, default ubuntu-latest). A template `runs-on` always wins. + (`prepare`, when it builds: `CH_GITHUB_BUILD_RUNNER` first), read when the + workflow runs, falling back to CHDeployConfig.ci_runner (`CH_GITHUB_RUNNER` in + the generating shell, default ubuntu-latest). A template `runs-on` always wins. """ import copy -import dataclasses import json import logging import re -from dataclasses import dataclass from functools import lru_cache from pathlib import Path from ruamel.yaml.scalarstring import LiteralScalarString from . import ci +from .ci import TEST_IMAGE_API, TEST_IMAGE_E2E from .model import CHValues, register_file -from .utils import MERGE_DIRNAME, GeneratedYAML, dict_merge, pipeline_relative_path # type: ignore +from .utils import GeneratedYAML, dict_merge, pipeline_relative_path # type: ignore WORKFLOW_FILE_NAME = "cloudharness.yaml" DEFAULT_RUNNER = "ubuntu-latest" @@ -71,19 +73,16 @@ BUILD_RUNNER_VARIABLE = "CH_GITHUB_BUILD_RUNNER" JOB_PREPARE = "prepare" -JOB_BUILD = "build" -JOB_BUILD_TEST_IMAGES = "build-test-images" JOB_UNIT_TESTS = "tests-unit" JOB_API_TESTS = "tests-api" JOB_E2E_TESTS = "tests-e2e" JOB_DEPLOY = "deploy" JOB_WAIT_DEPLOYMENT = "wait-deployment" JOB_PUBLISH = "publish" -PROTOTYPE_JOBS = (JOB_BUILD, JOB_BUILD_TEST_IMAGES, JOB_UNIT_TESTS, JOB_API_TESTS, JOB_E2E_TESTS) +PROTOTYPE_JOBS = (JOB_UNIT_TESTS, JOB_API_TESTS, JOB_E2E_TESTS) FRAGMENT_GIT_CLONES = "$GIT_CLONES" -FRAGMENT_UPLOAD_OVERRIDES = "$UPLOAD_OVERRIDES" -FRAGMENT_DOWNLOAD_OVERRIDES = "$DOWNLOAD_OVERRIDES" +FRAGMENT_BUILD = "$BUILD_STEPS" FRAGMENT_PUBLISH_STEPS = "$PUBLISH_STEPS" FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" FRAGMENT_ROLLOUT = "$ROLLOUT_STEPS" @@ -92,13 +91,10 @@ SETTINGS_KEY = "cloudharness" # generator-only template section, stripped from the workflow SETTING_KUBE_AUTH = "kube_auth" +SETTING_BUILD = "build" STEP_IMAGES = "images" # prepare step appending deployment/.env to $GITHUB_OUTPUT -STEP_CHECK = "check" # build step asking the registry whether the image exists -STEP_BUILD = "build" # build step running docker/build-push-action -TEST_IMAGE_API = "test-api" -TEST_IMAGE_E2E = "test-e2e" TEST_HOME = "/home/test" DEFAULT_E2E_COMMANDS = ("npx puppeteer browsers install chrome", "yarn test") @@ -155,13 +151,6 @@ def expand_steps(steps, fragments: dict[str, list]) -> list: return expanded -def step_by_id(steps, step_id: str): - return next( - (step for step in steps if isinstance(step, dict) and step.get("id") == step_id), - None, - ) - - def strip_expression(value) -> str: value = str(value).strip() match = _EXPRESSION.match(value) @@ -314,13 +303,6 @@ def tag_output(name: str) -> str: return prepare_output(ci.tag_variable(name)) -@dataclass(frozen=True) -class BuildContext: - path: str # docker build context, relative to the workflow's checkout root - dockerfile: str # Dockerfile, relative to the context - artifact: str | None = None # workflow artifact carrying a merged context from prepare - - # --- generator ------------------------------------------------------------------ @@ -366,47 +348,6 @@ def _pipeline_path(self, path) -> str: ) ) - def _context_for(self, entity) -> BuildContext: - root = self.project.root - context = entity.dockerfile.resolve_context(root).resolve_for_build(root) - return BuildContext( - self._pipeline_path(root / context.path), str(context.dockerfile.path) - ) - - def _dependencies(self, entity) -> list: - dependencies = [] - for dependency in self.project._combined_dependencies(entity): - if isinstance(dependency, str): - continue - if dependency.name not in {d.name for d in dependencies}: - dependencies.append(dependency) - return dependencies - - def _buildable_apps(self) -> list: - return [ - app - for app in self.project.involved_apps - if not isinstance(app, str) and app.is_buildable - ] - - def _entities(self) -> dict: - """Every image to build: buildable involved apps, their tasks and the - build dependencies the deployment needs - the same set helm's - `task-images` and `write_env_file` cover.""" - project = self.project - entities = {} - for app in project.involved_apps: - if isinstance(app, str): - continue - if app.is_buildable: - entities[app.name] = app - for task in app.buildable_tasks: - entities[task.name] = task - app_names = {app.name for app in project.involved_apps if not isinstance(app, str)} - for name, dependency in project.all_build_dependencies(app_names).items(): - entities.setdefault(name, dependency) - return entities - # --- generated fragments --- def _git_clone_steps(self, entities) -> list[dict]: @@ -446,37 +387,6 @@ def _git_clone_steps(self, entities) -> list[dict]: ) return steps - def _upload_overrides_steps(self, contexts: dict[str, BuildContext]) -> list[dict]: - return [ - { - "name": f"Share the merged {name} build context", - # an image whose tag exists is not built, so nobody downloads its context - "if": combine_conditions( - f"steps.{STEP_IMAGES}.outputs.{ci.tag_variable(name)}_EXISTS != '1'" - ), - "uses": "actions/upload-artifact@v4", - "with": { - "name": context.artifact, - "path": context.path, - "include-hidden-files": True, - "if-no-files-found": "error", - }, - } - for name, context in contexts.items() - if context.artifact - ] - - def _download_overrides_steps(self, name: str, context: BuildContext) -> list[dict]: - if not context.artifact: - return [] - return [ - { - "name": f"Download the merged {name} build context", - "uses": "actions/download-artifact@v4", - "with": {"name": context.artifact, "path": context.path}, - } - ] - def _publish_steps(self, entities: dict) -> list[dict]: steps = [] for name, entity in entities.items(): @@ -551,86 +461,9 @@ def _prototype(self, prototype, name, image_name): }, ) - def _specific_needs(self, prototype, replacements: dict[str, list]) -> list[str]: - needs = [] - for need in normalize_needs(prototype.get("needs")): - for target in replacements.get(need, [need]): - if target and target not in needs: - needs.append(target) - return needs - - def _build_args(self, entity) -> list[str]: - project = self.project - args = {"NOCACHE": "${{ github.run_id }}"} - if project.config.local or project.config.debug: - args["DEBUG"] = "true" - for dependency in self._dependencies(entity): - args[ci.env_key(dependency.name)] = ( - f"{self.qualify(dependency.image_name)}:{tag_output(dependency.name)}" - ) - args.update(project.all_source_images()) - args.update(getattr(entity, "build_args", None) or {}) - return [f"{key}={value}" for key, value in args.items()] - - def _build_job(self, prototype, entity, context, build_ids, fragments, extra_tags=()): - name = entity.name - image = self.qualify(entity.image_name) - tag_var = ci.tag_variable(name) - job = self._prototype(prototype, name, entity.image_name) - job["name"] = f"Build {name}" - job.setdefault("runs-on", self._runner(BUILD_RUNNER_VARIABLE)) - job["needs"] = self._specific_needs( - prototype, - { - JOB_BUILD: [], - JOB_BUILD_TEST_IMAGES: [], - JOB_PREPARE: [JOB_PREPARE], - }, - ) or [JOB_PREPARE] - if JOB_PREPARE not in job["needs"]: - job["needs"].insert(0, JOB_PREPARE) - for dependency in self._dependencies(entity): - dependency_job = build_ids.get(dependency.name) - if dependency_job and dependency_job not in job["needs"]: - job["needs"].append(dependency_job) - job["if"] = combine_conditions( - prototype.get("if"), f"needs.{JOB_PREPARE}.outputs.{tag_var}_EXISTS != '1'" - ) - steps = expand_steps( - job.get("steps"), - { - **fragments, - # prepare clones the git dependencies before merging: a shared context has them - FRAGMENT_GIT_CLONES: [] if context.artifact else self._git_clone_steps([entity]), - FRAGMENT_DOWNLOAD_OVERRIDES: self._download_overrides_steps(name, context), - }, - ) - build = step_by_id(steps, STEP_BUILD) - if build is not None: - with_ = build.setdefault("with", {}) - with_["context"] = f"./{context.path}" - with_["file"] = f"./{context.path}/{context.dockerfile}" - with_["build-args"] = "\n".join(self._build_args(entity)) - tags = [ - f"{image}:{tag_output(name)}", - f"{image}:{prepare_output('branch_tag')}", - *(f"{image}:{tag}" for tag in extra_tags), - ] - with_["tags"] = "\n".join(tags) - forced = ( - f"needs.{JOB_PREPARE}.outputs.force_build == 'all' || " - f"contains(format(',{{0}},', needs.{JOB_PREPARE}.outputs.force_build), ',{name},')" - ) - build["if"] = combine_conditions( - build.get("if"), f"steps.{STEP_CHECK}.outputs.exists != 'true' || {forced}" - ) - job["steps"] = steps - return job - - def _unit_test_job(self, prototype, app, build_ids, fragments): + def _unit_test_job(self, prototype, app, fragments): job = self._prototype(prototype, app.name, app.image_name) job["name"] = f"Unit tests {app.name}" - job["needs"] = self._specific_needs(prototype, {JOB_BUILD: [build_ids.get(app.name)]}) test_step = self._docker_run_step( f"Run {app.name} unit tests", f"{self.qualify(app.image_name)}:{tag_output(app.name)}", @@ -645,16 +478,13 @@ def _test_image_reference(self, name) -> str | None: return None return f"{self.qualify(test_image.image_name)}:{tag_output(name)}" - def _api_test_job(self, prototype, app, build_ids, fragments): + def _api_test_job(self, prototype, app, fragments): url = ci.api_test_url(app, "${{ vars.DOMAIN }}") image = self._test_image_reference(TEST_IMAGE_API) if url is None or image is None: return None job = self._prototype(prototype, app.name, app.image_name) job["name"] = f"API tests {app.name}" - job["needs"] = self._specific_needs( - prototype, {JOB_BUILD_TEST_IMAGES: [build_ids.get(TEST_IMAGE_API)]} - ) app_path = self._pipeline_path(app.path) test_step = self._docker_run_step( f"Run {app.name} API tests", @@ -670,16 +500,13 @@ def _api_test_job(self, prototype, app, build_ids, fragments): job["steps"] = expand_steps(job.get("steps"), {**fragments, FRAGMENT_TEST: [test_step]}) return job - def _e2e_test_job(self, prototype, app, build_ids, fragments): + def _e2e_test_job(self, prototype, app, fragments): image = self._test_image_reference(TEST_IMAGE_E2E) if image is None: return None url = ci.app_domain(app, "${{ vars.DOMAIN }}") job = self._prototype(prototype, app.name, app.image_name) job["name"] = f"E2E tests {app.name}" - job["needs"] = self._specific_needs( - prototype, {JOB_BUILD_TEST_IMAGES: [build_ids.get(TEST_IMAGE_E2E)]} - ) app_path = self._pipeline_path(app.path) test_step = self._docker_run_step( f"Run {app.name} E2E tests", @@ -706,45 +533,24 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: removed = [key for key, job in jobs.items() if job is None] jobs = {key: job for key, job in jobs.items() if job is not None} - entities = self._entities() - apps = self._buildable_apps() - unit_apps = [app for app in apps if app.test.unit.commands] - api_apps = ( - [app for app in apps if ci.has_api_tests(app) and app.openapi.server_urls] - if JOB_API_TESTS in jobs - else [] - ) - e2e_apps = [app for app in apps if ci.has_e2e_tests(app)] if JOB_E2E_TESTS in jobs else [] - test_entities = {} - if JOB_BUILD_TEST_IMAGES in jobs and JOB_BUILD in jobs: - for name, users in ((TEST_IMAGE_API, api_apps), (TEST_IMAGE_E2E, e2e_apps)): - image = project.test_images.get(name) - if users and image is not None and image.dockerfile.exists(): - test_entities[name] = image - - # prepare's harness-deployment merges the contexts of apps, tasks and build dependencies - # again (skaffold, tilt), not those of test images: only the former can be shared - contexts = {} - if JOB_BUILD in jobs: - for name, entity in entities.items(): - context = self._context_for(entity) - if Path(context.path).parts[:1] == (MERGE_DIRNAME,): - context = dataclasses.replace(context, artifact=f"cloudharness-overrides-{name}") - contexts[name] = context - for name, image in test_entities.items(): - contexts[name] = self._context_for(image) - - build_ids = {name: job_id(f"{JOB_BUILD}-{name}") for name in [*entities, *test_entities]} + entities = ci.build_entities(project) + build_steps = list(settings.get(SETTING_BUILD) or []) + # the test runner images are built (hence published) only by a workflow that builds + test_images = ci.test_runner_images(project) if build_steps else {} + unit_apps = [app for app in ci.buildable_apps(project) if app.test.unit.commands] + api_apps = ci.api_test_apps(project) if JOB_API_TESTS in jobs else [] + e2e_apps = ci.e2e_test_apps(project) if JOB_E2E_TESTS in jobs else [] + unit_ids = {app.name: job_id(f"{JOB_UNIT_TESTS}-{app.name}") for app in unit_apps} api_ids = {app.name: job_id(f"{JOB_API_TESTS}-{app.name}") for app in api_apps} e2e_ids = {app.name: job_id(f"{JOB_E2E_TESTS}-{app.name}") for app in e2e_apps} - generated_ids = {*build_ids.values(), *unit_ids.values(), *api_ids.values(), *e2e_ids.values()} + generated_ids = {*unit_ids.values(), *api_ids.values(), *e2e_ids.values()} fragments = { - FRAGMENT_GIT_CLONES: self._git_clone_steps(apps), - FRAGMENT_UPLOAD_OVERRIDES: self._upload_overrides_steps(contexts), - FRAGMENT_DOWNLOAD_OVERRIDES: [], - FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_entities}), + # prepare merges the build contexts (.overrides/) with the git dependencies in them + FRAGMENT_GIT_CLONES: self._git_clone_steps(entities.values()), + FRAGMENT_BUILD: build_steps, + FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_images}), FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), FRAGMENT_ROLLOUT: self._rollout_steps(), FRAGMENT_TEST: [], @@ -771,61 +577,26 @@ def expand(key, items, make): for key, job in jobs.items(): if key in overlays: continue - if key == JOB_BUILD: - expand( - key, - entities.items(), - lambda item: ( - build_ids[item[0]], - self._build_job(job, item[1], contexts[item[0]], build_ids, fragments), - ), - ) - elif key == JOB_BUILD_TEST_IMAGES: - prototype = dict_merge(jobs[JOB_BUILD], job) if JOB_BUILD in jobs else None - expand( - key, - test_entities.items() if prototype else [], - lambda item: ( - build_ids[item[0]], - self._build_job( - prototype, - item[1], - contexts[item[0]], - build_ids, - fragments, - extra_tags=("latest",), - ), - ), - ) - elif key == JOB_UNIT_TESTS: + if key == JOB_UNIT_TESTS: expand( key, unit_apps, - lambda app: ( - unit_ids[app.name], - self._unit_test_job(job, app, build_ids, fragments), - ), + lambda app: (unit_ids[app.name], self._unit_test_job(job, app, fragments)), ) elif key == JOB_API_TESTS: expand( key, api_apps, - lambda app: ( - api_ids[app.name], - self._api_test_job(job, app, build_ids, fragments), - ), + lambda app: (api_ids[app.name], self._api_test_job(job, app, fragments)), ) elif key == JOB_E2E_TESTS: expand( key, e2e_apps, - lambda app: ( - e2e_ids[app.name], - self._e2e_test_job(job, app, build_ids, fragments), - ), + lambda app: (e2e_ids[app.name], self._e2e_test_job(job, app, fragments)), ) elif key.startswith(overlay_prefixes): - # an overlay for an image/app that is not part of this deployment + # an overlay for an app that is not part of this deployment continue else: job = copy.deepcopy(job) @@ -834,6 +605,8 @@ def expand(key, items, make): for output, value in self._prepare_outputs().items(): outputs.setdefault(output, value) job["outputs"] = outputs + if build_steps: + job.setdefault("runs-on", self._runner(BUILD_RUNNER_VARIABLE)) job["steps"] = expand_steps(job.get("steps"), fragments) result[key] = job diff --git a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py index ae1b33ca0..7d9ccf6e7 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py +++ b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py @@ -65,12 +65,19 @@ overrides. """ +import json +import os +import shlex from functools import lru_cache from pathlib import Path +from . import ci from .model import CHValues, register_file from .utils import dict_merge # type: ignore +BUILD_CACHE_TAG = "buildcache" +BRANCH_TAG_VARIABLE = "CH_BRANCH_TAG" + # tools/clone.sh, shipped alongside this package - not part of any deployed # project, so it's located relative to this file, not project.root/ch_path. _CLONE_SH = Path(__file__).resolve().parent.parent.parent.parent / "clone.sh" @@ -341,3 +348,114 @@ def generate(self, write_on_disk=True, output_path="."): self.write(base, output_path=output_path) return base + + +def tag_template(tags: dict[str, str]) -> str: + """An envTemplate tag policy giving every image its own tag: skaffold has a single + tag policy for all the artifacts, so it looks the image up in a table.""" + table = " ".join(f"{json.dumps(image)} {json.dumps(tag)}" for image, tag in tags.items()) + return "{{ index (dict %s) .IMAGE_NAME }}" % table + + +def buildx_command(image: str, dockerfile: str, build_args: dict[str, str], extra_tags=()) -> str: + """The shell command a custom skaffold artifact builds and pushes `image` with, from its + context directory: tagged `$IMAGE` (skaffold's tag), the extra tags and `$CH_BRANCH_TAG` + when set, with the image's registry cache.""" + cache = f"{image}:{BUILD_CACHE_TAG}" + parts = [ + "docker buildx build --push", + f"--file {shlex.quote(dockerfile)}", + '--tag "$IMAGE"', + *(f"--tag {shlex.quote(f'{image}:{tag}')}" for tag in extra_tags), + f"${{{BRANCH_TAG_VARIABLE}:+--tag {image}:${BRANCH_TAG_VARIABLE}}}", + # value from the environment: a different one on every run busts the layers using it + "--build-arg NOCACHE", + *(f"--build-arg {shlex.quote(f'{key}={value}')}" for key, value in build_args.items()), + f"--cache-from type=registry,ref={cache}", + f"--cache-to type=registry,ref={cache},mode=max", + ".", + ] + return " ".join(parts) + + +@register_file("skaffold_build", lambda root: root / "deployment" / "skaffold-build.yaml") +class CHSkaffoldBuild(CHValues): + """deployment/skaffold-build.yaml: what a CI run still has to build. + + Written at pipeline run time (`harness-deployment --write-skaffold-build`), once + `ci.image_tag_env` has asked the registry which tags exist: the artifacts are only + the images whose tag is missing or forced. Since an image's content-hash tag folds + in the tags of the images it is built on, a changed base image is rebuilt along + with everything built on it. Every base image reaches a Dockerfile as a build arg + naming its tag in the registry, so the ones not rebuilt are pulled; `requires` + lists the ones built in the same run, which skaffold builds first. + + Each artifact is a custom build running `docker buildx build --push` with the + image's registry cache (`:buildcache`, mode=max): skaffold orders the + builds, runs them in parallel and tags each image from the table in its tag + policy. Run from the project root with `skaffold build -f + deployment/skaffold-build.yaml --cache-artifacts=false`; NOCACHE and + CH_BRANCH_TAG come from the environment. + """ + + def _context(self, entity) -> tuple[str, str]: + """The merged build context, relative to the project root (skaffold resolves contexts from + the directory it runs in, not from the file's), and the Dockerfile, relative to the context.""" + root = self.project.root + context = entity.dockerfile.resolve_context(root).resolve_for_build(root) + return os.path.relpath(root / context.path, root), str(context.dockerfile.path) + + def _artifact(self, entity, image: str, building: dict, extra_tags=()) -> dict: + project = self.project + context, dockerfile = self._context(entity) + build_args = {} + if project.config.local or project.config.debug: + build_args["DEBUG"] = "true" + requires = [] + for dependency in ci.build_dependencies(project, entity): + alias = ci.env_key(dependency.name) + build_args[alias] = project.qualify_image(dependency) + if dependency.name in building: + requires.append({"image": project.qualify(dependency.image_name), "alias": alias}) + build_args.update(project.all_source_images()) + build_args.update(getattr(entity, "build_args", None) or {}) + artifact = { + "image": image, + "context": context, + "custom": {"buildCommand": buildx_command(image, dockerfile, build_args, extra_tags)}, + } + if requires: + artifact["requires"] = requires + return artifact + + def generate(self, image_env: dict[str, str], write_on_disk=True) -> dict: + project = self.project + test_images = ci.test_runner_images(project) + building = { + name: entity + for name, entity in {**ci.build_entities(project), **test_images}.items() + if not ci.tag_exists(image_env, name) + } + tags = {} + artifacts = [] + for name, entity in building.items(): + image = project.qualify(entity.image_name) + tags[image] = ci.ImageReference.parse(project.qualify_image(entity)).tag + # the stage pipeline, which builds nothing, runs the tests in the `latest` test images + extra_tags = ("latest",) if name in test_images else () + artifacts.append(self._artifact(entity, image, building, extra_tags)) + + template = project.skaffold_template.all_values() + plan = { + "apiVersion": template["apiVersion"], + "kind": template.get("kind", "Config"), + "build": { + "tagPolicy": {"envTemplate": {"template": tag_template(tags)}}, + # the custom builds push; skaffold then reads each image's digest from the registry + "local": {"push": True, "concurrency": 0}, + "artifacts": artifacts, + }, + } + if write_on_disk: + self.write(plan) + return plan diff --git a/tools/deployment-cli-tools/harness-deployment b/tools/deployment-cli-tools/harness-deployment index 8db777d84..bffbefb1c 100644 --- a/tools/deployment-cli-tools/harness-deployment +++ b/tools/deployment-cli-tools/harness-deployment @@ -6,7 +6,7 @@ from pathlib import Path from cloudharness_utils.constants import DEPLOYMENT_PATH from ch_cli_tools.api import deploy, hosts_info, perform_migration -from ch_cli_tools.ci import parse_force_build +from ch_cli_tools.ci import image_tag_env, parse_force_build, write_env_file from ch_cli_tools.model import CHDeployConfig, CHProject from ch_cli_tools.utils import discover_root_paths, generation_argv @@ -179,8 +179,8 @@ if __name__ == "__main__": dest="force_build", action="store", default=None, - help="With --write-env, report these images (comma-separated, or `all`) as not built yet " - "so the pipeline rebuilds them even if their tag already exists in the registry", + help="With --write-env/--write-skaffold-build, report these images (comma-separated, or `all`) as " + "not built yet so the pipeline rebuilds them even if their tag already exists in the registry", ) parser.add_argument( "-we", @@ -191,6 +191,13 @@ if __name__ == "__main__": const=True, help=f"Write build env to .env file in {DEPLOYMENT_PATH}", ) + parser.add_argument( + "--write-skaffold-build", + dest="write_skaffold_build", + action="store_true", + help=f"Write {DEPLOYMENT_PATH}/skaffold-build.yaml, a skaffold build of the images whose tag is " + "not in the registry yet (see --force-build), pushed with their registry cache", + ) parser.add_argument( "--migrate", dest="migration", @@ -292,12 +299,15 @@ if __name__ == "__main__": if "github" in ci_providers: project.github_actions.generate() - if args.write_env: - project.codefresh.write_env_file( - root_paths[-1] / DEPLOYMENT_PATH / ".env", - args.image_cache_url, - force_build=parse_force_build(args.force_build), + if args.write_env or args.write_skaffold_build: + # one registry lookup per image, shared by both files + image_env = image_tag_env( + project, args.image_cache_url, force_build=parse_force_build(args.force_build) ) + if args.write_env: + write_env_file(root_paths[-1] / DEPLOYMENT_PATH / ".env", image_env) + if args.write_skaffold_build: + project.skaffold_build.generate(image_env) project.skaffold.generate() project.tilt.generate() diff --git a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml index d91745853..282839093 100644 --- a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml +++ b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml @@ -3,7 +3,7 @@ test_step: dev jobs: prepare: name: Overridden - build-myapp: + tests-unit-myapp: runs-on: big-runner custom-job: name: Custom diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index 23db57f8d..867c73e7a 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -10,7 +10,7 @@ from ruamel.yaml import YAML from test_util import write_tree_from_yaml -from ch_cli_tools import CHDeployConfig +from ch_cli_tools import CHDeployConfig, ci from ch_cli_tools.api import create_helm_chart from ch_cli_tools.github_actions import DEFAULT_RUNNER @@ -65,7 +65,7 @@ def test_template_layering(tmp_path): assert custom["needs"] == ["deploy"] assert "needs.deploy.result == 'success'" in custom["if"] # an overlay for an expanded job id is merged over the generated job - assert wf["jobs"]["build-myapp"]["runs-on"] == "big-runner" + assert wf["jobs"]["tests-unit-myapp"]["runs-on"] == "big-runner" # the generator-only section is consumed, not emitted; its kube_auth steps replace # the default ones wherever a job asks for $KUBE_AUTH assert "cloudharness" not in wf @@ -80,176 +80,65 @@ def test_template_layering(tmp_path): assert "id-token" not in wf["permissions"] -def test_build_jobs_follow_the_dependency_graph(tmp_path): +def test_prepare_builds_the_missing_images_with_skaffold(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] - - for name in ("cloudharness-base", "cloudharness-flask", "myapp", "myapp-mytask", "my-common", "samples"): - assert f"build-{name}" in jobs, name - # only what the deployment needs is built: no excluded app, no unused base image - assert "build-events" not in jobs - assert "build-cloudharness-base-debian" not in jobs - - assert jobs["build-cloudharness-base"]["needs"] == ["prepare"] - assert jobs["build-myapp"]["needs"][:2] == ["prepare", "build-cloudharness-flask"] - assert jobs["build-cloudharness-flask"]["needs"] == ["prepare", "build-cloudharness-base"] - - condition = jobs["build-myapp"]["if"] - assert "needs.prepare.outputs.MYAPP_TAG_EXISTS != '1'" in condition - assert "!cancelled()" in condition - assert "needs.prepare.result == 'success'" in condition - # a skipped dependency build must not skip the dependant - assert "needs.build-cloudharness-flask.result ==" not in condition - - -def test_build_step_inputs(tmp_path): - wf, _ = _generate(tmp_path, ["samples", "myapp"]) - jobs = wf["jobs"] - - build = _step(jobs["build-myapp"], "build") - with_ = build["with"] - assert with_["context"] == "./applications/myapp" - assert with_["file"] == "./applications/myapp/dev.Dockerfile", "env Dockerfile preferred" - assert isinstance(with_["build-args"], str) and isinstance(with_["tags"], str) - build_args = with_["build-args"].splitlines() - assert build_args[0] == "NOCACHE=${{ github.run_id }}" - assert ( - "CLOUDHARNESS_FLASK=${{ vars.REGISTRY }}/testprojectname/cloudharness-flask:" - "${{ needs.prepare.outputs.CLOUDHARNESS_FLASK_TAG }}" in build_args - ) - tags = with_["tags"].splitlines() - assert tags[0] == "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" - assert tags[1].endswith(":${{ needs.prepare.outputs.branch_tag }}") - assert with_["push"] is True - assert with_["cache-from"] == "type=registry,ref=${{ vars.REGISTRY }}/testprojectname/myapp:buildcache" - assert "steps.check.outputs.exists != 'true'" in build["if"] - assert "',myapp,'" in build["if"] - - check = _step(jobs["build-myapp"], "check") - assert check["env"]["IMAGE"] == ( - "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + prepare = jobs["prepare"] + + # one job builds every image: harness-deployment lists the missing ones, skaffold builds them + assert not [name for name in jobs if name.startswith("build")] + assert "--write-env --write-skaffold-build" in _step(prepare, "images")["run"] + build = _steps(prepare, "Build and push the images")[0] + assert build["run"].startswith( + "skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false" ) - assert 'imagetools inspect "$IMAGE"' in check["run"] - - # cloudharness-base is overridden by RESOURCES: built from the merged .overrides context - base = _step(jobs["build-cloudharness-base"], "build")["with"] - assert base["context"] == "./.overrides/cloudharness-base" - assert base["file"] == ( - "./.overrides/cloudharness-base/infrastructure/base-images/cloudharness-base/Dockerfile" - ) - # samples lives in cloud-harness, cloned into ./cloud-harness by the workflow - samples = _step(jobs["build-samples"], "build")["with"] - assert samples["context"] == "./cloud-harness/applications/samples" - assert samples["file"] == "./cloud-harness/applications/samples/Dockerfile" - # a test image gets the extra latest tag - assert "${{ vars.REGISTRY }}/testprojectname/test-e2e:latest" in ( - _step(jobs["build-test-e2e"], "build")["with"]["tags"].splitlines() + assert build["env"] == { + "NOCACHE": "${{ github.run_id }}", + "CH_BRANCH_TAG": "${{ steps.env.outputs.branch_tag }}", + } + names = [step.get("name") or step.get("uses") for step in prepare["steps"]] + assert names.index("Prepare helm chart") < names.index("Install skaffold") < names.index( + "Build and push the images" ) + login = next(step for step in prepare["steps"] if step.get("uses") == "docker/login-action@v3") + assert login["with"]["registry"] == "${{ steps.env.outputs.registry_host }}" + install = _steps(prepare, "Install skaffold")[0] + assert re.fullmatch(r"v\d+\.\d+\.\d+", install["env"]["SKAFFOLD_VERSION"]) + assert re.fullmatch(r"[0-9a-f]{64}", install["env"]["SKAFFOLD_SHA256"]) + assert 'sha256sum -c -' in install["run"] + # the merged contexts never leave prepare: the only artifact is the deployment + uploads = [step for step in prepare["steps"] if step.get("uses") == "actions/upload-artifact@v4"] + assert [step["with"]["name"] for step in uploads] == ["cloudharness-deployment"] + assert jobs["deploy"]["needs"][0] == "prepare" def test_git_dependency_checkouts(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"]) - jobs = wf["jobs"] + prepare = wf["jobs"]["prepare"] - clones = _steps(jobs["build-myapp"], "Clone ") - clones = [step for step in clones if step["name"] != "Clone cloud-harness"] + clones = [step for step in _steps(prepare, "Clone ") if step["name"] != "Clone cloud-harness"] assert len(clones) == 2, "myapp declares two git dependencies" assert clones[0]["uses"] == "actions/checkout@v4" assert clones[0]["with"]["repository"] == "a/b" assert clones[0]["with"]["ref"] == "master" assert clones[0]["with"]["path"] == "applications/myapp/dependencies/b" - step_names = [step.get("name") for step in jobs["build-myapp"]["steps"]] - assert step_names.index("Clone b") < step_names.index("Build and push myapp") - # prepare clones them too (the content hash needs them); samples has none - assert len([s for s in _steps(jobs["prepare"], "Clone ") if s["name"] != "Clone cloud-harness"]) == 2 - assert not [s for s in _steps(jobs["build-samples"], "Clone ") if s["name"] != "Clone cloud-harness"] - - -def test_merged_contexts_travel_as_their_own_artifacts(tmp_path): - # sentry overrides cloud-harness' own app, Dockerfile included: built from .overrides/sentry; - # my-base is the project's own base image, built from the project root - write_tree_from_yaml( - tmp_path, - """ - deployment-configuration: - values-template.yaml: | - name: testproj - mainapp: sentry - infrastructure: - base-images: - my-base: - Dockerfile: | - FROM scratch - applications: - sentry: - Dockerfile: | - FROM scratch - deploy: - values.yaml: | - harness: - dependencies: - build: - - my-base - git: - - url: https://github.com/a/b.git - branch_tag: master - """, - ) - project = chain( - CLOUDHARNESS_ROOT, - tmp_path, - config=CHDeployConfig(env="dev", registry="reg", tag="1", output_path=str(tmp_path / "deployment")), - ) - jobs = project.github_actions.generate(write_on_disk=False)["jobs"] - - def artifact_steps(job, action): - return [step for step in job["steps"] if step.get("uses") == f"actions/{action}-artifact@v4"] - - deployment, upload = artifact_steps(jobs["prepare"], "upload") - assert deployment["with"]["name"] == "cloudharness-deployment" - assert deployment["with"]["path"] == "deployment" - assert upload["with"] == { - "name": "cloudharness-overrides-sentry", - "path": ".overrides/sentry", - "include-hidden-files": True, - "if-no-files-found": "error", - } - assert upload["if"] == "${{ steps.images.outputs.SENTRY_TAG_EXISTS != '1' }}" - # prepare clones the git dependency before harness-deployment merges the context - step_names = [step.get("name") for step in jobs["prepare"]["steps"]] + # cloned before harness-deployment merges and hashes the build contexts + step_names = [step.get("name") for step in prepare["steps"]] assert step_names.index("Clone b") < step_names.index("Prepare helm chart") - - build = jobs["build-sentry"] - assert _step(build, "build")["with"]["context"] == "./.overrides/sentry" - assert [step["with"] for step in artifact_steps(build, "download")] == [ - {"name": "cloudharness-overrides-sentry", "path": ".overrides/sentry"} - ] - assert not _steps(build, "Clone b"), "the merged context already holds the git dependency" - assert _step(jobs["build-my-base"], "build")["with"]["context"] == "./." - for name, job in jobs.items(): - if name.startswith("build-") and name != "build-sentry": - assert not artifact_steps(job, "download"), f"{name} builds from the checkout" - assert [step["with"] for step in artifact_steps(jobs["deploy"], "download")] == [ - {"name": "cloudharness-deployment", "path": "deployment"} - ] - - # prepare's harness-deployment writes .overrides/ through skaffold and tilt, not through this - # generator: every context it uploads must come out of those two - shutil.rmtree(tmp_path / ".overrides") - project.skaffold.generate(write_on_disk=False) - project.tilt.generate(write_on_disk=False) - assert (tmp_path / upload["with"]["path"] / "Dockerfile").exists() + for name, job in wf["jobs"].items(): + if name != "prepare": + assert not [s for s in _steps(job, "Clone ") if s["name"] != "Clone cloud-harness"], name -def test_prepare_outputs_cover_every_build(tmp_path): - wf, _ = _generate(tmp_path, ["samples", "myapp"]) +def test_prepare_outputs_cover_every_image(tmp_path): + wf, project = _generate(tmp_path, ["samples", "myapp"]) outputs = wf["jobs"]["prepare"]["outputs"] assert list(outputs)[0] == "branch_tag", "template outputs come first" - for job_name in wf["jobs"]: - if not job_name.startswith("build-"): - continue - variable = job_name[len("build-"):].replace("-", "_").upper() + "_TAG" + names = [*ci.build_entities(project), *ci.test_runner_images(project)] + assert "cloudharness-base" in names and "test-api" in names + for name in names: + variable = ci.tag_variable(name) assert outputs[variable] == "${{ steps.images.outputs.%s }}" % variable assert outputs[f"{variable}_EXISTS"] == "${{ steps.images.outputs.%s_EXISTS }}" % variable # instances share their parent's image but still get their variables @@ -263,7 +152,7 @@ def test_unit_test_jobs(tmp_path): unit_jobs = [name for name in jobs if name.startswith("tests-unit-")] assert sorted(unit_jobs) == ["tests-unit-myapp", "tests-unit-samples"] job = jobs["tests-unit-myapp"] - assert job["needs"] == ["prepare", "build-myapp"] + assert job["needs"] == ["prepare"], "prepare builds the images" assert "needs.prepare.result == 'success'" in job["if"] step = _steps(job, "Run myapp unit tests")[0] assert step["env"]["CH_TEST_IMAGE"] == ( @@ -281,7 +170,7 @@ def test_api_and_e2e_test_jobs(tmp_path): jobs = wf["jobs"] api = jobs["tests-api-samples"] - assert "wait-deployment" in api["needs"] and "build-test-api" in api["needs"] + assert api["needs"] == ["prepare", "wait-deployment"] assert "needs.prepare.outputs.skip_tests != 'true'" in api["if"] # wait-deployment may be skipped (it has its own `if`), but must not have failed assert "needs.wait-deployment.result ==" not in api["if"] @@ -304,7 +193,7 @@ def test_api_and_e2e_test_jobs(tmp_path): assert commands[2] == "pytest -v test/api" e2e = jobs["tests-e2e-samples"] - assert "build-test-e2e" in e2e["needs"] + assert e2e["needs"] == ["prepare", "wait-deployment"] step = _steps(e2e, "Run samples E2E tests")[0] assert step["env"]["APP_URL"] == "https://www.${{ vars.DOMAIN }}" assert ( @@ -314,10 +203,6 @@ def test_api_and_e2e_test_jobs(tmp_path): assert step["env"]["CH_TEST_COMMANDS"] == "set -e\nnpx puppeteer browsers install chrome\nyarn test\n" assert "commands" not in e2e, "the prototype's commands key never reaches the workflow" - # the test runner images are built with the build prototype - assert jobs["build-test-api"]["needs"] == ["prepare", "build-cloudharness-base"] - assert "build-test-api" not in jobs["deploy"]["needs"] - def test_no_api_e2e_jobs_when_not_enabled(tmp_path): wf, _ = _generate(tmp_path, ["myapp"]) @@ -350,7 +235,7 @@ def test_deploy_secret_values(tmp_path): def test_rollout_wait_and_publish_steps(tmp_path): - wf, _ = _generate(tmp_path, ["samples", "myapp"]) + wf, project = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] rollout = _steps(jobs["wait-deployment"], "Wait for the rollouts")[0] @@ -369,8 +254,8 @@ def test_rollout_wait_and_publish_steps(tmp_path): # the API/E2E tests run after the deployment, so they cannot block it assert not [n for n in jobs["deploy"]["needs"] if n.startswith(("tests-api", "tests-e2e"))] published = {step["name"][len("Publish "):] for step in _steps(publish, "Publish ")} - built = {name[len("build-"):] for name in jobs if name.startswith("build-")} - assert published == built + built = {*ci.build_entities(project), *ci.test_runner_images(project)} + assert published == built and "test-e2e" in published step = _steps(publish, "Publish myapp")[0] assert step["if"] == "${{ vars.MYAPP_PUBLISH_SKIP == '' }}" assert step["env"]["SOURCE"] == ( @@ -387,7 +272,7 @@ def test_prepare_command_placeholders(tmp_path): assert "-e dev " in run assert "-i samples -i myapp -ex events" in run assert "$PATHS" not in run and "$ENV " not in run and "$PARAMS" not in run - assert "--write-env" in run and "--force-build" in run + assert "--write-env" in run and "--write-skaffold-build" in run and "--force-build" in run def test_multienv_test_overlay(tmp_path): @@ -409,6 +294,10 @@ def test_prod_deploys_only(tmp_path): jobs = wf["jobs"] assert list(jobs) == ["prepare", "deploy"] + # prod deploys published images: prepare builds nothing, on the default runner + assert jobs["prepare"]["name"] == "Prepare helm chart" + assert not _steps(jobs["prepare"], "Build and push") + assert jobs["prepare"]["runs-on"] == "${{ vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER assert jobs["deploy"]["needs"] == ["prepare"] assert jobs["deploy"]["environment"] == "prod" # the fixture's kube_auth override lives in the dev overlay only: prod keeps the @@ -422,7 +311,8 @@ def test_stage_keeps_tests_and_tags_the_repository(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"], envs=("stage",)) jobs = wf["jobs"] - assert not [name for name in jobs if name.startswith("build-")] + assert not _steps(jobs["prepare"], "Build and push"), "stage deploys published images" + assert not _steps(jobs["publish"], "Publish test-"), "the test images are not built here" assert "tests-api-samples" in jobs and "tests-unit-samples" not in jobs assert jobs["tests-api-samples"]["needs"] == ["prepare", "wait-deployment"] assert jobs["git-tag"]["needs"] == ["prepare", "publish"] @@ -441,13 +331,9 @@ def test_runner_configuration(tmp_path): # the runner is a repository variable read at run time; the generation-time runner is the fallback default = "${{ vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER build = "${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER - assert jobs["prepare"]["runs-on"] == default + assert jobs["prepare"]["runs-on"] == build, "prepare builds the images" assert jobs["deploy"]["runs-on"] == default - assert jobs["tests-unit-myapp"]["runs-on"] == default - builds = [name for name in jobs if name.startswith("build-") and name != "build-myapp"] - assert builds - assert all(jobs[name]["runs-on"] == build for name in builds) - assert jobs["build-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" + assert jobs["tests-unit-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig( env="dev", includes=["myapp"], excludes=["events"], registry="reg", tag="1", @@ -455,6 +341,9 @@ def test_runner_configuration(tmp_path): )) wf = project.github_actions.generate(write_on_disk=False) assert wf["jobs"]["prepare"]["runs-on"] == ( + """${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || fromJSON('["self-hosted", "linux"]') }}""" + ) + assert wf["jobs"]["deploy"]["runs-on"] == ( """${{ vars.CH_GITHUB_RUNNER || fromJSON('["self-hosted", "linux"]') }}""" ) @@ -491,18 +380,17 @@ def test_paths_are_cwd_independent(tmp_path): old_cwd = os.getcwd() try: os.chdir(sibling_dir) - wf, _ = _generate(tmp_path, ["samples"]) + wf, _ = _generate(tmp_path, ["samples", "myapp"]) finally: os.chdir(old_cwd) shutil.rmtree(sibling_dir, ignore_errors=True) - for name, job in wf["jobs"].items(): - if not name.startswith("build-"): - continue - context = _step(job, "build")["with"]["context"] - assert not context.startswith("./..") and "/../" not in context, (name, context) - assert not os.path.isabs(context), (name, context) - assert "../cloud-harness" not in _step(wf["jobs"]["prepare"], "images")["run"] + prepare = wf["jobs"]["prepare"] + paths = [step["with"]["path"] for step in _steps(prepare, "Clone ")] + assert "applications/myapp/dependencies/b" in paths + for path in paths: + assert not path.startswith("..") and "/../" not in path and not os.path.isabs(path), path + assert "../cloud-harness" not in _step(prepare, "images")["run"] def test_generate_writes_the_workflow_under_github_workflows(tmp_path): @@ -530,10 +418,9 @@ def test_generate_writes_the_workflow_under_github_workflows(tmp_path): assert workflow.exists() text = workflow.read_text() assert text.startswith("name: CloudHarness dev\n") and text.splitlines()[1].startswith("on:") - assert "build-args: |" in text, "multi-line inputs are written as literal blocks" - assert "run: |" in text + assert "run: |" in text, "multi-line strings are written as literal blocks" loaded = YAML(typ="safe").load(text) - assert "on" in loaded and "build-myapp" in loaded["jobs"] + assert "on" in loaded and "prepare" in loaded["jobs"] def test_no_template_means_no_workflow(tmp_path): diff --git a/tools/deployment-cli-tools/tests/test_github_actions_internals.py b/tools/deployment-cli-tools/tests/test_github_actions_internals.py index c229c7e17..ea56cec8b 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions_internals.py +++ b/tools/deployment-cli-tools/tests/test_github_actions_internals.py @@ -15,7 +15,6 @@ referenced_names, rewrite_needs, runner_expression, - step_by_id, substitute_vars, ) @@ -50,12 +49,6 @@ def test_expand_steps_replaces_fragments_and_rejects_unknown_ones(): expand_steps(["$NOPE"], {"$F": fragment}) -def test_step_by_id(): - steps = [{"run": "a"}, {"id": "build", "uses": "x"}] - assert step_by_id(steps, "build") == {"id": "build", "uses": "x"} - assert step_by_id(steps, "missing") is None - - def test_combine_conditions(): assert combine_conditions() == "" assert combine_conditions(None, "") == "" diff --git a/tools/deployment-cli-tools/tests/test_skaffold_build.py b/tools/deployment-cli-tools/tests/test_skaffold_build.py new file mode 100644 index 000000000..4c0405e18 --- /dev/null +++ b/tools/deployment-cli-tools/tests/test_skaffold_build.py @@ -0,0 +1,180 @@ +"""CHSkaffoldBuild: deployment/skaffold-build.yaml, the images a CI run still has to build.""" + +import os +import subprocess +from pathlib import Path + +from conftest import CLOUDHARNESS_ROOT, RESOURCES, chain +from ruamel.yaml import YAML +from test_util import write_tree_from_yaml + +from ch_cli_tools import CHDeployConfig, ci +from ch_cli_tools.api import create_helm_chart +from ch_cli_tools.skaffold import buildx_command, tag_template + + +def _project(tmp_path, include, tag=None): + values = create_helm_chart( + [CLOUDHARNESS_ROOT, RESOURCES], + output_path=tmp_path / "deployment", + include=include, + exclude=["events"], + domain="my.local", + namespace="test", + env="dev", + local=False, + tag=tag, + registry="reg", + ) + return values._ch_project + + +def _names(project): + return [*ci.build_entities(project), *ci.test_runner_images(project)] + + +def _existing(project, *missing): + """The `image_tag_env` of a registry holding every image but the missing ones.""" + return { + ci.tag_variable(name) + ("_NEW" if name in missing else "_EXISTS"): "1" + for name in _names(project) + } + + +def _artifacts(plan): + return {artifact["image"]: artifact for artifact in plan["build"]["artifacts"]} + + +def test_only_the_missing_images_are_built(tmp_path): + project = _project(tmp_path, ["samples", "myapp"]) + plan = project.skaffold_build.generate( + _existing(project, "myapp", "cloudharness-flask"), write_on_disk=False + ) + artifacts = _artifacts(plan) + myapp, flask = "reg/testprojectname/myapp", "reg/testprojectname/cloudharness-flask" + assert set(artifacts) == {myapp, flask} + assert plan["build"]["local"] == {"push": True, "concurrency": 0} + + # a base image built in the same run is required, so skaffold builds it first... + assert artifacts[myapp]["requires"] == [{"image": flask, "alias": "CLOUDHARNESS_FLASK"}] + # ...while one already in the registry is only pulled, by its tag + assert "requires" not in artifacts[flask] + base = project.qualify_image(project.base_images["cloudharness-base"]) + assert f"--build-arg CLOUDHARNESS_BASE={base}" in artifacts[flask]["custom"]["buildCommand"] + + # every image is tagged with the tag the helm chart deploys (here, its content hash) + flask_reference = project.qualify_image(project.base_images["cloudharness-flask"]) + assert f"--build-arg CLOUDHARNESS_FLASK={flask_reference}" in artifacts[myapp]["custom"]["buildCommand"] + template = plan["build"]["tagPolicy"]["envTemplate"]["template"] + for image, entity in ((myapp, project["myapp"]), (flask, project.base_images["cloudharness-flask"])): + tag = ci.ImageReference.parse(project.qualify_image(entity)).tag + assert len(tag) == 40, "a content hash" + assert f'"{image}" "{tag}"' in template + + +def test_build_command(tmp_path): + project = _project(tmp_path, ["myapp"]) + plan = project.skaffold_build.generate(_existing(project, "myapp"), write_on_disk=False) + command = _artifacts(plan)["reg/testprojectname/myapp"]["custom"]["buildCommand"] + + assert command.startswith("docker buildx build --push --file dev.Dockerfile ") + assert '--tag "$IMAGE"' in command + assert "${CH_BRANCH_TAG:+--tag reg/testprojectname/myapp:$CH_BRANCH_TAG}" in command + assert "--build-arg NOCACHE " in command + assert "--cache-from type=registry,ref=reg/testprojectname/myapp:buildcache " in command + assert command.endswith( + " --cache-to type=registry,ref=reg/testprojectname/myapp:buildcache,mode=max ." + ) + assert ":latest" not in command, "only the test runner images are tagged latest" + + +def test_contexts_are_relative_to_the_project_root(tmp_path): + # skaffold resolves the contexts from the directory it runs in: the workflow runs it from the root + project = _project(tmp_path, ["samples", "myapp"]) + plan = project.skaffold_build.generate({}, write_on_disk=False) + artifacts = _artifacts(plan) + + def context(image): + return (project.root / artifacts[f"reg/testprojectname/{image}"]["context"]).resolve() + + assert context("myapp") == (RESOURCES / "applications" / "myapp").resolve() + assert context("sampleapp") == (CLOUDHARNESS_ROOT / "applications" / "samples").resolve() + # the project overrides cloud-harness' base image: built from the context merged across layers + assert context("cloudharness-base") == (RESOURCES / ".overrides" / "cloudharness-base").resolve() + assert artifacts["reg/testprojectname/myapp"]["context"] == "applications/myapp" + + +def test_test_runner_images_get_the_latest_tag(tmp_path): + project = _project(tmp_path, ["samples"], tag="1") + artifacts = _artifacts(project.skaffold_build.generate({}, write_on_disk=False)) + for name in ("test-api", "test-e2e"): + command = artifacts[f"reg/testprojectname/{name}"]["custom"]["buildCommand"] + assert f"--tag reg/testprojectname/{name}:latest" in command + assert '"reg/testprojectname/test-api" "1"' in tag_template({"reg/testprojectname/test-api": "1"}) + + # no app runs API/E2E tests: no test runner image + project = _project(tmp_path, ["myapp"], tag="1") + artifacts = _artifacts(project.skaffold_build.generate({}, write_on_disk=False)) + assert not [image for image in artifacts if "/test-" in image] + + +def test_nothing_to_build(tmp_path): + project = _project(tmp_path, ["samples", "myapp"], tag="1") + plan = project.skaffold_build.generate(_existing(project), write_on_disk=False) + assert plan["build"]["artifacts"] == [] + assert plan["build"]["tagPolicy"]["envTemplate"]["template"] == "{{ index (dict ) .IMAGE_NAME }}" + + +def test_generate_writes_deployment_skaffold_build(tmp_path): + write_tree_from_yaml( + tmp_path, + """ + deployment-configuration: + values-template.yaml: | + name: testproj + mainapp: myapp + applications: + myapp: + Dockerfile: | + FROM scratch + """, + ) + project = chain( + CLOUDHARNESS_ROOT, + tmp_path, + config=CHDeployConfig(env="dev", registry="reg", tag="1", output_path=str(tmp_path / "deployment")), + ) + project.skaffold_build.generate({"MYAPP_TAG_EXISTS": "1"}) + + plan = YAML(typ="safe").load((tmp_path / "deployment" / "skaffold-build.yaml").read_text()) + assert plan["apiVersion"].startswith("skaffold/") + assert plan["kind"] == "Config" + assert "reg/testproj/myapp" not in _artifacts(plan), "its tag exists" + assert "reg/testproj/cloudharness-base" in _artifacts(plan) + + +def test_build_command_shell_words(tmp_path): + # the command runs through `sh -c`: check the words docker gets + fake = tmp_path / "bin" / "docker" + fake.parent.mkdir() + fake.write_text('#!/bin/sh\nfor arg in "$@"; do echo "$arg"; done\n') + fake.chmod(0o755) + command = buildx_command("reg/x", "my dir/Dockerfile", {"A": "b c", "B": "$HOME"}, ("latest",)) + + def words(**env): + result = subprocess.run( + ["sh", "-c", command], + env={"PATH": f"{fake.parent}{os.pathsep}{os.environ['PATH']}", "IMAGE": "reg/x:h1", **env}, + capture_output=True, + text=True, + check=True, + ) + return result.stdout.splitlines() + + args = words(CH_BRANCH_TAG="feature-1") + assert args[:5] == ["buildx", "build", "--push", "--file", "my dir/Dockerfile"] + assert args[5:11] == ["--tag", "reg/x:h1", "--tag", "reg/x:latest", "--tag", "reg/x:feature-1"] + assert "A=b c" in args and "B=$HOME" in args, "build args are passed literally" + assert args[-1] == "." + assert "reg/x:feature-1" not in words(), "no branch tag outside CI" + assert Path(fake).exists() From 59206343cd10b36cf29d3e4d661f4f32cc45af5f Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 16:50:36 +0100 Subject: [PATCH 06/11] CH-125 github actions: unit tests run by skaffold test in prepare deployment/skaffold-build.yaml gets a `test` section with every app's unit test commands, run in the app image's shell, and harness-deployment writes deployment/skaffold-images.json with every image of the deployment and its tag. prepare runs `skaffold test --build-artifacts` on it right after the build (skaffold build does not test), so the unit tests run against every image, rebuilt or not, and the tests-unit jobs are gone. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cloudharness-test.yaml | 27 ++--------- .../github-template-prod.yaml | 1 - .../github-template-stage.yaml | 1 - .../github-template-test.yaml | 2 +- deployment-configuration/github-template.yaml | 36 ++++++-------- docs/build-deploy/ci-cd/README.md | 12 +++-- .../ch_cli_tools/github_actions.py | 48 ++++++------------- .../ch_cli_tools/skaffold.py | 45 ++++++++++++++++- tools/deployment-cli-tools/harness-deployment | 4 +- .../github-template-dev.yaml | 2 +- .../tests/test_github_actions.py | 38 +++++++-------- .../tests/test_skaffold_build.py | 45 +++++++++++++---- 12 files changed, 143 insertions(+), 118 deletions(-) diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index 857888dd1..b12bdd5e0 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -158,33 +158,13 @@ jobs: NOCACHE: ${{ github.run_id }} CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} run: skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false --update-check=false --interactive=false + - name: Run the unit tests + run: skaffold test --filename deployment/skaffold-build.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' }} - tests-unit-samples: - name: Unit tests samples - needs: - - prepare - steps: - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Run samples unit tests - env: - CH_TEST_IMAGE: ${{ vars.REGISTRY }}/cloud-harness/sampleapp:${{ needs.prepare.outputs.SAMPLES_TAG }} - CH_TEST_COMMANDS: | - set -e - pytest /usr/src/app/samples/test - run: |- - docker run --rm \ - "$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS" - if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} - runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} deploy: name: Deploy needs: - prepare - - tests-unit-samples environment: test env: HELM_FLAGS: --timeout 200s --create-namespace @@ -226,7 +206,7 @@ jobs: env: NAMESPACE: ${{ needs.prepare.outputs.namespace }} run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS - if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' && needs.tests-unit-samples.result == 'success' }} + if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} wait-deployment: name: Wait for the deployment @@ -464,7 +444,6 @@ jobs: needs: - prepare - deploy - - tests-unit-samples - tests-api-common - tests-api-samples - tests-api-workflows diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml index 19cb08167..2bb1f6e79 100644 --- a/deployment-configuration/github-template-prod.yaml +++ b/deployment-configuration/github-template-prod.yaml @@ -14,7 +14,6 @@ cloudharness: jobs: prepare: name: Prepare helm chart - tests-unit: null tests-api: null tests-e2e: null wait-deployment: null diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml index 014c63a1a..57e2d1b22 100644 --- a/deployment-configuration/github-template-stage.yaml +++ b/deployment-configuration/github-template-stage.yaml @@ -22,7 +22,6 @@ cloudharness: jobs: prepare: name: Prepare helm chart - tests-unit: null deploy: env: HELM_FLAGS: --wait --timeout 600s --create-namespace diff --git a/deployment-configuration/github-template-test.yaml b/deployment-configuration/github-template-test.yaml index df18e4778..d50fceaab 100644 --- a/deployment-configuration/github-template-test.yaml +++ b/deployment-configuration/github-template-test.yaml @@ -20,7 +20,7 @@ jobs: publish: null cleanup: name: Delete the test deployment - needs: [prepare, deploy, tests-unit, tests-api, tests-e2e] + needs: [prepare, deploy, tests-api, tests-e2e] if: ${{ always() && needs.deploy.result == 'success' }} env: NAMESPACE: ${{ needs.prepare.outputs.namespace }} diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index e013f2d71..632414de5 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -2,8 +2,8 @@ # 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-unit`, `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. +# `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). @@ -12,11 +12,13 @@ permissions: packages: write # Generator-only settings, never part of the workflow. cloudharness: - # Steps building and pushing the images whose tag is not in the registry yet, inserted where prepare says - # `- $BUILD_STEPS`. prepare's harness-deployment lists just those images in deployment/skaffold-build.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. null builds nothing (stage and prod deploy + # 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-build.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 # published images). build: - uses: docker/setup-buildx-action@v3 @@ -40,6 +42,8 @@ cloudharness: NOCACHE: ${{ github.run_id }} CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} run: skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false --update-check=false --interactive=false + - name: Run the unit tests + run: skaffold test --filename deployment/skaffold-build.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 @@ -68,8 +72,8 @@ concurrency: env: CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} jobs: - # prepare also builds the images ($BUILD_STEPS): a re-run asks the registry again, so after a failure it only - # builds what the failed attempt did not push. + # 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: @@ -147,16 +151,6 @@ jobs: # a re-run of prepare (e.g. after a failed build) uploads it again overwrite: true - $BUILD_STEPS - tests-unit: - name: Unit tests - needs: [prepare] - steps: - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - $TEST_STEPS # deploy targets the GitHub environment named after the CloudHarness environment: its protection # rules (required reviewers on stage/prod) approve the deployment. Every job naming an environment is # gated by those rules, so wait-deployment and the test cleanup do not: they read the cluster @@ -164,7 +158,7 @@ jobs: # them for deploy). deploy: name: Deploy - needs: [prepare, tests-unit] + needs: [prepare] environment: $ENV env: HELM_FLAGS: --timeout 200s --create-namespace @@ -240,7 +234,7 @@ jobs: # environment with required reviewers. publish: name: Publish images - needs: [prepare, deploy, wait-deployment, tests-unit, tests-api, tests-e2e] + needs: [prepare, deploy, wait-deployment, tests-api, tests-e2e] if: ${{ !cancelled() && needs.prepare.outputs.publish_tag != '' && needs.deploy.result == 'success' && !contains(needs.*.result, 'failure') }} environment: publish steps: diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index e10ecf47c..ed7f85e3b 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -34,13 +34,15 @@ and publication. Pass `-ci codefresh -ci github` to generate both. 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. A re-run after a failure asks the registry - again and only builds what is still missing. The steps live under `cloudharness.build` in the template - (`null` in stage and prod, which deploy published images). + 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). - 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-unit-[app]` entry (or - `tests-api-`, `tests-e2e-`) in your template is merged over that app's generated job. + 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 diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index 7e900fa3b..c990fe1c3 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -7,9 +7,10 @@ --write-skaffold-build`: deployment/.env becomes job outputs (every image's tag) and deployment/skaffold-build.yaml lists only the images whose tag is not in the registry yet, which the same job then builds with skaffold (`cloudharness.build` -steps), in parallel and in dependency order. Like codefresh.yaml, the workflow -is generated once and committed, so everything only known at run time stays a -`${{ ... }}` expression (vars, secrets, prepare outputs). +steps), in parallel and in dependency order, before `skaffold test` runs every +app's unit tests. Like codefresh.yaml, the workflow is generated once and +committed, so everything only known at run time stays a `${{ ... }}` expression +(vars, secrets, prepare outputs). What differs from Codefresh, and shapes the template: - GitHub only runs workflows found in .github/workflows/, so that is where the @@ -30,20 +31,21 @@ Template mechanics (`github-template.yaml` + `github-template-.yaml`, layered across cloud-harness and the project exactly like the Codefresh templates): -- `jobs.tests-unit`, `jobs.tests-api` and `jobs.tests-e2e` are prototypes, - expanded into one job per app at their position; a `null` or missing - prototype means that kind of job is not generated. Inside a prototype - `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for the app's image. +- `jobs.tests-api` and `jobs.tests-e2e` are prototypes, expanded into one job + per app at their position; a `null` or missing prototype means that kind of + job is not generated. Inside a prototype `$CH_NAME`, `$CH_IMAGE` and + `$CH_TAG` stand for the app's image. - A string item in a `steps` list is a fragment the generator fills: `$GIT_CLONES`, `$BUILD_STEPS`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$ROLLOUT_STEPS`, `$TEST_STEPS` and `$KUBE_AUTH`. The steps of `$BUILD_STEPS` and `$KUBE_AUTH` come from the template's own `cloudharness.build` and `cloudharness.kube_auth` lists, so a project - changes how images are built or how the cluster is reached in one place; - `cloudharness.build: null` builds nothing (stage, prod). The top-level + changes how images are built and unit-tested or how the cluster is reached + in one place; `cloudharness.build: null` builds and tests nothing (stage, + prod). The top-level `cloudharness` section is for the generator only and never reaches GitHub. - `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. -- A template key matching an expanded job id (`jobs.tests-unit-myapp`) is merged +- A template key matching an expanded job id (`jobs.tests-api-myapp`) is merged over the generated job, so one app can get a bigger runner or extra steps; such a key is dropped when its app is not part of the deployment being generated. @@ -73,13 +75,12 @@ BUILD_RUNNER_VARIABLE = "CH_GITHUB_BUILD_RUNNER" JOB_PREPARE = "prepare" -JOB_UNIT_TESTS = "tests-unit" JOB_API_TESTS = "tests-api" JOB_E2E_TESTS = "tests-e2e" JOB_DEPLOY = "deploy" JOB_WAIT_DEPLOYMENT = "wait-deployment" JOB_PUBLISH = "publish" -PROTOTYPE_JOBS = (JOB_UNIT_TESTS, JOB_API_TESTS, JOB_E2E_TESTS) +PROTOTYPE_JOBS = (JOB_API_TESTS, JOB_E2E_TESTS) FRAGMENT_GIT_CLONES = "$GIT_CLONES" FRAGMENT_BUILD = "$BUILD_STEPS" @@ -461,17 +462,6 @@ def _prototype(self, prototype, name, image_name): }, ) - def _unit_test_job(self, prototype, app, fragments): - job = self._prototype(prototype, app.name, app.image_name) - job["name"] = f"Unit tests {app.name}" - test_step = self._docker_run_step( - f"Run {app.name} unit tests", - f"{self.qualify(app.image_name)}:{tag_output(app.name)}", - app.test.unit.commands, - ) - job["steps"] = expand_steps(job.get("steps"), {**fragments, FRAGMENT_TEST: [test_step]}) - return job - def _test_image_reference(self, name) -> str | None: test_image = self.project.test_images.get(name) if test_image is None or not test_image.dockerfile.exists(): @@ -537,14 +527,12 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: build_steps = list(settings.get(SETTING_BUILD) or []) # the test runner images are built (hence published) only by a workflow that builds test_images = ci.test_runner_images(project) if build_steps else {} - unit_apps = [app for app in ci.buildable_apps(project) if app.test.unit.commands] api_apps = ci.api_test_apps(project) if JOB_API_TESTS in jobs else [] e2e_apps = ci.e2e_test_apps(project) if JOB_E2E_TESTS in jobs else [] - unit_ids = {app.name: job_id(f"{JOB_UNIT_TESTS}-{app.name}") for app in unit_apps} api_ids = {app.name: job_id(f"{JOB_API_TESTS}-{app.name}") for app in api_apps} e2e_ids = {app.name: job_id(f"{JOB_E2E_TESTS}-{app.name}") for app in e2e_apps} - generated_ids = {*unit_ids.values(), *api_ids.values(), *e2e_ids.values()} + generated_ids = {*api_ids.values(), *e2e_ids.values()} fragments = { # prepare merges the build contexts (.overrides/) with the git dependencies in them @@ -577,13 +565,7 @@ def expand(key, items, make): for key, job in jobs.items(): if key in overlays: continue - if key == JOB_UNIT_TESTS: - expand( - key, - unit_apps, - lambda app: (unit_ids[app.name], self._unit_test_job(job, app, fragments)), - ) - elif key == JOB_API_TESTS: + if key == JOB_API_TESTS: expand( key, api_apps, diff --git a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py index 7d9ccf6e7..cc5bf342e 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py +++ b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py @@ -77,6 +77,7 @@ BUILD_CACHE_TAG = "buildcache" BRANCH_TAG_VARIABLE = "CH_BRANCH_TAG" +IMAGES_FILE_NAME = "skaffold-images.json" # tools/clone.sh, shipped alongside this package - not part of any deployed # project, so it's located relative to this file, not project.root/ch_path. @@ -378,9 +379,15 @@ def buildx_command(image: str, dockerfile: str, build_args: dict[str, str], extr return " ".join(parts) +def unit_test_command(commands) -> str: + """A custom skaffold test running an app's unit test commands in its image, through the image's shell.""" + script = "\n".join(["set -e", *commands]) + return f'docker run --rm "$IMAGE" sh -c {shlex.quote(script)}' + + @register_file("skaffold_build", lambda root: root / "deployment" / "skaffold-build.yaml") class CHSkaffoldBuild(CHValues): - """deployment/skaffold-build.yaml: what a CI run still has to build. + """deployment/skaffold-build.yaml: what a CI run still has to build, and the unit tests. Written at pipeline run time (`harness-deployment --write-skaffold-build`), once `ci.image_tag_env` has asked the registry which tags exist: the artifacts are only @@ -396,8 +403,40 @@ class CHSkaffoldBuild(CHValues): policy. Run from the project root with `skaffold build -f deployment/skaffold-build.yaml --cache-artifacts=false`; NOCACHE and CH_BRANCH_TAG come from the environment. + + The `test` section runs the unit tests of every app that has some, rebuilt or + not: `skaffold build` does not test, `skaffold test -f deployment/skaffold-build.yaml + --build-artifacts deployment/skaffold-images.json` does, against the images + listed in skaffold-images.json - every image of the deployment with its tag. So + an image pushed by a run whose tests then failed is tested again on the next run. """ + @property + def images_path(self) -> Path: + return self.path.with_name(IMAGES_FILE_NAME) + + def images(self) -> dict: + """Every image of the deployment with the tag it is deployed with, in skaffold's build + output format (`skaffold test --build-artifacts`).""" + project = self.project + entities = {**ci.build_entities(project), **ci.test_runner_images(project)} + return { + "builds": [ + {"imageName": project.qualify(entity.image_name), "tag": project.qualify_image(entity)} + for entity in entities.values() + ] + } + + def _tests(self) -> list[dict]: + return [ + { + "image": self.project.qualify(app.image_name), + "custom": [{"command": unit_test_command(app.test.unit.commands)}], + } + for app in ci.buildable_apps(self.project) + if app.test.unit.commands + ] + def _context(self, entity) -> tuple[str, str]: """The merged build context, relative to the project root (skaffold resolves contexts from the directory it runs in, not from the file's), and the Dockerfile, relative to the context.""" @@ -456,6 +495,10 @@ def generate(self, image_env: dict[str, str], write_on_disk=True) -> dict: "artifacts": artifacts, }, } + tests = self._tests() + if tests: + plan["test"] = tests if write_on_disk: self.write(plan) + self.images_path.write_text(json.dumps(self.images(), indent=2) + "\n", encoding="utf-8") return plan diff --git a/tools/deployment-cli-tools/harness-deployment b/tools/deployment-cli-tools/harness-deployment index bffbefb1c..750112cf0 100644 --- a/tools/deployment-cli-tools/harness-deployment +++ b/tools/deployment-cli-tools/harness-deployment @@ -196,7 +196,9 @@ if __name__ == "__main__": dest="write_skaffold_build", action="store_true", help=f"Write {DEPLOYMENT_PATH}/skaffold-build.yaml, a skaffold build of the images whose tag is " - "not in the registry yet (see --force-build), pushed with their registry cache", + "not in the registry yet (see --force-build), pushed with their registry cache, with the apps' unit " + f"tests; and {DEPLOYMENT_PATH}/skaffold-images.json, every image with its tag, to run them all with " + "`skaffold test --build-artifacts`", ) parser.add_argument( "--migrate", diff --git a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml index 282839093..7200edacb 100644 --- a/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml +++ b/tools/deployment-cli-tools/tests/resources/deployment-configuration/github-template-dev.yaml @@ -3,7 +3,7 @@ test_step: dev jobs: prepare: name: Overridden - tests-unit-myapp: + tests-api-samples: runs-on: big-runner custom-job: name: Custom diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index 867c73e7a..2340673e8 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -65,7 +65,7 @@ def test_template_layering(tmp_path): assert custom["needs"] == ["deploy"] assert "needs.deploy.result == 'success'" in custom["if"] # an overlay for an expanded job id is merged over the generated job - assert wf["jobs"]["tests-unit-myapp"]["runs-on"] == "big-runner" + assert wf["jobs"]["tests-api-samples"]["runs-on"] == "big-runner" # the generator-only section is consumed, not emitted; its kube_auth steps replace # the default ones wherever a job asks for $KUBE_AUTH assert "cloudharness" not in wf @@ -99,7 +99,7 @@ def test_prepare_builds_the_missing_images_with_skaffold(tmp_path): names = [step.get("name") or step.get("uses") for step in prepare["steps"]] assert names.index("Prepare helm chart") < names.index("Install skaffold") < names.index( "Build and push the images" - ) + ) < names.index("Run the unit tests") login = next(step for step in prepare["steps"] if step.get("uses") == "docker/login-action@v3") assert login["with"]["registry"] == "${{ steps.env.outputs.registry_host }}" install = _steps(prepare, "Install skaffold")[0] @@ -145,24 +145,20 @@ def test_prepare_outputs_cover_every_image(tmp_path): assert "MYAPP_INST1_TAG" in outputs -def test_unit_test_jobs(tmp_path): +def test_unit_tests_run_in_prepare_with_skaffold(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] - unit_jobs = [name for name in jobs if name.startswith("tests-unit-")] - assert sorted(unit_jobs) == ["tests-unit-myapp", "tests-unit-samples"] - job = jobs["tests-unit-myapp"] - assert job["needs"] == ["prepare"], "prepare builds the images" - assert "needs.prepare.result == 'success'" in job["if"] - step = _steps(job, "Run myapp unit tests")[0] - assert step["env"]["CH_TEST_IMAGE"] == ( - "${{ vars.REGISTRY }}/testprojectname/myapp:${{ needs.prepare.outputs.MYAPP_TAG }}" + # skaffold runs every app's unit tests (the `test` section of deployment/skaffold-build.yaml) + # against every image of the deployment, rebuilt or not: no job of their own + assert not [name for name in jobs if name.startswith("tests-unit")] + step = _steps(jobs["prepare"], "Run the unit tests")[0] + assert step["run"].startswith( + "skaffold test --filename deployment/skaffold-build.yaml " + "--build-artifacts deployment/skaffold-images.json" ) - assert step["env"]["CH_TEST_COMMANDS"].startswith("set -e\ntox\n") - assert step["run"].startswith("docker run --rm") - assert '"$CH_TEST_IMAGE" sh -c "$CH_TEST_COMMANDS"' in step["run"] - # deploy waits for the unit tests, as the Codefresh unittest stage precedes deploy - assert "tests-unit-myapp" in jobs["deploy"]["needs"] + # the deployment waits for them, as the Codefresh unittest stage precedes deploy + assert jobs["deploy"]["needs"] == ["prepare"] def test_api_and_e2e_test_jobs(tmp_path): @@ -286,7 +282,7 @@ def test_multienv_test_overlay(tmp_path): assert "-e dev-test " in _step(jobs["prepare"], "images")["run"] cleanup = jobs["cleanup"] assert cleanup["if"] == "${{ always() && needs.deploy.result == 'success' }}" - assert "tests-unit-myapp" in cleanup["needs"] and "tests-e2e-samples" in cleanup["needs"] + assert "tests-api-samples" in cleanup["needs"] and "tests-e2e-samples" in cleanup["needs"] def test_prod_deploys_only(tmp_path): @@ -313,7 +309,8 @@ def test_stage_keeps_tests_and_tags_the_repository(tmp_path): assert not _steps(jobs["prepare"], "Build and push"), "stage deploys published images" assert not _steps(jobs["publish"], "Publish test-"), "the test images are not built here" - assert "tests-api-samples" in jobs and "tests-unit-samples" not in jobs + assert "tests-api-samples" in jobs + assert not _steps(jobs["prepare"], "Run the unit tests"), "stage runs no unit tests" assert jobs["tests-api-samples"]["needs"] == ["prepare", "wait-deployment"] assert jobs["git-tag"]["needs"] == ["prepare", "publish"] assert jobs["git-tag"]["permissions"] == {"contents": "write"} @@ -326,14 +323,15 @@ def test_stage_keeps_tests_and_tags_the_repository(tmp_path): def test_runner_configuration(tmp_path): - wf, _ = _generate(tmp_path, ["myapp"]) + wf, _ = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] # the runner is a repository variable read at run time; the generation-time runner is the fallback default = "${{ vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER build = "${{ vars.CH_GITHUB_BUILD_RUNNER || vars.CH_GITHUB_RUNNER || '%s' }}" % DEFAULT_RUNNER assert jobs["prepare"]["runs-on"] == build, "prepare builds the images" assert jobs["deploy"]["runs-on"] == default - assert jobs["tests-unit-myapp"]["runs-on"] == "big-runner", "a template runs-on is kept" + assert jobs["tests-e2e-samples"]["runs-on"] == default + assert jobs["tests-api-samples"]["runs-on"] == "big-runner", "a template runs-on is kept" project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig( env="dev", includes=["myapp"], excludes=["events"], registry="reg", tag="1", diff --git a/tools/deployment-cli-tools/tests/test_skaffold_build.py b/tools/deployment-cli-tools/tests/test_skaffold_build.py index 4c0405e18..eb678a8b9 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold_build.py +++ b/tools/deployment-cli-tools/tests/test_skaffold_build.py @@ -1,8 +1,8 @@ """CHSkaffoldBuild: deployment/skaffold-build.yaml, the images a CI run still has to build.""" +import json import os import subprocess -from pathlib import Path from conftest import CLOUDHARNESS_ROOT, RESOURCES, chain from ruamel.yaml import YAML @@ -10,7 +10,7 @@ from ch_cli_tools import CHDeployConfig, ci from ch_cli_tools.api import create_helm_chart -from ch_cli_tools.skaffold import buildx_command, tag_template +from ch_cli_tools.skaffold import buildx_command, tag_template, unit_test_command def _project(tmp_path, include, tag=None): @@ -125,6 +125,27 @@ def test_nothing_to_build(tmp_path): assert plan["build"]["tagPolicy"]["envTemplate"]["template"] == "{{ index (dict ) .IMAGE_NAME }}" +def test_unit_tests_cover_every_app(tmp_path): + project = _project(tmp_path, ["samples", "myapp"]) + # nothing to build: the unit tests still run, against the images in the registry + plan = project.skaffold_build.generate(_existing(project), write_on_disk=False) + assert plan["build"]["artifacts"] == [] + tests = {test["image"]: test["custom"] for test in plan["test"]} + assert set(tests) == {"reg/testprojectname/myapp", "reg/testprojectname/sampleapp"} + assert tests["reg/testprojectname/myapp"] == [ + {"command": 'docker run --rm "$IMAGE" sh -c \'set -e\ntox\necho "hello"\''} + ] + + # `skaffold test --build-artifacts` takes every image's tag from skaffold-images.json + images = {build["imageName"]: build["tag"] for build in project.skaffold_build.images()["builds"]} + assert images["reg/testprojectname/myapp"] == project.qualify_image(project["myapp"]) + assert set(tests) <= set(images) + assert set(images) == { + project.qualify(entity.image_name) + for entity in {**ci.build_entities(project), **ci.test_runner_images(project)}.values() + } + + def test_generate_writes_deployment_skaffold_build(tmp_path): write_tree_from_yaml( tmp_path, @@ -151,17 +172,18 @@ def test_generate_writes_deployment_skaffold_build(tmp_path): assert plan["kind"] == "Config" assert "reg/testproj/myapp" not in _artifacts(plan), "its tag exists" assert "reg/testproj/cloudharness-base" in _artifacts(plan) + images = json.loads((tmp_path / "deployment" / "skaffold-images.json").read_text()) + assert {"imageName": "reg/testproj/myapp", "tag": "reg/testproj/myapp:1"} in images["builds"] -def test_build_command_shell_words(tmp_path): - # the command runs through `sh -c`: check the words docker gets +def test_shell_words(tmp_path): + # the build and test commands run through `sh -c`: check the words docker gets fake = tmp_path / "bin" / "docker" fake.parent.mkdir() fake.write_text('#!/bin/sh\nfor arg in "$@"; do echo "$arg"; done\n') fake.chmod(0o755) - command = buildx_command("reg/x", "my dir/Dockerfile", {"A": "b c", "B": "$HOME"}, ("latest",)) - def words(**env): + def words(command, **env): result = subprocess.run( ["sh", "-c", command], env={"PATH": f"{fake.parent}{os.pathsep}{os.environ['PATH']}", "IMAGE": "reg/x:h1", **env}, @@ -171,10 +193,15 @@ def words(**env): ) return result.stdout.splitlines() - args = words(CH_BRANCH_TAG="feature-1") + build = buildx_command("reg/x", "my dir/Dockerfile", {"A": "b c", "B": "$HOME"}, ("latest",)) + args = words(build, CH_BRANCH_TAG="feature-1") assert args[:5] == ["buildx", "build", "--push", "--file", "my dir/Dockerfile"] assert args[5:11] == ["--tag", "reg/x:h1", "--tag", "reg/x:latest", "--tag", "reg/x:feature-1"] assert "A=b c" in args and "B=$HOME" in args, "build args are passed literally" assert args[-1] == "." - assert "reg/x:feature-1" not in words(), "no branch tag outside CI" - assert Path(fake).exists() + assert "reg/x:feature-1" not in words(build), "no branch tag outside CI" + + # the unit tests run in the image's own shell, one container for all the commands + args = words(unit_test_command(["tox", 'echo "a b" $HOME'])) + assert args[:5] == ["run", "--rm", "reg/x:h1", "sh", "-c"] + assert "\n".join(args[5:]) == 'set -e\ntox\necho "a b" $HOME' From 48a802ff724bd9fb3c7b9e452914e9958b5c7737 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 17:25:25 +0100 Subject: [PATCH 07/11] CH-125 github actions: deploy with skaffold deploy, no wait-deployment job The pipeline's skaffold file becomes deployment/skaffold-ci.yaml (--write-skaffold-ci, schema v4beta14) and gets a deploy section: the helm chart harness-deployment wrote, release and namespace named after the deployment namespace, secret values passed with --set-file from files under ~/.cloudharness/secrets, and a status check tolerating restarts for up to 15 minutes. The deploy job runs skaffold deploy with a constant skaffold.dev/run-id label: skaffold puts the run id in every pod template, so a new one per run would restart every pod. The certificate settle pause moves to the start of the API/E2E test jobs. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cloudharness-test.yaml | 104 +++++++----------- .gitignore | 3 +- .../github-template-prod.yaml | 4 - .../github-template-stage.yaml | 3 - deployment-configuration/github-template.yaml | 70 ++++++------ docs/build-deploy/ci-cd/README.md | 20 ++-- tools/deployment-cli-tools/ch_cli_tools/ci.py | 14 +++ .../ch_cli_tools/github_actions.py | 57 +++++----- .../ch_cli_tools/skaffold.py | 58 ++++++++-- tools/deployment-cli-tools/harness-deployment | 21 ++-- .../tests/test_github_actions.py | 78 +++++++------ ..._skaffold_build.py => test_skaffold_ci.py} | 44 ++++++-- 12 files changed, 259 insertions(+), 217 deletions(-) rename tools/deployment-cli-tools/tests/{test_skaffold_build.py => test_skaffold_ci.py} (81%) diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index b12bdd5e0..a9037845c 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -125,7 +125,7 @@ jobs: 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-build --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS -i samples + 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" @@ -157,17 +157,15 @@ jobs: env: NOCACHE: ${{ github.run_id }} CH_BRANCH_TAG: ${{ steps.env.outputs.branch_tag }} - run: skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false --update-check=false --interactive=false + 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-build.yaml --build-artifacts deployment/skaffold-images.json --update-check=false --interactive=false + 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 - env: - HELM_FLAGS: --timeout 200s --create-namespace steps: - uses: actions/download-artifact@v4 with: @@ -189,72 +187,38 @@ jobs: 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: Collect secret values + - name: Write the secret values env: ASECRET: ${{ secrets.ASECRET }} run: | set -e - secrets_dir="$RUNNER_TEMP/ch-secrets" + secrets_dir="$HOME/.cloudharness/secrets" mkdir -p "$secrets_dir" - args="" - printf '%s' "$ASECRET" > "$secrets_dir/0" - args="$args --set-file apps.samples.harness.secrets.asecret=$secrets_dir/0" - printf '%s' "$ASECRET" > "$secrets_dir/1" - args="$args --set-file apps.samples-instance1.harness.secrets.asecret=$secrets_dir/1" - echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV" - - name: Install chart - env: - NAMESPACE: ${{ needs.prepare.outputs.namespace }} - run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS - if: ${{ !cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success' }} - runs-on: ${{ vars.CH_GITHUB_RUNNER || 'ubuntu-latest' }} - wait-deployment: - name: Wait for the deployment - 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') }} - timeout-minutes: 15 - env: - NAMESPACE: ${{ needs.prepare.outputs.namespace }} - steps: - - uses: azure/setup-kubectl@v4 - - name: Configure kubectl + chmod 700 "$secrets_dir" + printf '%s' "$ASECRET" > "$secrets_dir/ASECRET" + - name: Install skaffold 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: Select the namespace - run: kubectl config set-context --current --namespace="$NAMESPACE" - - name: Wait for the rollouts + SKAFFOLD_VERSION: v2.25.0 + SKAFFOLD_SHA256: 42b9e2e3246c19b78fcc53dd60cc7ded1da8704293886b909a2a02b9bef34d20 run: | - kubectl rollout status deployment/accounts - kubectl rollout status deployment/argo-gk - kubectl rollout status deployment/common - kubectl rollout status statefulset/samples - kubectl rollout status deployment/www-gk - kubectl rollout status deployment/samples-instance1 - kubectl rollout status deployment/samples1-gk - kubectl rollout status deployment/volumemanager - kubectl rollout status deployment/workflows - sleep 60 + 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 - - wait-deployment - if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + - 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -290,9 +254,11 @@ jobs: name: API tests samples needs: - prepare - - wait-deployment - if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + - 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -333,9 +299,11 @@ jobs: name: API tests workflows needs: - prepare - - wait-deployment - if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + - 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -371,9 +339,11 @@ jobs: name: E2E tests jupyterhub needs: - prepare - - wait-deployment - if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + - 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -405,9 +375,11 @@ jobs: name: E2E tests samples needs: - prepare - - wait-deployment - if: ${{ (needs.prepare.outputs.skip_tests != 'true') && (!cancelled() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && needs.prepare.result == 'success') }} + - 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 - name: Clone cloud-harness uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index 704b6b065..b8629105b 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,8 @@ node_modules *.DS_Store deployment/helm deployment/compose -deployment/skaffold-build.yaml +deployment/skaffold-ci.yaml +deployment/skaffold-images.json /docker-compose.yaml *.egg-info *.idea diff --git a/deployment-configuration/github-template-prod.yaml b/deployment-configuration/github-template-prod.yaml index 2bb1f6e79..9e3670f15 100644 --- a/deployment-configuration/github-template-prod.yaml +++ b/deployment-configuration/github-template-prod.yaml @@ -16,8 +16,4 @@ jobs: name: Prepare helm chart tests-api: null tests-e2e: null - wait-deployment: null publish: null - deploy: - env: - HELM_FLAGS: --wait --timeout 600s --create-namespace diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml index 57e2d1b22..cc01b08cf 100644 --- a/deployment-configuration/github-template-stage.yaml +++ b/deployment-configuration/github-template-stage.yaml @@ -22,9 +22,6 @@ cloudharness: jobs: prepare: name: Prepare helm chart - deploy: - env: - HELM_FLAGS: --wait --timeout 600s --create-namespace # Only once the images were actually published: publish is skipped when the deployment or a test fails. git-tag: name: Tag the repository diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index 632414de5..4537e7ccb 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -12,9 +12,21 @@ permissions: 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-build.yaml, each one a `docker buildx build --push` with its registry cache + # 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 @@ -27,23 +39,14 @@ cloudharness: 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" + - *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-build.yaml --cache-artifacts=false --update-check=false --interactive=false + 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-build.yaml --build-artifacts deployment/skaffold-images.json --update-check=false --interactive=false + 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 @@ -137,7 +140,7 @@ jobs: 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-build --cache-url "$IMAGE_CACHE_URL" --force-build "$FORCE_BUILD" -N $HELM_META_ARGS $PARAMS + 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" -N $HELM_META_ARGS $PARAMS cat deployment/.env >> "$GITHUB_OUTPUT" - name: View helm chart run: helm template ./deployment/helm --debug -n "$NAMESPACE" @@ -153,15 +156,15 @@ jobs: - $BUILD_STEPS # deploy targets the GitHub environment named after the CloudHarness environment: its protection # rules (required reviewers on stage/prod) approve the deployment. Every job naming an environment is - # gated by those rules, so wait-deployment and the test cleanup do not: they read the cluster - # credentials from repository/organization secrets (an environment secret of the same name overrides - # them for deploy). + # gated by those rules, so the test cleanup does not: it reads the cluster credentials from + # repository/organization secrets (an environment secret of the same name overrides them for deploy). + # 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 - env: - HELM_FLAGS: --timeout 200s --create-namespace steps: - uses: actions/download-artifact@v4 with: @@ -170,27 +173,16 @@ jobs: - uses: azure/setup-helm@v4 - $KUBE_AUTH - $HELM_SECRETS_STEPS - - name: Install chart - env: - NAMESPACE: ${{ needs.prepare.outputs.namespace }} - run: helm upgrade --install "$NAMESPACE" deployment/helm -n "$NAMESPACE" $HELM_FLAGS -f deployment/helm/values.yaml $HELM_SET_ARGS - wait-deployment: - name: Wait for the deployment - needs: [prepare, deploy] - if: ${{ needs.prepare.outputs.skip_tests != 'true' }} - timeout-minutes: 15 - env: - NAMESPACE: ${{ needs.prepare.outputs.namespace }} - steps: - - $KUBE_AUTH - - name: Select the namespace - run: kubectl config set-context --current --namespace="$NAMESPACE" - - $ROLLOUT_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, wait-deployment] + 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -210,12 +202,14 @@ jobs: - $TEST_STEPS tests-e2e: name: End to end tests - needs: [prepare, wait-deployment] + 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 - name: Clone cloud-harness uses: actions/checkout@v4 @@ -234,7 +228,7 @@ jobs: # environment with required reviewers. publish: name: Publish images - needs: [prepare, deploy, wait-deployment, tests-api, tests-e2e] + needs: [prepare, deploy, tests-api, tests-e2e] if: ${{ !cancelled() && needs.prepare.outputs.publish_tag != '' && needs.deploy.result == 'success' && !contains(needs.*.result, 'failure') }} environment: publish steps: diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index ed7f85e3b..61d53a4b2 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -27,10 +27,11 @@ When defining an applications values you can provide details on dockerfile confi `harness-deployment -ci github -e [ENV]` generates `.github/workflows/cloudharness-[ENV].yaml`, a workflow with the same stages as the Codefresh pipeline: image build, unit tests, helm deployment, rollout wait, API/E2E tests -and publication. Pass `-ci codefresh -ci github` to generate both. +and publication. Pass `-ci codefresh -ci github` to generate both. 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-build`, which asks the - registry for every image's content-hash tag and writes `deployment/skaffold-build.yaml` with only the images +- 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. @@ -39,6 +40,11 @@ and publication. Pass `-ci codefresh -ci github` to generate both. (`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 @@ -53,13 +59,13 @@ and publication. Pass `-ci codefresh -ci github` to generate both. as the Codefresh variables) the workflow expects. Approvals are GitHub environment protection rules on the `publish` and `prod`/`stage` environments. `workflow_dispatch` inputs replace the `DEPLOYMENT_PUBLISH_TAG`, `DEPLOYMENT_TAG`, `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. -- Cluster credentials: the `deploy`, `wait-deployment` and test `cleanup` jobs run the steps listed under +- 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. Only `deploy` targets the GitHub environment named after the CloudHarness environment (so required reviewers on - `stage`/`prod` approve the deployment once): `wait-deployment` and `cleanup` read repository or organization - secrets, which an environment secret of the same name overrides for `deploy`. For GKE with workload identity + `stage`/`prod` approve the deployment once): `cleanup` reads repository or organization secrets, which an + environment secret of the same name overrides for `deploy`. 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): @@ -77,7 +83,7 @@ and publication. Pass `-ci codefresh -ci github` to generate both. jobs: deploy: permissions: {contents: read, packages: write, id-token: write} - wait-deployment: + cleanup: permissions: {contents: read, packages: write, id-token: write} ``` - Test failures: unit tests gate the deployment, as in Codefresh. The API/E2E tests run after the deployment diff --git a/tools/deployment-cli-tools/ch_cli_tools/ci.py b/tools/deployment-cli-tools/ch_cli_tools/ci.py index c1b856d2f..b1186fe18 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/ci.py +++ b/tools/deployment-cli-tools/ch_cli_tools/ci.py @@ -9,6 +9,7 @@ """ import logging +import re from dataclasses import dataclass from ch_cli_tools.configuration.secrets import ( @@ -305,6 +306,9 @@ def rollout_wait_commands(project) -> list[str]: return commands +SECRETS_HOME_DIR = ".cloudharness/secrets" # under the home directory of the job deploying the chart + + @dataclass(frozen=True) class HelmSecretValue: """A helm value the pipeline must supply from one of its own secret variables.""" @@ -312,6 +316,16 @@ class HelmSecretValue: path: tuple[str, ...] # helm value path, e.g. ("apps", "myapp", "harness", "secrets", "token") variable: str # pipeline variable holding the value, e.g. TOKEN + @property + def key(self) -> str: + """The `--set-file` key: the value path, dots inside a segment escaped.""" + return ".".join(segment.replace(".", "\\.") for segment in self.path) + + @property + def file_name(self) -> str: + """The file under ~/SECRETS_HOME_DIR the pipeline writes the value to, for `--set-file`.""" + return re.sub(r"[^A-Za-z0-9_]", "_", self.variable) + def deployment_secret_values(project) -> list[HelmSecretValue]: """CloudHarness-managed secrets, auto-generated DB connect strings and the registry diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index c990fe1c3..5e59bae46 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -4,13 +4,14 @@ the deployment needs, run the unit tests, deploy the helm chart, wait for the rollout, run the API/E2E tests, publish (re-tag) the images - with the same content-hash skip. The `prepare` job runs `harness-deployment --write-env ---write-skaffold-build`: deployment/.env becomes job outputs (every image's tag) -and deployment/skaffold-build.yaml lists only the images whose tag is not in the +--write-skaffold-ci`: deployment/.env becomes job outputs (every image's tag) +and deployment/skaffold-ci.yaml lists only the images whose tag is not in the registry yet, which the same job then builds with skaffold (`cloudharness.build` steps), in parallel and in dependency order, before `skaffold test` runs every -app's unit tests. Like codefresh.yaml, the workflow is generated once and -committed, so everything only known at run time stays a `${{ ... }}` expression -(vars, secrets, prepare outputs). +app's unit tests. The `deploy` job runs `skaffold deploy` on the same file, which +installs the helm chart and waits for its rollout. Like codefresh.yaml, the +workflow is generated once and committed, so everything only known at run time +stays a `${{ ... }}` expression (vars, secrets, prepare outputs). What differs from Codefresh, and shapes the template: - GitHub only runs workflows found in .github/workflows/, so that is where the @@ -37,13 +38,13 @@ `$CH_TAG` stand for the app's image. - A string item in a `steps` list is a fragment the generator fills: `$GIT_CLONES`, `$BUILD_STEPS`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, - `$ROLLOUT_STEPS`, `$TEST_STEPS` and `$KUBE_AUTH`. The steps of - `$BUILD_STEPS` and `$KUBE_AUTH` come from the template's own - `cloudharness.build` and `cloudharness.kube_auth` lists, so a project - changes how images are built and unit-tested or how the cluster is reached - in one place; `cloudharness.build: null` builds and tests nothing (stage, - prod). The top-level - `cloudharness` section is for the generator only and never reaches GitHub. + `$TEST_STEPS` and `$KUBE_AUTH`. The steps of `$BUILD_STEPS` and + `$KUBE_AUTH` come from the template's own `cloudharness.build` and + `cloudharness.kube_auth` lists, so a project changes how images are built + and unit-tested or how the cluster is reached in one place; + `cloudharness.build: null` builds and tests nothing (stage, prod). The + top-level `cloudharness` section is for the generator only and never + reaches GitHub. - `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. - A template key matching an expanded job id (`jobs.tests-api-myapp`) is merged over the generated job, so one app can get a bigger runner or extra steps; @@ -78,7 +79,6 @@ JOB_API_TESTS = "tests-api" JOB_E2E_TESTS = "tests-e2e" JOB_DEPLOY = "deploy" -JOB_WAIT_DEPLOYMENT = "wait-deployment" JOB_PUBLISH = "publish" PROTOTYPE_JOBS = (JOB_API_TESTS, JOB_E2E_TESTS) @@ -86,7 +86,6 @@ FRAGMENT_BUILD = "$BUILD_STEPS" FRAGMENT_PUBLISH_STEPS = "$PUBLISH_STEPS" FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" -FRAGMENT_ROLLOUT = "$ROLLOUT_STEPS" FRAGMENT_TEST = "$TEST_STEPS" FRAGMENT_KUBE_AUTH = "$KUBE_AUTH" @@ -408,33 +407,28 @@ def _publish_steps(self, entities: dict) -> list[dict]: return steps def _helm_secrets_steps(self) -> list[dict]: - """One step writing every pipeline-supplied secret to a file and exporting the - matching `--set-file` arguments as HELM_SET_ARGS: no quoting or escaping of the - values is needed, and no secret ever appears on a command line.""" + """One step writing every pipeline-supplied secret to the file skaffold's deploy passes to + helm with `--set-file` (deployment/skaffold-ci.yaml): no quoting or escaping of the values + is needed, and no secret ever appears on a command line.""" values = ci.deployment_secret_values(self.project) if not values: return [] env: dict[str, str] = {} lines = [ "set -e", - 'secrets_dir="$RUNNER_TEMP/ch-secrets"', + f'secrets_dir="$HOME/{ci.SECRETS_HOME_DIR}"', 'mkdir -p "$secrets_dir"', - 'args=""', + 'chmod 700 "$secrets_dir"', ] - for index, value in enumerate(values): + written = set() + for value in values: + if value.file_name in written: # one secret can feed several helm values + continue + written.add(value.file_name) secret = github_secret_name(value.variable) env[secret] = "${{ secrets.%s }}" % secret - key = ".".join(segment.replace(".", "\\.") for segment in value.path) - lines.append(f"printf '%s' \"${secret}\" > \"$secrets_dir/{index}\"") - lines.append(f'args="$args --set-file {key}=$secrets_dir/{index}"') - lines.append('echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV"') - return [{"name": "Collect secret values", "env": env, "run": "\n".join(lines) + "\n"}] - - def _rollout_steps(self) -> list[dict]: - commands = ci.rollout_wait_commands(self.project) - if not commands: - return [] - return [{"name": "Wait for the rollouts", "run": "\n".join(commands) + "\n"}] + lines.append(f"printf '%s' \"${secret}\" > \"$secrets_dir/{value.file_name}\"") + return [{"name": "Write the secret values", "env": env, "run": "\n".join(lines) + "\n"}] def _docker_run_step(self, name, image, commands, env=None, volumes=(), workdir=None): env = dict(env or {}) @@ -540,7 +534,6 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: FRAGMENT_BUILD: build_steps, FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_images}), FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), - FRAGMENT_ROLLOUT: self._rollout_steps(), FRAGMENT_TEST: [], FRAGMENT_KUBE_AUTH: list(settings.get(SETTING_KUBE_AUTH) or []), } diff --git a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py index cc5bf342e..02cc3c543 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py +++ b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py @@ -78,6 +78,9 @@ BUILD_CACHE_TAG = "buildcache" BRANCH_TAG_VARIABLE = "CH_BRANCH_TAG" IMAGES_FILE_NAME = "skaffold-images.json" +# deploy.tolerateFailuresUntilDeadline needs a v4 schema: the newest of the skaffold the CI installs (v2.25.0) +CI_API_VERSION = "skaffold/v4beta14" +STATUS_CHECK_DEADLINE_SECONDS = 900 # tools/clone.sh, shipped alongside this package - not part of any deployed # project, so it's located relative to this file, not project.root/ch_path. @@ -385,11 +388,11 @@ def unit_test_command(commands) -> str: return f'docker run --rm "$IMAGE" sh -c {shlex.quote(script)}' -@register_file("skaffold_build", lambda root: root / "deployment" / "skaffold-build.yaml") -class CHSkaffoldBuild(CHValues): - """deployment/skaffold-build.yaml: what a CI run still has to build, and the unit tests. +@register_file("skaffold_ci", lambda root: root / "deployment" / "skaffold-ci.yaml") +class CHSkaffoldCI(CHValues): + """deployment/skaffold-ci.yaml: what a CI run still has to build, the unit tests and the deployment. - Written at pipeline run time (`harness-deployment --write-skaffold-build`), once + Written at pipeline run time (`harness-deployment --write-skaffold-ci`), once `ci.image_tag_env` has asked the registry which tags exist: the artifacts are only the images whose tag is missing or forced. Since an image's content-hash tag folds in the tags of the images it is built on, a changed base image is rebuilt along @@ -401,14 +404,24 @@ class CHSkaffoldBuild(CHValues): image's registry cache (`:buildcache`, mode=max): skaffold orders the builds, runs them in parallel and tags each image from the table in its tag policy. Run from the project root with `skaffold build -f - deployment/skaffold-build.yaml --cache-artifacts=false`; NOCACHE and + deployment/skaffold-ci.yaml --cache-artifacts=false`; NOCACHE and CH_BRANCH_TAG come from the environment. The `test` section runs the unit tests of every app that has some, rebuilt or - not: `skaffold build` does not test, `skaffold test -f deployment/skaffold-build.yaml + not: `skaffold build` does not test, `skaffold test -f deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json` does, against the images listed in skaffold-images.json - every image of the deployment with its tag. So an image pushed by a run whose tests then failed is tested again on the next run. + + The `deploy` section installs or upgrades the helm chart harness-deployment wrote + (release and namespace named after the deployment namespace), then waits until + its deployments and statefulsets are rolled out: + `skaffold deploy -f deployment/skaffold-ci.yaml --build-artifacts + deployment/skaffold-images.json --label skaffold.dev/run-id=`. The + constant label matters: skaffold labels every pod template with its run id, a new + one per run unless overridden, which would restart every pod on every deployment. + Secret values come from files the pipeline writes under ~/.cloudharness/secrets + (`ci.HelmSecretValue.file_name`), passed with `--set-file`. """ @property @@ -437,6 +450,31 @@ def _tests(self) -> list[dict]: if app.test.unit.commands ] + def _deploy(self) -> dict | None: + project = self.project + namespace = project.config.namespace + if not namespace: + return None + release = { + "name": namespace, + "namespace": namespace, + "chartPath": os.path.relpath(self.path.parent / "helm", project.root), + "createNamespace": True, + # the chart is deployed as harness-deployment wrote it: no `helm dependency build` + "skipBuildDependencies": True, + } + secrets = ci.deployment_secret_values(project) + if secrets: + release["setFiles"] = { + value.key: f"~/{ci.SECRETS_HOME_DIR}/{value.file_name}" for value in secrets + } + return { + "statusCheckDeadlineSeconds": STATUS_CHECK_DEADLINE_SECONDS, + # an app restarting while what it depends on starts up only fails at the deadline + "tolerateFailuresUntilDeadline": True, + "helm": {"releases": [release]}, + } + def _context(self, entity) -> tuple[str, str]: """The merged build context, relative to the project root (skaffold resolves contexts from the directory it runs in, not from the file's), and the Dockerfile, relative to the context.""" @@ -484,10 +522,9 @@ def generate(self, image_env: dict[str, str], write_on_disk=True) -> dict: extra_tags = ("latest",) if name in test_images else () artifacts.append(self._artifact(entity, image, building, extra_tags)) - template = project.skaffold_template.all_values() plan = { - "apiVersion": template["apiVersion"], - "kind": template.get("kind", "Config"), + "apiVersion": CI_API_VERSION, + "kind": "Config", "build": { "tagPolicy": {"envTemplate": {"template": tag_template(tags)}}, # the custom builds push; skaffold then reads each image's digest from the registry @@ -498,6 +535,9 @@ def generate(self, image_env: dict[str, str], write_on_disk=True) -> dict: tests = self._tests() if tests: plan["test"] = tests + deploy = self._deploy() + if deploy: + plan["deploy"] = deploy if write_on_disk: self.write(plan) self.images_path.write_text(json.dumps(self.images(), indent=2) + "\n", encoding="utf-8") diff --git a/tools/deployment-cli-tools/harness-deployment b/tools/deployment-cli-tools/harness-deployment index 750112cf0..9c0c41f4b 100644 --- a/tools/deployment-cli-tools/harness-deployment +++ b/tools/deployment-cli-tools/harness-deployment @@ -179,7 +179,7 @@ if __name__ == "__main__": dest="force_build", action="store", default=None, - help="With --write-env/--write-skaffold-build, report these images (comma-separated, or `all`) as " + help="With --write-env/--write-skaffold-ci, report these images (comma-separated, or `all`) as " "not built yet so the pipeline rebuilds them even if their tag already exists in the registry", ) parser.add_argument( @@ -192,13 +192,14 @@ if __name__ == "__main__": help=f"Write build env to .env file in {DEPLOYMENT_PATH}", ) parser.add_argument( - "--write-skaffold-build", - dest="write_skaffold_build", + "--write-skaffold-ci", + dest="write_skaffold_ci", action="store_true", - help=f"Write {DEPLOYMENT_PATH}/skaffold-build.yaml, a skaffold build of the images whose tag is " - "not in the registry yet (see --force-build), pushed with their registry cache, with the apps' unit " - f"tests; and {DEPLOYMENT_PATH}/skaffold-images.json, every image with its tag, to run them all with " - "`skaffold test --build-artifacts`", + help=f"Write {DEPLOYMENT_PATH}/skaffold-ci.yaml, the skaffold configuration of a CI run: a build of the " + "images whose tag is not in the registry yet (see --force-build), pushed with their registry cache, the " + "apps' unit tests and the deployment of the helm chart; and " + f"{DEPLOYMENT_PATH}/skaffold-images.json, every image with its tag, for `skaffold test|deploy " + "--build-artifacts`", ) parser.add_argument( "--migrate", @@ -301,15 +302,15 @@ if __name__ == "__main__": if "github" in ci_providers: project.github_actions.generate() - if args.write_env or args.write_skaffold_build: + if args.write_env or args.write_skaffold_ci: # one registry lookup per image, shared by both files image_env = image_tag_env( project, args.image_cache_url, force_build=parse_force_build(args.force_build) ) if args.write_env: write_env_file(root_paths[-1] / DEPLOYMENT_PATH / ".env", image_env) - if args.write_skaffold_build: - project.skaffold_build.generate(image_env) + if args.write_skaffold_ci: + project.skaffold_ci.generate(image_env) project.skaffold.generate() project.tilt.generate() diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index 2340673e8..1fea79327 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -69,13 +69,10 @@ def test_template_layering(tmp_path): # the generator-only section is consumed, not emitted; its kube_auth steps replace # the default ones wherever a job asks for $KUBE_AUTH assert "cloudharness" not in wf - for name in ("deploy", "wait-deployment"): - steps = wf["jobs"][name]["steps"] - assert [s for s in steps if s.get("name") == "Custom cluster access"], name - assert not [s for s in steps if s.get("name") == "Configure kubectl"], name + steps = wf["jobs"]["deploy"]["steps"] + assert [s for s in steps if s.get("name") == "Custom cluster access"] + assert not [s for s in steps if s.get("name") == "Configure kubectl"] assert wf["jobs"]["deploy"]["environment"] == "dev" - # only deploy is gated by the environment's protection rules, not every job using the cluster - assert "environment" not in wf["jobs"]["wait-deployment"] # OIDC tokens are not minted for every job assert "id-token" not in wf["permissions"] @@ -87,10 +84,10 @@ def test_prepare_builds_the_missing_images_with_skaffold(tmp_path): # one job builds every image: harness-deployment lists the missing ones, skaffold builds them assert not [name for name in jobs if name.startswith("build")] - assert "--write-env --write-skaffold-build" in _step(prepare, "images")["run"] + assert "--write-env --write-skaffold-ci" in _step(prepare, "images")["run"] build = _steps(prepare, "Build and push the images")[0] assert build["run"].startswith( - "skaffold build --filename deployment/skaffold-build.yaml --cache-artifacts=false" + "skaffold build --filename deployment/skaffold-ci.yaml --cache-artifacts=false" ) assert build["env"] == { "NOCACHE": "${{ github.run_id }}", @@ -149,12 +146,12 @@ def test_unit_tests_run_in_prepare_with_skaffold(tmp_path): wf, _ = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] - # skaffold runs every app's unit tests (the `test` section of deployment/skaffold-build.yaml) + # skaffold runs every app's unit tests (the `test` section of deployment/skaffold-ci.yaml) # against every image of the deployment, rebuilt or not: no job of their own assert not [name for name in jobs if name.startswith("tests-unit")] step = _steps(jobs["prepare"], "Run the unit tests")[0] assert step["run"].startswith( - "skaffold test --filename deployment/skaffold-build.yaml " + "skaffold test --filename deployment/skaffold-ci.yaml " "--build-artifacts deployment/skaffold-images.json" ) # the deployment waits for them, as the Codefresh unittest stage precedes deploy @@ -166,10 +163,11 @@ def test_api_and_e2e_test_jobs(tmp_path): jobs = wf["jobs"] api = jobs["tests-api-samples"] - assert api["needs"] == ["prepare", "wait-deployment"] + assert api["needs"] == ["prepare", "deploy"] + assert api["steps"][0] == {"name": "Give the certificates time to settle", "run": "sleep 60"} assert "needs.prepare.outputs.skip_tests != 'true'" in api["if"] - # wait-deployment may be skipped (it has its own `if`), but must not have failed - assert "needs.wait-deployment.result ==" not in api["if"] + # skaffold deploy waits for the rollout: the deployment must have succeeded + assert "needs.deploy.result == 'success'" in api["if"] assert "!contains(needs.*.result, 'failure')" in api["if"] step = _steps(api, "Run samples API tests")[0] assert step["env"]["APP_URL"] == "https://www.${{ vars.DOMAIN }}/api" @@ -189,7 +187,7 @@ def test_api_and_e2e_test_jobs(tmp_path): assert commands[2] == "pytest -v test/api" e2e = jobs["tests-e2e-samples"] - assert e2e["needs"] == ["prepare", "wait-deployment"] + assert e2e["needs"] == ["prepare", "deploy"] step = _steps(e2e, "Run samples E2E tests")[0] assert step["env"]["APP_URL"] == "https://www.${{ vars.DOMAIN }}" assert ( @@ -204,41 +202,51 @@ def test_no_api_e2e_jobs_when_not_enabled(tmp_path): wf, _ = _generate(tmp_path, ["myapp"]) names = list(wf["jobs"]) assert not [n for n in names if n.startswith(("tests-api", "tests-e2e", "build-test-"))] - assert "wait-deployment" in names + assert "deploy" in names # nothing references the removed prototypes any more for job in wf["jobs"].values(): for need in job.get("needs", []): assert need in wf["jobs"], need -def test_deploy_secret_values(tmp_path): - wf, _ = _generate(tmp_path, ["samples", "myapp"], registry_secret_name="my-pull-secret") - deploy = wf["jobs"]["deploy"] +def test_deploy_with_skaffold(tmp_path): + wf, project = _generate(tmp_path, ["samples", "myapp"], registry_secret_name="my-pull-secret") + jobs = wf["jobs"] + deploy = jobs["deploy"] - step = _steps(deploy, "Collect secret values")[0] + # skaffold deploy installs the chart and waits for its rollout: no job of its own waits for it + assert "wait-deployment" not in jobs + run = _steps(deploy, "Deploy and wait for the rollout")[0]["run"] + assert run.startswith( + "skaffold deploy --filename deployment/skaffold-ci.yaml --build-artifacts deployment/skaffold-images.json " + ) + # skaffold labels every pod template with its run id: a new one would restart every pod on every deploy + assert "--label skaffold.dev/run-id=cloudharness" in run + names = [step.get("name") or step.get("uses") for step in deploy["steps"]] + assert names.index("Write the secret values") < names.index("Deploy and wait for the rollout") + assert names.index("Install skaffold") < names.index("Deploy and wait for the rollout") + + # every secret value lands in the file skaffold-ci.yaml passes to helm with --set-file + step = _steps(deploy, "Write the secret values")[0] assert step["env"]["ASECRET"] == "${{ secrets.ASECRET }}" assert step["env"]["MYAPP_DB_CONNECT_STRING"] == "${{ secrets.MYAPP_DB_CONNECT_STRING }}" assert step["env"]["K8S_SA_JSON"] == "${{ secrets.K8S_SA_JSON }}" - assert "--set-file apps.samples.harness.secrets.asecret=$secrets_dir/" in step["run"] - assert "--set-file apps.myapp.harness.database.connect_string=$secrets_dir/" in step["run"] - assert "--set-file registry.secret.value=$secrets_dir/" in step["run"] - assert 'echo "HELM_SET_ARGS=$args" >> "$GITHUB_ENV"' in step["run"] - install = _steps(deploy, "Install chart")[0] - assert "$HELM_SET_ARGS" in install["run"] - assert "helm upgrade --install" in install["run"] + assert 'secrets_dir="$HOME/.cloudharness/secrets"' in step["run"] + plan = project.skaffold_ci.generate({}, write_on_disk=False) + set_files = plan["deploy"]["helm"]["releases"][0]["setFiles"] + assert set_files["registry.secret.value"] == "~/.cloudharness/secrets/K8S_SA_JSON" + for path in set_files.values(): + file_name = path[len("~/.cloudharness/secrets/"):] + assert f'"$secrets_dir/{file_name}"' in step["run"], file_name + assert step["run"].count('"$secrets_dir/ASECRET"') == 1, "a secret is written once" # secrets only ever travel through env, never inline in a script assert not [run for run in _run_strings(wf) if "${{ secrets." in run] -def test_rollout_wait_and_publish_steps(tmp_path): +def test_publish_steps(tmp_path): wf, project = _generate(tmp_path, ["samples", "myapp"]) jobs = wf["jobs"] - rollout = _steps(jobs["wait-deployment"], "Wait for the rollouts")[0] - lines = rollout["run"].splitlines() - assert any(line.startswith("kubectl rollout status deployment/") for line in lines) - assert lines[-1] == "sleep 60" - publish = jobs["publish"] assert "needs.prepare.outputs.publish_tag != ''" in publish["if"] assert "deploy" in publish["needs"] and "tests-e2e-samples" in publish["needs"] @@ -268,7 +276,7 @@ def test_prepare_command_placeholders(tmp_path): assert "-e dev " in run assert "-i samples -i myapp -ex events" in run assert "$PATHS" not in run and "$ENV " not in run and "$PARAMS" not in run - assert "--write-env" in run and "--write-skaffold-build" in run and "--force-build" in run + assert "--write-env" in run and "--write-skaffold-ci" in run and "--force-build" in run def test_multienv_test_overlay(tmp_path): @@ -299,7 +307,7 @@ def test_prod_deploys_only(tmp_path): # the fixture's kube_auth override lives in the dev overlay only: prod keeps the # default step (KUBECONFIG secret or the runner's own cluster access) assert [s for s in jobs["deploy"]["steps"] if s.get("name") == "Configure kubectl"] - assert jobs["deploy"]["env"]["HELM_FLAGS"].startswith("--wait") + assert _steps(jobs["deploy"], "Deploy and wait for the rollout") assert wf["on"]["workflow_dispatch"]["inputs"]["deployment_tag"]["required"] is True @@ -311,7 +319,7 @@ def test_stage_keeps_tests_and_tags_the_repository(tmp_path): assert not _steps(jobs["publish"], "Publish test-"), "the test images are not built here" assert "tests-api-samples" in jobs assert not _steps(jobs["prepare"], "Run the unit tests"), "stage runs no unit tests" - assert jobs["tests-api-samples"]["needs"] == ["prepare", "wait-deployment"] + assert jobs["tests-api-samples"]["needs"] == ["prepare", "deploy"] assert jobs["git-tag"]["needs"] == ["prepare", "publish"] assert jobs["git-tag"]["permissions"] == {"contents": "write"} # the tag is pushed only when the images were published: a failed deployment or test diff --git a/tools/deployment-cli-tools/tests/test_skaffold_build.py b/tools/deployment-cli-tools/tests/test_skaffold_ci.py similarity index 81% rename from tools/deployment-cli-tools/tests/test_skaffold_build.py rename to tools/deployment-cli-tools/tests/test_skaffold_ci.py index eb678a8b9..2eb0a9f7b 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold_build.py +++ b/tools/deployment-cli-tools/tests/test_skaffold_ci.py @@ -1,4 +1,4 @@ -"""CHSkaffoldBuild: deployment/skaffold-build.yaml, the images a CI run still has to build.""" +"""CHSkaffoldCI: deployment/skaffold-ci.yaml, the images a CI run still has to build.""" import json import os @@ -47,7 +47,7 @@ def _artifacts(plan): def test_only_the_missing_images_are_built(tmp_path): project = _project(tmp_path, ["samples", "myapp"]) - plan = project.skaffold_build.generate( + plan = project.skaffold_ci.generate( _existing(project, "myapp", "cloudharness-flask"), write_on_disk=False ) artifacts = _artifacts(plan) @@ -74,7 +74,7 @@ def test_only_the_missing_images_are_built(tmp_path): def test_build_command(tmp_path): project = _project(tmp_path, ["myapp"]) - plan = project.skaffold_build.generate(_existing(project, "myapp"), write_on_disk=False) + plan = project.skaffold_ci.generate(_existing(project, "myapp"), write_on_disk=False) command = _artifacts(plan)["reg/testprojectname/myapp"]["custom"]["buildCommand"] assert command.startswith("docker buildx build --push --file dev.Dockerfile ") @@ -91,7 +91,7 @@ def test_build_command(tmp_path): def test_contexts_are_relative_to_the_project_root(tmp_path): # skaffold resolves the contexts from the directory it runs in: the workflow runs it from the root project = _project(tmp_path, ["samples", "myapp"]) - plan = project.skaffold_build.generate({}, write_on_disk=False) + plan = project.skaffold_ci.generate({}, write_on_disk=False) artifacts = _artifacts(plan) def context(image): @@ -106,7 +106,7 @@ def context(image): def test_test_runner_images_get_the_latest_tag(tmp_path): project = _project(tmp_path, ["samples"], tag="1") - artifacts = _artifacts(project.skaffold_build.generate({}, write_on_disk=False)) + artifacts = _artifacts(project.skaffold_ci.generate({}, write_on_disk=False)) for name in ("test-api", "test-e2e"): command = artifacts[f"reg/testprojectname/{name}"]["custom"]["buildCommand"] assert f"--tag reg/testprojectname/{name}:latest" in command @@ -114,13 +114,13 @@ def test_test_runner_images_get_the_latest_tag(tmp_path): # no app runs API/E2E tests: no test runner image project = _project(tmp_path, ["myapp"], tag="1") - artifacts = _artifacts(project.skaffold_build.generate({}, write_on_disk=False)) + artifacts = _artifacts(project.skaffold_ci.generate({}, write_on_disk=False)) assert not [image for image in artifacts if "/test-" in image] def test_nothing_to_build(tmp_path): project = _project(tmp_path, ["samples", "myapp"], tag="1") - plan = project.skaffold_build.generate(_existing(project), write_on_disk=False) + plan = project.skaffold_ci.generate(_existing(project), write_on_disk=False) assert plan["build"]["artifacts"] == [] assert plan["build"]["tagPolicy"]["envTemplate"]["template"] == "{{ index (dict ) .IMAGE_NAME }}" @@ -128,7 +128,7 @@ def test_nothing_to_build(tmp_path): def test_unit_tests_cover_every_app(tmp_path): project = _project(tmp_path, ["samples", "myapp"]) # nothing to build: the unit tests still run, against the images in the registry - plan = project.skaffold_build.generate(_existing(project), write_on_disk=False) + plan = project.skaffold_ci.generate(_existing(project), write_on_disk=False) assert plan["build"]["artifacts"] == [] tests = {test["image"]: test["custom"] for test in plan["test"]} assert set(tests) == {"reg/testprojectname/myapp", "reg/testprojectname/sampleapp"} @@ -137,7 +137,7 @@ def test_unit_tests_cover_every_app(tmp_path): ] # `skaffold test --build-artifacts` takes every image's tag from skaffold-images.json - images = {build["imageName"]: build["tag"] for build in project.skaffold_build.images()["builds"]} + images = {build["imageName"]: build["tag"] for build in project.skaffold_ci.images()["builds"]} assert images["reg/testprojectname/myapp"] == project.qualify_image(project["myapp"]) assert set(tests) <= set(images) assert set(images) == { @@ -146,7 +146,26 @@ def test_unit_tests_cover_every_app(tmp_path): } -def test_generate_writes_deployment_skaffold_build(tmp_path): +def test_deploy_installs_the_chart_and_waits_for_the_rollout(tmp_path): + project = _project(tmp_path, ["samples", "myapp"]) + plan = project.skaffold_ci.generate(_existing(project), write_on_disk=False) + # tolerateFailuresUntilDeadline needs a v4 schema + assert plan["apiVersion"] == "skaffold/v4beta14" + deploy = plan["deploy"] + assert deploy["tolerateFailuresUntilDeadline"] is True + assert deploy["statusCheckDeadlineSeconds"] == 900 + [release] = deploy["helm"]["releases"] + assert release["name"] == release["namespace"] == "test" + assert release["chartPath"] == "deployment/helm" + assert release["createNamespace"] is True and release["skipBuildDependencies"] is True + # secret values come from the files the pipeline writes, never from the file itself + assert release["setFiles"]["apps.samples.harness.secrets.asecret"] == "~/.cloudharness/secrets/ASECRET" + assert release["setFiles"]["apps.myapp.harness.database.connect_string"] == ( + "~/.cloudharness/secrets/MYAPP_DB_CONNECT_STRING" + ) + + +def test_generate_writes_deployment_skaffold_ci(tmp_path): write_tree_from_yaml( tmp_path, """ @@ -165,11 +184,12 @@ def test_generate_writes_deployment_skaffold_build(tmp_path): tmp_path, config=CHDeployConfig(env="dev", registry="reg", tag="1", output_path=str(tmp_path / "deployment")), ) - project.skaffold_build.generate({"MYAPP_TAG_EXISTS": "1"}) + project.skaffold_ci.generate({"MYAPP_TAG_EXISTS": "1"}) - plan = YAML(typ="safe").load((tmp_path / "deployment" / "skaffold-build.yaml").read_text()) + plan = YAML(typ="safe").load((tmp_path / "deployment" / "skaffold-ci.yaml").read_text()) assert plan["apiVersion"].startswith("skaffold/") assert plan["kind"] == "Config" + assert "deploy" not in plan, "no namespace to deploy to" assert "reg/testproj/myapp" not in _artifacts(plan), "its tag exists" assert "reg/testproj/cloudharness-base" in _artifacts(plan) images = json.loads((tmp_path / "deployment" / "skaffold-images.json").read_text()) From a8aa281a0c3c4be39f157d2cebd22674265dd95f Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 18:44:41 +0100 Subject: [PATCH 08/11] CH-125 skaffold based github action --- .github/workflows/cloudharness-test.yaml | 2 +- .../skaffold-template.yaml | 4 +- .../ch_cli_tools/model.py | 13 +++- .../ch_cli_tools/skaffold.py | 61 +++++++++++++------ .../tests/test_skaffold.py | 42 ++++++------- .../tests/test_skaffold_ci.py | 4 +- .../tests/test_skaffold_internals.py | 50 +++++++++++---- 7 files changed, 115 insertions(+), 61 deletions(-) diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index a9037845c..3f5b64463 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -1,4 +1,4 @@ -# Generated with: harness-deployment . -e test -i samples -ci github +# Generated with: harness-deployment . -i samples -e test -ci github name: CloudHarness test on: pull_request: 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/tools/deployment-cli-tools/ch_cli_tools/model.py b/tools/deployment-cli-tools/ch_cli_tools/model.py index 156f1ecfa..70cf65a69 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/model.py +++ b/tools/deployment-cli-tools/ch_cli_tools/model.py @@ -278,7 +278,7 @@ def dockerfile(self) -> "CHDockerfile": @property def build_context(self) -> Path: - return self.path + return dockerfile_directory(self) def __getitem__(self, key) -> "CHAppTask": try: @@ -643,6 +643,15 @@ def _build_values(self, app_values: dict, instance_values: dict) -> dict: return instance_app +def dockerfile_directory(entity: "CHApp | CHAppTask") -> Path: + """Where an app or task builds from: the directory holding its Dockerfile, which may be a + subdirectory (server/, ...) whose files the Dockerfile COPYs as `./...`. An inherited + Dockerfile gives the same subdirectory of the entity's own directory, so every layer merged + into .overrides/ contributes the same part of its tree.""" + dockerfile = entity.dockerfile + return entity.path / dockerfile.path.resolve().parent.relative_to(dockerfile.app.path.resolve()) + + class CHValues: """A values.yaml file, resolved across environments and base layers.""" @@ -857,7 +866,7 @@ def dockerfile(self) -> "CHDockerfile": @property def build_context(self) -> Path: - return self.path + return dockerfile_directory(self) @property def readme(self) -> Path: diff --git a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py index 02cc3c543..1b990b570 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py +++ b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py @@ -61,12 +61,15 @@ 6. tagPolicy is envTemplate for compose or an explicit external tag, sha256 content-hash otherwise. 7. The deploy block is either a compose block (useCompose + image list) or - a helm block with per-app/task image overrides and entrypoint - overrides. + a helm block - release named after the namespace - setting each app's and + task's image to the one skaffold built (setValueTemplates) and the + entrypoint overrides. The template declares the newest skaffold schema + (the one of the skaffold the CI installs, CI_API_VERSION). """ import json import os +import re import shlex from functools import lru_cache from pathlib import Path @@ -104,6 +107,22 @@ def all_values(self): return dict_merge(base.skaffold_template.all_values(), own) +def image_value_template(image: str) -> str: + """A helm `setValueTemplates` value skaffold fills with the image it built, tag included.""" + return "{{.IMAGE_FULLY_QUALIFIED_%s}}" % re.sub(r"[./:-]", "_", image) + + +def helm_release(project) -> dict: + """The name and namespace of the chart's helm release: both the configured namespace or the + helm values' default one, as the CI deploys; the chart's name when there is no namespace at + all (helm requires a release name).""" + values = project.all_values() + namespace = project.config.namespace or values.get("namespace") + if not namespace: + return {"name": values["name"]} + return {"name": namespace, "namespace": namespace} + + @register_file("skaffold", lambda root: root / "skaffold.yaml") class CHSkaffold(CHValues): def qualify(self, image_name): @@ -216,6 +235,10 @@ def _collect_task_dockerfile_artifacts(self, app): "context": str(context.path), "docker": self._build_docker_options(context.dockerfile.path), } + # a task FROMs its base image too (ARG CLOUDHARNESS_BASE): skaffold passes it by alias + requires = self._requires_for(task) + if requires: + artifact["requires"] = requires artifacts.append(artifact) overrides[task.name] = artifact["image"] return artifacts, overrides @@ -318,7 +341,9 @@ def generate(self, write_on_disk=True, output_path="."): if project.config.backend == "compose" or ( project.config.tag and not project.config.local ): - build["tagPolicy"] = {"envTemplate": {"template": '"{{.TAG}}"'}} + # the configured tag, or $TAG (skaffold falls back to `latest` when unset); a quoted + # template would make every tag invalid, which skaffold also turns into `latest` + build["tagPolicy"] = {"envTemplate": {"template": project.config.tag or "{{.TAG}}"}} elif not build.get("tagPolicy"): # Checked for falsy, not just absent: the default skaffold-template.yaml # already ships an empty `build.tagPolicy: {}`, so a plain `setdefault` @@ -336,15 +361,19 @@ def generate(self, write_on_disk=True, output_path="."): deploy = base.setdefault("deploy", {}) releases = deploy.setdefault("helm", {}).setdefault("releases", [{}]) release_config = releases[0] - if project.config.namespace: - release_config["name"] = project.config.namespace - release_config["namespace"] = project.config.namespace - artifact_overrides = release_config.setdefault("artifactOverrides", {}) - artifact_overrides["apps"] = { - name: {"harness": {"deployment": {"image": image}}} + release_config.update(helm_release(project)) + # every built image reaches the chart through the value skaffold templates with its tag + images = { + f"apps.{name}.harness.deployment.image": image for name, image in app_image_overrides.items() } - artifact_overrides["task-images"] = task_image_overrides + images.update( + {f"task-images.{name}": image for name, image in task_image_overrides.items()} + ) + release_config["setValueTemplates"] = { + **(release_config.get("setValueTemplates") or {}), + **{key: image_value_template(image) for key, image in images.items()}, + } release_config.setdefault("overrides", {})["apps"] = entrypoint_overrides @@ -450,14 +479,10 @@ def _tests(self) -> list[dict]: if app.test.unit.commands ] - def _deploy(self) -> dict | None: + def _deploy(self) -> dict: project = self.project - namespace = project.config.namespace - if not namespace: - return None release = { - "name": namespace, - "namespace": namespace, + **helm_release(project), "chartPath": os.path.relpath(self.path.parent / "helm", project.root), "createNamespace": True, # the chart is deployed as harness-deployment wrote it: no `helm dependency build` @@ -535,9 +560,7 @@ def generate(self, image_env: dict[str, str], write_on_disk=True) -> dict: tests = self._tests() if tests: plan["test"] = tests - deploy = self._deploy() - if deploy: - plan["deploy"] = deploy + plan["deploy"] = self._deploy() if write_on_disk: self.write(plan) self.images_path.write_text(json.dumps(self.images(), indent=2) + "\n", encoding="utf-8") diff --git a/tools/deployment-cli-tools/tests/test_skaffold.py b/tools/deployment-cli-tools/tests/test_skaffold.py index 5024ff87c..046e86172 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold.py +++ b/tools/deployment-cli-tools/tests/test_skaffold.py @@ -40,19 +40,23 @@ def test_create_skaffold_configuration(tmp_path): # CHApp.dockerfile now checks the same conventional subdirectories. exp_apps = ("accounts", "samples", "workflows", "myapp", "common") artifact_images = [a["image"] for a in sk["build"]["artifacts"]] - artifact_overrides = sk["deploy"]["helm"]["releases"][0]["artifactOverrides"] + # each built image reaches the chart through a helm value skaffold templates with its tag + templates = sk["deploy"]["helm"]["releases"][0]["setValueTemplates"] + overridden_apps = {key.split(".")[1] for key in templates if key.startswith(f"{KEY_APPS}.")} + task_images = {key.split(".", 1)[1] for key in templates if key.startswith(f"{KEY_TASK_IMAGES}.")} for app in exp_apps: - assert app in artifact_overrides[KEY_APPS] + assert app in overridden_apps + assert templates["apps.myapp.harness.deployment.image"] == ( + "{{.IMAGE_FULLY_QUALIFIED_reg_testprojectname_myapp}}" + ) # values[KEY_TASK_IMAGES] isn't populated by # ng.api.create_helm_chart (no task-images aggregation yet - see - # test_helm.py's test_collect_helm_values). artifactOverrides' - # task-images comes straight from ng.skaffold.CHSkaffold's own generation - # instead, which is what's actually under test here. - assert artifact_overrides[KEY_TASK_IMAGES], "task image overrides should be present" - assert any( - image.endswith("myapp-mytask") for image in artifact_overrides[KEY_TASK_IMAGES] - ) + # test_helm.py's test_collect_helm_values). The task-images templates come + # straight from ng.skaffold.CHSkaffold's own generation instead, which is + # what's actually under test here. + assert task_images, "task image overrides should be present" + assert any(image.endswith("myapp-mytask") for image in task_images) # Legacy asserted an exact artifact count (len(exp_apps) + len(task # images)) because its "task-images" bucket already lumped in every @@ -61,13 +65,11 @@ def test_create_skaffold_configuration(tmp_path): # dependencies (base/common images pulled in via all_build_dependencies) # - so the equivalent total needs all three, not just the first two. build_dependency_count = len( - project.all_build_dependencies( - {*artifact_overrides[KEY_APPS], *artifact_overrides[KEY_TASK_IMAGES]} - ) + project.all_build_dependencies({*overridden_apps, *task_images}) ) assert len(artifact_images) == ( len(exp_apps) + - len(artifact_overrides[KEY_TASK_IMAGES]) + + len(task_images) + build_dependency_count ) @@ -79,17 +81,9 @@ def test_create_skaffold_configuration(tmp_path): ] assert overrides[KEY_APPS]["samples"][KEY_HARNESS][KEY_DEPLOYMENT]["args"] - assert ( - "reg" == - artifact_overrides[KEY_APPS]["accounts"][KEY_HARNESS][KEY_DEPLOYMENT][ - "image" - ][0:3] - ) - assert ( - "harness" - not in artifact_overrides[KEY_APPS]["accounts"][KEY_HARNESS][KEY_DEPLOYMENT][ - "image" - ] + # accounts comes from cloud-harness, but is the project's own image, in the project's registry + assert templates["apps.accounts.harness.deployment.image"] == ( + "{{.IMAGE_FULLY_QUALIFIED_reg_testprojectname_accounts}}" ) cloudharness_base_artifact = next( diff --git a/tools/deployment-cli-tools/tests/test_skaffold_ci.py b/tools/deployment-cli-tools/tests/test_skaffold_ci.py index 2eb0a9f7b..b021b9de2 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold_ci.py +++ b/tools/deployment-cli-tools/tests/test_skaffold_ci.py @@ -189,7 +189,9 @@ def test_generate_writes_deployment_skaffold_ci(tmp_path): plan = YAML(typ="safe").load((tmp_path / "deployment" / "skaffold-ci.yaml").read_text()) assert plan["apiVersion"].startswith("skaffold/") assert plan["kind"] == "Config" - assert "deploy" not in plan, "no namespace to deploy to" + # no namespace configured: the helm values' default one + [release] = plan["deploy"]["helm"]["releases"] + assert release["name"] == release["namespace"] == "ch" assert "reg/testproj/myapp" not in _artifacts(plan), "its tag exists" assert "reg/testproj/cloudharness-base" in _artifacts(plan) images = json.loads((tmp_path / "deployment" / "skaffold-images.json").read_text()) diff --git a/tools/deployment-cli-tools/tests/test_skaffold_internals.py b/tools/deployment-cli-tools/tests/test_skaffold_internals.py index bb05dca46..468c1087c 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold_internals.py +++ b/tools/deployment-cli-tools/tests/test_skaffold_internals.py @@ -60,10 +60,10 @@ def test_build_only_dependency_is_not_deployed(): CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig(includes=["dependantapp"]) ) generated = project.skaffold.generate(write_on_disk=False) - overrides = generated["deploy"]["helm"]["releases"][0]["artifactOverrides"]["apps"] + templates = generated["deploy"]["helm"]["releases"][0]["setValueTemplates"] - assert "dependantapp" in overrides - assert "myapp" not in overrides + assert "apps.dependantapp.harness.deployment.image" in templates + assert not [key for key in templates if key.startswith("apps.myapp.")] def test_build_dependency_on_base_image_gets_its_own_artifact(): @@ -94,6 +94,25 @@ def test_build_dependency_on_base_image_gets_its_own_artifact(): assert context == expected.resolve() +def test_task_artifacts_require_the_images_they_are_built_on(): + # a task's Dockerfile FROMs a build arg like an app's (ARG CLOUDHARNESS_BASE, or its + # own app's image): without `requires` skaffold passes no value and FROM is empty + project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig(includes=["samples"])) + artifacts = { + a["image"]: a for a in project.skaffold.generate(write_on_disk=False)["build"]["artifacts"] + } + + assert artifacts["testprojectname/sampleapp-secret"]["requires"] == [ + {"image": "testprojectname/cloudharness-base", "alias": "CLOUDHARNESS_BASE"} + ] + assert artifacts["testprojectname/sampleapp-sum"]["requires"] == [ + {"image": "testprojectname/sampleapp", "alias": "SAMPLES"} + ] + for artifact in artifacts.values(): + for required in artifact.get("requires", []): + assert required["image"] in artifacts, f"{artifact['image']} requires an image nobody builds" + + def test_build_dependency_on_task_owned_by_an_undeployed_app_resolves(): # Ports test_skaffold_builds_cross_app_task_image: taskdep declares # dependencies.build: [cloudharness-flask, myapp-mytask]. myapp-mytask is a @@ -146,16 +165,26 @@ def test_namespace_sets_helm_release_name_and_namespace(tmp_path): assert release["namespace"] == "my-ns" -def test_no_namespace_leaves_helm_release_name_unset(tmp_path): +def test_no_namespace_names_the_release_after_the_chart(tmp_path): + # skaffold rejects a release without a name; with no namespace configured + # nor set in the helm values, the chart's name is used project = minimal_project(tmp_path) release = project.skaffold.generate(write_on_disk=False)["deploy"]["helm"][ "releases" ][0] - assert "name" not in release + assert release["name"] == "testproj" assert "namespace" not in release +def test_default_namespace_comes_from_the_helm_values(): + # cloud-harness' helm values default the namespace to `ch` + project = chain(CLOUDHARNESS_ROOT, RESOURCES, config=CHDeployConfig(includes=["myapp"])) + release = project.skaffold.generate(write_on_disk=False)["deploy"]["helm"]["releases"][0] + + assert release["name"] == release["namespace"] == "ch" + + def test_tag_policy_is_sha256_by_default(tmp_path): project = minimal_project(tmp_path) build = project.skaffold.generate(write_on_disk=False)["build"] @@ -167,7 +196,7 @@ def test_tag_policy_is_env_template_when_external_tag_and_not_local(tmp_path): # handed rather than compute its own content hash. project = minimal_project(tmp_path, tag="v1", local=False) build = project.skaffold.generate(write_on_disk=False)["build"] - assert build["tagPolicy"] == {"envTemplate": {"template": '"{{.TAG}}"'}} + assert build["tagPolicy"] == {"envTemplate": {"template": "v1"}} def test_tag_policy_is_sha256_when_tag_set_but_local(tmp_path): @@ -185,9 +214,8 @@ def test_compose_backend_builds_docker_compose_deploy_block(tmp_path): project = minimal_project(tmp_path, backend="compose") generated = project.skaffold.generate(write_on_disk=False) - assert generated["build"]["tagPolicy"] == { - "envTemplate": {"template": '"{{.TAG}}"'} - } + # no tag configured: $TAG, which skaffold replaces with `latest` when unset + assert generated["build"]["tagPolicy"] == {"envTemplate": {"template": "{{.TAG}}"}} assert generated["deploy"] == { "docker": { "useCompose": True, @@ -919,5 +947,5 @@ def test_app_with_explicit_deployment_image_is_never_built(tmp_path): assert "testproj/myapp-mytask" in images assert result.get("test", []) == [] - overrides = result["deploy"]["helm"]["releases"][0]["artifactOverrides"]["apps"] - assert "myapp" not in overrides + templates = result["deploy"]["helm"]["releases"][0]["setValueTemplates"] + assert not [key for key in templates if key.startswith("apps.myapp.")] From 0fd14aae27e1d9f08843d590d27f504e80bfc649 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 19:11:31 +0100 Subject: [PATCH 09/11] CH-125 fix cloudharness test pipeline --- .github/workflows/cloudharness-test.yaml | 40 +------------------ deployment-configuration/github-template.yaml | 25 ++---------- docs/build-deploy/ci-cd/README.md | 4 +- .../ch_cli_tools/github_actions.py | 38 ++++++++++++++++-- .../tests/test_github_actions.py | 32 ++++++++++++++- 5 files changed, 74 insertions(+), 65 deletions(-) diff --git a/.github/workflows/cloudharness-test.yaml b/.github/workflows/cloudharness-test.yaml index 3f5b64463..bc5deb52a 100644 --- a/.github/workflows/cloudharness-test.yaml +++ b/.github/workflows/cloudharness-test.yaml @@ -20,8 +20,6 @@ permissions: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false -env: - CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} jobs: prepare: name: Prepare and build @@ -89,18 +87,12 @@ jobs: TEST_E2E_TAG_EXISTS: ${{ steps.images.outputs.TEST_E2E_TAG_EXISTS }} steps: - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: actions/setup-python@v5 with: python-version: '3.12' - uses: azure/setup-helm@v4 - name: Install cloud-harness tools - run: bash cloud-harness/install.sh + run: bash ./install.sh - name: Resolve pipeline variables id: env run: | @@ -220,12 +212,6 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: actions/download-artifact@v4 with: name: cloudharness-deployment @@ -260,12 +246,6 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: actions/download-artifact@v4 with: name: cloudharness-deployment @@ -305,12 +285,6 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: actions/download-artifact@v4 with: name: cloudharness-deployment @@ -345,12 +319,6 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} @@ -381,12 +349,6 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index 4537e7ccb..b35fe8a40 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -72,8 +72,6 @@ cloudharness: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false -env: - CLOUDHARNESS_BRANCH: ${{ vars.CLOUDHARNESS_BRANCH || 'develop' }} 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. @@ -103,19 +101,14 @@ jobs: force_build: ${{ steps.env.outputs.force_build }} steps: - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness + - $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 cloud-harness/install.sh + run: bash $CLOUDHARNESS_PATH/install.sh - name: Resolve pipeline variables id: env run: | @@ -184,12 +177,7 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness + - $CLONE_CLOUDHARNESS - uses: actions/download-artifact@v4 with: name: cloudharness-deployment @@ -211,12 +199,7 @@ jobs: - name: Give the certificates time to settle run: sleep 60 - uses: actions/checkout@v4 - - name: Clone cloud-harness - uses: actions/checkout@v4 - with: - repository: MetaCell/cloud-harness - ref: ${{ env.CLOUDHARNESS_BRANCH }} - path: cloud-harness + - $CLONE_CLOUDHARNESS - uses: docker/login-action@v3 with: registry: ${{ needs.prepare.outputs.registry_host }} diff --git a/docs/build-deploy/ci-cd/README.md b/docs/build-deploy/ci-cd/README.md index 61d53a4b2..c63d74179 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -58,7 +58,9 @@ and publication. Pass `-ci codefresh -ci github` to generate both. Build, unit t 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 on the `publish` and `prod`/`stage` environments. `workflow_dispatch` inputs replace the `DEPLOYMENT_PUBLISH_TAG`, - `DEPLOYMENT_TAG`, `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. + `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 diff --git a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py index 5e59bae46..6abd9555b 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/github_actions.py +++ b/tools/deployment-cli-tools/ch_cli_tools/github_actions.py @@ -37,7 +37,8 @@ job is not generated. Inside a prototype `$CH_NAME`, `$CH_IMAGE` and `$CH_TAG` stand for the app's image. - A string item in a `steps` list is a fragment the generator fills: - `$GIT_CLONES`, `$BUILD_STEPS`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, + `$CLONE_CLOUDHARNESS` (nothing in cloud-harness' own workflow, which tests + its checkout), `$GIT_CLONES`, `$BUILD_STEPS`, `$PUBLISH_STEPS`, `$HELM_SECRETS_STEPS`, `$TEST_STEPS` and `$KUBE_AUTH`. The steps of `$BUILD_STEPS` and `$KUBE_AUTH` come from the template's own `cloudharness.build` and `cloudharness.kube_auth` lists, so a project changes how images are built @@ -45,7 +46,9 @@ `cloudharness.build: null` builds and tests nothing (stage, prod). The top-level `cloudharness` section is for the generator only and never reaches GitHub. -- `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh. +- `$ENV`, `$PARAMS` and `$PATHS` are substituted everywhere, as in Codefresh, and + `$CLOUDHARNESS_PATH`: where the tools are installed from (`cloud-harness`, + `.` in cloud-harness' own workflow). - A template key matching an expanded job id (`jobs.tests-api-myapp`) is merged over the generated job, so one app can get a bigger runner or extra steps; such a key is dropped when its app is not part of the deployment being @@ -83,6 +86,7 @@ PROTOTYPE_JOBS = (JOB_API_TESTS, JOB_E2E_TESTS) FRAGMENT_GIT_CLONES = "$GIT_CLONES" +FRAGMENT_CLONE_CLOUDHARNESS = "$CLONE_CLOUDHARNESS" FRAGMENT_BUILD = "$BUILD_STEPS" FRAGMENT_PUBLISH_STEPS = "$PUBLISH_STEPS" FRAGMENT_HELM_SECRETS = "$HELM_SECRETS_STEPS" @@ -348,8 +352,29 @@ def _pipeline_path(self, path) -> str: ) ) + def _cloudharness_root(self) -> Path: + return self.project.all_layers()[-1].root + # --- generated fragments --- + def _cloudharness_clone_steps(self) -> list[dict]: + """A project's jobs clone cloud-harness into ./cloud-harness, at the branch the + CLOUDHARNESS_BRANCH variable names (default develop). cloud-harness' own workflow already + has it checked out at the branch that triggered the run, the version under test.""" + if self._cloudharness_root().resolve() == self.project.root.resolve(): + return [] + return [ + { + "name": "Clone cloud-harness", + "uses": "actions/checkout@v4", + "with": { + "repository": "MetaCell/cloud-harness", + "ref": "${{ vars.CLOUDHARNESS_BRANCH || 'develop' }}", + "path": "cloud-harness", + }, + } + ] + def _git_clone_steps(self, entities) -> list[dict]: steps = [] for entity in entities: @@ -531,6 +556,7 @@ def _expand_jobs(self, jobs: dict, settings: dict | None = None) -> dict: fragments = { # prepare merges the build contexts (.overrides/) with the git dependencies in them FRAGMENT_GIT_CLONES: self._git_clone_steps(entities.values()), + FRAGMENT_CLONE_CLOUDHARNESS: self._cloudharness_clone_steps(), FRAGMENT_BUILD: build_steps, FRAGMENT_PUBLISH_STEPS: self._publish_steps({**entities, **test_images}), FRAGMENT_HELM_SECRETS: self._helm_secrets_steps(), @@ -604,7 +630,13 @@ def generate(self, write_on_disk=True, output_path=None): ) return {} - base = substitute_vars(base, ci.placeholder_values(project, self._pipeline_path)) + base = substitute_vars( + base, + { + **ci.placeholder_values(project, self._pipeline_path), + "CLOUDHARNESS_PATH": self._pipeline_path(self._cloudharness_root()), + }, + ) settings = base.pop(SETTINGS_KEY, None) or {} base["jobs"] = self._expand_jobs(base.get("jobs") or {}, settings) # the env template contributes name/on after the base keys: put them first diff --git a/tools/deployment-cli-tools/tests/test_github_actions.py b/tools/deployment-cli-tools/tests/test_github_actions.py index 1fea79327..a8d71baab 100644 --- a/tools/deployment-cli-tools/tests/test_github_actions.py +++ b/tools/deployment-cli-tools/tests/test_github_actions.py @@ -12,7 +12,7 @@ from ch_cli_tools import CHDeployConfig, ci from ch_cli_tools.api import create_helm_chart -from ch_cli_tools.github_actions import DEFAULT_RUNNER +from ch_cli_tools.github_actions import DEFAULT_RUNNER, referenced_names JOB_ID = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$") @@ -127,6 +127,36 @@ def test_git_dependency_checkouts(tmp_path): assert not [s for s in _steps(job, "Clone ") if s["name"] != "Clone cloud-harness"], name +def test_cloudharness_is_cloned_by_projects_only(tmp_path): + # a project's jobs clone cloud-harness (CLOUDHARNESS_BRANCH, default develop) and install its tools + wf, _ = _generate(tmp_path, ["samples", "myapp"]) + prepare = wf["jobs"]["prepare"]["steps"] + [clone] = [step for step in prepare if step.get("name") == "Clone cloud-harness"] + assert clone["with"] == { + "repository": "MetaCell/cloud-harness", + "ref": "${{ vars.CLOUDHARNESS_BRANCH || 'develop' }}", + "path": "cloud-harness", + } + assert _steps(wf["jobs"]["prepare"], "Install cloud-harness tools")[0]["run"] == ( + "bash cloud-harness/install.sh" + ) + assert _steps(wf["jobs"]["tests-api-samples"], "Clone cloud-harness") + + # cloud-harness' own workflow tests the branch that triggered it, tools included: it never + # clones another branch nor reads CLOUDHARNESS_BRANCH + project = chain( + CLOUDHARNESS_ROOT, + config=CHDeployConfig(env="test", includes=["samples"], output_path=str(tmp_path / "deployment")), + ) + wf = project.github_actions.generate(write_on_disk=False) + assert "CLOUDHARNESS_BRANCH" not in referenced_names(wf)["vars"] + assert "CLOUDHARNESS_BRANCH" not in wf.get("env", {}) + assert not [ + name for name, job in wf["jobs"].items() if _steps(job, "Clone cloud-harness") + ] + assert _steps(wf["jobs"]["prepare"], "Install cloud-harness tools")[0]["run"] == "bash ./install.sh" + + def test_prepare_outputs_cover_every_image(tmp_path): wf, project = _generate(tmp_path, ["samples", "myapp"]) outputs = wf["jobs"]["prepare"]["outputs"] From 6b0af817c22ae1fa5bf2bcca83093ef590dab039 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Fri, 6 Nov 2026 20:37:20 +0100 Subject: [PATCH 10/11] CH-125 build fix --- .../ch_cli_tools/model.py | 19 ++++++++++++------- .../ch_cli_tools/skaffold.py | 8 +++++--- .../tests/test_skaffold_ci.py | 4 ++++ 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/tools/deployment-cli-tools/ch_cli_tools/model.py b/tools/deployment-cli-tools/ch_cli_tools/model.py index f34b03938..bbe4eccb6 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/model.py +++ b/tools/deployment-cli-tools/ch_cli_tools/model.py @@ -86,7 +86,7 @@ class CHTemplate from collections.abc import Callable from dataclasses import dataclass, field from functools import lru_cache -from pathlib import Path +from pathlib import Path, PurePosixPath from typing import Literal, cast from cloudharness_model import HarnessMainConfig # type: ignore @@ -458,11 +458,8 @@ def app_entrypoint(self) -> Path | None: @property def image_name(self): - return f"{self.project.base_image_name()} / { - resolve_path( - self.harness_config, 'image_name', default=self.dockerfile.app.name - ) - }" + name = resolve_path(self.harness_config, "image_name", default=self.dockerfile.app.name) + return str(PurePosixPath(self.project.base_image_name(), name)) @property def is_buildable(self) -> bool: @@ -815,7 +812,7 @@ def build_context(self) -> Path: @property def image_name(self): - return f"{self.project.base_image_name()}/{self.name}" + return str(PurePosixPath(self.project.base_image_name(), self.name)) def build_dependencies(self) -> list["CHApp | CHBaseImage | CHAppTask | str"]: return [] @@ -827,6 +824,14 @@ def __repr__(self): class CHTestImage(CHBaseImage): """A base image under test/.""" + @property + def build_context(self) -> Path: + """test-api COPYs the libraries and tools it tests with, so it builds from its layer's + root, like the shared base images; the other test images from their own directory.""" + if self.name == "test-api": + return self.containing_project.root + return self.path + def _lower_registry(self, lower: "CHProject") -> dict: return lower.test_images diff --git a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py index 1b990b570..5d02857ca 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/skaffold.py +++ b/tools/deployment-cli-tools/ch_cli_tools/skaffold.py @@ -68,7 +68,6 @@ """ import json -import os import re import shlex from functools import lru_cache @@ -483,7 +482,9 @@ def _deploy(self) -> dict: project = self.project release = { **helm_release(project), - "chartPath": os.path.relpath(self.path.parent / "helm", project.root), + "chartPath": str( + (self.path.parent / "helm").resolve().relative_to(project.root.resolve(), walk_up=True) + ), "createNamespace": True, # the chart is deployed as harness-deployment wrote it: no `helm dependency build` "skipBuildDependencies": True, @@ -505,7 +506,8 @@ def _context(self, entity) -> tuple[str, str]: the directory it runs in, not from the file's), and the Dockerfile, relative to the context.""" root = self.project.root context = entity.dockerfile.resolve_context(root).resolve_for_build(root) - return os.path.relpath(root / context.path, root), str(context.dockerfile.path) + path = (root / context.path).resolve().relative_to(root.resolve(), walk_up=True) + return str(path), str(context.dockerfile.path) def _artifact(self, entity, image: str, building: dict, extra_tags=()) -> dict: project = self.project diff --git a/tools/deployment-cli-tools/tests/test_skaffold_ci.py b/tools/deployment-cli-tools/tests/test_skaffold_ci.py index b021b9de2..97b809e12 100644 --- a/tools/deployment-cli-tools/tests/test_skaffold_ci.py +++ b/tools/deployment-cli-tools/tests/test_skaffold_ci.py @@ -102,6 +102,10 @@ def context(image): # the project overrides cloud-harness' base image: built from the context merged across layers assert context("cloudharness-base") == (RESOURCES / ".overrides" / "cloudharness-base").resolve() assert artifacts["reg/testprojectname/myapp"]["context"] == "applications/myapp" + # test-api COPYs cloud-harness' libraries and tools: it builds from the root of its layer + assert context("test-api") == CLOUDHARNESS_ROOT.resolve() + assert "--file test/test-api/Dockerfile " in artifacts["reg/testprojectname/test-api"]["custom"]["buildCommand"] + assert context("test-e2e") == (CLOUDHARNESS_ROOT / "test" / "test-e2e").resolve() def test_test_runner_images_get_the_latest_tag(tmp_path): From d03635dbec7bb79d20f1613277b407a750962a79 Mon Sep 17 00:00:00 2001 From: Filippo Ledda Date: Wed, 11 Nov 2026 12:27:13 +0100 Subject: [PATCH 11/11] CH-125 github actions WIP; rethink ci-cd generation with harness-generate and different criteria --- CLAUDE.md | 4 +- deployment-configuration/README.md | 12 +- .../codefresh-template-prod.yaml | 2 +- .../codefresh-template-stage.yaml | 2 +- .../codefresh-template-test.yaml | 2 +- .../github-template-dev.yaml | 96 ++++++++++++- .../github-template-prod.yaml | 7 +- .../github-template-stage.yaml | 29 +--- .../github-template-test.yaml | 6 +- deployment-configuration/github-template.yaml | 38 +----- docs/applications/harness-generate.md | 27 +++- docs/build-deploy/README.md | 3 +- docs/build-deploy/ci-cd/README.md | 44 ++++-- docs/build-deploy/ci-cd/codefresh.md | 19 +-- docs/testing.md | 2 +- tools/deployment-cli-tools/CLAUDE.md | 4 +- .../deployment-cli-tools/ch_cli_tools/api.py | 55 +++++++- tools/deployment-cli-tools/ch_cli_tools/ci.py | 47 +++++++ .../ch_cli_tools/codefresh.py | 23 +++- .../ch_cli_tools/github_actions.py | 87 ++++++------ .../ch_cli_tools/model.py | 17 +-- tools/deployment-cli-tools/harness-deployment | 28 +--- tools/deployment-cli-tools/harness-generate | 99 +++++++++++++- .../deployment-cli-tools/tests/test_ci_cd.py | 128 ++++++++++++++++++ .../tests/test_codefresh.py | 22 ++- .../tests/test_generated_files.py | 4 +- .../tests/test_github_actions.py | 90 +++++++----- .../tests/test_skaffold_internals.py | 4 +- 28 files changed, 668 insertions(+), 233 deletions(-) create mode 100644 tools/deployment-cli-tools/tests/test_ci_cd.py 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 3bc60e951..9b379bf07 100644 --- a/deployment-configuration/README.md +++ b/deployment-configuration/README.md @@ -10,12 +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/cloudharness-[env].yaml`), - generated with `harness-deployment -ci github`: the job prototypes expanded per image/app and the shared steps +- `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/` + 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 index ff61f6d1e..a0a7b4271 100644 --- a/deployment-configuration/github-template-dev.yaml +++ b/deployment-configuration/github-template-dev.yaml @@ -1,15 +1,11 @@ -# Development pipeline: build, unit tests, deployment, API/E2E tests and, when a publish tag is given, -# publication of the images after approval (protect the `publish` environment with required reviewers). +# 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: - publish_tag: - description: Tag to publish the images with when the run succeeds (leave empty not to publish) - type: string - default: "" force_build: description: Comma-separated image names to rebuild even if their tag already exists, or `all` type: string @@ -18,3 +14,91 @@ on: 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 index 9e3670f15..eb830db12 100644 --- a/deployment-configuration/github-template-prod.yaml +++ b/deployment-configuration/github-template-prod.yaml @@ -1,14 +1,14 @@ -# Production pipeline: deploys images published by the development or staging pipeline, nothing else. +# 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 published by the development or staging pipeline) + description: Tag of the images to deploy (a tag given by the promote workflow) type: string required: true -# deploys the published images: builds nothing +# deploys the promoted images: builds nothing cloudharness: build: null jobs: @@ -16,4 +16,3 @@ jobs: name: Prepare helm chart tests-api: null tests-e2e: null - publish: null diff --git a/deployment-configuration/github-template-stage.yaml b/deployment-configuration/github-template-stage.yaml index cc01b08cf..e2287f466 100644 --- a/deployment-configuration/github-template-stage.yaml +++ b/deployment-configuration/github-template-stage.yaml @@ -1,39 +1,22 @@ -# Staging pipeline: deploys images published by the development pipeline, runs the API/E2E tests and, -# after approval, publishes them again under the given tag and tags the repository. +# 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 published by the development pipeline) + description: Tag of the images to deploy (a tag given by the promote workflow) type: string required: true - publish_tag: - description: Tag to publish the deployed images with after approval (leave empty not to publish) - type: string - default: "" skip_tests: description: Set to `true` to skip the tests type: string default: "" -# deploys the published images: builds nothing +# deploys the promoted images: builds nothing cloudharness: build: null jobs: prepare: name: Prepare helm chart - # Only once the images were actually published: publish is skipped when the deployment or a test fails. - git-tag: - name: Tag the repository - needs: [prepare, publish] - if: ${{ needs.publish.result == 'success' && needs.prepare.outputs.publish_tag != '' }} - permissions: - contents: write - env: - PUBLISH_TAG: ${{ needs.prepare.outputs.publish_tag }} - steps: - - uses: actions/checkout@v4 - - name: Push the tag - run: | - git tag "$PUBLISH_TAG" - git push origin "refs/tags/$PUBLISH_TAG" diff --git a/deployment-configuration/github-template-test.yaml b/deployment-configuration/github-template-test.yaml index d50fceaab..6422f7c59 100644 --- a/deployment-configuration/github-template-test.yaml +++ b/deployment-configuration/github-template-test.yaml @@ -17,11 +17,15 @@ jobs: prepare: env: NAMESPACE: test-${{ vars.NAMESPACE_BASENAME }} - publish: null + # 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' }} diff --git a/deployment-configuration/github-template.yaml b/deployment-configuration/github-template.yaml index b35fe8a40..cd110b0aa 100644 --- a/deployment-configuration/github-template.yaml +++ b/deployment-configuration/github-template.yaml @@ -1,4 +1,4 @@ -# Base of the GitHub Actions workflows generated by `harness-deployment -ci github`. +# 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). @@ -31,7 +31,7 @@ cloudharness: # 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 - # published images). + # promoted images). build: - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 @@ -86,7 +86,6 @@ jobs: 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 }} @@ -95,7 +94,6 @@ jobs: 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 }} @@ -118,7 +116,6 @@ jobs: 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" @@ -133,7 +130,7 @@ jobs: 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" -N $HELM_META_ARGS $PARAMS + 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" @@ -147,10 +144,9 @@ jobs: # 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) approve the deployment. Every job naming an environment is - # gated by those rules, so the test cleanup does not: it reads the cluster credentials from - # repository/organization secrets (an environment secret of the same name overrides them for deploy). + # 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. @@ -206,25 +202,3 @@ jobs: username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - $TEST_STEPS - # Runs once the tests are done, and only if nothing failed. To publish despite failing API/E2E tests - # (Codefresh's fail_fast: false), override the `if` in the project template and protect the `publish` - # environment with required reviewers. - publish: - name: Publish images - needs: [prepare, deploy, tests-api, tests-e2e] - if: ${{ !cancelled() && needs.prepare.outputs.publish_tag != '' && needs.deploy.result == 'success' && !contains(needs.*.result, 'failure') }} - environment: publish - steps: - - uses: docker/login-action@v3 - with: - registry: ${{ needs.prepare.outputs.registry_host }} - username: ${{ secrets.REGISTRY_USERNAME }} - password: ${{ secrets.REGISTRY_PASSWORD }} - - name: Log in to the publish registry - if: ${{ vars.REGISTRY_PUBLISH_URL != '' }} - env: - REGISTRY_PUBLISH_URL: ${{ vars.REGISTRY_PUBLISH_URL }} - 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 - - $PUBLISH_STEPS 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 c63d74179..cbfc7b260 100644 --- a/docs/build-deploy/ci-cd/README.md +++ b/docs/build-deploy/ci-cd/README.md @@ -19,16 +19,25 @@ 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). ## CI/CD with GitHub Actions -`harness-deployment -ci github -e [ENV]` generates `.github/workflows/cloudharness-[ENV].yaml`, a workflow with -the same stages as the Codefresh pipeline: image build, unit tests, helm deployment, rollout wait, API/E2E tests -and publication. Pass `-ci codefresh -ci github` to generate both. Build, unit tests and deployment run with -[Skaffold](https://skaffold.dev/), from the `deployment/skaffold-ci.yaml` the pipeline writes. +`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 @@ -56,18 +65,19 @@ and publication. Pass `-ci codefresh -ci github` to generate both. Build, unit t `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 on the - `publish` and `prod`/`stage` environments. `workflow_dispatch` inputs replace the `DEPLOYMENT_PUBLISH_TAG`, - `DEPLOYMENT_TAG`, `*_TAG_FORCE_BUILD` and `SKIP_TESTS` pipeline variables. A project's jobs clone and install + 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. Only `deploy` - targets the GitHub environment named after the CloudHarness environment (so required reviewers on - `stage`/`prod` approve the deployment once): `cleanup` reads repository or organization secrets, which an - environment secret of the same name overrides for `deploy`. For GKE with workload identity + 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): @@ -88,7 +98,13 @@ and publication. Pass `-ci codefresh -ci github` to generate both. Build, unit t 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, but `publish` (and `git-tag` on stage) is skipped when anything failed. To publish - despite failing tests, as Codefresh's `fail_fast: false` does, override the `if` of `publish` in your - project's template and protect the `publish` environment with required reviewers. + 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/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 index b1186fe18..adb0e6def 100644 --- a/tools/deployment-cli-tools/ch_cli_tools/ci.py +++ b/tools/deployment-cli-tools/ch_cli_tools/ci.py @@ -11,6 +11,7 @@ import logging import re from dataclasses import dataclass +from pathlib import Path from ch_cli_tools.configuration.secrets import ( is_cloudharness_managed, @@ -28,6 +29,52 @@ 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 `